Saturday, November 13, 2010

Custom Web Request Test Plugin – Extracted by Regex

Web test requests might include Form Post or QueryString Parameters. For example, if some link of the web site should be clicked, these parameters might include ID of this link. In previous post I showed how to use data source in such case. But data source contains Name of the target link, but not it ID value. Of course, we can add ID value to the data source, but if this ID is unknown for us. For example, in the first request we create application data with corresponding name from the data source and in the second request we click on the newly created item. For such case following custom web request plugin can be created:
[Description("Extract by RegEx \n Sample BeginRegEx + e.WebTest.Context[TextToSearch].ToString() + EndRegEx")]
public class ExtractByRegEx : WebTestRequestPlugin
{
    [Description("Context paramete with UserName")]
    public string ContextParamWithSearchValue
    { set; get; }

    [Description("Context param name to store UserID value")]
    public string ContextParamToStoreValue
    { set; get; }

    [Description("First part of RegEx")]
    public string BeginRegEx
    { set; get; }

    [Description("End part of RegEx")]
    public string EndRegEx
    { set; get; }

    public override void PostRequest(
        object sender, PostRequestEventArgs e)
    {
        if (e.Response == null)
        {
            return;
        }

        var context = e.WebTest.Context;
        var match =
            Regex.Match(
                e.Response.BodyString,
                string.Format("{0}{1}{2}",
                    BeginRegEx,
                    context[ContextParamWithSearchValue],
                    EndRegEx)
            )
            .Groups[1].Value;

        if (context.ContainsKey(ContextParamToStoreValue))
        {
            context[ContextParamToStoreValue] = match;
        }
        else
        {
            context.Add(ContextParamToStoreValue, match);
        }
    }
}
When plugin is created, add it to the request and fill all necessary parameters:
BeginRegEx – this is the first part of the regex expression,
ContestParamToStoreValue – context parameter for extracted value,
ContextParamWithSearchValue – data source value,
EndRegEx – last part of the regular expression.


Context Parameters with extracted value can be used as the data source in further requests.


For create and check regular expression you may use this link.