Author Archives: Gerben

SharePoint people-pickers in loadtests

A significant number of the webtests in out loadtest need to simulate a human tying into a people-picker control. This control waits until the first few letters have been entered and after that calls SharePoint’s client.svc web-service every time the user enters data into the control.

I simulate this with the following logic in webtests:

GET https://...
For Each Character In Targetusers display name:
    POST https://.../_vti_bin/client.svc/ProcessQuery
GET https:/...

As Visual Studio doesn’t contain a plugin that iterates over characters in a string, I wrote my own. This plug-in allows you to choose:

  1. Which input parameter contains the display name to iterate over.
  2. Into which output parameter to place the sub-string.
  3. At which index to start iterating. The 1st iteration of the loop includes all characters upto the starting index. All subsequent iterations add one more letter from the input string into the output string.

Some nice-to-have improvements to this plugin are:

  • Add a configurable delay in milliseconds to each loop. This would be nice as think-times on requests can only be configured in intervals of whole seconds
  • Add an option to automatically clear the output parameter once all iterations have finished

Here is the code for the plug-in:

using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.VisualStudio.TestTools.WebTesting;
using Microsoft.VisualStudio.TestTools.WebTesting.Rules;

namespace LoadTestPlugins
{

    [DisplayNameAttribute("For Each character in context parameter")]
    [DescriptionAttribute("Sequentially copies each character from the source into the destination. You can use this to simulate a user that types a name into a peoplepicker for example")]
    public class ForEachCharacter : ConditionalRule
    {

        #region Methods
        public override void CheckCondition(object sender, ConditionalEventArgs e)
        {
            string Input = e.WebTest.Context[this.InputContextParameterName].ToString();
            string Output;
            try
            {
                Output = e.WebTest.Context[this.OutputContextParameterName].ToString();
            }
            catch (KeyNotFoundException)
            {
                Output = string.Empty;
            }


            //Only do something if the output is not yet complete
            if (Input.Length == Output.Length)
            {
                e.IsMet = false;
                return;
            }
            

            int LengthToCopy;
            if(Output.Length == 0)
            {
                //Copy all characters before the starting index and 1 extra
                LengthToCopy = this.StartIndex + 1;
            }
            else 
            {
                //Copy 1 extra character to the output
                LengthToCopy = Output.Length + 1;
            }

            e.IsMet = true;
            e.WebTest.Context[this.OutputContextParameterName] = Input.Substring(0, LengthToCopy);
            return;
        }
        
        #endregion

        #region Properties
        [Description("Name of context parameter that contains the characters to iterate over"),
        DisplayName("Input Context parameter"), IsContextParameterName(true)]
        public string InputContextParameterName {get; set;}

        [Description("Name of context parameter to store the each successive iteration"),
        DisplayName("Ouput Context parameter"), IsContextParameterName(true)]
        public string OutputContextParameterName { get; set; }

        [Description("The zero-based index to start the iteration from"),
        DisplayName("Start Index")]
        public int StartIndex { get; set; }
        #endregion
    }
}

A loadtest plugin to select the transition from a probability matrix

An important part of loadtesting with Markov chains is choosing which transition the test should take. This boils down to generating a random number and then seeing in which of the transitions in the probability matrix that number belongs to.

In a previous post I showed how to generate a random number. In this post we’ll see how we can decide which transition to actually take based upon the probabilities from the matrix.

Webtests can include various types of plugins that execute requests based on some boolean condition. These type of plugins are called ConditionalRule plugins. I created a simple plugin that determines if the random number falls within a user specified range. This allows me to implement the following kind of logic in my webtest:

Picture showing how the plug-in is included in a .webtest

Here is the code for the plugin:

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

namespace LoadTestPlugins
{

    [DisplayNameAttribute("Number in range")]
    [DescriptionAttribute("Determines if the number in the context parameter is in the specified range")]
    public class NumberInRange : ConditionalRule
    {

        #region Methods
        public override void CheckCondition(object sender, ConditionalEventArgs e)
        {
            Int32 Input = Convert.ToInt32(e.WebTest.Context[this.ContextParameterName]);
            e.IsMet = (Input >= this.LowerBound && Input <= this.UpperBound) ? true : false;
            return;
        }

        public override string StringRepresentation()
        {
            return string.Format("{0} (Number in range [{1} - {2}])"
                , this.Description
                , this.LowerBound
                , this.UpperBound);
        }
        
        #endregion

        #region Properties
        // Properties
        [Description("Name of context parameter that contains the number"),
        DisplayName("Context parameter"), IsContextParameterName(true)]
        public string ContextParameterName {get; set;}

        [Description("The lower bound"),
        DisplayName("Lower bound")]
        public Int32 LowerBound { get; set; }


        [Description("The upper (inclusive) bound"),
        DisplayName("Upper bound")]
        public Int32 UpperBound { get; set; }

        [Description("Your description of this rule"),
        DisplayName("Description")]
        public string Description { get; set; }
        
        #endregion
    }
}

A loadtest plugin to simulate random chance

An important part of loadtesting with Markov chains is choosing which transition the test should take. This boils down to generating a random number and then seeing in which of the transitions in the probability matrix that number belongs to.

The plugin code below generates a random number between your specified lower- and upper bound and places it into the specified context parameter. Its very similar to the out-of-the box plugin. However Visual Studio’s plugin can only be executed once when a webtest starts. I needed a new random number every time that my loops executes.

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

namespace LoadTestPlugins
{

    [DisplayNameAttribute("Generate random number")]
    [DescriptionAttribute("Generates a random number during a request")]
    public class GenerateRandomNumber : WebTestRequestPlugin
    {

        #region Methods
        private void GenerateIt(WebTestContext Context)
        {
            Context[this.ContextParameterName] = new Random().Next(this.LowerBound, this.UpperBound);
        }

        public override void PostRequest(object sender, PostRequestEventArgs e)
        {
            if(this.BeforeRequest == false)
            {
                this.GenerateIt(e.WebTest.Context);
            }
        }
        
        public override void PreRequest(object sender, PreRequestEventArgs e)
        {
            if(this.BeforeRequest == true)
            {
                this.GenerateIt(e.WebTest.Context);
            }
        }
        #endregion

        #region Properties
        [Description("Name of context parameter to store the number in"),
        DisplayName("Context parameter"), IsContextParameterName(true)]
        public string ContextParameterName {get; set;}

        [Description("The lower bound"),
        DisplayName("Lower bound"),
        DefaultValue(1)]
        public Int32 LowerBound { get; set; }


        [Description("The upper (inclusive) bound"),
        DisplayName("Upper bound"),
        DefaultValue(100)]
        public Int32 UpperBound { get; set; }

        [Description("Whether to generate the number before or after the request has executed"),
        DisplayName("Apply before request"),
        DefaultValue(true)]
        public bool BeforeRequest { get; set; }
        #endregion
    }
}

A loadtest plugin to extract querystring parameters from responses

When a user creates a new casefile in our system. Its created as a custom content-type that inherits from SharePoint’s document set. My load tests need at least the following information in order to continue working with that casefile:

  1. The title of the document set.
  2. SharePoint’s ID of the content-type.
  3. SharePoint’s ID of the list item.
  4. SharePoint’s ID of the list where its created in.

The POST to a MVC controller is the starting point for our system to create the casefile. The only way to find out what the values are is by following a URL contained within the HTTP 200 response (looks like this)

<script type="text/javascript">window.parent.location.href="https://...../DocSetHome.aspx?......";</script>

By doing a GET request to that URL, we get a HTTP 302 response, Visual Studio automatically follows the redirect and the final HTTP 200 response’s URI contains all the dynamic values as querystring parameters:
https://……/docsethomepage.aspx?ID=…&FolderCTID=…&List=…&RootFolder=…&RecSrc=…

Visual Studio doesn’t have an out-of-the-box plugin that can extract the values of those querystring parameters. So I created my own:

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.Globalization;
using System.ComponentModel;
using System.Web;
using System.Collections.Specialized;
using Microsoft.VisualStudio.TestTools.WebTesting.Rules;

namespace LoadTestPlugins
{
    [DisplayNameAttribute("Extract querystring parameter")]
    [DescriptionAttribute("Extracts the value of a querystring parameter from the URI of a response")]
    public class ExtractQuerystringParameter : ExtractionRule
    {
        //Which field to parse and store in the context
        [Description("Name of the querystring parameter to extract"),
        DisplayName("Field name")]
        public string FieldName {get; set;}


        public override void Extract(object sender, ExtractionEventArgs e)
        {
            if (e.Response.ResponseUri != null)
            {
                NameValueCollection NVC = HttpUtility.ParseQueryString(e.Response.ResponseUri.Query);
                string value = NVC[this.FieldName];
                if(!string.IsNullOrEmpty(value))
                {
                    //The last part of the RootFolder or RecSrc contains the name of the 
                    //documentset. It needs to be Url encoded as it might contain spaces  
                    if (   this.FieldName.ToLower().Equals("RootFolder".ToLower())
                        || this.FieldName.ToLower().Equals("RecSrc".ToLower()))
                    {
                       value = Uri.EscapeUriString(value.Split('/').Last());
                    }
                    e.WebTest.Context.Add(this.ContextParameterName, value);
                    e.Success = true;
                    return;
                }
                else
                {
                    e.Success = false;
                    e.Message = string.Format(CultureInfo.CurrentCulture
                        , "Querystring Parameter Not Found: {0}"
                        , this.FieldName);
                }
            }
        }
    }
}

Loadtesting using Markov chains to simulate user behavior

One of my clients has a rather large SharePoint farm and uses the add-in / provider-hosted-app model a lot. Everyone who looks at the topology and machine specs, expects the farm to provide a ‘huge’ amount of performance. In practice the users report that its rather slow.

The guys in maintenance had done some rudimentary measurements and didn’t really see any reason to doubt the machine specs. So we were wondering…

how come that users are perceiving a lack of performance? Are we measuring correctly? How do we compare the farm’s performance before and after major changes? If we fix bottlenecks, how far can we push the farm?

These are different questions, that all need the results from a ‘proper’ loadtest. So what is a ‘proper’ loadtest and how do we build that?

Besides the criteria described in My Definition of Done for performance and loadtest cases, a proper loadtest needs to simulate realistic behavior patterns. In our case that means:

  • Users will choose to sequentially do many different actions in a short time period.
  • Some actions are usually only done by some types of users. Some actions are usually done by all types of users.
  • Action sometimes depend on data that was generated during an earlier action.
  • Some actions are always followed by another type of action.
  • Its not fixed exactly in which order and when the actions will be executed. Its dependent on probabilities.
  • We have a rough idea what the probabilities are, but we expect these probabilities to change as time progresses and our knowledge increases. We don’t want to invest significant time to change the tests.

In order to satisfy the above, I decided that a plain-old operational profile wasn’t suitable. We needed to combine it with a Markov chain (see Kozialek’s paper on Operational Profiles). Also I wanted the loadtest to decide during run-time which path through the chain would be taken. I really didn’t want to generate the chains at design time and have to redo them once the probabilities are measured more accurately. Visual Studio doesn’t support this out of the box, so I had create some plug-ins that would achieve this:

Plugin Type Purpose
GenerateRandomNumber WebTestRequestPlugin Generates a random number between a user defined lower- and upperbound. Visual Studio only had a plugin that would generate the number once during a test. I needed to generate it every iteration within a single test.
NumberInRange ConditionalRule Executes a block of requests only when the input number falls in a user defined range. This lets me dynamically select the transtions/action in the Markov chain like in the following pseudo-code:

probability = GenerateRandomNumber(1,100)
if probability between 1 and 5: do action1; stay in current state;
if probability between 6 and 90: do action2; go to state xxx;
if probability between 91 and 98 do action3; go to state yyy;
if probability between 99 and 100: go to exit state;
ChooseDocumentSet WebTestRequestPlugin About 70% of the users will select a case-file and start working with it. This plugin queries SharePoint to find a suitable document set and ensures that this document set is never shared by multiple users.
ForEachCharacter ConditionalRule (loop) Simulates a user typing into a people-picker. Its a plugin that that executes a block of requests for each character in user defined context parameter.
GenerateGuid WebTestRequestPlugin Is able to generate a new GUID every time a certain request is executed instead on only once per test.
ExtractQuerystringParameter ExtractionRule Retrieves the value of a specific querystring parameter. My system dynamically generates information and returns a URI containg this information in various querystring parameters. My testcases needed to remember these values for later use.
ClearContextParameter WebTestPlugin Is able to clear the value of an existing context parameter each time a .webtest is called by another webtest.

When Impersonation is useful

In a previous post I stated that Impersonation is not suitable for starting a Selenium browser session as a different user. Even so there are still a few scenarios where I do need it.

In my testcases I want to check that the state of the various tasks in SharePoint are conform my expectations. I use CSOM to query for the tasks and I verify that the results match the testcase. Due to SharePoint’s security trimming I can only see the tasks that I am authorized to see. As I don’t want my test user to have full site-collection admin privileges, I wrapped the CSOM calls in an Impersonation to another account that does have site-collection admin permissions. This lets me receive all relevant tasks regardless whether my account does or does not have permission to access to them.

The system I am testing will, in certain scenarios, set unique permissions on documents in a document-set. Even if I am the owner of the set, I will at most have Contribute permissions on those documents. Other users may or may-not have Contribute depending on the exact scenario. Therefore, my testcases need to check if the documents have the correct permissions. For this I use CSOM, however I cannot run that query under my own credentials as you need at least Design permissions to view the RoleAssignments and RoleDefinitionBindings of an object. So also here I wrapped the CSOM calls in a Impersonation to a site-coll admin.

‘Insert Call to webtest’ and the ‘Inherit Web Test Settings” property

One of the nice things in Visual Studio’s load test framework is the ability for a webtest to include calls to other webtests. This allows you to compose complex scenarios from a bunch of simple .webtests. In fact my load test uses statistical modelling to dynamically decide which tests its going to call.

If your webtest includes User Name / Password properties then you need to set the ‘Inherit Web Test Settngs‘ to True. Otherwise the called webtest won’t use the same credentials that the calling test is using. Especially in situations where you are running with Controllers and Agents you will probably need to set this setting.

Lets assume we have Webtest1 and it includes several calls to Webtest2. This has a few consequences you need to be aware of and deal with:

  1. Any WebTestPlugins in Webtest1 will execute when Webtest1 starts and each time Webtest2 starts. You probably don’t want that. Many people use the ‘Generate GUID’ plugin to store a unique ID in the context for the test session. However in this case the context parameter’s value will change every time one of the webtests is started. In my opinion its best to avoid using any WebTestPlugins on webtests that call to other webtests.
  2. Any validation rules in Webtest1 will also be applied to all requests in Webtest2. This can be problematic if webtest2 needs less or different validation.
  3. If webtest2 includes a call to webtest3, then webtest3 will also show the above issues.

Loadtest summary shows many URLs for a single page

When you are running a load test against an MVC page you will see an enormous amount of different URLs reported. That’s because dynamic parameters such as IDs are frequently included in the URL of the page that is being accessed.

For example, here is an URL that will update an invoice whose ID is 129101 https://my-system.local/invoice/update/129101?SPHostUrl=..... If we update 5 different invoices, the load test summary will report 5 different URLS. That’s not useful at all.

The solution is to open the .webtest that sends the GET/POST requests and set the “Reporting Name” property. All the calls to that action will then be reported as one URL.There’s no need to have a different “Reporting Name” for the GET and POST requests to this URL, the load test summary will automatically report 2 separate summary lines for the URL.

How to get Selenium to run the browser as a different user

Selenium is great for testing web-apps. One of the challenges that you’ll eventually run into is needing to control which user is connecting to the system under test. Achieving this is far from intuitive. A search for this topic gives many links that don’t solve this problem:

Most of these are attempting to make use of Impersonation. This doesn’t work as the web-browser process ends-up running under your credentials not the credentials that you impersonated into. This is because Selenium’s code on Windows uses the CreateProcess() function to starts its sub-processes. The MSDN page on that says

“If the calling process is impersonating another user, the new process uses the token for the calling process, not the impersonation token”

How do we achieve our objective then? The answer is to start using RemoteWebDriver together with Selenium Grid. Lets assume we want to run testcases under your account and the account of a user I will call user1.

Start a Selenium hub on your local machine under your account.

Start a Selenium node on your local machine under your account.This node will run web-browsers using your credentials. The following command will start a node that can run Firefox and Internet Explorer on Windows:

java 
-jar Selenium-server-standalone-x.xx.x.jar 
-role node 
-port 55565 
-hub "http://<yourmachine>:4444/grid/register" 
-browser "browserName=firefox" 
-browser "browserName=iexplore"

Start a Selenium node on another machine that is logged on as user1. This node will run web browsers as user1. Make sure that node is starting with different capabilities than your node. For example, here although we start the node on Windows, we manually overrule that and the node tells the hub that its running on Mac.

java 
-jar Selenium-server-standalone-x.xx.x.jar 
-role node 
-port 5556 
-hub "http://<yourmachine>:4444/grid/register" 
-browser "platform=MAC,browserName=firefox,maxinstances=12"

Instead of instantiating the actual implementations such as InternetExplorerDriver or FirefoxDriver, you need to instantiate a RemoteWebDriver. When instantiating the RemoteWebDriver, you can use the DesiredCapabilities object to determine which machine (and thus which user) Selenium will choose to run the browser on. For example:

public IWebDriver CreateNewBrowserFor(string Who)
{
    //Decide which of Selenium nodes we want to connect to 
    string CapabilitiesOfTargetUser;
    if(Who.Equals("user1"))
    {
        //We need to control a browser for user1 on his node
        CapabilitiesOfTargetUser = "platform=Mac;browserName=firefox";
    }
    else if(Who.Equals("me"))
    {
        //We need to control a browser for me on my node
        CapabilitiesOfTargetUser = "platform=WINDOWS";
    }
    else
    {
        throw new ArgumentException();
    }
    
    //Create a Selenium DesiredCapabilities object that contains our choosen capabilities
    Dictionary<string, object> RequestedCapabilities = new Dictionary<string, object> ();
    string[] CapabilitiesArray = CapabilitiesOfTargetUser.Split(';');
    foreach(string KeyValuePair in CapabilitiesArray)
    {
        string key = KeyValuePair.Split('=').First().Trim();
        string value = KeyValuePair.Split('=').Last().Trim();
        RequestedCapabilities[key] = value;
    }
    DesiredCapabilities Capabilities = new DesiredCapabilities(RequestedCapabilities);
    
    //Create the RemoteWebDriver. Selenium's hub will ensure that this RemoteWebDriver is
    //actually controlling a new browser on the correct machine
    return  new RemoteWebDriver
    (
         new Uri("http://localhost:4444/wd/hub")
       , Capabilities
       , new TimeSpan(0, 0, 50)
    );
}

Running your testcases concurrently

System- and integration tests can take a lot of time to complete. If you want to speed this up then you can choose to run multiple test cases at the same time in parallel.

Unit Testcases in Visual Studio


You can configure Visual Studio to run unit concurrent testcases on your local machine using the following procedure:

  1. Ensure your project is using a .testsettings file
  2. Open it in an XML editor (Notepad++ or visual Studio’s “Open With” command)
  3. Set the parallelTestCount attribute on the Execution entity some some integer value

This will only work for situations where all the following is true:

  • The testcases and related frameworks are thread-safe
  • The testcases are of type unit testcase. It really won’t work for coded-ui tests
  • Its NOT a Data-Driven Unit Test
  • There are 0 diagnostic adapters included in the .testsettings file
  • Your machine has multiple cores

Controller and Agents with Visual Studio


If you have enough Physical or Virtual Machines available, then its always possible to configure a Controller and multiple agents. That will allow you to distribute your testcases over the machines. There’s no limitation on the type of testcases here. The only thing to take into account that running testcases that interact with a User Interface will require specific configuration on part of the agent machines. I use this setup mainly for running a lot of performance-tests against my client’s SharePoint farm.

See Configuring Test Controllers and Test Agents for Load Testing for details.

SpecFlow / SpecRun


SpecRun is a test-runner from the makers of SpecFlow that will allow you to run many concurrent SpecFlow scenarios. Its easy to setup and doesn’t really have any significant limitations. I use a combination of SpecFlow, SpecRun and an on-premise Selenium Grid to run my 250+ automated regression tests.