135 lines
8.2 KiB
Python
135 lines
8.2 KiB
Python
import copy
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
HERE = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(HERE))
|
|
spec = importlib.util.spec_from_file_location('p11_adversarial_tests', HERE / 'run-p11-adversarial.py')
|
|
gate = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(gate)
|
|
|
|
|
|
class P11AdversarialTests(unittest.TestCase):
|
|
def fixture(self, root):
|
|
project = 'tests/Example/Example.Tests.csproj'
|
|
source = 'tests/Example/Cases.cs'
|
|
(root / source).parent.mkdir(parents=True)
|
|
(root / source).write_text('namespace Example; class Cases { public void Case() {} }')
|
|
(root / project).write_text('<Project/>')
|
|
case = {'source': source, 'project': project, 'selector': 'Example.Cases.Case'}
|
|
return {'schema_version': 1, 'obligations': [{'id': 'test-obligation', 'description': 'Actual deterministic assertion', 'tests': [case]}]}
|
|
|
|
def trx(self, root, outcome='Passed', name='Example.Cases.Case', suffix=''):
|
|
path = root / ('results' + suffix + '.trx')
|
|
path.write_text(f'<TestRun><TestDefinitions><UnitTest id="1"><TestMethod className="Example.Cases" name="Case"/></UnitTest></TestDefinitions><Results><UnitTestResult testId="1" testName="{name}" outcome="{outcome}"><Output><ErrorInfo><Message>reason</Message></ErrorInfo></Output></UnitTestResult></Results></TestRun>')
|
|
return path
|
|
|
|
def test_registry_covers_every_obligation_with_exact_methods_and_source_paths(self):
|
|
document = gate.registry()
|
|
self.assertEqual(gate.REQUIRED, {row['id'] for row in document['obligations']})
|
|
for obligation in document['obligations']:
|
|
self.assertTrue(obligation['tests'])
|
|
for case in obligation['tests']:
|
|
self.assertNotIn('~', case['selector'])
|
|
self.assertTrue(case['project'].endswith('.csproj'))
|
|
|
|
def test_only_exact_selected_projects_methods_are_executed(self):
|
|
cases = [{'selector': 'Example.Cases.First'}, {'selector': 'Example.Cases.Second'}]
|
|
discovery, execute = gate.commands('tests/Example/Example.Tests.csproj', cases, '/private/trx')
|
|
self.assertEqual(execute[:3], ['dotnet', 'test', 'tests/Example/Example.Tests.csproj'])
|
|
expression = execute[execute.index('--filter') + 1]
|
|
self.assertEqual(expression, 'FullyQualifiedName=Example.Cases.First|FullyQualifiedName=Example.Cases.Second')
|
|
self.assertNotIn('Category', expression)
|
|
self.assertNotIn('--no-build', discovery)
|
|
self.assertIn('--no-build', execute)
|
|
|
|
def test_consumer_role_continuity_registers_all_exact_methods(self):
|
|
obligation = next(row for row in gate.registry()['obligations'] if row['id'] == 'consumer-role-continuity')
|
|
methods = {case['selector'].rsplit('.', 1)[-1] for case in obligation['tests']}
|
|
self.assertEqual(methods, {
|
|
'Hot_eligible_role_transitions_preserve_the_existing_route_but_epoch_aba_invalidates_it',
|
|
'Host_effective_non_hot_mode_drains_even_when_artifact_is_hot',
|
|
'Retained_metadata_guard_survives_borrower_disposal_but_not_unobserved_epoch_loss',
|
|
'Non_hot_retained_metadata_does_not_revive_after_missed_ineligible_transition',
|
|
'Read_epoch_is_stable_between_known_roles_and_changes_on_unknown_and_owner_replacement',
|
|
'Hot_retained_guard_reads_role_without_waiting_for_dispatch_fence',
|
|
'Healthy_origin_catalog_stays_ready_while_another_thread_holds_the_dispatch_fence',
|
|
})
|
|
|
|
def test_actual_passes_need_nonzero_discovery_and_all_theory_rows(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
root = Path(folder); document = self.fixture(root)
|
|
self.trx(root, name='Example.Cases.Case(value: 1)')
|
|
rows = gate.result_rows(root)
|
|
discovery = {'Example.Cases.Case': ['Example.Cases.Case(value: 1)']}
|
|
self.assertTrue(gate.reconcile(document, discovery, rows, root)['passed'])
|
|
discovery['Example.Cases.Case'].append('Example.Cases.Case(value: 2)')
|
|
self.assertFalse(gate.reconcile(document, discovery, rows, root)['passed'])
|
|
self.assertFalse(gate.reconcile(document, {}, rows, root)['passed'])
|
|
self.assertFalse(gate.reconcile(document, discovery, [], root)['passed'])
|
|
|
|
def test_skipped_failed_and_missing_source_never_become_synthetic_passes(self):
|
|
for outcome in ('NotExecuted', 'Failed', 'Inconclusive'):
|
|
with self.subTest(outcome=outcome), tempfile.TemporaryDirectory() as folder:
|
|
root = Path(folder); document = self.fixture(root); self.trx(root, outcome)
|
|
report = gate.reconcile(document, {'Example.Cases.Case': ['Example.Cases.Case']}, gate.result_rows(root), root)
|
|
self.assertFalse(report['passed'])
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
root = Path(folder); document = self.fixture(root); self.trx(root)
|
|
(root / document['obligations'][0]['tests'][0]['source']).unlink()
|
|
report = gate.reconcile(document, {'Example.Cases.Case': ['Example.Cases.Case']}, gate.result_rows(root), root)
|
|
self.assertFalse(report['passed'])
|
|
self.assertEqual(len(report['source_gaps']), 1)
|
|
|
|
def test_unexpected_method_is_a_failure(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
root = Path(folder); document = self.fixture(root); self.trx(root)
|
|
rows = gate.result_rows(root)
|
|
rows.append({**rows[0], 'selector': 'Example.Cases.Other'})
|
|
self.assertFalse(gate.reconcile(document, {'Example.Cases.Case': ['Example.Cases.Case']}, rows, root)['passed'])
|
|
|
|
def test_packet_rechecks_real_trx_hash_and_candidate_not_just_passed_bit(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
root = Path(folder); document = self.fixture(root); trx = self.trx(root)
|
|
registry = root / 'registry.json'; registry.write_text(json.dumps(document))
|
|
packet = root / 'packet.json'
|
|
identity = {'input_sha256': 'same-candidate', 'runtime_source_tree_hash': 'runtime', 'files': {}}
|
|
payload = {'schema_version': 1, 'passed': True, 'registry_sha256': gate.digest(registry), 'identity': identity,
|
|
'discovery': {'Example.Cases.Case': ['Example.Cases.Case']}, 'command_exit_codes': {'0-discovery': 0, '0-test': 0},
|
|
'trx_files': {str(trx.resolve()): gate.digest(trx)}}
|
|
gate.private_json(packet, payload)
|
|
real_reconcile = gate.reconcile
|
|
with patch.object(gate, 'registry', return_value=document), patch.object(gate, 'input_identity', return_value=identity), patch.object(gate, 'reconcile', side_effect=lambda d, n, r: real_reconcile(d, n, r, root)):
|
|
self.assertTrue(gate.checked_packet(packet, registry)['passed'])
|
|
self.trx(root, 'NotExecuted')
|
|
with self.assertRaises(gate.AdversarialError): gate.checked_packet(packet, registry)
|
|
payload['trx_files'][str(trx.resolve())] = gate.digest(trx)
|
|
packet.write_text(json.dumps(payload))
|
|
with self.assertRaises(gate.AdversarialError): gate.checked_packet(packet, registry)
|
|
self.trx(root)
|
|
payload['trx_files'][str(trx.resolve())] = gate.digest(trx)
|
|
payload['identity'] = {'input_sha256': 'old-candidate'}
|
|
packet.write_text(json.dumps(payload))
|
|
with self.assertRaises(gate.AdversarialError): gate.checked_packet(packet, registry)
|
|
|
|
def test_invalid_registry_patterns_or_missing_obligations_fail(self):
|
|
document = gate.registry()
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
path = Path(folder) / 'registry.json'
|
|
for mutate in ('pattern', 'missing'):
|
|
modified = copy.deepcopy(document)
|
|
if mutate == 'pattern': modified['obligations'][0]['tests'][0]['selector'] += '*'
|
|
else: modified['obligations'].pop()
|
|
path.write_text(json.dumps(modified))
|
|
with self.assertRaises(gate.AdversarialError): gate.registry(path)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|