blob: f1c848442795ca9d0ecc451c49d5598015ade813 [file]
# Copyright 2026 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import csv
import hashlib
import io
import json
import os
import pathlib
import statistics
import subprocess
import tempfile
import unittest
import unittest.mock
from typing import Any
import local_workflow
import perfcompare
InstanceDigestPair = tuple[str, str]
# Test case helper class for creating temporary directories that will
# be cleaned up when the test finishes.
class TempDirTestCase(unittest.TestCase):
def MakeTempDir(self):
return self.enterContext(
tempfile.TemporaryDirectory(
prefix="tmp_unittest_%s_" % self.__class__.__name__
)
)
def WriteJsonFile(filename: str, json_data: Any):
with open(filename, "w") as fh:
json.dump(json_data, fh)
def _cas_digest(content: str) -> str:
content_bytes = content.encode("utf-8")
return f"{hashlib.sha256(content_bytes).hexdigest()}/{len(content_bytes)}"
def _make_perf_dataset(values: list[float]) -> dict[str, str]:
return {
f"by_boot/boot{idx:06d}/test.fuchsiaperf.json": json.dumps(
[
{
"test_suite": "fuchsia.test",
"label": "metric1",
"unit": "ms",
"values": [value],
}
]
)
for idx, value in enumerate(values)
}
class FakeInfra:
"""In-memory fake for LUCI Infra tools (bb and cas)."""
def __init__(self) -> None:
self.builds: dict[str, dict[str, Any]] = {}
self.cas_dirs: dict[
InstanceDigestPair, dict[str, InstanceDigestPair]
] = {}
self.cas_files: dict[InstanceDigestPair, str] = {}
self._next_build_id = 5001
self.next_try_build_perf_dataset: dict[str, str] | None = None
def patch_subprocess_run(self) -> Any:
return unittest.mock.patch.object(
subprocess, "run", autospec=True, side_effect=self._subprocess_run
)
def add_build(
self,
build_id: str,
perf_dataset: dict[str, str] | None = None,
properties: dict[str, Any] | None = None,
dataset_key: str = "perf_dataset_digest",
status: str = "SUCCESS",
steps: list[Any] | None = None,
) -> None:
if steps is None:
steps = []
if properties is None:
instance = "chromium_swarm"
digest = f"digest_{build_id}/82"
properties = {"cas_instance": instance, dataset_key: digest}
if perf_dataset is not None:
instance = properties["cas_instance"]
digest = properties[dataset_key]
filenames_to_digests: dict[str, InstanceDigestPair] = {}
for rel_path, content in perf_dataset.items():
file_key = (instance, _cas_digest(content))
self.cas_files[file_key] = content
filenames_to_digests[rel_path] = file_key
self.cas_dirs[(instance, digest)] = filenames_to_digests
self.builds[build_id] = {
"id": build_id,
"status": status,
"output": {"properties": properties},
"steps": steps,
}
def add_cas_dir(
self,
instance: str,
digest: str,
filenames_to_digests: dict[str, str],
) -> None:
self.cas_dirs[(instance, digest)] = {
filename: (instance, file_digest)
for filename, file_digest in filenames_to_digests.items()
}
for file_digest in filenames_to_digests.values():
self.cas_files[
(instance, file_digest)
] = f"{instance}:{file_digest}"
def _subprocess_run(
self, cmd: list[str], **kwargs: Any
) -> subprocess.CompletedProcess[str]:
tool = os.path.basename(cmd[0])
if tool.startswith("bb"):
result = self._handle_bb(cmd[1:])
elif tool.startswith("cas"):
result = self._handle_cas(cmd[1:])
else:
raise AssertionError(f"Unexpected command: {cmd}")
if kwargs.get("check") and result.returncode != 0:
raise subprocess.CalledProcessError(
result.returncode,
cmd,
output=result.stdout,
stderr=result.stderr,
)
return result
def _handle_bb(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
if not argv:
raise AssertionError("Missing bb subcommand")
subcommand = argv[0]
if subcommand == "auth-info":
return subprocess.CompletedProcess(
argv, 0, stdout="auth ok", stderr=""
)
if subcommand == "add":
return self._handle_bb_add(argv[1:])
if subcommand == "collect":
return self._handle_bb_collect(argv[1:])
if subcommand == "get":
return self._handle_bb_get(argv[1:])
raise AssertionError(f"Unexpected bb subcommand: {subcommand}")
def _handle_bb_add(
self, argv: list[str]
) -> subprocess.CompletedProcess[str]:
parser = argparse.ArgumentParser(
exit_on_error=False, allow_abbrev=False
)
parser.add_argument("-json", action="store_true", required=True)
parser.add_argument("-cl", required=True)
parser.add_argument("-commit", required=True)
parser.add_argument("-ref", required=True)
parser.add_argument("-t", action="append", default=[])
parser.add_argument("-p", action="append", default=[])
parser.add_argument("builder")
args = parser.parse_args(argv)
if len(args.builder.split("/")) != 3:
raise AssertionError(
f"Expected project/bucket/builder, got: {args.builder}"
)
properties: dict[str, Any] = {}
for prop in args.p:
if "=" not in prop:
raise AssertionError(f"Expected key=value for -p, got: {prop}")
key, raw_value = prop.split("=", 1)
properties[key] = json.loads(raw_value)
build_id = str(self._next_build_id)
self._next_build_id += 1
perf_dataset = self.next_try_build_perf_dataset
if perf_dataset is None:
raise AssertionError("next_try_build_perf_dataset must be set")
self.add_build(build_id, status="SCHEDULED", perf_dataset=perf_dataset)
self.builds[build_id]["builder"] = args.builder
self.builds[build_id]["cl"] = args.cl
self.builds[build_id]["commit"] = args.commit
self.builds[build_id]["ref"] = args.ref
self.builds[build_id]["tags"] = args.t
self.builds[build_id]["input_properties"] = properties
return subprocess.CompletedProcess(
argv,
0,
stdout=json.dumps({"id": build_id, "status": "SCHEDULED"}),
stderr="",
)
def _handle_bb_collect(
self, argv: list[str]
) -> subprocess.CompletedProcess[str]:
parser = argparse.ArgumentParser(
exit_on_error=False, allow_abbrev=False
)
parser.add_argument("-json", action="store_true", required=True)
parser.add_argument("-interval", required=True)
parser.add_argument("build_id")
args = parser.parse_args(argv)
if args.build_id.lower().startswith("b"):
raise AssertionError(
f"bb CLI rejects 'b' prefix in build ID: {args.build_id}"
)
if args.build_id not in self.builds:
return subprocess.CompletedProcess(
argv, 1, stdout="", stderr=f"Build {args.build_id} not found"
)
build = self.builds[args.build_id]
if build["status"] == "SCHEDULED":
build["status"] = "SUCCESS"
return subprocess.CompletedProcess(
argv,
0,
stdout=json.dumps({"id": build["id"], "status": build["status"]}),
stderr="",
)
def _handle_bb_get(
self, argv: list[str]
) -> subprocess.CompletedProcess[str]:
parser = argparse.ArgumentParser(
exit_on_error=False, allow_abbrev=False
)
parser.add_argument("-json", action="store_true", required=True)
parser.add_argument("-fields", choices=("output.properties,steps",))
parser.add_argument("build_id")
args = parser.parse_args(argv)
if args.build_id.lower().startswith("b"):
raise AssertionError(
f"bb CLI rejects 'b' prefix in build ID: {args.build_id}"
)
if args.build_id not in self.builds:
return subprocess.CompletedProcess(
argv, 1, stdout="", stderr=f"Build {args.build_id} not found"
)
build = self.builds[args.build_id]
if args.fields == "output.properties,steps":
output = {"output": build["output"], "steps": build["steps"]}
else:
output = {"id": build["id"], "status": build["status"]}
return subprocess.CompletedProcess(
argv, 0, stdout=json.dumps(output), stderr=""
)
def _handle_cas(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
if not argv:
raise AssertionError("Missing cas subcommand")
subcommand = argv[0]
if subcommand == "download":
return self._handle_cas_download(argv[1:])
if subcommand == "tree":
return self._handle_cas_tree(argv[1:])
raise AssertionError(f"Unexpected cas subcommand: {subcommand}")
def _handle_cas_tree(
self, argv: list[str]
) -> subprocess.CompletedProcess[str]:
parser = argparse.ArgumentParser(
exit_on_error=False, allow_abbrev=False
)
parser.add_argument("-cas-instance", required=True)
parser.add_argument("-digest", required=True)
args = parser.parse_args(argv)
key = (args.cas_instance, args.digest)
if key not in self.cas_dirs:
return subprocess.CompletedProcess(
argv,
1,
stdout="",
stderr=f"CAS dir {key} not found in FakeInfra",
)
tree = self.cas_dirs[key]
files = {
path: {"digest": file_digest, "size": 1}
for path, (_, file_digest) in tree.items()
}
return subprocess.CompletedProcess(
argv,
0,
stdout=json.dumps({"digest": args.digest, "files": files}),
stderr="",
)
def _handle_cas_download(
self, argv: list[str]
) -> subprocess.CompletedProcess[str]:
parser = argparse.ArgumentParser(
exit_on_error=False, allow_abbrev=False
)
parser.add_argument("-cas-instance", required=True)
parser.add_argument("-digest", required=True)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-dir")
group.add_argument("-file")
args = parser.parse_args(argv)
key = (args.cas_instance, args.digest)
if args.dir is not None:
assert args.file is None
if key not in self.cas_dirs:
return subprocess.CompletedProcess(
argv,
1,
stdout="",
stderr=f"CAS dir {key} not found in FakeInfra",
)
os.makedirs(args.dir, exist_ok=True)
for rel_path, file_key in self.cas_dirs[key].items():
dest_path = os.path.join(args.dir, rel_path)
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
with open(dest_path, "w") as f:
f.write(self.cas_files[file_key])
return subprocess.CompletedProcess(
argv, 0, stdout="download ok", stderr=""
)
else:
assert args.file is not None
if key not in self.cas_files:
return subprocess.CompletedProcess(
argv,
1,
stdout="",
stderr=f"CAS file {key} not found in FakeInfra",
)
with open(args.file, "w") as f:
f.write(self.cas_files[key])
return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
class LocalWorkflowTest(TempDirTestCase):
def setUp(self):
super().setUp()
self.state_file = os.path.join(self.MakeTempDir(), "state.json")
state_data = {
"2026-04-09": {
"rev_info": {
"commit_id": "commit1",
"public_commit_id": "public_commit1",
},
"launched": {
"builder1": {"build_id": "1001"},
},
},
"2026-04-10": {
"rev_info": {
"commit_id": "commit2",
"public_commit_id": "public_commit2",
},
"launched": {
"builder1": {"build_id": "1002"},
"builder2": {"build_id": "1003"},
},
},
}
with open(self.state_file, "w") as f:
json.dump(state_data, f)
# Patch the code for finding the "bb" and "cas" tools so that the
# test does not depend on the FUCHSIA_DIR env var being set and the
# tools being present.
self.enterContext(
unittest.mock.patch(
"local_workflow._find_bb_tool",
lambda: pathlib.Path("bb_for_testing"),
)
)
self.enterContext(
unittest.mock.patch(
"local_workflow._find_cas_tool",
lambda: pathlib.Path("cas_for_testing"),
)
)
@staticmethod
def _task_step(instance: str, digest: str) -> dict[str, str]:
"""Returns a build step that links to a task's CAS outputs."""
return {
"summaryMarkdown": (
"* [task outputs](https://cas-viewer.appspot.com/"
f"{instance}/blobs/{digest}/tree)"
)
}
@staticmethod
def _read_dir_tree(root_dir: str) -> dict[str, str]:
"""Returns {relative_path: file_contents} for all files under root_dir."""
files = {}
for dirpath, _, filenames in os.walk(root_dir):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
rel_path = os.path.relpath(full_path, root_dir)
with open(full_path) as f:
files[rel_path] = f.read()
return files
def test_download_metrics(self):
infra = FakeInfra()
infra.add_build(
"1000",
perf_dataset={"metrics.json": '{"metric": 1.0}'},
)
self.enterContext(infra.patch_subprocess_run())
# Use unittest.TestCase.subTest rather than third_party/parameterized
# so these tests remain runnable directly via python3 without
# requiring non-stdlib packages to be installed or packaged via GN.
for build_id in ("1000", "b1000"):
with self.subTest(build_id=build_id):
out_dir = self.MakeTempDir()
stdout = io.StringIO()
perfcompare.Main(
["download_metrics", build_id, out_dir], stdout
)
self.assertEqual(
self._read_dir_tree(out_dir),
{"metrics.json": '{"metric": 1.0}'},
)
output = stdout.getvalue()
self.assertIn("Fetching build info for 1000 using bb", output)
self.assertIn("Downloading from cas to", output)
def test_normalize_build_id(self):
self.assertEqual(local_workflow._normalize_build_id("1000"), "1000")
self.assertEqual(local_workflow._normalize_build_id("b1000"), "1000")
self.assertEqual(local_workflow._normalize_build_id("B1000"), "1000")
self.assertEqual(local_workflow._normalize_build_id(" b1000 "), "1000")
def test_download_metrics_perfcompare_digest(self):
infra = FakeInfra()
infra.add_build(
"1000",
perf_dataset={"metrics.json": '{"metric": 1.0}'},
dataset_key="perfcompare_dataset_digest",
)
self.enterContext(infra.patch_subprocess_run())
out_dir = self.MakeTempDir()
stdout = io.StringIO()
perfcompare.Main(["download_metrics", "1000", out_dir], stdout)
self.assertEqual(
self._read_dir_tree(out_dir), {"metrics.json": '{"metric": 1.0}'}
)
output = stdout.getvalue()
self.assertIn("Fetching build info for 1000 using bb", output)
self.assertIn("Downloading from cas to", output)
def test_download_metrics_missing_properties(self):
# A dataset digest without a cas_instance should fail rather than
# guess an instance.
infra = FakeInfra()
infra.add_build(
"1000",
properties={"perf_dataset_digest": "123abc/82"},
)
self.enterContext(infra.patch_subprocess_run())
with self.assertRaises(RuntimeError) as cm:
perfcompare.Main(
["download_metrics", "1000", self.MakeTempDir()], io.StringIO()
)
self.assertIn("Download failed for build 1000", str(cm.exception))
self.assertIsInstance(cm.exception.__cause__, KeyError)
self.assertIn("cas_instance", str(cm.exception.__cause__))
def test_download_metrics_bb_get_fails(self):
infra = FakeInfra()
self.enterContext(infra.patch_subprocess_run())
with self.assertRaises(RuntimeError) as cm:
perfcompare.Main(
["download_metrics", "1000", self.MakeTempDir()], io.StringIO()
)
self.assertIn("Download failed for build 1000", str(cm.exception))
cause = cm.exception.__cause__
self.assertIsInstance(cause, subprocess.CalledProcessError)
self.assertIn("get", cause.cmd)
self.assertIn("Build 1000 not found", cause.stderr)
def test_download_metrics_cas_download_fails(self):
infra = FakeInfra()
infra.add_build(
"1000",
properties={
"cas_instance": "chromium_swarm",
"perf_dataset_digest": "invalid_cas_digest_id",
},
)
self.enterContext(infra.patch_subprocess_run())
with self.assertRaises(RuntimeError) as cm:
perfcompare.Main(
["download_metrics", "1000", self.MakeTempDir()],
io.StringIO(),
)
self.assertIn("Download failed for build 1000", str(cm.exception))
cause = cm.exception.__cause__
self.assertIsInstance(cause, subprocess.CalledProcessError)
self.assertIn("download", cause.cmd)
self.assertIn(
"CAS dir ('chromium_swarm', 'invalid_cas_digest_id') not found",
cause.stderr,
)
def test_download_metrics_fallback_success(self):
# Set up a build with no perf_dataset_digest, a failed test in
# output.properties, and three test task CAS trees in the build steps.
infra = FakeInfra()
infra.add_build(
"1000",
properties={
"failed_test_names": [
"fuchsia-pkg://fuchsia.com/failing#meta/failing.cm"
]
},
steps=[
{"name": "no summary"},
self._task_step("projects/p1/instances/i1", "aaaa/1"),
self._task_step("projects/p1/instances/i1", "bbbb/2"),
# A repeated link to the first task must not produce a
# second boot directory.
self._task_step("projects/p1/instances/i1", "aaaa/1"),
self._task_step("projects/p2/instances/i2", "cccc/3"),
],
)
infra.add_cas_dir(
"projects/p1/instances/i1",
"aaaa/1",
{
"out/test1/0/a2.fuchsiaperf.json": "a2/10",
"out/test1/0/a1.fuchsiaperf.json": "a1/10",
"out/test1/0/trace.fxt": "a3/1000000000",
"out/summary.json": "a4/10",
# Results from the failed test are excluded. testrunner
# removes colons from the test name and then URL-escapes it
# to name the directory.
"out/fuchsia-pkg%2F%2Ffuchsia.com%2Ffailing%23meta%2Ffailing.cm/0/a5.fuchsiaperf.json": "a5/10",
},
)
# A task without perf results is skipped so that boot directories
# are numbered contiguously.
infra.add_cas_dir(
"projects/p1/instances/i1",
"bbbb/2",
{"out/test2/0/log.txt": "b1/10"},
)
infra.add_cas_dir(
"projects/p2/instances/i2",
"cccc/3",
{"out/test3/0/c1.fuchsiaperf.json": "c1/10"},
)
self.enterContext(infra.patch_subprocess_run())
out_dir = self.MakeTempDir()
stdout = io.StringIO()
perfcompare.Main(["download_metrics", "1000", out_dir], stdout)
# Check that only *.fuchsiaperf.json files from passing tests were
# downloaded, with the "out/" prefix stripped and grouped into
# bootNNNNNN directories.
self.assertEqual(
self._read_dir_tree(out_dir),
{
os.path.join(
"by_boot", "boot000000", "test1", "0", "a1.fuchsiaperf.json"
): "projects/p1/instances/i1:a1/10",
os.path.join(
"by_boot", "boot000000", "test1", "0", "a2.fuchsiaperf.json"
): "projects/p1/instances/i1:a2/10",
os.path.join(
"by_boot", "boot000001", "test3", "0", "c1.fuchsiaperf.json"
): "projects/p2/instances/i2:c1/10",
},
)
output = stdout.getvalue()
self.assertIn(
"Excluding results from failed tests:\n"
" fuchsia-pkg://fuchsia.com/failing#meta/failing.cm\n",
output,
)
def test_download_metrics_fallback_no_task_outputs(self):
infra = FakeInfra()
infra.add_build(
"1000",
properties={},
steps=[{"summaryMarkdown": "No CAS viewer URLs here"}],
)
self.enterContext(infra.patch_subprocess_run())
with self.assertRaises(RuntimeError) as cm:
perfcompare.Main(
["download_metrics", "1000", self.MakeTempDir()], io.StringIO()
)
self.assertIn("Download failed for build 1000", str(cm.exception))
self.assertIn(
"No task outputs found in build steps for 1000",
str(cm.exception.__cause__),
)
def test_download_metrics_fallback_no_perf_results(self):
infra = FakeInfra()
infra.add_build(
"1000",
properties={},
steps=[self._task_step("projects/p/instances/i", "aaaa/1")],
)
infra.add_cas_dir(
"projects/p/instances/i",
"aaaa/1",
{"out/log.txt": "a1/10"},
)
self.enterContext(infra.patch_subprocess_run())
out_dir = self.MakeTempDir()
with self.assertRaises(RuntimeError) as cm:
perfcompare.Main(
["download_metrics", "1000", out_dir], io.StringIO()
)
self.assertIn(
"No .fuchsiaperf.json files found in task outputs for build 1000",
str(cm.exception.__cause__),
)
self.assertEqual(os.listdir(out_dir), [])
def test_download_metrics_fallback_by_boot_already_exists(self):
infra = FakeInfra()
infra.add_build(
"1000",
properties={},
steps=[self._task_step("projects/p/instances/i", "aaaa/1")],
)
self.enterContext(infra.patch_subprocess_run())
out_dir = self.MakeTempDir()
old_file = os.path.join(out_dir, "by_boot", "boot000000", "old.txt")
os.makedirs(os.path.dirname(old_file))
with open(old_file, "w") as f:
f.write("old data")
with self.assertRaises(RuntimeError) as cm:
perfcompare.Main(
["download_metrics", "1000", out_dir], io.StringIO()
)
self.assertIn("already exists", str(cm.exception.__cause__))
# Check that the existing directory was left untouched.
self.assertEqual(
self._read_dir_tree(out_dir),
{os.path.join("by_boot", "boot000000", "old.txt"): "old data"},
)
def test_download_metrics_fallback_cas_download_fails(self):
infra = FakeInfra()
infra.add_build(
"1000",
properties={},
steps=[self._task_step("projects/p/instances/i", "aaaa/1")],
)
infra.add_cas_dir(
"projects/p/instances/i",
"aaaa/1",
{
"out/a1.fuchsiaperf.json": "a1/10",
"out/a2.fuchsiaperf.json": "a2/10",
},
)
del infra.cas_files[("projects/p/instances/i", "a2/10")]
self.enterContext(infra.patch_subprocess_run())
out_dir = self.MakeTempDir()
with self.assertRaises(RuntimeError) as cm:
perfcompare.Main(
["download_metrics", "1000", out_dir], io.StringIO()
)
self.assertIn("Download failed for build 1000", str(cm.exception))
# Check that neither a partial by_boot directory nor the staging
# directory is left behind.
self.assertEqual(os.listdir(out_dir), [])
def test_extract_task_outputs_from_steps(self):
steps: list[local_workflow._BuildStep] = [
{"summaryMarkdown": "No url here"},
{}, # No summaryMarkdown
{
"summaryMarkdown": (
"* [task outputs](https://cas-viewer.appspot.com/projects/p2/instances/i2/blobs/5678/20/tree)\n"
"* [task outputs](https://cas-viewer.api.luci.app/projects/p1/instances/i1/blobs/ABCD12/10/tree)"
)
},
{
# The same task, linked from a different host.
"summaryMarkdown": (
"* [task outputs](https://cas-viewer.api.luci.app/projects/p1/instances/i1/blobs/ABCD12/10/tree)"
)
},
{
# The same digest in a different instance is kept.
"summaryMarkdown": (
"* [task outputs](https://cas-viewer.appspot.com/projects/p2/instances/i2/blobs/ABCD12/10/tree)"
)
},
{
# Links to other CAS uploads, such as the aggregated perf
# dataset, are ignored.
"summaryMarkdown": (
"* [CAS UI](https://cas-viewer.appspot.com/projects/p3/instances/i3/blobs/EEEE/82/tree)\n"
"* [task cas outputs: shard](https://cas-viewer.appspot.com/projects/p3/instances/i3/blobs/FFFF/10/tree)"
)
},
]
self.assertEqual(
local_workflow._extract_task_outputs_from_steps(steps),
[
("projects/p1/instances/i1", "ABCD12/10"),
("projects/p2/instances/i2", "5678/20"),
("projects/p2/instances/i2", "ABCD12/10"),
],
)
self.assertEqual(
local_workflow._extract_task_outputs_from_steps([]), []
)
def test_parallel_map(self):
self.assertEqual(
local_workflow._parallel_map(lambda x: x * x, range(20)),
[x * x for x in range(20)],
)
def fail_on_3(x: int) -> int:
if x == 3:
raise ValueError("boom")
return x
with self.assertRaisesRegex(ValueError, "boom"):
local_workflow._parallel_map(fail_on_3, range(10))
def test_download_baseline_success(self):
infra = FakeInfra()
infra.add_build(
"1003",
perf_dataset={"metrics.json": '{"metric": 1.0}'},
)
self.enterContext(infra.patch_subprocess_run())
out_dir = self.MakeTempDir()
stdout = io.StringIO()
perfcompare.Main(
[
"download_baseline",
"--state_file",
self.state_file,
"builder2",
out_dir,
],
stdout,
)
expected_file = os.path.join(out_dir, "metrics.json")
self.assertTrue(os.path.exists(expected_file))
with open(expected_file) as f:
self.assertEqual(f.read(), '{"metric": 1.0}')
output = stdout.getvalue()
self.assertIn("1003 (SUCCESS)", output)
self.assertIn("Triggering download to", output)
def test_download_baseline_fallback(self):
infra = FakeInfra()
infra.add_build("1002", status="FAILURE")
infra.add_build(
"1001",
status="SUCCESS",
perf_dataset={"metrics.json": '{"metric": 1.0}'},
)
self.enterContext(infra.patch_subprocess_run())
out_dir = self.MakeTempDir()
stdout = io.StringIO()
perfcompare.Main(
[
"download_baseline",
"--state_file",
self.state_file,
"builder1",
out_dir,
],
stdout,
)
expected_file = os.path.join(out_dir, "metrics.json")
self.assertTrue(os.path.exists(expected_file))
with open(expected_file) as f:
self.assertEqual(f.read(), '{"metric": 1.0}')
output = stdout.getvalue()
self.assertIn("1002 (FAILURE) - Skipping", output)
self.assertIn("1001 (SUCCESS)", output)
self.assertIn("Triggering download to", output)
def test_download_baseline_no_successful_build(self):
infra = FakeInfra()
infra.add_build("1002", status="FAILURE")
infra.add_build("1001", status="FAILURE")
self.enterContext(infra.patch_subprocess_run())
out_dir = self.MakeTempDir()
stdout = io.StringIO()
perfcompare.Main(
[
"download_baseline",
"--state_file",
self.state_file,
"builder1",
out_dir,
],
stdout,
)
output = stdout.getvalue()
self.assertIn("1002 (FAILURE) - Skipping", output)
self.assertIn("1001 (FAILURE) - Skipping", output)
self.assertIn("No successful sample build IDs found", output)
def test_extract_metrics(self):
data_dir = self.MakeTempDir()
WriteJsonFile(
os.path.join(data_dir, "test.fuchsiaperf.json"),
[
{
"test_suite": "fuchsia.test",
"label": "metric1",
"values": [10.5],
},
{
"test_suite": "fuchsia.test",
"label": "metric2",
"values": [20.0],
},
{
"test_suite": "other.suite",
"label": "metric3",
"values": [30.0],
},
],
)
stdout = io.StringIO()
perfcompare.Main(["extract_metrics", "fuchsia", data_dir], stdout)
output = stdout.getvalue()
self.assertIn("fuchsia.test,metric1,10.5", output)
self.assertIn("fuchsia.test,metric2,20.0", output)
self.assertNotIn("other.suite", output)
def test_extract_metrics_aggregation(self):
data_dir = self.MakeTempDir()
WriteJsonFile(
os.path.join(data_dir, "test1.fuchsiaperf.json"),
[
{
"test_suite": "fuchsia.test",
"label": "metric1",
"values": [10.5],
}
],
)
WriteJsonFile(
os.path.join(data_dir, "test2.fuchsiaperf.json"),
[
{
"test_suite": "fuchsia.test",
"label": "metric1",
"values": [15.0],
}
],
)
stdout = io.StringIO()
perfcompare.Main(["extract_metrics", "fuchsia", data_dir], stdout)
stdout.seek(0)
reader = csv.reader(stdout)
rows = list(reader)
self.assertEqual(rows, [["fuchsia.test", "metric1", "10.5", "15.0"]])
def test_extract_metrics_empty_values(self):
data_dir = self.MakeTempDir()
WriteJsonFile(
os.path.join(data_dir, "test.fuchsiaperf.json"),
[
{
"test_suite": "fuchsia.test",
"label": "metric1",
"values": [],
}
],
)
with self.assertRaises(statistics.StatisticsError):
perfcompare.Main(
["extract_metrics", "fuchsia", data_dir], io.StringIO()
)
def test_extract_metrics_malformed_json(self):
data_dir = self.MakeTempDir()
file_path = os.path.join(data_dir, "bad.fuchsiaperf.json")
with open(file_path, "w") as f:
f.write("{invalid}")
with self.assertRaises(RuntimeError) as cm:
perfcompare.Main(
["extract_metrics", "fuchsia", data_dir], io.StringIO()
)
self.assertIn("Malformed JSON", str(cm.exception))
def test_compare_builds_success(self):
infra = FakeInfra()
infra.add_build("1001", perf_dataset=_make_perf_dataset([10.0, 10.1]))
infra.add_build("1002", perf_dataset=_make_perf_dataset([20.0, 20.1]))
self.enterContext(infra.patch_subprocess_run())
stdout = io.StringIO()
perfcompare.Main(["compare_builds", "1001", "1002"], stdout)
output = stdout.getvalue()
self.assertIn("Downloading results from build 1001 into", output)
self.assertIn("Downloading results from build 1002 into", output)
self.assertIn("Comparing performance results:", output)
self.assertRegex(
output,
r"fuchsia\.test: metric1 +regressed +1\.275-3\.383 +10\.1 \+/- 3\.2 ms +20\.1 \+/- 3\.2 ms",
)
def test_compare_builds_with_dest(self):
infra = FakeInfra()
dataset1 = _make_perf_dataset([10.0, 10.1])
dataset2 = _make_perf_dataset([20.0, 20.1])
infra.add_build("1001", perf_dataset=dataset1)
infra.add_build("1002", perf_dataset=dataset2)
self.enterContext(infra.patch_subprocess_run())
dest_dir = self.MakeTempDir()
stdout = io.StringIO()
perfcompare.Main(
[
"compare_builds",
"1001",
"1002",
"--dest",
dest_dir,
],
stdout,
)
self.assertEqual(
self._read_dir_tree(os.path.join(dest_dir, "build_1001")),
dataset1,
)
self.assertEqual(
self._read_dir_tree(os.path.join(dest_dir, "build_1002")),
dataset2,
)
output = stdout.getvalue()
self.assertIn("Comparing performance results:", output)
self.assertRegex(
output,
r"fuchsia\.test: metric1 +regressed +1\.275-3\.383 +10\.1 \+/- 3\.2 ms +20\.1 \+/- 3\.2 ms",
)
def test_perfcompare_cl_dry_run(self):
cases = [
(
"turquoise",
"commit2",
"turquoise-internal.googlesource.com",
"turquoise/global.try/builder2",
),
(
"fuchsia",
"public_commit2",
"fuchsia.googlesource.com",
"fuchsia/try/builder2",
),
]
for project, revision, host, builder_target in cases:
infra = FakeInfra()
infra.add_build("1003", status="SUCCESS")
with (
self.subTest(project=project),
infra.patch_subprocess_run(),
):
stdout = io.StringIO()
perfcompare.Main(
[
"perfcompare_cl",
"--dry_run",
"--builder",
"builder2",
"--project",
project,
"--state_file",
self.state_file,
"https://fuchsia-review.googlesource.com/c/fuchsia/+/12345",
],
stdout,
)
# Assert that no other builds were triggered.
self.assertEqual(infra.builds.keys(), {"1003"})
output = stdout.getvalue()
self.assertIn(
f"Using sample build 1003 with revision {revision} as baseline.",
output,
)
self.assertIn("bb_for_testing add -json", output)
self.assertIn(
"-cl https://fuchsia-review.googlesource.com/c/fuchsia/+/12345",
output,
)
self.assertIn(
f"-commit https://{host}/integration/+/{revision}",
output,
)
self.assertIn("-ref refs/heads/main", output)
self.assertIn("-t perfcompare_with_cl:", output)
self.assertIn("-p runs_per_shard=5", output)
self.assertIn("-p perf_tests_only=true", output)
self.assertIn("cherry_pick_patches", output)
self.assertIn(builder_target, output)
def test_perfcompare_cl_success(self):
for dest_dir in (None, self.MakeTempDir()):
infra = FakeInfra()
baseline_dataset = _make_perf_dataset([10.0, 10.1])
try_dataset = _make_perf_dataset([20.0, 20.1])
infra.add_build(
"1003", status="SUCCESS", perf_dataset=baseline_dataset
)
infra.next_try_build_perf_dataset = try_dataset
with (
self.subTest(dest_dir=dest_dir),
infra.patch_subprocess_run(),
):
cmd_args = [
"perfcompare_cl",
"--builder",
"builder2",
"--project",
"turquoise",
"--state_file",
self.state_file,
]
if dest_dir is not None:
cmd_args.extend(["--dest", dest_dir])
cmd_args.append(
"https://fuchsia-review.googlesource.com/c/fuchsia/+/12345"
)
stdout = io.StringIO()
perfcompare.Main(cmd_args, stdout)
# Assert that no other builds were triggered.
self.assertEqual(infra.builds.keys(), {"1003", "5001"})
# Verify the triggered try build in FakeInfra.
self.assertEqual(
infra.builds["5001"],
{
"id": "5001",
"status": "SUCCESS",
"output": {
"properties": {
"cas_instance": "chromium_swarm",
"perf_dataset_digest": "digest_5001/82",
}
},
"steps": [],
"builder": "turquoise/global.try/builder2",
"cl": "https://fuchsia-review.googlesource.com/c/fuchsia/+/12345",
"commit": "https://turquoise-internal.googlesource.com/integration/+/commit2",
"ref": "refs/heads/main",
"tags": ["perfcompare_with_cl:"],
"input_properties": {
"runs_per_shard": 5,
"perf_tests_only": True,
"$fuchsia/checkout": {
"cherry_pick_patches": True,
"respect_gitiles_commit_with_gerrit_change": True,
},
},
},
)
output = stdout.getvalue()
self.assertIn(
"To compare builds manually, run: "
"python3 src/testing/perfcompare/perfcompare.py compare_builds 1003 5001",
output,
)
self.assertIn("Comparing performance results:", output)
self.assertRegex(
output,
r"fuchsia\.test: metric1 +regressed +1\.275-3\.383 +10\.1 \+/- 3\.2 ms +20\.1 \+/- 3\.2 ms",
)
if dest_dir is not None:
self.assertEqual(
self._read_dir_tree(
os.path.join(dest_dir, "without_cl")
),
baseline_dataset,
)
self.assertEqual(
self._read_dir_tree(os.path.join(dest_dir, "with_cl")),
try_dataset,
)
def test_perfcompare_cl_no_successful_sample_build(self):
infra = FakeInfra()
infra.add_build("1003", status="FAILURE")
self.enterContext(infra.patch_subprocess_run())
with self.assertRaisesRegex(
RuntimeError,
"No successful sample build found for builder 'builder2' in project 'turquoise'",
):
perfcompare.Main(
[
"perfcompare_cl",
"--builder",
"builder2",
"--project",
"turquoise",
"--state_file",
self.state_file,
"https://fuchsia-review.googlesource.com/c/fuchsia/+/12345",
],
io.StringIO(),
)
def test_perfcompare_cl_missing_commit_id(self):
state_file = os.path.join(self.MakeTempDir(), "state.json")
WriteJsonFile(
state_file,
{"2026-04-10": {"launched": {"builder1": {"build_id": "1001"}}}},
)
infra = FakeInfra()
infra.add_build("1001", status="SUCCESS")
self.enterContext(infra.patch_subprocess_run())
with self.assertRaisesRegex(
RuntimeError,
"Sample build 1001 does not have a commit ID in state file",
):
perfcompare.Main(
[
"perfcompare_cl",
"--builder",
"builder1",
"--project",
"turquoise",
"--state_file",
state_file,
"https://fuchsia-review.googlesource.com/c/fuchsia/+/12345",
],
io.StringIO(),
)
if __name__ == "__main__":
unittest.main()