import hashlib import importlib import json import subprocess import sys from collections import Counter from pathlib import Path import pytest APP = Path('/app') PROJECT = APP / 'vendor/project' FIXTURES = Path('/tests/fixtures') sys.path.insert(0, str(PROJECT)) def clean_number(value): return ''.join(character for character in value.upper().strip() if character not in ' -.') def gb_checksum(number): weights = (8, 7, 6, 5, 4, 3, 2, 10, 1) return sum(weight * int(digit) for weight, digit in zip(weights, number)) % 97 def independent_gb_valid(payload): if len(payload) == 5: suffix = payload[2:] if not suffix.isascii() or not suffix.isdigit(): return False, 'InvalidFormat' if payload.startswith('GD') and int(suffix) < 500: return True, None if payload.startswith('HA') and int(suffix) >= 500: return True, None return False, 'InvalidComponent' if len(payload) == 11 and payload[:6] in ('GD8888', 'HA8888'): suffix = payload[6:] if not suffix.isascii() or not suffix.isdigit(): return False, 'InvalidFormat' code = int(payload[6:9]) if payload.startswith('GD') and code >= 500: return False, 'InvalidComponent' if payload.startswith('HA') and code < 500: return False, 'InvalidComponent' if code % 97 != int(payload[9:11]): return False, 'InvalidChecksum' return True, None if len(payload) in (9, 12): if not payload.isascii() or not payload.isdigit(): return False, 'InvalidFormat' checksum = gb_checksum(payload[:9]) allowed = (0, 42, 55) if int(payload[:3]) >= 100 else (0,) return (True, None) if checksum in allowed else (False, 'InvalidChecksum') return False, 'InvalidLength' def independent_record(record): normalized = clean_number(record['vat_number']) prefix = normalized[:2] if prefix != 'XI': return { 'id': record['id'], 'input': record['vat_number'], 'prefix': prefix, 'member_state': False, 'route': None, 'compact': None, 'valid': False, 'error': 'InvalidComponent', } payload = normalized[2:] valid, error = independent_gb_valid(payload) compact = payload if payload.startswith('XI') else 'XI' + payload return { 'id': record['id'], 'input': record['vat_number'], 'prefix': prefix, 'member_state': True, 'route': 'stdnum.gb.vat', 'compact': compact, 'valid': valid, 'error': error, } def independent_report(input_payload): records = [independent_record(record) for record in input_payload['records']] route_counts = Counter(record['route'] for record in records if record['route']) return { 'output_schema_version': 'vat-compliance-report.v1', 'records': records, 'summary': { 'total': len(records), 'valid': sum(record['valid'] for record in records), 'invalid': sum(not record['valid'] for record in records), 'member_state_records': sum(record['member_state'] for record in records), 'route_counts': dict(sorted(route_counts.items())), }, } def test_gate_workspace_artifact_and_immutable_assets(): artifact = APP / 'output.json' assert artifact.is_file() report = json.loads(artifact.read_text()) contract = json.loads((APP / 'output_contract.json').read_text()) assert contract['schema_version'] == 'vat-compliance-report.v1' assert contract['artifact_path'] == '/app/output.json' assert contract['record_keys'] == [ 'id', 'input', 'prefix', 'member_state', 'route', 'compact', 'valid', 'error', ] assert contract['ordering'] == 'records preserve input order; summary.route_counts keys are sorted' assert contract['null_policy'] == 'route, compact, and error use JSON null when not applicable' assert report['output_schema_version'] == contract['output_schema_version'] assert set(report) == set(contract['required_top_level_keys']) assert len(report['records']) == 12 hashes = json.loads((FIXTURES / 'immutable_hashes.json').read_text()) for relative_path, expected_hash in hashes.items(): path = APP / relative_path assert path.is_file(), relative_path assert hashlib.sha256(path.read_bytes()).hexdigest() == expected_hash, relative_path def test_core_router_membership_and_canonicalization(): eu_vat = importlib.import_module('stdnum.eu.vat') gb_vat = importlib.import_module('stdnum.gb.vat') assert 'xi' in eu_vat.MEMBER_STATES assert 'gb' not in eu_vat.MEMBER_STATES assert eu_vat._get_cc_module('XI') is gb_vat assert eu_vat._get_cc_module('GB') is None assert eu_vat.compact(' xi-980.7806 84 ') == 'XI980780684' assert eu_vat.validate('XI 980 7806 84') == 'XI980780684' assert gb_vat.compact('XI 980 7806 84') == '980780684' assert gb_vat.validate('XI 980 7806 84') == '980780684' def test_core_private_checksum_and_special_format_matrix(): eu_vat = importlib.import_module('stdnum.eu.vat') gb_vat = importlib.import_module('stdnum.gb.vat') cases = json.loads((FIXTURES / 'private_cases.json').read_text()) for case in cases['standard'] + cases['special']: independently_valid, _ = independent_gb_valid(case['payload']) assert independently_valid is case['valid'] assert gb_vat.compact(case['number']) == case['payload'] assert gb_vat.is_valid(case['number']) is case['valid'] assert eu_vat.is_valid(case['number']) is case['valid'] if case['valid']: assert eu_vat.validate(case['number']) == 'XI' + case['payload'] def test_core_batch_workflow_matches_independent_recompute(tmp_path): input_payload = json.loads((APP / 'input/invoices.json').read_text()) submitted = json.loads((APP / 'output.json').read_text()) expected = independent_report(input_payload) assert submitted == expected regenerated = tmp_path / 'regenerated.json' subprocess.run([ sys.executable, str(APP / 'run_audit.py'), '--input', str(APP / 'input/invoices.json'), '--output', str(regenerated), ], check=True, cwd=APP, env={'PYTHONPATH': str(PROJECT)}) assert json.loads(regenerated.read_text()) == expected def test_edge_duplicate_prefix_arbitrary_prefix_and_gb_boundary(): eu_vat = importlib.import_module('stdnum.eu.vat') gb_vat = importlib.import_module('stdnum.gb.vat') assert not eu_vat.is_valid('XI XI 980 7806 84') assert not gb_vat.is_valid('XI XI 980 7806 84') assert not gb_vat.is_valid('ZZ 980 7806 84') assert not eu_vat.is_valid('GB 980 7806 84') assert gb_vat.is_valid('GB 980 7806 84') assert gb_vat.is_valid('XI GD 001') assert gb_vat.is_valid('XI HA 500') with pytest.raises(Exception) as exc_info: eu_vat.validate('XI 802 3117 81') assert type(exc_info.value).__name__ == 'InvalidChecksum'