379 lines
19 KiB
Python
379 lines
19 KiB
Python
# #region Test.VerifyDashboardTestingCurrent [C:2] [TYPE Module] [SEMANTICS test,freeze,privacy,launcher]
|
|
# @BRIEF SQL-free refusal and report-privacy guards for the final one-dispatch launcher; no migration or final suite is executed.
|
|
import importlib.util
|
|
import json
|
|
import logging
|
|
from pathlib import Path
|
|
import subprocess
|
|
|
|
import pytest
|
|
|
|
ROOT = Path(__file__).resolve().parents[3]
|
|
SPEC = importlib.util.spec_from_file_location('verify_current', ROOT / 'scripts/verify_dashboard_testing_current.py')
|
|
launcher = importlib.util.module_from_spec(SPEC)
|
|
SPEC.loader.exec_module(launcher)
|
|
|
|
|
|
@pytest.mark.parametrize('changed', [
|
|
{'host':'localhost'}, {'port':5432}, {'port':True}, {'database':'ss_tools'},
|
|
{'database':'catalog_empty_v3'}, {'username':''}, {'password':None},
|
|
])
|
|
def test_foreign_or_malformed_final_connection_refuses_privately(tmp_path, changed):
|
|
path = tmp_path / 'connection.json'
|
|
config = {'username':'private-user','password':'PRIVATE_CONNECTION_SENTINEL',
|
|
'host':'127.0.0.1','port':15439,'database':'catalog_final_empty_20261010',**changed}
|
|
path.write_text(json.dumps(config))
|
|
path.chmod(0o600)
|
|
with pytest.raises(RuntimeError, match='^FINAL_CONNECTION_SCOPE_INVALID$') as failure:
|
|
launcher.read_connection(path, expected_database="catalog_final_empty_20261010")
|
|
assert failure.value.__suppress_context__
|
|
assert 'PRIVATE_CONNECTION_SENTINEL' not in str(failure.value)
|
|
|
|
|
|
def test_final_connection_requires_private_file_mode_and_exact_owned_locator(tmp_path):
|
|
path = tmp_path / 'connection.json'
|
|
config = {'username':'private-user','password':'PRIVATE_CONNECTION_SENTINEL',
|
|
'host':'127.0.0.1','port':15439,'database':'catalog_final_empty_20261010'}
|
|
path.write_text(json.dumps(config))
|
|
path.chmod(0o644)
|
|
with pytest.raises(RuntimeError, match='^FINAL_CONNECTION_FILE_MODE_INVALID$'):
|
|
launcher.read_connection(path, expected_database="catalog_final_empty_20261010")
|
|
path.chmod(0o600)
|
|
assert launcher.read_connection(path, expected_database="catalog_final_empty_20261010") == config
|
|
|
|
|
|
def test_wrong_source_commit_refuses_before_any_database_import():
|
|
with pytest.raises(RuntimeError, match='^FINAL_SOURCE_COMMIT_CONFLICT$'):
|
|
launcher.check_freeze(ROOT, '0' * 40)
|
|
|
|
|
|
def test_nearby_commit_identity_is_not_accepted():
|
|
commit = subprocess.check_output(['git','rev-parse','HEAD'], cwd=ROOT, text=True).strip()
|
|
# This guard is independent of whether the surrounding checkout is dirty.
|
|
with pytest.raises(RuntimeError, match='^FINAL_SOURCE_COMMIT_CONFLICT$'):
|
|
launcher.check_freeze(ROOT, ('1' if commit[0] != '1' else '2') + commit[1:])
|
|
|
|
|
|
def test_molecular_filter_removes_credentials_and_exception_body():
|
|
safe = launcher.SafeLogs(['PRIVATE_PASSWORD_SENTINEL', 'private-user'])
|
|
try:
|
|
raise RuntimeError('[SQL: private body] PRIVATE_PASSWORD_SENTINEL')
|
|
except RuntimeError:
|
|
import sys
|
|
record = logging.LogRecord('cot', logging.ERROR, __file__, 1,
|
|
'postgresql+psycopg2://private-user:PRIVATE_PASSWORD_SENTINEL@127.0.0.1/db', (), sys.exc_info())
|
|
record.payload = {'nested':['PRIVATE_PASSWORD_SENTINEL'], 'reason':'connection_unavailable'}
|
|
assert safe.filter(record)
|
|
projected = json.dumps({'message':record.getMessage(),'payload':record.payload,'error':record.error})
|
|
assert 'PRIVATE_PASSWORD_SENTINEL' not in projected and 'private-user' not in projected
|
|
assert '[SQL:' not in projected and 'postgresql' not in projected
|
|
assert record.exc_info is None and record.error == {'failure_type':'RuntimeError'}
|
|
assert record.payload['reason'] == 'connection_unavailable'
|
|
from src.core.cot_formatter import CotJsonFormatter
|
|
wire = CotJsonFormatter().format(record)
|
|
assert 'PRIVATE_PASSWORD_SENTINEL' not in wire and '[SQL:' not in wire and 'postgresql' not in wire
|
|
assert json.loads(wire)['error'] == {'failure_type':'RuntimeError'}
|
|
|
|
|
|
def test_junit_failure_projection_keeps_type_and_stack_without_driver_message():
|
|
try:
|
|
raise RuntimeError('postgresql://user:PRIVATE_JUNIT_SENTINEL@localhost/db [SQL: body]')
|
|
except RuntimeError as exc:
|
|
observed = launcher.safe_failure(pytest.ExceptionInfo.from_exception(exc))
|
|
projection = json.loads(observed)
|
|
assert projection['failure_type'] == 'RuntimeError'
|
|
assert projection['locations'][-1]['path'] == __file__
|
|
assert projection['locations'][-1]['line'] > 0
|
|
assert 'PRIVATE_JUNIT_SENTINEL' not in observed and '[SQL:' not in observed
|
|
|
|
|
|
def test_delayed_node_observes_locations_without_locals_or_source_and_cancels_timer():
|
|
import sys
|
|
from contextvars import ContextVar
|
|
from types import SimpleNamespace
|
|
timers, events = [], []
|
|
private = 'PRIVATE_DELAYED_NODE_SENTINEL'
|
|
trace = ContextVar('test_delay_trace', default='foreign')
|
|
|
|
class Timer:
|
|
def __init__(self, seconds, callback):
|
|
assert seconds == 60
|
|
self.callback, self.cancelled, self.started = callback, False, False
|
|
timers.append(self)
|
|
|
|
def start(self):
|
|
self.started = True
|
|
|
|
def cancel(self):
|
|
self.cancelled = True
|
|
|
|
foreign = SimpleNamespace(f_code=SimpleNamespace(co_filename='https://' + private, co_name=private),
|
|
f_lineno=7, f_back=None, f_locals={'password':private})
|
|
token = trace.set('owned-node-trace')
|
|
observer = launcher.DelayedNode(ROOT, 'tests/test_current.py::test_owned',
|
|
lambda message, **event: events.append({'trace':trace.get(), **event}), timer_factory=Timer,
|
|
frames=lambda: {1:sys._getframe(), 2:foreign})
|
|
trace.reset(token)
|
|
observer.start()
|
|
observer.stage = 'call'
|
|
timers[0].callback()
|
|
assert timers[0].started
|
|
assert len(events) == 1 and events[0]['error_code'] == 'FINAL_NODE_DELAYED'
|
|
assert events[0]['trace'] == 'owned-node-trace'
|
|
assert events[0]['payload']['stage'] == 'call'
|
|
assert {'file':'outside_source_roots','line':7,'function':'unavailable'} in events[0]['payload']['locations']
|
|
wire = json.dumps(events)
|
|
assert private not in wire and 'password' not in wire and 'https://' not in wire
|
|
observer.finish()
|
|
assert timers[0].cancelled
|
|
timers[0].callback()
|
|
assert len(events) == 1
|
|
|
|
|
|
# #region Test.VerifyDashboardTestingCurrent.ExplicitDatabase [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT The reviewed fresh target must be requested explicitly and match private configuration; no inferred old/new target is accepted.
|
|
@pytest.mark.parametrize("expected", ["catalog_final_empty_20261010", "ss_tools", "", None])
|
|
def test_new_final_database_requires_exact_explicit_binding(tmp_path, expected):
|
|
path = tmp_path / "connection.json"
|
|
path.write_text(json.dumps({"username": "unit-user", "password": "PRIVATE_BINDING_SENTINEL",
|
|
"host": "127.0.0.1", "port": 15439, "database": "catalog_full_current_20261011"}))
|
|
path.chmod(0o600)
|
|
with pytest.raises(RuntimeError, match="^FINAL_CONNECTION_SCOPE_INVALID$"):
|
|
launcher.read_connection(path, expected_database=expected)
|
|
assert launcher.read_connection(path, expected_database="catalog_full_current_20261011")["database"] == "catalog_full_current_20261011"
|
|
# #endregion Test.VerifyDashboardTestingCurrent.ExplicitDatabase
|
|
|
|
|
|
# #region Test.VerifyDashboardTestingCurrent.MissingDatabase [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT Missing explicit target refuses before source or database access.
|
|
def test_missing_expected_database_cli_never_reaches_database(monkeypatch, tmp_path):
|
|
import sys
|
|
from unittest.mock import Mock
|
|
source = Mock(side_effect=AssertionError("source must not be read"))
|
|
connection = Mock(side_effect=AssertionError("database must not be read"))
|
|
monkeypatch.setattr(launcher, "check_freeze", source)
|
|
monkeypatch.setattr(launcher, "read_connection", connection)
|
|
monkeypatch.setattr(sys, "argv", ["verify-current", "--commit", "a" * 40, "--suite-scope", "dashboard",
|
|
"--connection-file", str(tmp_path / "connection.json"), "--evidence-dir", str(tmp_path / "evidence")])
|
|
with pytest.raises(SystemExit) as failure:
|
|
launcher.main()
|
|
assert failure.value.code == 2
|
|
source.assert_not_called()
|
|
connection.assert_not_called()
|
|
# #endregion Test.VerifyDashboardTestingCurrent.MissingDatabase
|
|
|
|
|
|
# #region Test.VerifyDashboardTestingCurrent.ClonedBusinessLogs [C:3] [TYPE Function]
|
|
# @TEST_INVARIANT Private verification events never enter app handlers; evidence redaction cannot mutate the original record or nested payload.
|
|
def test_private_emitter_clones_business_records_and_preserves_original_handlers(tmp_path):
|
|
import sys
|
|
from src.core.cot_formatter import CotJsonFormatter
|
|
received = []
|
|
|
|
class Capture(logging.Handler):
|
|
def emit(self, record):
|
|
received.append(record)
|
|
|
|
owner = logging.getLogger('superset_tools_app')
|
|
capture, late = Capture(), logging.NullHandler()
|
|
original_handlers, original_filters = owner.handlers[:], owner.filters[:]
|
|
format_exception = logging.Formatter.formatException
|
|
owner.addHandler(capture)
|
|
try:
|
|
try:
|
|
raise RuntimeError('PRIVATE_BUSINESS_EXCEPTION_SENTINEL')
|
|
except RuntimeError:
|
|
record = logging.LogRecord(owner.name, logging.ERROR, __file__, 1,
|
|
'business %s', ('PRIVATE_BUSINESS_VALUE_SENTINEL',), sys.exc_info())
|
|
payload = {'nested':['PRIVATE_BUSINESS_VALUE_SENTINEL']}
|
|
record.payload = payload
|
|
before = record.__dict__.copy()
|
|
with launcher.VerificationEvents(tmp_path, launcher.SafeLogs([
|
|
'PRIVATE_BUSINESS_VALUE_SENTINEL']), '3'*32) as events:
|
|
with launcher.business_logs(events):
|
|
events.reflect('Only the private verification sink receives this event')
|
|
launcher.BusinessTap(events.handler).handle(record)
|
|
assert record.__dict__ == before and record.payload is payload
|
|
owner.addHandler(late)
|
|
# Existing standard handlers may populate message/exc_text themselves.
|
|
# Their original exception formatting must remain available after the tap closes.
|
|
owner.handle(record)
|
|
assert received == [record]
|
|
assert record.payload is payload
|
|
assert record.exc_info is before['exc_info'] and record.args == ('PRIVATE_BUSINESS_VALUE_SENTINEL',)
|
|
assert 'PRIVATE_BUSINESS_EXCEPTION_SENTINEL' in CotJsonFormatter().format(record)
|
|
assert owner.handlers == [*original_handlers, capture, late]
|
|
assert owner.filters == original_filters and logging.Formatter.formatException is format_exception
|
|
wire = [json.loads(line) for line in (tmp_path / 'molecular.jsonl').read_text().splitlines()]
|
|
assert wire[0]['payload']['verification_session_id'] == '3'*32
|
|
assert 'verification_session_id' not in wire[1]['payload']
|
|
assert wire[1]['error'] == {'failure_type':'RuntimeError'}
|
|
assert wire[1]['payload'] == {'nested':['[private]']}
|
|
assert all('PRIVATE_BUSINESS_' not in json.dumps(event) for event in wire)
|
|
finally:
|
|
owner.removeHandler(capture)
|
|
owner.removeHandler(late)
|
|
capture.close()
|
|
late.close()
|
|
# #endregion Test.VerifyDashboardTestingCurrent.ClonedBusinessLogs
|
|
|
|
|
|
# #region Test.VerifyDashboardTestingCurrent.RealReportIntegrity [C:3] [TYPE Function]
|
|
# @TEST_INVARIANT Installed pytest retains actual pass/fail/setup-failure/skip phases privately without contaminating app logger guards or leaking exception bodies.
|
|
def test_real_mini_pytest_keeps_application_wire_and_private_failure_causes(tmp_path, monkeypatch):
|
|
import xml.etree.ElementTree as ET
|
|
project, evidence = tmp_path / 'project', tmp_path / 'evidence'
|
|
tests = project / 'backend/tests'
|
|
tests.mkdir(parents=True)
|
|
evidence.mkdir()
|
|
(project / 'backend/pytest.ini').write_text('[pytest]\n')
|
|
(tests / 'test_logging_boundary.py').write_text('''import json
|
|
import logging
|
|
import pytest
|
|
from src.core.logger import logger
|
|
from src.core.cot_formatter import CotJsonFormatter
|
|
|
|
@pytest.fixture
|
|
def wire():
|
|
received = []
|
|
class Capture(logging.Handler):
|
|
def emit(self, record):
|
|
received.append(json.loads(self.format(record)))
|
|
handler = Capture()
|
|
handler.setFormatter(CotJsonFormatter())
|
|
logger.addHandler(handler)
|
|
try:
|
|
yield received
|
|
finally:
|
|
logger.removeHandler(handler)
|
|
|
|
def test_pass(wire):
|
|
logger.reason("Owned application event", src="Test.Mini.Application")
|
|
assert len(wire) == 1
|
|
assert wire[0]["intent"] == "Owned application event"
|
|
assert "verification_session_id" not in wire[0].get("payload", {})
|
|
|
|
def test_fail():
|
|
raise RuntimeError("PRIVATE_MINI_CALL_SENTINEL")
|
|
|
|
@pytest.fixture
|
|
def broken():
|
|
raise ValueError("PRIVATE_MINI_SETUP_SENTINEL")
|
|
|
|
def test_setup_fail(broken):
|
|
raise AssertionError("CALL_MUST_NOT_EXECUTE")
|
|
|
|
@pytest.mark.skip(reason="PRIVATE_MINI_SKIP_SENTINEL")
|
|
def test_skip():
|
|
raise AssertionError("CALL_MUST_NOT_EXECUTE")
|
|
''')
|
|
monkeypatch.setattr(launcher, 'check_freeze', lambda *unused: None)
|
|
monkeypatch.setenv('PYTEST_DISABLE_PLUGIN_AUTOLOAD', '1')
|
|
diagnostics = launcher.PrivateFailures(evidence)
|
|
try:
|
|
with launcher.private_output():
|
|
code = launcher.run_suite(project, evidence, 'f'*40, launcher.SafeLogs([]),
|
|
diagnostics, suite_scope='backend', verification_session_id='4'*32)
|
|
finally:
|
|
diagnostics.close()
|
|
summary = json.loads((evidence / 'summary.json').read_text())
|
|
assert code == 1 and summary['verification_session_id'] == '4'*32
|
|
assert summary['collected'] == 4 and summary['private_failure_diagnostics'] == 2
|
|
assert summary['outcomes'] == {'setup:passed':2, 'call:passed':1, 'call:failed':1,
|
|
'setup:failed':1, 'setup:skipped':1, 'teardown:passed':4}
|
|
private = (evidence / 'private/failures.jsonl').read_text()
|
|
assert 'PRIVATE_MINI_CALL_SENTINEL' in private and 'PRIVATE_MINI_SETUP_SENTINEL' in private
|
|
events = [json.loads(line) for line in (evidence / 'molecular.jsonl').read_text().splitlines()]
|
|
verification = [event for event in events if event['src'] == 'Tooling.VerifyDashboardTestingCurrent']
|
|
assert verification and all(event['payload']['verification_session_id'] == '4'*32 for event in verification)
|
|
business = [event for event in events if event['src'] == 'Test.Mini.Application']
|
|
assert len(business) == 1 and 'verification_session_id' not in business[0].get('payload', {})
|
|
public = (evidence / 'junit.xml').read_text() + (evidence / 'summary.json').read_text() + json.dumps(events)
|
|
assert 'PRIVATE_MINI_' not in public and 'CALL_MUST_NOT_EXECUTE' not in public
|
|
junit = ET.parse(evidence / 'junit.xml')
|
|
assert len(junit.findall('.//failure')) == 1 and len(junit.findall('.//error')) == 1
|
|
assert len(junit.findall('.//skipped')) == 1 and not any(event.get('error_code') == 'FINAL_INTERNAL_ERROR' for event in events)
|
|
# #endregion Test.VerifyDashboardTestingCurrent.RealReportIntegrity
|
|
|
|
# #region Test.VerifyDashboardTestingCurrent.SessionAdmission [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT Malformed session identity and a caller-authored conflicting identity cannot create plausible verification evidence.
|
|
@pytest.mark.parametrize('session_id', [None, '', 'A'*32, 'f'*31, 1])
|
|
def test_private_emitter_refuses_malformed_or_conflicting_session_identity(tmp_path, session_id):
|
|
with pytest.raises(RuntimeError, match='^FINAL_VERIFICATION_SESSION_INVALID$'):
|
|
launcher.VerificationEvents(tmp_path, launcher.SafeLogs([]), session_id)
|
|
assert not (tmp_path / 'molecular.jsonl').exists()
|
|
with launcher.VerificationEvents(tmp_path, launcher.SafeLogs([]), 'd'*32) as events:
|
|
with pytest.raises(RuntimeError, match='^FINAL_VERIFICATION_SESSION_CONFLICT$'):
|
|
events.reason('Foreign session', payload={'verification_session_id':'e'*32})
|
|
assert (tmp_path / 'molecular.jsonl').read_text() == ''
|
|
# #endregion Test.VerifyDashboardTestingCurrent.SessionAdmission
|
|
|
|
|
|
# #region Test.VerifyDashboardTestingCurrent.ExceptionSession [C:3] [TYPE Function]
|
|
# @TEST_INVARIANT Collection/internal diagnostics and delayed callbacks retain the closure session after trace changes without exposing private exception bodies.
|
|
def test_collection_internal_and_delayed_events_keep_explicit_session(tmp_path, monkeypatch):
|
|
from types import SimpleNamespace
|
|
from src.core.cot_logger import seed_trace_id
|
|
project, evidence = tmp_path / 'project', tmp_path / 'evidence'
|
|
(project / 'backend').mkdir(parents=True)
|
|
evidence.mkdir()
|
|
monkeypatch.setattr(launcher, 'check_freeze', lambda *unused: None)
|
|
callbacks = []
|
|
|
|
class Timer:
|
|
def __init__(self, seconds, callback):
|
|
callbacks.append(callback)
|
|
|
|
def start(self):
|
|
pass
|
|
|
|
def cancel(self):
|
|
pass
|
|
|
|
def dispatch(argv, *, plugins):
|
|
plugin = plugins[0]
|
|
report = SimpleNamespace(failed=True, nodeid='fixture::collection',
|
|
longrepr='PRIVATE_COLLECTION_SENTINEL', sections=[])
|
|
plugin.retain_collection_failure(report)
|
|
assert report.longrepr == 'FINAL_COLLECTION_FAILED: fixture::collection'
|
|
with launcher.VerificationEvents(tmp_path, launcher.SafeLogs([]), 'e'*32) as foreign:
|
|
seed_trace_id()
|
|
foreign.reason('Unrelated session must not relabel callback')
|
|
callbacks[0]()
|
|
try:
|
|
raise AssertionError('PRIVATE_INTERNAL_SENTINEL')
|
|
except AssertionError as exc:
|
|
assert plugin.pytest_internalerror(None, pytest.ExceptionInfo.from_exception(exc)) is True
|
|
return 3
|
|
|
|
# Use the actual protocol callback; replace only its timer to avoid a 60-second wait.
|
|
actual_delayed = launcher.DelayedNode
|
|
def delayed(root, node, emit):
|
|
return actual_delayed(root, node, emit, timer_factory=Timer, frames=lambda: {})
|
|
original_dispatch = dispatch
|
|
def dispatch_with_protocol(argv, *, plugins):
|
|
protocol = plugins[0].pytest_runtest_protocol(SimpleNamespace(nodeid='fixture::delayed'))
|
|
next(protocol)
|
|
try:
|
|
return original_dispatch(argv, plugins=plugins)
|
|
finally:
|
|
with pytest.raises(StopIteration):
|
|
next(protocol)
|
|
monkeypatch.setattr(launcher, 'DelayedNode', delayed)
|
|
monkeypatch.setattr(pytest, 'main', dispatch_with_protocol)
|
|
diagnostics = launcher.PrivateFailures(evidence)
|
|
try:
|
|
assert launcher.run_suite(project, evidence, 'f'*40, launcher.SafeLogs([]), diagnostics,
|
|
suite_scope='backend', verification_session_id='f'*32) == 3
|
|
finally:
|
|
diagnostics.close()
|
|
events = [json.loads(line) for line in (evidence / 'molecular.jsonl').read_text().splitlines()]
|
|
assert {event['payload']['verification_session_id'] for event in events} == {'f'*32}
|
|
assert {event.get('error_code') for event in events} >= {
|
|
'FINAL_COLLECTION_FAILED', 'FINAL_INTERNAL_ERROR', 'FINAL_NODE_DELAYED'}
|
|
private = (evidence / 'private/failures.jsonl').read_text()
|
|
assert 'PRIVATE_COLLECTION_SENTINEL' in private and 'PRIVATE_INTERNAL_SENTINEL' in private
|
|
assert 'PRIVATE_' not in json.dumps(events)
|
|
# #endregion Test.VerifyDashboardTestingCurrent.ExceptionSession
|
|
# #endregion Test.VerifyDashboardTestingCurrent
|