At work our Selenium regression suite for the portal project runs every night in Azure DevOps. Each morning someone has to look at the failures. For a long time that meant opening the test tab, clicking each failed test, reading the message and the stack trace, and deciding whether this was a known problem or something new. Most mornings the same five or six errors came back with small differences: another GUID, another timestamp, another element id. We spent time reading things we had already read the day before.
So I wrote a small tool in Python. It takes the results of each run, reduces every error message to a “fingerprint”, stores everything in PostgreSQL, and uses Pandas to count failures by fingerprint and by test over the last N runs. Versions I use: Python 3.10, pandas 1.5, SQLAlchemy 1.4, psycopg2 2.9, Plotly 5, PostgreSQL 14.
Getting the results out of Azure DevOps
There are two ways, and I used both.
The REST API. The Test Runs and Test Results endpoints give you everything the web UI shows. You need a personal access token with the Test Management read scope.
import os
import requests
BASE = "https://dev.azure.com/example-org/example-project"
AUTH = ("", os.environ["AZDO_PAT"]) # empty user name, PAT as password
def runs_for_build(build_id):
r = requests.get(
f"{BASE}/_apis/test/runs",
params={"buildUri": f"vstfs:///Build/Build/{build_id}", "api-version": "6.0"},
auth=AUTH,
timeout=30,
)
r.raise_for_status()
return r.json()["value"]
def results_for_run(run_id):
out, skip = [], 0
while True:
r = requests.get(
f"{BASE}/_apis/test/Runs/{run_id}/results",
params={"$top": 1000, "$skip": skip, "api-version": "6.0"},
auth=AUTH,
timeout=60,
)
r.raise_for_status()
page = r.json()["value"]
out.extend(page)
if len(page) < 1000:
return out
skip += 1000
Each result has automatedTestName, outcome, errorMessage and stackTrace. The page size is at most 1000 when you do not ask for extra details. One limit I hit later: the API stores the stack trace with a maximum size of 1000 characters, and it does not have the console output of the test.
The TRX files. In the pipeline from August, dotnet test --logger trx writes one TRX file for the first run into run1 and one for the rerun of failed tests into run2. I added one step that publishes both folders as a pipeline artifact, even when tests fail:
- task: PublishPipelineArtifact@1
condition: always()
inputs:
targetPath: '$(Agent.TempDirectory)'
artifact: 'trx'
Publishing the whole temp folder is lazy. If other tasks put large files there, point it at a folder that only holds run1 and run2.
Then on my machine (or in a small scheduled job) I download it with the Azure DevOps extension for the Azure CLI:
az pipelines runs artifact download --run-id 1234 --artifact-name trx --path ./trx/1234
I started with the REST API because it needs no pipeline change. I moved to TRX because it has the full stack trace and the test output, which I wanted later for log search. If you only need the fingerprints, the API is enough.
Parsing TRX in Python
TRX is plain XML with one namespace. The test definitions and the results are in separate lists, linked by testId. The standard library is enough.
import xml.etree.ElementTree as ET
NS = {"t": "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"}
def parse_trx(path):
root = ET.parse(path).getroot()
started = root.find("t:Times", NS).get("start")
names = {}
for ut in root.iterfind("t:TestDefinitions/t:UnitTest", NS):
m = ut.find("t:TestMethod", NS)
cls = m.get("className").split(",")[0]
names[ut.get("id")] = f"{cls}.{m.get('name')}"
results = []
for r in root.iterfind("t:Results/t:UnitTestResult", NS):
results.append({
"test_name": names.get(r.get("testId"), r.get("testName")),
"outcome": r.get("outcome"),
"message": r.findtext("t:Output/t:ErrorInfo/t:Message", "", NS),
"stack_trace": r.findtext("t:Output/t:ErrorInfo/t:StackTrace", "", NS),
"stdout": r.findtext("t:Output/t:StdOut", "", NS),
})
return root.get("id"), started, results
The split(",") is there because some adapters write an assembly-qualified class name. Data-driven tests put their rows in InnerResults; we had few of those, so I ignored them.
Turning a message into a fingerprint
This is the part that matters. Two failures belong to the same group when they have the same exception type, the same message after removing the noise, and the same first stack frame in our own code.
With NUnit, a typical Selenium failure message in the TRX looks like this:
OpenQA.Selenium.WebDriverTimeoutException : Timed out after 30 seconds
An assertion failure has no exception type in the message, only the Expected: and But was: lines.
The noise is everything that changes between runs: GUIDs (the portal uses them everywhere), timestamps, numbers, URLs with query strings, session ids, and element ids that the page generates.
import hashlib
import re
EXC_RE = re.compile(r"\b((?:[A-Za-z_]\w*\.)*[A-Za-z_]\w*(?:Exception|Error))\b")
FRAME_RE = re.compile(r"^\s*at (.+?)(?: in .+)?$", re.M)
OWN_CODE = "UiTests."
NOISE = [
(re.compile(r"https?://\S+"), "<url>"),
(re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.I), "<guid>"),
(re.compile(r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?"), "<ts>"),
(re.compile(r"\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2}(?: [AP]M)?"), "<ts>"),
(re.compile(r"\b[0-9a-f]{16,}\b", re.I), "<hex>"),
(re.compile(r"(#|id=[\"'])([\w-]*\d[\w-]*)"), r"\1<id>"),
(re.compile(r"\d+"), "<n>"),
]
def normalise(text):
for rx, repl in NOISE:
text = rx.sub(repl, text)
return " ".join(text.split())[:300]
def first_frame(stack):
frames = [f.strip() for f in FRAME_RE.findall(stack or "")]
for f in frames:
if f.startswith(OWN_CODE):
return f
return frames[0] if frames else ""
def fingerprint(message, stack):
message = message or ""
m = EXC_RE.search(message)
if m:
exc, rest = m.group(1), message[m.end():]
else:
exc, rest = ("Assertion" if "Expected:" in message else "Other"), message
rest = rest.lstrip(": ").strip()
first_line = normalise(rest.splitlines()[0]) if rest else ""
frame = first_frame(stack)
key = f"{exc}|{first_line}|{frame}"
return hashlib.sha1(key.encode()).hexdigest()[:12], exc, first_line, frame
Some notes from getting this right:
- The order of the rules matters. GUIDs and timestamps must go before the generic number rule, or you get
<n>-<n>-<n>and a messy pattern. - I only replace element ids that contain a digit. On our pages those were the generated ones. Stable ids stay, so the fingerprint still tells you which element was missing.
- I drop the
in C:\...\File.cs:line 57part of the frame. Line numbers change every time someone edits the file, and then the same error gets a new fingerprint. - I skip Selenium’s own frames and take the first frame in our namespace.
OpenQA.Selenium.Support.UI.DefaultWaitis the top frame for every timeout, so it says nothing. - Only the first line of the message is used. ChromeDriver adds session info and the browser version on later lines.
My first version hashed the whole message. It produced almost one fingerprint per failure, which was useless. The second version removed only GUIDs, and it was better but still split timeouts by the number of seconds. Removing all numbers felt too aggressive at first, but in practice it grouped things the way a person would.
Storing it in PostgreSQL
Three tables are enough.
CREATE TABLE run (
id text PRIMARY KEY, -- TRX run id or Azure DevOps run id
build_id bigint NOT NULL,
started_at timestamptz NOT NULL
);
CREATE TABLE fingerprint (
id text PRIMARY KEY, -- 12 hex chars
exc_type text NOT NULL,
pattern text NOT NULL,
frame text NOT NULL,
first_seen timestamptz NOT NULL
);
CREATE TABLE result (
run_id text REFERENCES run (id),
test_name text NOT NULL,
outcome text NOT NULL,
message text,
stack_trace text,
fingerprint text REFERENCES fingerprint (id),
PRIMARY KEY (run_id, test_name)
);
The loader:
from psycopg2.extras import execute_values
def store(conn, run_id, build_id, started, results):
with conn, conn.cursor() as cur:
cur.execute(
"INSERT INTO run (id, build_id, started_at) VALUES (%s, %s, %s) "
"ON CONFLICT (id) DO NOTHING",
(run_id, build_id, started),
)
rows = []
for r in results:
fp = None
if r["outcome"] == "Failed":
fp, exc, pattern, frame = fingerprint(r["message"], r["stack_trace"])
cur.execute(
"INSERT INTO fingerprint (id, exc_type, pattern, frame, first_seen) "
"VALUES (%s, %s, %s, %s, %s) "
"ON CONFLICT (id) DO UPDATE "
"SET first_seen = LEAST(fingerprint.first_seen, EXCLUDED.first_seen)",
(fp, exc, pattern, frame, started),
)
rows.append((run_id, r["test_name"], r["outcome"],
r["message"], r["stack_trace"], fp))
execute_values(
cur,
"INSERT INTO result (run_id, test_name, outcome, message, stack_trace, fingerprint) "
"VALUES %s ON CONFLICT DO NOTHING",
rows,
)
The LEAST in the upsert is there because I backfilled old runs after new ones. Without it, first_seen was the date I happened to load the data, not the date the error first appeared.
Pandas: counting by fingerprint and by test
I read the last N runs into one DataFrame and do the rest in Pandas.
import pandas as pd
from sqlalchemy import create_engine, text
engine = create_engine("postgresql+psycopg2://tests:secret@localhost/testresults")
SQL = text("""
SELECT r.id AS run_id, r.build_id, r.started_at,
res.test_name, res.outcome, res.fingerprint,
f.exc_type, f.pattern, f.first_seen
FROM run r
JOIN result res ON res.run_id = r.id
LEFT JOIN fingerprint f ON f.id = res.fingerprint
WHERE r.id IN (SELECT id FROM run ORDER BY started_at DESC LIMIT :n)
""")
df = pd.read_sql(SQL, engine, params={"n": 20})
failed = df[df.outcome == "Failed"]
by_fp = (
failed.groupby(["fingerprint", "exc_type", "pattern"])
.agg(failures=("test_name", "size"),
tests=("test_name", "nunique"),
runs=("run_id", "nunique"),
last_seen=("started_at", "max"))
.sort_values("failures", ascending=False)
)
by_test = (
df.assign(failed=df.outcome.eq("Failed"))
.groupby("test_name")["failed"]
.agg(["sum", "count", "mean"])
.sort_values("sum", ascending=False)
)
by_fp is the main table for triage. A fingerprint that hits many tests in one run usually means an environment problem (login page down, a slow deployment). A fingerprint that hits one test in many runs is usually a real bug or a bad test.
New and old errors
A fingerprint is new when it first appeared in the latest run:
latest = df.started_at.max()
new_fps = by_fp.reset_index().merge(
failed[["fingerprint", "first_seen"]].drop_duplicates(), on="fingerprint"
)
new_fps = new_fps[new_fps.first_seen >= latest]
This is the first list I read every morning. Old fingerprints already have a work item or a note. New ones need a person.
Flaky tests
The pipeline reruns failed tests in the same build as a second test run, so one build can have two runs. A test that both passed and failed on the same build had no code change in between. That is my working definition of flaky.
outcomes = df.groupby(["build_id", "test_name"])["outcome"].agg(set)
flaky = outcomes[outcomes.apply(lambda s: {"Passed", "Failed"} <= s)]
flaky_tests = flaky.reset_index().test_name.value_counts()
flaky_tests counts on how many builds each test flipped. Many of the tests at the top of this list were ones with fixed sleeps, which I replaced with dynamic waits.
A chart per run
Tables are fine for triage, but a chart shows trends. A stacked bar of fingerprints per run makes it easy to see when a new error starts and whether it goes away after a fix.
import plotly.express as px
counts = (
failed.assign(run=failed.started_at.dt.strftime("%m-%d %H:%M"))
.groupby(["run", "fingerprint"])
.size()
.reset_index(name="failures")
)
fig = px.bar(counts, x="run", y="failures", color="fingerprint",
title="Failures per run by fingerprint")
fig.write_html("fingerprints.html")
I also tried a heatmap of test by run (px.imshow on a pivot with 1 for failed, 0 for passed). It is good for spotting flaky tests, because they look like a broken line, but with more than a few dozen tests it gets hard to read. I keep it as a second page.
With many fingerprints the colours repeat. I only colour the top ten and put the rest in one “other” group.
What changed in daily triage
The morning check now starts with two short lists: new fingerprints, and tests that flipped on the same build. Old failures with a known cause are one line each with a count, so nobody opens them again. When a developer asks “since when does this fail?”, first_seen answers it. When I talked with the developers and the business analysts about a failure, I could show that one error hit many different tests in the same run, which usually moved the talk quickly from “the test is broken” to “the page is slow after deployment”.
The method has a weak spot: two different problems can share a fingerprint when the message is generic, like Timed out after <n> seconds from the same wait helper. The first frame in our own code helps, but a shared helper method still merges them. Adding the page object name to the fingerprint would split them. Searching inside the long logs is a different problem, and fingerprints do not help with it.