mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 21:15:43 +00:00
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.
210 lines
13 KiB
Python
210 lines
13 KiB
Python
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_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', '<!-- build -->')
|
|
comments = [dict(id=1, user=dict(login='someone'), body='<!-- build --> forged'),
|
|
dict(id=2, user=dict(login='github-actions[bot]'), body='<!-- build --> 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_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'])
|
|
|