ci: run Kotlin unit tests separately from APK builds (#3566)

Run Kotlin tests beside APK compilation while keeping merge and release checks intact. Pin the APK and test workflows to the same pull request base, retry Robolectric rate limits on both Maven Central hosts, and verify source parity when main advances.
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-12-02 16:47:42 -05:00
1 parent 5d05c36033
commit 34fff40b56
13 files changed
+381 -171

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Exports the build metadata Gradle bakes into BuildConfig and prints the label for DROIDDECK_BUILD_LABEL.
set -euo pipefail
if [[ -n "$(git status --porcelain)" ]]; then
tree_state=dirty
else
tree_state=clean
fi
echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV"
if [[ -n "${PR_NUMBER:-}" ]]; then
label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}"
else
label="${BUILD_REF} at ${BUILD_SHA:0:7}"
fi
echo "label=$label" >> "$GITHUB_OUTPUT"
echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV"
echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV"
echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV"
echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY"
+6 -1
View File
@@ -10,13 +10,18 @@ flowchart LR
Source[Pin source tree] --> Components[Prepare verified components]
Source --> Xbox[Xbox ARM64 backend]
Source --> Tests[Python and native tests]
Components --> APK[Compile APK and Android tests]
Components --> APK[Compile APK]
Xbox --> APK
APK --> Gate[Compile and test APK gate]
Tests --> Gate
Gate --> Publish[Main only: signing and publishing]
```
Kotlin unit tests run in the separate `Unit tests` workflow (`unit-tests.yml`), so a
PR test build is published as soon as the APK compiles. Build validation folds both
workflows into the `Build APK` commit status, and Release APKs requires both for the
released commit.
All workers verify the same source tree. The component artifact records that tree,
recipe identities and every output hash; the APK worker verifies the inventory
before building. This handoff verifies consistency within the same CI run. It is
+6 -22
View File
@@ -7,37 +7,21 @@ MARK="<!-- droiddeck-pr-build -->"
echo
[ -f /tmp/pr-merge.md ] && cat /tmp/pr-merge.md
echo
case "$BUILD_OUTCOME:$UNIT_TEST_OUTCOME:$APK_OUTCOME" in
success:success:success)
case "$BUILD_OUTCOME:$APK_OUTCOME" in
success:success)
echo "### Build passed"
echo
echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key."
echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key. Unit tests run in the separate **Unit tests** workflow and must pass before merging."
echo
echo "Same-repository PRs and PRs opened by contributors listed in \`.github/trusted-test-builds.txt\` are eligible for automatic release-signed test builds after the full build passes. Label the PR \`no-test-build\` to skip that."
echo "Same-repository PRs and PRs opened by contributors listed in \`.github/trusted-test-builds.txt\` are eligible for automatic release-signed test builds once the APK compiles. Label the PR \`no-test-build\` to skip that."
echo "For other PRs, a maintainer can add the \`publish-test\` label to request a signed build."
echo
echo "Fallback: [open **PR Release Publish**]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/workflows/pr-release-publish.yml) on \`main\` and enter PR \`$PR\`."
;;
success:success:*)
success:*)
echo "### APK publication incomplete"
echo
echo "Compilation and unit tests passed, but APK publication did not complete. See [the run]($RUN_URL)."
;;
success:failure:*)
echo "### ERROR: Unit tests failed"
echo
echo "The APK compiled, but unit tests failed. No installable artifact was published."
echo
if [ -n "$TEST_DIAGNOSTICS_URL" ]; then
echo "The [unit-test-results]($TEST_DIAGNOSTICS_URL) artifact contains the test log and any generated reports."
else
echo "The test diagnostics upload did not complete. See [the test log]($RUN_URL)."
fi
;;
success:*)
echo "### Build incomplete"
echo
echo "The APK compiled, but unit tests did not complete successfully. See [the run]($RUN_URL)."
echo "Compilation passed, but APK publication did not complete. See [the run]($RUN_URL)."
;;
failure:*)
echo "### ERROR: Build failed"
+51 -11
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import json
import os
import re
import subprocess
import sys
import time
@@ -40,6 +41,39 @@ def compilation_state(run, jobs):
return "failure" if run["status"] == "completed" else "pending"
def run_state(run):
if run["status"] != "completed":
return "pending"
return "success" if run["conclusion"] == "success" else "failure"
def latest_run(repo, workflow, sha, source_event):
query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20})
runs = api(f"repos/{repo}/actions/workflows/{workflow}/runs?{query}")["workflow_runs"]
runs = [item for item in runs if item["head_sha"] == sha]
return max(runs, key=lambda item: item["id"]) if runs else None
def pull_request_run_base(run, sha):
# A PR can reopen at the same head SHA after main advances. Do not mix results
# from different event snapshots, even if both workflows individually passed.
title = run.get("display_title") or ""
match = re.search(rf" on {re.escape(sha)} against ([0-9a-f]{{40}})$", title)
return match[1] if match else None
def combined_state(build, tests):
if build == "failure":
return "failure", "APK compilation failed"
if tests == "failure":
return "failure", "Unit tests failed"
if build == "pending":
return "pending", "Source validated; awaiting APK compilation"
if tests == "pending":
return "pending", "APK compiled; awaiting unit tests"
return "success", "Source validation, APK compilation and unit tests passed"
def fetch_source(ref, sha):
subprocess.run(["git", "fetch", "--no-tags", "origin", ref], check=True)
fetched = subprocess.check_output(["git", "rev-parse", "FETCH_HEAD"], text=True).strip()
@@ -123,19 +157,25 @@ def main():
state = "success"
description = "Source validated; no APK source changes"
return
query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20})
runs = api(f"repos/{repo}/actions/workflows/build.yml/runs?{query}")["workflow_runs"]
runs = [item for item in runs if item["head_sha"] == sha]
if runs:
latest = max(runs, key=lambda item: item["id"])
build_state = tests_state = "pending"
latest = latest_run(repo, "build.yml", sha, source_event)
if latest:
jobs = api(f"repos/{repo}/actions/runs/{latest['id']}/jobs?per_page=100")["jobs"]
state = compilation_state(latest, jobs)
build_state = compilation_state(latest, jobs)
target = latest["html_url"]
else:
state = "pending"
description = {"pending": "Source validated; awaiting APK compilation",
"success": "Source validation and APK compilation passed",
"failure": "APK compilation failed"}[state]
tests = latest_run(repo, "unit-tests.yml", sha, source_event)
if tests:
if pr and latest and build_state == "success":
build_base = pull_request_run_base(latest, sha)
tests_base = pull_request_run_base(tests, sha)
if not build_base or build_base != tests_base:
state = "pending"
description = "APK and unit tests must run against the same main commit"
return
tests_state = run_state(tests)
if tests_state == "failure" and build_state != "failure":
target = tests["html_url"]
state, description = combined_state(build_state, tests_state)
finally:
api(f"repos/{repo}/statuses/{sha}", "--method", "POST",
"-f", "context=Build APK", "-f", f"state={state}",
+42 -7
View File
@@ -25,7 +25,7 @@ class CiChecksTest(unittest.TestCase):
self.assertIn("gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit])", gradle)
def test_robolectric_cache_saves_and_restores_the_same_absolute_path(self):
steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
caches = [step['with'] for step in steps if step.get('uses', '').startswith('actions/cache')]
for cache in caches:
for path in cache['path'].split('\n'):
@@ -34,13 +34,17 @@ class CiChecksTest(unittest.TestCase):
self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2)
def test_unit_test_retry_requires_maven_exception(self):
steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
run = next(step['run'] for step in steps if step.get('id') == 'unit-tests')
line = next(line for line in run.splitlines() if 'grep -Eq' in line)
pattern = shlex.split(line)[shlex.split(line).index('-Eq') + 1]
for log, expected in (
("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo.maven.apache.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0),
("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo.maven.apache.org/maven2/a.jar", 0),
("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo1.maven.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0),
("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo1.maven.org/maven2/a.pom.sha512", 0),
("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://example.org/a.jar", 1),
("Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: https://repo1.maven.org/maven2/a.jar", 1),
("SomeTest > test FAILED: Too Many Requests", 1),
("Caused by: java.lang.AssertionError: HTTP 429", 1),
):
@@ -59,15 +63,46 @@ class CiChecksTest(unittest.TestCase):
self.assertEqual(result.strip(), '2')
def test_build_and_tests_use_identical_generated_metadata(self):
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
steps = {step.get('id'): step for step in jobs['build']['steps']}
self.assertEqual(steps['build']['env'], steps['unit-tests']['env'])
self.assertIn('DROIDDECK_BUILD_LABEL', steps['unit-tests']['env'])
self.assertIn('SGDB_API_KEY', steps['unit-tests']['env'])
build = {step.get('id'): step for step in
yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']}
tests = {step.get('id'): step for step in
yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']}
self.assertEqual(build['build']['env'], tests['unit-tests']['env'])
self.assertIn('DROIDDECK_BUILD_LABEL', tests['unit-tests']['env'])
self.assertIn('SGDB_API_KEY', tests['unit-tests']['env'])
self.assertEqual(build['build-label'], tests['build-label'])
gradle = (ROOT / 'app/build.gradle').read_text()
self.assertIn("outputs.doNotCacheIf('CI executes the test suite on every run') { true }", gradle)
self.assertIn('outputs.upToDateWhen { false }', gradle)
def test_unit_tests_do_not_hold_up_the_apk(self):
build = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())
for step in build['jobs']['build']['steps']:
self.assertNotIn('UnitTest', step.get('run', ''))
tests = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())
for event in ('push', 'pull_request'):
self.assertEqual(tests[True][event], build[True][event])
authorship = yaml.safe_load((ROOT / '.github/workflows/authorship.yml').read_text())
self.assertEqual(set(authorship[True]['workflow_run']['workflows']), {build['name'], tests['name']})
self.assertIn('workflow_run.head_sha', authorship['concurrency']['group'])
self.assertFalse(authorship['concurrency']['cancel-in-progress'])
self.assertIn('unit-tests.yml', (ROOT / '.github/workflows/release.yml').read_text())
run = next(step['run'] for step in tests['jobs']['unit-tests']['steps'] if step.get('id') == 'unit-tests')
self.assertIn('-PunitTestsOnly=true', run)
def test_apk_and_unit_tests_pin_the_same_pr_event_base(self):
for filename, job, name in (
("build.yml", "source", "Pin and merge the APK source"),
("unit-tests.yml", "unit-tests", "Merge the pinned APK base"),
):
with self.subTest(workflow=filename):
workflow = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text())
step = next(step for step in workflow["jobs"][job]["steps"] if step.get("name") == name)
self.assertEqual(step["env"]["PR_BASE_SHA"], "${{ github.event.pull_request.base.sha }}")
self.assertIn('git fetch --no-tags origin "$PR_BASE_SHA"', step["run"])
self.assertIn("git merge --no-ff --no-edit FETCH_HEAD", step["run"])
self.assertIn("github.event.pull_request.base.sha", workflow["run-name"])
def test_independent_jobs_wait_only_for_the_pinned_source(self):
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
for name in ('xbox', 'python-tests', 'components-runner'):
+30 -2
View File
@@ -28,7 +28,7 @@ class ValidateApkTest(unittest.TestCase):
def git(self, *args):
return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip()
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write", fork=False):
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write", fork=False, tests="success", build_base="a" * 40, tests_base="a" * 40):
(self.root / filename).parent.mkdir(parents=True, exist_ok=True)
(self.root / filename).write_text(message)
self.git("add", filename)
@@ -56,7 +56,16 @@ class ValidateApkTest(unittest.TestCase):
if path.endswith("/pulls?state=open&head=contributor%3Afix%2Fbranch"):
return [pr]
if "workflows/build.yml/runs?" in path:
return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", "html_url": "https://example.org/build"}]}
title = f"building pr 1 on {sha}" + (f" against {build_base}" if build_base else "")
return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed",
"display_title": title, "html_url": "https://example.org/build"}]}
if "workflows/unit-tests.yml/runs?" in path:
if tests is None:
return {"workflow_runs": []}
title = f"unit tests for pr 1 on {sha}" + (f" against {tests_base}" if tests_base else "")
return {"workflow_runs": [{"id": 9, "head_sha": sha, "html_url": "https://example.org/tests",
"display_title": title, "status": "in_progress" if tests == "pending" else "completed",
"conclusion": None if tests == "pending" else tests}]}
if path.endswith("/jobs?per_page=100"):
return {"jobs": [{"name": "Compile and test APK", "status": "in_progress" if result == "pending" else "completed", "conclusion": result}]}
raise AssertionError(path)
@@ -85,6 +94,25 @@ class ValidateApkTest(unittest.TestCase):
self.validate(result=result)
self.assertEqual(self.statuses[-1]["state"], result)
def test_unit_tests_must_pass_too(self):
for tests, state in (("pending", "pending"), (None, "pending"), ("failure", "failure"), ("cancelled", "failure")):
with self.subTest(tests=tests):
self.validate(tests=tests)
self.assertEqual(self.statuses[-1]["state"], state)
self.assertEqual(self.statuses[-1]["target_url"], "https://example.org/tests")
def test_successful_runs_must_use_the_same_pr_base(self):
for build_base, tests_base in (("a" * 40, "b" * 40), ("a" * 40, None), (None, "a" * 40)):
with self.subTest(build_base=build_base, tests_base=tests_base):
self.validate(build_base=build_base, tests_base=tests_base)
self.assertEqual(self.statuses[-1]["state"], "pending")
self.assertIn("same main commit", self.statuses[-1]["description"])
def test_a_compile_failure_is_reported_before_test_results(self):
self.validate(result="failure", tests="failure")
self.assertEqual(self.statuses[-1]["description"], "APK compilation failed")
self.assertEqual(self.statuses[-1]["target_url"], "https://example.org/build")
def test_superseded_event_cannot_replace_current_status(self):
self.validate(stale=True)
self.assertEqual(self.statuses, [])
+14 -4
View File
@@ -11,8 +11,10 @@ class XboxBuildSourceTest(unittest.TestCase):
import yaml
except ImportError:
self.fail('PyYAML is required to execute workflow steps')
workflow = yaml.safe_load((Path(__file__).resolve().parents[2] / '.github/workflows/build.yml').read_text())
jobs = workflow['jobs']
workflows = Path(__file__).resolve().parents[2] / '.github/workflows'
jobs = yaml.safe_load((workflows / 'build.yml').read_text())['jobs']
unit_jobs = yaml.safe_load((workflows / 'unit-tests.yml').read_text())['jobs']
jobs.update(unit_jobs)
step = lambda job, name: next(s['run'] for s in jobs[job]['steps'] if s.get('name') == name)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
@@ -31,13 +33,17 @@ class XboxBuildSourceTest(unittest.TestCase):
git('switch', '-q', 'main')
(root / 'backend').write_text('merged backend')
git('commit', '-qam', 'backend changed after branch')
for name in ('source', 'xbox', 'components', 'apk', 'tests', 'dispatch'):
event_base = git('rev-parse', 'HEAD')
for name in ('source', 'xbox', 'components', 'apk', 'tests', 'unit-tests', 'dispatch'):
git('clone', '-q', str(root), str(root / name))
git('checkout', '-q', head, cwd=root / name)
output = root / 'output'
env['GITHUB_OUTPUT'] = str(output)
env.update(GITHUB_OUTPUT=str(output), PR_BASE_SHA=event_base)
(root / 'backend').write_text('newer main, after PR event')
git('commit', '-qam', 'main advanced before source pinning')
subprocess.run(['bash', '-c', step('source', 'Pin and merge the APK source')], cwd=root / 'source', env=env, check=True, capture_output=True)
base = output.read_text().strip().split('=', 1)[1]
self.assertEqual(base, event_base)
tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'source')
(root / 'backend').write_text('newer main, after backend build')
git('commit', '-qam', 'main advanced again')
@@ -51,6 +57,10 @@ class XboxBuildSourceTest(unittest.TestCase):
subprocess.run(['bash', '-c', step('python-tests', 'Verify backend and test source match')], cwd=root / 'tests', env=env, check=True, capture_output=True)
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'tests'), tree)
subprocess.run(['bash', '-c', step('unit-tests', 'Merge the pinned APK base')], cwd=root / 'unit-tests', env=env, check=True, capture_output=True)
self.assertEqual((root / 'unit-tests/backend').read_text(), 'merged backend')
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'unit-tests'), tree)
env['SOURCE_TREE'] = tree
for job in ('xbox', 'components'):
subprocess.run(['bash', '-c', step(job, 'Merge the pinned APK base')], cwd=root / job, env=env, check=True, capture_output=True)