Files
ss-tools/backend/tests/scripts/test_verify_dashboard_testing_scope.py

241 lines
15 KiB
Python

# #region Test.VerifyDashboardTestingScope [C:3] [TYPE Module] [SEMANTICS test,launcher,scope,backend]
# @BRIEF Exercise the exact pytest dispatch boundary without application tests or a database connection.
# @RELATION VERIFIES -> [Tooling.VerifyDashboardTestingCurrent.SuiteScope]
import importlib.util
import json
import logging
from pathlib import Path
import sys
from types import SimpleNamespace
import pytest
ROOT = Path(__file__).resolve().parents[3]
SPEC = importlib.util.spec_from_file_location('verify_scope', ROOT / 'scripts/verify_dashboard_testing_current.py')
launcher = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(launcher)
EXPECTED_API = '''catalog_publications_api dashboard_scenarios dashboard_testing
dashboard_testing_approval_guards dashboard_testing_closed_period dashboard_testing_feature037
dashboard_testing_inheritance dashboard_testing_openapi dashboard_testing_openapi_yaml
dashboard_testing_verification_api dashboard_testing_verification_persistence mcp_parity_baseline_037
reference_discovery_api reference_selection_api scenario_analytics_api scenario_artifact_content_api
scenario_artifact_routes scenario_automation_api scenario_editor_routes scenario_live_bindings_api
scenario_registry scenario_routes scenario_run_center scenario_runs_api scenario_wire_routes
structure_snapshot_routes git_repo_lifecycle_deploy_routes git_repo_lifecycle_deployment_routes
git_release_routes'''.split()
# #region Test.VerifyDashboardTestingScope.ClosedAdmission [C:2] [TYPE Function]
# @TEST_INVARIANT Missing/foreign scope refuses before source, connection, or pytest access; no selector fallback exists.
@pytest.mark.parametrize('scope', [None, 'tests', '../tests', 'backend -k auth', ''])
def test_missing_and_foreign_scope_refuse_before_io(monkeypatch, scope):
accessed = []
monkeypatch.setattr(launcher, 'check_freeze', lambda *args: accessed.append('source'))
monkeypatch.setattr(launcher, 'read_connection', lambda *args, **kwargs: accessed.append('connection'))
argv = ['launcher', '--commit', 'f'*40, '--connection-file', '/not/read',
'--expected-database', 'catalog_full_current_20261011', '--evidence-dir', '/not/created']
if scope is not None:
argv += ['--suite-scope', scope]
monkeypatch.setattr(sys, 'argv', argv)
with pytest.raises(SystemExit) as caught:
launcher.main()
assert caught.value.code == 2 and accessed == []
with pytest.raises(RuntimeError, match='^FINAL_SUITE_SCOPE_INVALID$'):
launcher.suite_selectors(scope)
# #endregion Test.VerifyDashboardTestingScope.ClosedAdmission
# #region Test.VerifyDashboardTestingScope.ExactDispatch [C:3] [TYPE Function]
# @TEST_INVARIANT Exactly one explicit pytest invocation retains the declared scope and actual nodes/stages; default integration skips are not removed or enabled.
@pytest.mark.parametrize('scope', ['dashboard', 'backend'])
@pytest.mark.parametrize('active_container', [False, True])
def test_actual_dispatch_retains_scope_and_container_boundary(tmp_path, monkeypatch, scope, active_container):
monkeypatch.syspath_prepend(str(ROOT / 'backend'))
monkeypatch.setattr(launcher, 'check_freeze', lambda *args: None)
calls = []
nodes = ['tests/test_auth.py::test_actor', 'tests/integration/test_container.py::test_live']
def item(node, skipped):
return SimpleNamespace(nodeid=node, fixturenames=['postgres_container'] if skipped or active_container else [],
iter_markers=lambda *, name: iter([object()] if skipped and name == 'skip' else []))
def dispatch(argv, *, plugins):
calls.append(argv)
assert '--run-integration' not in argv and '-k' not in argv and '-m' not in argv
plugin = plugins[0]
if active_container:
with pytest.raises(pytest.UsageError, match='^FINAL_UNPLANNED_CONTAINER_FIXTURE$'):
plugin.pytest_collection_finish(SimpleNamespace(items=[item(nodes[0], False), item(nodes[1], True)]))
return 4
plugin.pytest_collection_finish(SimpleNamespace(items=[item(nodes[0], False), item(nodes[1], True)]))
for node in nodes:
for stage in ('setup', 'call', 'teardown'):
if node == nodes[1] and stage == 'call':
continue # An unconditional setup skip has no call-stage report.
plugin.pytest_runtest_logreport(SimpleNamespace(nodeid=node, when=stage,
outcome='skipped' if node == nodes[1] and stage == 'setup' else 'passed'))
return 0
monkeypatch.setattr(pytest, 'main', dispatch)
# Real formatter and logger; dispatch must clean up only its own additions.
owners = [logging.getLogger(name) for name in ('superset_tools_app', 'cot')]
old_handlers = [owner.handlers[:] for owner in owners]
old_filters = [owner.filters[:] for owner in owners]
result = launcher.run_suite(ROOT, tmp_path, 'f'*40, launcher.SafeLogs([]),
SimpleNamespace(index=0), suite_scope=scope)
assert [owner.handlers for owner in owners] == old_handlers
assert [owner.filters for owner in owners] == old_filters
assert result == (4 if active_container else 0) and len(calls) == 1
expected = ['tests'] if scope == 'backend' else ['tests/services/dashboard_testing'] + [
'tests/api/test_' + name + '.py' for name in EXPECTED_API]
assert calls[0][calls[0].index('--junitxml=' + str(tmp_path / 'junit.xml')) + 1:] == expected
assert json.loads((tmp_path / 'nodes.json').read_text()) == nodes
summary = json.loads((tmp_path / 'summary.json').read_text())
assert summary['suite_scope'] == scope and summary['targets'] == expected and summary['collected'] == 2
events = [json.loads(line) for line in (tmp_path / 'molecular.jsonl').read_text().splitlines()]
assert all(event['payload']['verification_session_id'] == summary['verification_session_id'] for event in events)
scope_events = [event for event in events if event.get('contract_id') == 'Tooling.VerifyDashboardTestingCurrent.SuiteScope']
assert [(event['marker'], event['payload']['suite_scope']) for event in scope_events] == [('REASON', scope), ('REFLECT', scope)]
assert scope_events[1]['payload']['collected'] == 2
stages = [event for event in events if event['intent'] == 'Frozen suite node stage observed']
if not active_container:
assert len(stages) == 5 and all(event['payload']['wasxfail'] is False for event in stages)
assert summary['outcomes']['setup:skipped'] == 1
# #endregion Test.VerifyDashboardTestingScope.ExactDispatch
# #region Test.VerifyDashboardTestingScope.RealSkipAdmission [C:3] [TYPE Function]
# @TEST_INVARIANT Actual pytest applies default skip before final admission; a forbidden fixture never executes, while an active request refuses before fixture IO.
@pytest.mark.parametrize('skipped,exit_code', [(True, 0), (False, 4)])
def test_real_pytest_session_preserves_skips_and_refuses_active_container(tmp_path, monkeypatch, skipped, exit_code):
monkeypatch.syspath_prepend(str(ROOT / 'backend'))
monkeypatch.setattr(launcher, 'check_freeze', lambda *args: None)
project, evidence = tmp_path / 'project', tmp_path / 'evidence'
backend = project / 'backend'
backend.mkdir(parents=True)
evidence.mkdir()
tests = backend / 'tests'
tests.mkdir()
marker = tmp_path / 'forbidden-fixture-executed'
(backend / 'pytest.ini').write_text('[pytest]\n')
module = 'test_scope_skip.py' if skipped else 'test_scope_active.py'
(tests / module).write_text('def test_external(postgres_container):\n assert postgres_container\n')
(tests / 'conftest.py').write_text(
'import pathlib\nimport pytest\n'
'@pytest.fixture\ndef postgres_container():\n'
f' pathlib.Path({str(marker)!r}).write_text("unexpected")\n'
' raise AssertionError("FORBIDDEN_FIXTURE_EXECUTED")\n'
'@pytest.hookimpl(trylast=True)\ndef pytest_collection_modifyitems(items):\n'
+ (' for item in items:\n item.add_marker(pytest.mark.skip(reason="default integration skip"))\n'
if skipped else ' pass\n'))
monkeypatch.setenv('PYTEST_DISABLE_PLUGIN_AUTOLOAD', '1')
owners = [logging.getLogger(name) for name in ('superset_tools_app', 'cot')]
old_handlers, old_filters = [owner.handlers[:] for owner in owners], [owner.filters[:] for owner in owners]
diagnostics = launcher.PrivateFailures(evidence)
try:
result = launcher.run_suite(project, evidence, 'a'*40, launcher.SafeLogs([]), diagnostics, suite_scope='backend')
finally:
diagnostics.close()
assert [owner.handlers for owner in owners] == old_handlers
assert [owner.filters for owner in owners] == old_filters
assert result == exit_code and not marker.exists()
assert json.loads((evidence / 'nodes.json').read_text()) == ['tests/' + module + '::test_external']
summary = json.loads((evidence / 'summary.json').read_text())
assert summary['suite_scope'] == 'backend' and summary['targets'] == ['tests'] and summary['collected'] == 1
events = [json.loads(line) for line in (evidence / 'molecular.jsonl').read_text().splitlines()]
if skipped:
assert summary['outcomes'] == {'setup:skipped':1, 'teardown:passed':1}
stages = [(event['payload']['stage'], event['payload']['outcome']) for event in events
if event['intent'] == 'Frozen suite node stage observed']
assert stages == [('setup', 'skipped'), ('teardown', 'passed')]
else:
assert summary['outcomes'] == {}
assert sum(event.get('error_code') == 'FINAL_UNPLANNED_CONTAINER_FIXTURE' for event in events) == 1
# #endregion Test.VerifyDashboardTestingScope.RealSkipAdmission
# #region Test.VerifyDashboardTestingScope.BackendDatabase [C:2] [TYPE Function]
# @TEST_INVARIANT The fresh whole-backend database is a reviewed exact target, never silently substituted for either earlier database.
@pytest.mark.parametrize('expected', ['catalog_final_empty_20261010', 'catalog_full_current_20261011', 'ss_tools', None])
def test_backend_database_requires_explicit_exact_identity(tmp_path, expected):
path = tmp_path / 'connection.json'
path.write_text(json.dumps({'username':'unit', 'password':'PRIVATE_DATABASE_BINDING_SENTINEL',
'host':'127.0.0.1', 'port':15439, 'database':'catalog_backend_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_backend_current_20261011')['database'] == 'catalog_backend_current_20261011'
# #endregion Test.VerifyDashboardTestingScope.BackendDatabase
# #region Test.VerifyDashboardTestingScope.NestedSessions [C:3] [TYPE Function]
# @TEST_INVARIANT Nested dispatch hooks retain only their own explicit session IDs and cleanup never removes the outer taps or unrelated new handlers.
def test_nested_dispatch_keeps_sessions_and_owned_handler_lifetimes_separate(tmp_path, monkeypatch):
monkeypatch.setattr(launcher, 'check_freeze', lambda *unused: None)
project = tmp_path / 'project'
(project / 'backend').mkdir(parents=True)
outer, inner = tmp_path / 'outer', tmp_path / 'inner'
outer.mkdir()
inner.mkdir()
owner = logging.getLogger('superset_tools_app')
original_handlers, original_filters = owner.handlers[:], owner.filters[:]
late = logging.NullHandler()
diagnostics = [launcher.PrivateFailures(path) for path in (outer, inner)]
calls = []
def dispatch(argv, *, plugins):
plugin = plugins[0]
calls.append(argv)
if len(calls) == 1:
outer_taps = [handler for handler in owner.handlers if handler not in original_handlers]
assert len(outer_taps) == 1
owner.addHandler(late)
assert launcher.run_suite(project, inner, 'f'*40, launcher.SafeLogs([]), diagnostics[1],
suite_scope='backend', verification_session_id='b'*32) == 0
assert owner.handlers == [*original_handlers, *outer_taps, late]
plugin.pytest_collection_finish(SimpleNamespace(items=[]))
plugin.pytest_runtest_logreport(SimpleNamespace(when='call', outcome='passed', nodeid='fixture::owned'))
return 0
monkeypatch.setattr(pytest, 'main', dispatch)
try:
assert launcher.run_suite(project, outer, 'f'*40, launcher.SafeLogs([]), diagnostics[0],
suite_scope='backend', verification_session_id='a'*32) == 0
assert len(calls) == 2
assert owner.handlers == [*original_handlers, late] and owner.filters == original_filters
for path, session_id in ((outer, 'a'*32), (inner, 'b'*32)):
events = [json.loads(line) for line in (path / 'molecular.jsonl').read_text().splitlines()]
assert len(events) == 3
assert {event['payload']['verification_session_id'] for event in events} == {session_id}
assert json.loads((path / 'summary.json').read_text())['verification_session_id'] == session_id
finally:
for diagnostic in diagnostics:
diagnostic.close()
owner.removeHandler(late)
late.close()
# #endregion Test.VerifyDashboardTestingScope.NestedSessions
# #region Test.VerifyDashboardTestingScope.ExceptionCleanup [C:2] [TYPE Function]
# @TEST_INVARIANT Unexpected dispatch failure propagates, closes only owned handlers and restores the caller directory.
def test_dispatch_exception_restores_directory_and_only_owned_handlers(tmp_path, monkeypatch):
monkeypatch.setattr(launcher, 'check_freeze', lambda *unused: None)
project, evidence = tmp_path / 'project', tmp_path / 'evidence'
(project / 'backend').mkdir(parents=True)
evidence.mkdir()
previous = Path.cwd()
owners = [logging.getLogger(name) for name in ('superset_tools_app', 'cot')]
handlers = [owner.handlers[:] for owner in owners]
filters = [owner.filters[:] for owner in owners]
diagnostics = launcher.PrivateFailures(evidence)
def dispatch(*args, **kwargs):
raise RuntimeError('PRIVATE_DISPATCH_FAILURE_SENTINEL')
monkeypatch.setattr(pytest, 'main', dispatch)
try:
with pytest.raises(RuntimeError, match='^PRIVATE_DISPATCH_FAILURE_SENTINEL$'):
launcher.run_suite(project, evidence, 'f'*40, launcher.SafeLogs([]), diagnostics,
suite_scope='backend', verification_session_id='c'*32)
assert Path.cwd() == previous
assert [owner.handlers for owner in owners] == handlers
assert [owner.filters for owner in owners] == filters
assert 'PRIVATE_DISPATCH_FAILURE_SENTINEL' not in (evidence / 'molecular.jsonl').read_text()
finally:
diagnostics.close()
# #endregion Test.VerifyDashboardTestingScope.ExceptionCleanup
# #endregion Test.VerifyDashboardTestingScope