Поделиться через


ExtractionRule - класс

Обновлен: Ноябрь 2007

Базовый класс, используемый для определения правил получения данных из веб-ответов, создаваемых веб-тестами.

Пространство имен:  Microsoft.VisualStudio.TestTools.WebTesting
Сборка:  Microsoft.VisualStudio.QualityTools.WebTestFramework (в Microsoft.VisualStudio.QualityTools.WebTestFramework.dll)

Синтаксис

'Декларация
Public MustInherit Class ExtractionRule
'Применение
Dim instance As ExtractionRule
public abstract class ExtractionRule
public ref class ExtractionRule abstract
public abstract class ExtractionRule

Заметки

Класс ExtractionRule должен наследоваться любым правилом извлечения, будь оно пользовательским или встроенным. Правила извлечения, связанные с определением запроса, запускаются после получения ответа, и результаты извлечения добавляются к контексту WebTestContext.

Примечания для наследующих объектов:

При наследовании от класса ExtractionRule необходимо переопределить следующие члены: Extract, RuleDescription и RuleName.

Примеры

Следующее пользовательское правило извлечения извлекает флажки из документа HtmlDocument и помещает состояние найденных флажков в контекст.

using System;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace ClassLibrary2
{
    public class ExtractCheckBoxes : ExtractionRule
    {
        private string myContextParameter = "ExtractCBoxParam";
        private bool isChecked = true;

        public override string ContextParameterName
        {
            get { return myContextParameter; }
            set
            {
                if (value != string.Empty)
                    myContextParameter = value;
            }
        }

        public bool FindCheckedBoxes
        {
            get { return isChecked; }
            set { isChecked = value; }
        }

        public override string RuleName
        {
            get { return "Extract Check Boxes"; }
        }

        public override string RuleDescription
        {
            get { return "Extract check boxes based on whether they are" +
                    " checked or not."; }
        }

        public override void Extract(object sender, ExtractionEventArgs e)
        {   
            e.Success = false;
            
            if (e.Response.HtmlDocument != null)
            {   // Gets all input tags
                foreach (HtmlTag tag in e.Response.HtmlDocument
                    .GetFilteredHtmlTags(new string[] { "input" }))
                {   // Verify that current tag is a checkbox
                    if (tag.GetAttributeValueAsString("type") == "checkbox")
                    {   // Is the checkbox checked
                        if (tag.GetAttributeValueAsString("checked") == "CHECKED")
                        {   // Add checked checkboxes to context
                            if (isChecked)
                            {
                                e.WebTest.Context.Add(myContextParameter + "_" +
                                    tag.GetAttributeValueAsString("id"),
                                    "Is Checked");
                                e.Success = true;
                            }
                        }
                        else // The checkbox is not checked
                        {   // Add non-checked boxes to context
                            if (!isChecked)
                            {
                                e.WebTest.Context.Add(myContextParameter + "_" +
                                    tag.GetAttributeValueAsString("id"),
                                    "Is Not Checked");
                                e.Success = true;
                            }
                        }
                    }
                }
            }
            if (e.Success)
                e.Message = "Extracted checkboxes.";
            else
                e.Message = "No checkboxes extracted.";
        }
    }
}
Imports System
Imports Microsoft.VisualStudio.TestTools.WebTesting

Namespace ClassLibrary2
    Public Class ExtractCheckBoxes
        Inherits ExtractionRule

        Private myContextParameter As String = "ExtractCBoxParam"
        Private isChecked As Boolean = True

        Public Overrides Property ContextParameterName() As String
            Get
                Return myContextParameter
            End Get
            Set(ByVal value As String)
                If (value <> String.Empty) Then
                    myContextParameter = value
                End If
            End Set
        End Property

        Public Property FindCheckedBoxes() As Boolean
            Get
                Return isChecked
            End Get
            Set(ByVal value As Boolean)
                isChecked = value
            End Set
        End Property

        Public Overrides ReadOnly Property RuleName() As String
            Get
                Return "Extract Check Boxes"
            End Get
        End Property

        Public Overrides ReadOnly Property RuleDescription() As String
            Get
                Return "Extract check boxes based on whether they are" + _
                    " checked or not."
            End Get
        End Property

        Public Overrides Sub Extract(ByVal sender As Object, ByVal e As ExtractionEventArgs)
            e.Success = False
            If Not e.Response.HtmlDocument Is Nothing Then
                ' Gets all input tags
                Dim tag As HtmlTag
                For Each tag In e.Response.HtmlDocument.GetFilteredHtmlTags(New String() {"input"})
                    ' Verify if current tag is a checkbox
                    If tag.GetAttributeValueAsString("type") = "checkbox" Then
                        ' Is the check box checked
                        If tag.GetAttributeValueAsString("checked") = "CHECKED" Then
                            ' Add checked checkbox to context
                            If isChecked = True Then
                                e.WebTest.Context.Add(myContextParameter + "_" + _
                                tag.GetAttributeValueAsString("id"), "Is Checked")
                                e.Success = True
                            End If
                        Else ' The check box is not checked
                            If isChecked = False Then
                                ' Add non-checked boxes to context
                                e.WebTest.Context.Add(myContextParameter + "_" + _
                                tag.GetAttributeValueAsString("id"), "Is Not Checked")
                                e.Success = True
                            End If
                        End If
                    End If
                Next
            End If
            If e.Success = True Then
                e.Message = "Extracted check boxes."
            Else
                e.Message = "No check boxes extracted."
            End If
        End Sub
    End Class
End Namespace

Иерархия наследования

System.Object
  Microsoft.VisualStudio.TestTools.WebTesting.ExtractionRule
    Microsoft.VisualStudio.TestTools.WebTesting.Rules.ExtractAttributeValue
    Microsoft.VisualStudio.TestTools.WebTesting.Rules.ExtractFormField
    Microsoft.VisualStudio.TestTools.WebTesting.Rules.ExtractHiddenFields
    Microsoft.VisualStudio.TestTools.WebTesting.Rules.ExtractHttpHeader
    Microsoft.VisualStudio.TestTools.WebTesting.Rules.ExtractRegularExpression
    Microsoft.VisualStudio.TestTools.WebTesting.Rules.ExtractText

Потокобезопасность

Любые открытые члены этого типа, объявленные как static (Shared в Visual Basic), являются потокобезопасными. Потокобезопасность членов экземпляров не гарантируется.

См. также

Ссылки

ExtractionRule - члены

Microsoft.VisualStudio.TestTools.WebTesting - пространство имен

Другие ресурсы

Практическое руководство. Создание пользовательского правила извлечения

Практическое руководство. Добавление правила извлечения к веб-тесту