archive2022

Running a Selenium regression suite in Azure DevOps pipelines

A YAML pipeline that builds and runs a C# Selenium suite with headless Chrome, keeps ChromeDriver in step with the agent, publishes TRX results with failure screenshots, and reruns failed tests without hiding them.

Last month I wrote about replacing Thread.Sleep with dynamic waits in the UI tests for the portal project at work. Stable waits were step one. Step two was running the regression suite in Azure DevOps on its own, so nobody has to start it from their laptop. Below is the pipeline we ended with, and the parts that took the most time.

The setup: a C# test project (.NET 6, NUnit 3, Selenium 4), Microsoft-hosted Windows agents, Chrome, and a Dynamics 365 / Power Apps portal as the system under test.

The test project

Packages in the test .csproj:

<ItemGroup>
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
  <PackageReference Include="NUnit" Version="3.13.3" />
  <PackageReference Include="NUnit3TestAdapter" Version="4.2.1" />
  <PackageReference Include="Selenium.WebDriver" Version="4.4.0" />
  <PackageReference Include="Selenium.Support" Version="4.4.0" />
</ItemGroup>

NUnit3TestAdapter is what lets dotnet test (and the VSTest task) find NUnit tests. Without it, dotnet test runs and reports zero tests, which is easy to miss in a pipeline log.

Headless Chrome

On a build agent there is no screen, so Chrome runs headless. The options we use:

var options = new ChromeOptions();
options.AddArgument("--headless");
options.AddArgument("--window-size=1920,1080");
options.AddArgument("--disable-gpu");
options.AddArgument("--disable-extensions");

var driver = new ChromeDriver(options);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.Zero;

The window size is the important one. Headless Chrome starts with a small window. The portal is responsive, so at a small width the top menu collapses into a hamburger button, and every test that clicks a menu item fails with “element not interactable”. Locally the tests passed, because my browser window was large. I lost an afternoon on this.

I let a setting decide between headless and normal, so I can still watch a test run on my machine:

bool headless = Environment.GetEnvironmentVariable("UI_TESTS_HEADLESS") != "false";

Keeping ChromeDriver in step with Chrome

ChromeDriver must match the major version of Chrome. The hosted agents update Chrome regularly, and when the versions differ, every test fails at startup with “This version of ChromeDriver only supports Chrome version …”. There is no built-in driver management in the .NET bindings, so you have to pick a way.

The options I looked at:

  1. The Selenium.WebDriver.ChromeDriver NuGet package. It copies chromedriver.exe into the build output. Simple, and it works offline. But the driver version is fixed in the project file, so when the agent gets a new Chrome, the suite breaks until someone updates the package. This is what we had at first.

  2. WebDriverManager (WebDriverManager.Net). It downloads a driver at runtime. With VersionResolveStrategy.MatchingBrowser it reads the installed Chrome version and downloads the matching driver:

    using WebDriverManager;
    using WebDriverManager.DriverConfigs.Impl;
    using WebDriverManager.Helpers;
    
    new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);
    var driver = new ChromeDriver(options);

    This needs internet access from the agent to the ChromeDriver download site. On hosted agents that is fine. On a locked-down self-hosted agent it may not be.

  3. The driver that comes with the hosted image. The Microsoft-hosted Windows images include a ChromeDriver that matches their Chrome, and its folder is in the ChromeWebDriver environment variable. Then new ChromeDriver(Environment.GetEnvironmentVariable("ChromeWebDriver"), options) works on the agent, but you still need another way for local runs.

We use option 2. It fixes itself when Chrome updates, and the same code runs locally and on the agent. If the download site has a problem, the run fails at startup with a clear message, which is easy to recognise.

The pipeline

This is a shortened version of our YAML. The project path and variable names are examples.

trigger: none

schedules:
- cron: '0 3 * * 1-5'
  displayName: Nightly regression
  branches:
    include:
    - main
  always: true

pool:
  vmImage: 'windows-2022'

variables:
  buildConfiguration: 'Release'
  testProject: 'tests/Portal.UiTests/Portal.UiTests.csproj'

steps:
- task: UseDotNet@2
  inputs:
    packageType: 'sdk'
    version: '6.0.x'

- task: DotNetCoreCLI@2
  displayName: 'Build UI tests'
  inputs:
    command: 'build'
    projects: '$(testProject)'
    arguments: '-c $(buildConfiguration)'

- task: DotNetCoreCLI@2
  displayName: 'Run UI tests'
  continueOnError: true
  inputs:
    command: 'test'
    projects: '$(testProject)'
    arguments: '-c $(buildConfiguration) --no-build --logger trx --results-directory $(Agent.TempDirectory)/run1'
    publishTestResults: false
  env:
    PORTAL_BASE_URL: $(PortalBaseUrl)
    PORTAL_TEST_PASSWORD: $(PortalTestPassword)

- task: PublishTestResults@2
  displayName: 'Publish test results'
  condition: succeededOrFailed()
  inputs:
    testResultsFormat: 'VSTest'
    testResultsFiles: '*.trx'
    searchFolder: '$(Agent.TempDirectory)/run1'
    testRunTitle: 'UI regression'

Some notes:

  • DotNetCoreCLI@2 with command: test can publish results by itself. I turned that off (publishTestResults: false) and used PublishTestResults@2, because I want to choose the results folder and the run title. That matters for the rerun below.
  • testResultsFormat: 'VSTest' means TRX. The results then show in the Tests tab of the pipeline run, with the error message, stack trace and console output per test.
  • continueOnError: true keeps the pipeline going after failed tests, so results and screenshots are still published. A failed test step then marks the run as “partially succeeded” (orange), not green.
  • Secret variables are not passed to scripts and tasks as environment variables automatically. You have to map them with env: like above. Our first runs failed at login because the password was empty.
  • The VSTest@2 task also works, and it has its own rerun options. I chose dotnet test because it is what everyone on the team runs locally, and I wanted the pipeline to run the same command.

Screenshot on failure

A stack trace that says “timeout waiting for loading overlay to disappear” is much more useful with a screenshot of the page next to it. NUnit 3 has TestContext.AddTestAttachment (since NUnit 3.7). The adapter writes the attachment into the TRX file, and PublishTestResults@2 uploads TRX result files as attachments of that test result. In the Tests tab you open the failed test and find the image under Attachments.

using System.IO;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;

[TearDown]
public void TearDown()
{
    try
    {
        if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed && Driver != null)
        {
            string name = string.Concat(TestContext.CurrentContext.Test.Name.Split(Path.GetInvalidFileNameChars()));
            string dir = TestContext.CurrentContext.WorkDirectory;

            string png = Path.Combine(dir, $"{name}.png");
            ((ITakesScreenshot)Driver).GetScreenshot().SaveAsFile(png, ScreenshotImageFormat.Png);
            TestContext.AddTestAttachment(png, "Screenshot at failure");

            string html = Path.Combine(dir, $"{name}.html");
            File.WriteAllText(html, Driver.PageSource);
            TestContext.AddTestAttachment(html, "Page source at failure");
        }
    }
    finally
    {
        Driver?.Quit();
    }
}

The file must exist before you call AddTestAttachment. The page source turned out to be almost as useful as the screenshot, because it shows hidden validation messages and field IDs.

The finally is there because a failing screenshot (for example, when the browser already crashed) should not leave Chrome processes running on the agent.

If the attachments do not appear, open the .trx file and look for ResultFiles under the failed result. If they are in the TRX, the problem is in publishing. If not, the attachment code did not run.

Running in parallel, and why we kept it small

The full suite took long enough that parallel runs were the obvious next step. NUnit supports it with two assembly attributes:

[assembly: Parallelizable(ParallelScope.Fixtures)]
[assembly: LevelOfParallelism(3)]

ParallelScope.Fixtures runs different test classes at the same time, but the tests inside one class one after another. That fits a driver per fixture, created in [OneTimeSetUp] or [SetUp]. Do not share one IWebDriver between parallel tests. It is not thread-safe.

Speed was never the problem. Test data was. Many of our tests use the same few test accounts and the same records in the Dynamics environment. Two tests that edit the same contact at the same time, or one test that checks a list while another adds to it, fail randomly, and the failures look exactly like timing problems. So we:

  • marked fixtures that change shared records with [NonParallelizable],
  • gave the parallel fixtures their own test accounts where we could,
  • kept the level of parallelism low.

The honest summary is that parallel runs saved noticeably less time than we hoped, because the tests that touch shared data are a big part of the suite. Better test data setup would help more than more threads. That is still on the list.

Retries, reported separately

Some tests still fail now and then for reasons outside the test: the environment is slow after a deployment, or a backend call times out. A rerun is reasonable for those. Hiding them is not. If a retry turns red into green and nobody sees it, the flaky tests never get fixed, and real intermittent bugs are hidden too.

NUnit’s [Retry] attribute does not help much here anyway. In NUnit 3 it only retries on assertion failures. A WebDriverTimeoutException is an unexpected exception, so the test is not retried.

What we do instead: after the first run, a small PowerShell step reads the TRX, collects the failed tests, and runs only those again as a second test run with its own title.

- pwsh: |
    $trx = Get-ChildItem "$(Agent.TempDirectory)/run1" -Filter *.trx | Select-Object -First 1
    if (-not $trx) { Write-Host "No TRX found"; exit 0 }
    [xml]$xml = Get-Content $trx.FullName
    $failedIds = $xml.TestRun.Results.UnitTestResult |
      Where-Object { $_.outcome -eq 'Failed' } | ForEach-Object { $_.testId }
    $names = $xml.TestRun.TestDefinitions.UnitTest |
      Where-Object { $failedIds -contains $_.id } |
      ForEach-Object { "FullyQualifiedName=$($_.TestMethod.className).$($_.TestMethod.name)" }
    $count = @($names).Count
    Write-Host "Failed in first run: $count"
    if ($count -eq 0) { exit 0 }
    if ($count -gt 10) {
      Write-Host "##vso[task.logissue type=warning]Too many failures ($count), not rerunning. Check the environment."
      exit 0
    }
    $filter = $names -join '|'
    Write-Host "##vso[task.setvariable variable=RerunFilter]$filter"
  displayName: 'Collect failed tests'
  condition: succeededOrFailed()

- task: DotNetCoreCLI@2
  displayName: 'Rerun failed UI tests'
  condition: and(succeededOrFailed(), ne(variables['RerunFilter'], ''))
  inputs:
    command: 'test'
    projects: '$(testProject)'
    arguments: '-c $(buildConfiguration) --no-build --logger trx --results-directory $(Agent.TempDirectory)/run2 --filter "$(RerunFilter)"'
    publishTestResults: false
  env:
    PORTAL_BASE_URL: $(PortalBaseUrl)
    PORTAL_TEST_PASSWORD: $(PortalTestPassword)

- task: PublishTestResults@2
  displayName: 'Publish rerun results'
  condition: and(succeededOrFailed(), ne(variables['RerunFilter'], ''))
  inputs:
    testResultsFormat: 'VSTest'
    testResultsFiles: '*.trx'
    searchFolder: '$(Agent.TempDirectory)/run2'
    testRunTitle: 'UI regression - rerun of failed tests'

What this gives:

  • The first run is published as it was. Its failures stay in the Tests tab and in the history.
  • The rerun is a separate test run with a clear title. Anyone can see which tests needed a second try.
  • If a test fails in the rerun too, the rerun step fails, and the pipeline fails.
  • If everything passes in the rerun, the pipeline is still orange because of the first run. Green means it passed the first time.
  • If many tests fail, we do not rerun. Many failures at once usually mean the environment is down, and a rerun just wastes time.

The filter works for our tests because they have no parameters. For [TestCase] tests the names in the TRX include the arguments, and you need a different filter. I have not tried that yet. A very long filter can also hit command line limits, which is one more reason for the cap.

Once a week I look at which tests appear in the rerun runs. A test that shows up again and again goes on the board as a bug in the test or in the portal.

Nightly or per pull request

We run the full suite nightly on a schedule, against the test environment after the daily deployment. Note that the cron time is in UTC, and always: true runs it even when there were no code changes in the test repository. That is what we want, because the portal changes in a different repository.

For pull requests on the test code itself, we run a small smoke set (filtered by an NUnit [Category("Smoke")]) with --filter "TestCategory=Smoke". With Azure Repos, the pr: section in YAML is ignored. PR builds are set up as a build validation policy on the branch instead.

Running the full UI suite on every PR was too slow, and it would also fight with the nightly run over the same test data.

What the built-in reporting does not give us

The Tests tab is good for one run: what failed, the error, the screenshot. The test analytics pages also show pass rates over time. Where it was not enough for us is across many runs. I wanted to group failures by error type (all “overlay did not disappear” timeouts together, all login failures together), see how one error is distributed over the nightly runs of the last weeks, and search the console logs of many runs for one message. The wait logs from the helper class are full of useful lines, but they are spread over many test results.

So I started to export the TRX files and logs and analyse them outside Azure DevOps.