mirror of
https://github.com/storytold/craft-common-actions.git
synced 2026-12-01 10:51:35 +01:00
The rust-cache key hashes the root [profile] tables except wasm-only ones (web, wasm-*), so a web-profile edit no longer starts every native cache cold. A new warm-command input adds a default-branch leg that runs only the build and saves the gate entry as soon as it succeeds, instead of after the tests.
254 lines
12 KiB
Python
254 lines
12 KiB
Python
"""The shared gate workflow: pinned actions, a cache with explicit manual-branch opt-in, and caller
|
|
input that reaches the shell only through the environment."""
|
|
from pathlib import Path
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
|
|
import yaml
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
WORKFLOW = yaml.load((ROOT / '.github/workflows/gate.yml').read_text(), Loader=yaml.BaseLoader)
|
|
STEPS = WORKFLOW['jobs']['gate']['steps']
|
|
OWN_ACTION = re.compile(r'^storytold/craft-common-actions/actions/[a-z0-9-]+@main$')
|
|
|
|
|
|
def step(name):
|
|
return next(s for s in STEPS if s.get('name') == name)
|
|
|
|
|
|
class GateWorkflowTests(unittest.TestCase):
|
|
def test_third_party_actions_are_pinned_to_a_commit(self):
|
|
for s in STEPS:
|
|
if 'uses' in s:
|
|
with self.subTest(uses=s['uses']):
|
|
if not OWN_ACTION.match(s['uses']):
|
|
self.assertRegex(s['uses'], r'@[0-9a-f]{40}$')
|
|
|
|
def test_manual_branch_saves_require_explicit_opt_in(self):
|
|
cache = next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))
|
|
condition = re.sub(r'\s+', ' ', cache['with']['save-if'])
|
|
self.assertIn("github.event_name != 'pull_request'", condition)
|
|
self.assertIn('github.ref_name == github.event.repository.default_branch', condition)
|
|
self.assertIn("inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch'", condition)
|
|
self.assertEqual(WORKFLOW['on']['workflow_call']['inputs']['cache-save-on-dispatch']['default'], 'false')
|
|
|
|
def test_packages_are_optional_and_empty_installs_none(self):
|
|
packages = WORKFLOW['on']['workflow_call']['inputs']['packages']
|
|
self.assertEqual(packages['required'], 'false')
|
|
self.assertEqual(packages['default'], '')
|
|
condition = step('Install Linux build dependencies')['if']
|
|
self.assertIn("runner.os == 'Linux'", condition)
|
|
self.assertIn("inputs.packages != ''", condition)
|
|
|
|
def test_inputs_reach_scripts_only_through_env(self):
|
|
for s in STEPS:
|
|
if 'run' in s:
|
|
with self.subTest(step=s.get('name')):
|
|
self.assertNotIn('${{', s['run'])
|
|
|
|
|
|
class GateTimeoutTests(unittest.TestCase):
|
|
STEP = step('Gate')
|
|
|
|
def run_gate(self, command, minutes, fake_timeout=None):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
path = os.environ['PATH']
|
|
if fake_timeout is not None:
|
|
Path(directory, 'bin').mkdir()
|
|
fake = Path(directory, 'bin', 'timeout')
|
|
fake.write_text(fake_timeout)
|
|
fake.chmod(0o755)
|
|
path = f"{directory}/bin:{path}"
|
|
result = subprocess.run(
|
|
['bash', '--noprofile', '--norc', '-eo', 'pipefail', '-c', self.STEP['run']],
|
|
cwd=directory, capture_output=True, text=True, timeout=60,
|
|
env={**os.environ, 'PATH': path, 'GATE': command, 'GATE_TIMEOUT': minutes,
|
|
'RUNNER_TEMP': directory, 'RUNNER_OS': 'Linux'})
|
|
return result.returncode, result.stdout + result.stderr
|
|
|
|
def test_input_defaults_to_no_limit(self):
|
|
self.assertEqual(WORKFLOW['on']['workflow_call']['inputs']['gate-timeout-minutes']['default'], '0')
|
|
self.assertEqual(set(self.STEP['env']), {'GATE', 'GATE_TIMEOUT'})
|
|
|
|
def test_no_limit_runs_the_command_as_before(self):
|
|
self.assertEqual(self.run_gate('echo ran; exit 3', '0'), (3, 'ran\n'))
|
|
|
|
def test_limit_keeps_the_exit_status(self):
|
|
self.assertEqual(self.run_gate('echo ran', '5'), (0, 'ran\n'))
|
|
status, out = self.run_gate('false', '5')
|
|
self.assertEqual(status, 1)
|
|
self.assertNotIn('timed out', out)
|
|
|
|
def test_watchdog_prints_processes_a_minute_before(self):
|
|
# with a 1 minute limit the snapshot is due at once
|
|
status, out = self.run_gate('sleep 2', '1')
|
|
self.assertEqual(status, 0)
|
|
self.assertIn('::group::Processes running one minute before the gate timeout', out)
|
|
|
|
def test_timeout_is_reported(self):
|
|
status, out = self.run_gate('true', '5', '#!/bin/sh\n[ "$1" = --version ] && exit 0\nexit 124\n')
|
|
self.assertEqual(status, 124)
|
|
self.assertIn('::error title=Gate timed out::', out)
|
|
|
|
def test_without_gnu_timeout_runs_unlimited(self):
|
|
status, out = self.run_gate('echo ran', '5', '#!/bin/sh\nexit 1\n')
|
|
self.assertEqual(status, 0)
|
|
self.assertIn('ran', out)
|
|
self.assertIn('Gate timeout not set', out)
|
|
|
|
def test_bad_value_warns_and_runs(self):
|
|
status, out = self.run_gate('echo ran', '1.5')
|
|
self.assertEqual(status, 0)
|
|
self.assertIn('Gate timeout not set', out)
|
|
|
|
|
|
class CallerEnvironmentTests(unittest.TestCase):
|
|
STEP = step('Caller environment')
|
|
|
|
def run_step(self, runner_os='Linux', **inputs):
|
|
env = {'ALL': '', 'LINUX': '', 'WINDOWS': '', 'DEV_DEBUG': '', **inputs}
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
github_env = Path(directory, 'github_env')
|
|
github_env.touch()
|
|
result = subprocess.run(
|
|
['bash', '--noprofile', '--norc', '-eo', 'pipefail', '-c', self.STEP['run']],
|
|
cwd=directory, capture_output=True, text=True,
|
|
env={**os.environ, **env, 'RUNNER_OS': runner_os, 'GITHUB_ENV': str(github_env)})
|
|
return result.returncode, github_env.read_text().splitlines()
|
|
|
|
def test_the_step_reads_its_inputs_from_env(self):
|
|
self.assertEqual(set(self.STEP['env']), {'ALL', 'LINUX', 'WINDOWS', 'DEV_DEBUG'})
|
|
|
|
def test_writes_shared_and_per_os_lines(self):
|
|
inputs = {'ALL': 'A=1\n\nB=two words', 'LINUX': 'ONLY_LINUX=1', 'WINDOWS': 'ONLY_WINDOWS=1',
|
|
'DEV_DEBUG': 'line-tables-only'}
|
|
self.assertEqual(self.run_step('Linux', **inputs), (0, [
|
|
'CARGO_PROFILE_DEV_DEBUG=line-tables-only', 'A=1', 'B=two words', 'ONLY_LINUX=1']))
|
|
self.assertEqual(self.run_step('Windows', **inputs)[1][-1], 'ONLY_WINDOWS=1')
|
|
|
|
def test_rejects_a_line_that_is_not_key_value(self):
|
|
for line in ('NOT AN ASSIGNMENT', '1X=1', 'X<<EOF'):
|
|
with self.subTest(line=line):
|
|
self.assertEqual(self.run_step(ALL=f'GOOD=1\n{line}')[0], 1)
|
|
|
|
|
|
class CallerSetupTests(unittest.TestCase):
|
|
STEP = step('Caller setup')
|
|
|
|
def run_step(self, setup):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
github_env = Path(directory, 'github_env')
|
|
github_env.touch()
|
|
result = subprocess.run(
|
|
['bash', '--noprofile', '--norc', '-eo', 'pipefail', '-c', self.STEP['run']],
|
|
cwd=directory, capture_output=True, text=True,
|
|
env={**os.environ, 'SETUP': setup, 'RUNNER_TEMP': directory,
|
|
'GITHUB_ENV': str(github_env)})
|
|
return result.returncode, github_env.read_text().splitlines(), Path(directory, 'setup-ran').exists()
|
|
|
|
def test_setup_input_is_passed_through_env_before_the_gate(self):
|
|
self.assertEqual(set(self.STEP['env']), {'SETUP'})
|
|
self.assertLess(STEPS.index(self.STEP), STEPS.index(step('Gate')))
|
|
self.assertNotIn('${{', self.STEP['run'])
|
|
|
|
def test_setup_can_provision_data_and_export_its_path(self):
|
|
setup = 'touch setup-ran\necho "CRAFT_PSD_CORPUS=/corpus" >> "$GITHUB_ENV"'
|
|
self.assertEqual(self.run_step(setup), (0, ['CRAFT_PSD_CORPUS=/corpus'], True))
|
|
|
|
def test_setup_failure_stops_the_gate_job(self):
|
|
self.assertEqual(self.run_step('exit 17')[0], 17)
|
|
|
|
|
|
class CallerCacheTests(unittest.TestCase):
|
|
def test_restored_before_the_setup_and_saved_after_it(self):
|
|
restore, setup, save = step('Restore caller cache'), step('Caller setup'), step('Save caller cache')
|
|
self.assertLess(STEPS.index(restore), STEPS.index(setup))
|
|
self.assertEqual(STEPS.index(save), STEPS.index(setup) + 1)
|
|
for s in (restore, save):
|
|
with self.subTest(step=s['name']):
|
|
self.assertEqual(s['with']['key'], '${{ steps.caller-key.outputs.key }}')
|
|
self.assertEqual(s['with']['path'], '${{ inputs.cache-paths }}')
|
|
self.assertIn("inputs.cache-paths != '' && matrix.part != 'lint'", s['if'])
|
|
|
|
def test_saved_only_where_the_dependency_cache_saves(self):
|
|
rust = next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))['with']['save-if']
|
|
policy = re.sub(r'\s+', ' ', rust.removeprefix('${{').removesuffix('}}')).strip()
|
|
condition = re.sub(r'\s+', ' ', step('Save caller cache')['if'])
|
|
# The test part leaves the save to the cache-warm leg when there is one.
|
|
writes = policy.removesuffix("&& (matrix.part != 'test' || inputs.warm-command == '')").strip()
|
|
self.assertNotEqual(writes, policy)
|
|
self.assertTrue(condition.endswith(f'&& {writes}'), condition)
|
|
self.assertIn("steps.caller-cache.outputs.cache-hit != 'true'", condition)
|
|
|
|
def run_key(self, key, files='', files_hash=''):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
output = Path(directory, 'output')
|
|
output.touch()
|
|
result = subprocess.run(
|
|
['bash', '--noprofile', '--norc', '-eo', 'pipefail', '-c', step('Caller cache key')['run']],
|
|
cwd=directory, capture_output=True, text=True,
|
|
env={**os.environ, 'KEY': key, 'FILES': files, 'FILES_HASH': files_hash, 'GITHUB_OUTPUT': str(output)})
|
|
return result.returncode, output.read_text()
|
|
|
|
def test_the_key_holds_the_pins_and_the_files_hash(self):
|
|
self.assertEqual(self.run_key('psd-corpus-7433'), (0, 'key=gate-caller-psd-corpus-7433\n'))
|
|
self.assertEqual(self.run_key('psd', 'scripts/x.sh', 'abc'), (0, 'key=gate-caller-psd-abc\n'))
|
|
|
|
def test_a_missing_key_or_unmatched_files_fail(self):
|
|
self.assertEqual(self.run_key('')[0], 1)
|
|
self.assertEqual(self.run_key('psd', 'scripts/missing.sh', '')[0], 1)
|
|
|
|
|
|
class WarmPartTests(unittest.TestCase):
|
|
JOB = WORKFLOW['jobs']['gate']
|
|
|
|
def test_the_warm_leg_exists_only_where_the_cache_saves(self):
|
|
inputs = WORKFLOW['on']['workflow_call']['inputs']
|
|
self.assertEqual(inputs['warm-command']['default'], '')
|
|
part = re.sub(r'\s+', ' ', self.JOB['strategy']['matrix']['part'])
|
|
save = re.sub(r'\s+', ' ', next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))['with']['save-if'])
|
|
writes = save.removeprefix('${{').split("&& (matrix.part")[0].strip()
|
|
self.assertIn(f"inputs.warm-command != '' && {writes} && ',\"warm\"'", part)
|
|
|
|
def test_the_warm_leg_runs_its_command_and_saves_the_gate_entry(self):
|
|
self.assertTrue(step('Gate')['env']['GATE'].startswith(
|
|
"${{ matrix.part == 'lint' && inputs.lint-command || matrix.part == 'warm' && inputs.warm-command || "))
|
|
cache = next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))['with']
|
|
self.assertEqual(cache['job'], "${{ matrix.part == 'lint' && 'lint' || '' }}")
|
|
self.assertIn("matrix.part != 'test' || inputs.warm-command == ''", cache['save-if'])
|
|
self.assertEqual(cache['cache-on-failure'], 'false')
|
|
|
|
|
|
class LintPartTests(unittest.TestCase):
|
|
JOB = WORKFLOW['jobs']['gate']
|
|
|
|
def test_lint_legs_exist_only_when_a_lint_command_is_given(self):
|
|
inputs = WORKFLOW['on']['workflow_call']['inputs']
|
|
self.assertEqual(inputs['lint-command']['default'], '')
|
|
part = re.sub(r'\s+', ' ', self.JOB['strategy']['matrix']['part'])
|
|
self.assertIn("inputs.lint-command != '' && ',\"lint\"'", part)
|
|
self.assertTrue(part.startswith("${{ fromJSON(format('[\"test\"{0}{1}]', "), part)
|
|
|
|
def test_the_test_part_keeps_the_gate_check_name(self):
|
|
self.assertEqual(self.JOB['name'], "${{ matrix.part == 'lint' && 'lint' || matrix.part == 'warm' && 'cache warm' || 'gate' }} (${{ matrix.os }})")
|
|
|
|
def test_lint_runs_its_own_command_and_skips_the_test_setup(self):
|
|
gate = step('Gate')['env']['GATE']
|
|
self.assertTrue(gate.startswith("${{ matrix.part == 'lint' && inputs.lint-command || "), gate)
|
|
self.assertIn("matrix.part != 'lint'", step('Caller setup')['if'])
|
|
|
|
def test_lint_keeps_a_cache_entry_of_its_own(self):
|
|
cache = next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))
|
|
self.assertEqual(cache['with']['job'], "${{ matrix.part == 'lint' && 'lint' || '' }}")
|
|
|
|
|
|
# The profile half of the cache key, and the rest of the key's layout, are tested where they now
|
|
# live: tests/test_rust_cache.py.
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|