import itertools import json import os from pathlib import Path import shlex import shutil import subprocess import tempfile import unittest import yaml ROOT = Path(__file__).resolve().parents[2] class CiChecksTest(unittest.TestCase): def test_pr_cache_writes_and_source_timestamp_policy(self): jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs'] cache = next(step for step in jobs['build']['steps'] if step.get('uses') == 'gradle/actions/setup-gradle@v4')['with'] self.assertEqual(cache['cache-read-only'], "${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}") gradle = (ROOT / 'app/build.gradle').read_text() 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/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'): self.assertNotIn('..', path.split('/')) robolectric = [cache['path'] for cache in caches if cache['key'].startswith('robolectric-')] self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2) def test_only_main_saves_the_robolectric_cache(self): steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] saves = [step for step in steps if step.get('uses', '').startswith('actions/cache/save') and step['with']['key'].startswith('robolectric-')] self.assertEqual(len(saves), 1) self.assertIn("github.event_name != 'pull_request'", saves[0]['if']) def test_unit_test_retry_requires_maven_exception(self): 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), ): self.assertEqual(subprocess.run(['grep', '-Eq', pattern], input=log, text=True).returncode, expected) def test_report_comment_lookup_ignores_human_marker(self): if not shutil.which('jq'): self.skipTest('jq required to execute comment selection') script = (ROOT / 'tools/release/report-build.sh').read_text() line = next(line for line in script.splitlines() if line.startswith('ID=')) arguments = shlex.split(line[len('ID=$('):].split(' | head', 1)[0]) query = arguments[arguments.index('--jq') + 1].replace('$MARK', '') comments = [dict(id=1, user=dict(login='someone'), body=' forged'), dict(id=2, user=dict(login='github-actions[bot]'), body=' result')] result = subprocess.check_output(['jq', '-r', query], input=json.dumps(comments), text=True) self.assertEqual(result.strip(), '2') def test_build_and_tests_use_identical_generated_metadata(self): 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_switch_mirrors_only_for_robolectric_rate_limits(self): steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] script = next(step['run'] for step in steps if step.get('id') == 'unit-tests') central = 'https://repo.maven.apache.org/maven2/' native = f'{central}org/robolectric/nativeruntime-dist-compat/1.0.18/nativeruntime-dist-compat-1.0.18.jar' sdk = 'https://repo1.maven.org/maven2/org/robolectric/android-all-instrumented/sdk.jar.sha512' gradle_error = 'org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException' get_error = f"Could not GET '{native}'. Received status code 429 from server: Too Many Requests" mirror = '-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2' # These two resolvers report the status and URL in opposite orders. cases = [ ('ok', 0, 0, 0, 1), (f'Could not GET {native}. Received status code 429', 1, 0, 0, 2), (f'Server returned HTTP response code: 429 for URL: {sdk}', 1, 9, 9, 2), (f' Caused by: {gradle_error}: {get_error}', 1, 0, 0, 2), (f' Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: {sdk}', 1, 0, 0, 2), (f'Failed to get resource: GET. [HTTP HTTP/1.1 429 Too Many Requests: {native})]\n' 'java.lang.AssertionError: expected a visible window', 7, 0, 7, 1), ('AssertionError: expected 429', 7, 0, 7, 1), (f'AssertionError: expected status code 429 for URL: {sdk}', 7, 0, 7, 1), (f'Caused by: java.lang.AssertionError: {get_error}', 7, 0, 7, 1), (f'Could not GET {central}other/group/lib.jar. Received status code 429', 8, 0, 8, 1), ] for message, first, retry, expected, attempts in cases: with self.subTest(message=message), tempfile.TemporaryDirectory() as directory: root = Path(directory) gradle = root / 'gradlew' gradle.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> calls\n' 'case "$*" in *-ProbolectricMavenMirror=*) exit "$RETRY";; esac\n' 'echo "$MESSAGE"\nexit "$FIRST"\n') gradle.chmod(0o755) sleep = root / 'sleep' sleep.write_text('#!/bin/sh\necho "sleep $*" >> calls\n') sleep.chmod(0o755) env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], NDK_VERSION='test', MESSAGE=message, FIRST=str(first), RETRY=str(retry)) result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env, capture_output=True, timeout=15) self.assertEqual(result.returncode, expected, result.stdout) calls = (root / 'calls').read_text().splitlines() self.assertEqual(len(calls), attempts) self.assertNotIn(mirror, calls[0]) if attempts == 2: self.assertEqual(calls[1].split(), [*calls[0].split(), mirror]) def test_unit_tests_back_off_on_maven_central_rate_limits(self): steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] script = next(step['run'] for step in steps if step.get('id') == 'unit-tests') rate_limit = ( "Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: " "Could not GET 'https://repo.maven.apache.org/maven2/junit/junit/4.13.2/junit-4.13.2.jar'. " "Received status code 429 from server: Too Many Requests" ) for exit_codes, expected_status, expected_events in ( ([7, 0], 0, ['gradle', 'sleep 60', 'gradle']), ([7, 9, 23, 0], 23, ['gradle', 'sleep 60', 'gradle', 'sleep 180', 'gradle']), ): with self.subTest(exit_codes=exit_codes), tempfile.TemporaryDirectory() as directory: root = Path(directory) (root / 'statuses').write_text(''.join(f'{code}\n' for code in exit_codes)) gradle = root / 'gradlew' gradle.write_text('#!/bin/sh\n' 'echo gradle >> events\n' 'echo "$*" >> gradle-args\n' 'attempt=$(wc -l < gradle-args)\n' 'status=$(sed -n "${attempt}p" statuses)\n' 'if [ "$status" != 0 ]; then echo "$MAVEN_ERROR"; fi\n' 'exit "${status:-99}"\n') gradle.chmod(0o755) sleep = root / 'sleep' sleep.write_text('#!/bin/sh\necho "sleep $*" >> events\n') sleep.chmod(0o755) env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], NDK_VERSION='test', MAVEN_ERROR=rate_limit) result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env, capture_output=True, text=True, timeout=15) self.assertEqual(result.returncode, expected_status, result.stdout + result.stderr) self.assertEqual((root / 'events').read_text().splitlines(), expected_events) self.assertNotIn('-ProbolectricMavenMirror=', (root / 'gradle-args').read_text()) 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'): self.assertEqual(jobs[name]['needs'], 'source') self.assertEqual(set(jobs['components']['needs']), {'source', 'components-runner'}) self.assertEqual(jobs['build-runner']['needs'], ['components']) self.assertEqual(set(jobs['build']['needs']), {'source', 'components', 'xbox', 'build-runner'}) def test_dependency_update_errors_block_installation(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) sudo = root / 'sudo' sudo.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> "$APT_LOG"\n' 'for arg; do case "$arg" in Dir::Etc::sourcelist=*) ' 'grep -hE "^(URIs|Suites):" "${arg#*=}" >> "$APT_LOG.mirrors";; esac; done\n' 'exit "${APT_RESULT:-0}"\n') sudo.chmod(0o755) query = root / 'dpkg-query' query.write_text('#!/bin/sh\nexit 1\n') query.chmod(0o755) dpkg = root / 'dpkg' dpkg.write_text('#!/bin/sh\necho "${DPKG_ARCH:-amd64}"\n') dpkg.chmod(0o755) log = root / 'apt.log' sources = root / 'ubuntu.sources' sources.write_text('URIs: http://mirror.invalid/ubuntu\n') env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], APT_LOG=str(log), UBUNTU_SOURCES_FILE=str(sources)) installer = ROOT / 'tools/ci/install-ubuntu-packages.sh' result = subprocess.run(['bash', str(installer), 'qemu-user'], env=dict(env, APT_RESULT='17')) self.assertEqual(result.returncode, 17) self.assertEqual(len(log.read_text().splitlines()), 3) mirrors = Path(str(log) + '.mirrors') self.assertEqual(mirrors.read_text().splitlines(), [ 'URIs: http://mirror.invalid/ubuntu', 'URIs: https://archive.ubuntu.com/ubuntu', 'URIs: https://mirrors.edge.kernel.org/ubuntu', ]) log.unlink() mirrors.unlink() result = subprocess.run(['bash', str(installer), 'qemu-user'], env=dict(env, APT_RESULT='17', DPKG_ARCH='arm64')) self.assertEqual(result.returncode, 17) self.assertEqual(mirrors.read_text().splitlines()[1:], [ 'URIs: https://ports.ubuntu.com/ubuntu-ports', 'URIs: https://mirrors.ocf.berkeley.edu/ubuntu-ports', ]) log.unlink() mirrors.unlink() subprocess.run(['bash', str(installer), 'qemu-user'], env=env, check=True) update, install = log.read_text().splitlines() for command in (update, install): self.assertIn('Dir::Etc::sourceparts=-', command) self.assertIn(f'Dir::Etc::sourcelist={sources}', command) self.assertIn('Acquire::https::Timeout=15', command) self.assertIn('Acquire::Retries=1', command) self.assertIn('APT::Update::Error-Mode=any', update) self.assertIn('install -y -q --no-install-recommends qemu-user', install) log.unlink() mirrors.unlink() release = root / 'os-release' release.write_text('ID=ubuntu\n') absent = dict(env, UBUNTU_SOURCES_FILE=str(root / 'missing.sources'), APT_RESULT='17', OS_RELEASE_FILE=str(release)) result = subprocess.run(['bash', str(installer), 'qemu-user'], env=absent) self.assertEqual(result.returncode, 1) self.assertEqual(len(log.read_text().splitlines()), 1) self.assertNotIn('Dir::Etc::sourceparts', log.read_text()) log.unlink() release.write_text('ID=ubuntu\nVERSION_CODENAME=noble\nUBUNTU_CODENAME=noble\n') result = subprocess.run(['bash', str(installer), 'qemu-user'], env=absent) self.assertEqual(result.returncode, 17) first, *fallbacks = log.read_text().splitlines() self.assertNotIn('Dir::Etc::sourcelist', first) self.assertEqual(len(fallbacks), 2) for command in (first, *fallbacks): self.assertIn('Acquire::Retries=1', command) self.assertIn('Acquire::https::Timeout=15', command) for command in fallbacks: self.assertIn('Dir::Etc::sourceparts=-', command) self.assertEqual(mirrors.read_text().splitlines(), [ 'URIs: https://archive.ubuntu.com/ubuntu', 'Suites: noble noble-updates noble-security', 'URIs: https://mirrors.edge.kernel.org/ubuntu', 'Suites: noble noble-updates noble-security', ]) def test_required_status_rejects_failed_cancelled_or_skipped_test_jobs(self): jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs'] gate = jobs['checks'] self.assertEqual(gate['name'], 'Compile and test APK') self.assertEqual(set(gate['needs']), {'build', 'python-tests', 'store-tests'}) self.assertIn('!cancelled()', gate['if']) for build, python, store in itertools.product(('success', 'failure', 'cancelled', 'skipped'), repeat=3): with self.subTest(build=build, python=python, store=store): result = subprocess.run( ['bash', '-c', gate['steps'][0]['run']], env=dict(os.environ, BUILD_RESULT=build, PYTHON_RESULT=python, STORE_RESULT=store), capture_output=True) self.assertEqual(result.returncode == 0, build == python == store == 'success') for publisher in ('sign', 'packs'): self.assertIn('checks', jobs[publisher]['needs'])