Search code examples
asp.netvisual-studiotestingvisual-studio-2015visual-studio-test-runner

Extract nested fields in Visual Studio Web load test


Here is an html code I would like to test load and extract data from

<body>
    <h1>Hello StackOverflow</h1>

    <input type="hidden" name="Secret" value="66"/>
    <input type="hidden" name="Field[66].value" value="333" />
</body>

I need the 333 value. To do that, I need to extract the value 66 from Secret, and then use this value to deduce the name of the field (here Field[66].value). How can I do that?

I've tried to use two Extract Attribute Value extraction rules, but because there are on the same response, the first value is not yet in the context.


Solution

  • The solution was to create a Custom Extraction Rule as explained here and to use a regex to parse twice the html body

    Extract Method:

    public override void Extract(object sender, ExtractionEventArgs e)
    {
        var val1 = GetInputValueByName(e.Response.BodyString, "Secret");
        var val2 = GetInputValueByName(e.Response.BodyString, $"Field[{val1}].value");
    
        if (!string.IsNullOrEmpty(val2 ))
        {
            e.Success = true;
            e.WebTest.Context.Add(this.ContextParameterName, val2);
        }
        else
        {
            // If the extraction fails, set the error text that the user sees
            e.Success = false;
            e.Message = String.Format(CultureInfo.CurrentCulture, "Not Found: {0}", Name);
        }
    
    }
    
    
    private string GetInputValueByName(string html, string name)
    {
        Match match = Regex.Match(html, "<input[^>]*name=\"" + Regex.Escape(name) + "\"[^>]*value=\"([^\"]*)\"");
        if (match.Success)
        {
            return match.Groups[1].Value;
        }
        return string.Empty;
    }