472 lines
22 KiB
Python
472 lines
22 KiB
Python
# #region Test.PytestWatchdog [C:3] [TYPE Module] [SEMANTICS test,pytest,watchdog,timeout,subprocess]
|
|
# @BRIEF Real short-lived subprocess hangs verify deadline termination, private diagnostics and normal watcher cleanup without database access.
|
|
# @INVARIANT Controlled timeout is an expected assertion only inside these tooling guards; no product outcome becomes PASS.
|
|
from hashlib import sha256
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
import pytest
|
|
|
|
BACKEND = Path(__file__).resolve().parents[2]
|
|
ROOT = BACKEND.parent
|
|
|
|
|
|
def _environment(evidence, *, suite='3', stage='0.25'):
|
|
environment = {**os.environ, 'PYTHONPATH':str(BACKEND), 'PYTEST_DISABLE_PLUGIN_AUTOLOAD':'1',
|
|
'PYTEST_WATCHDOG_EVIDENCE_DIR':str(evidence), 'PYTEST_WATCHDOG_SUITE_SECONDS':suite,
|
|
'PYTEST_WATCHDOG_STAGE_SECONDS':stage}
|
|
# Child pytest runs are standalone tools, not descendants of the parent's owned xdist worker.
|
|
for name in (
|
|
'PYTEST_ADDOPTS',
|
|
'PYTEST_WORKER_PG_RUN_ID', 'PYTEST_WORKER_PG_RUN_MANIFEST', 'PYTEST_WORKER_PG_STORAGE_ROOT',
|
|
'PYTEST_XDIST_WORKER', 'PYTEST_XDIST_TESTRUNUID', 'PYTEST_XDIST_WORKER_COUNT',
|
|
):
|
|
environment.pop(name, None)
|
|
return environment
|
|
|
|
|
|
def test_child_environment_drops_parent_worker_context_only(monkeypatch, tmp_path):
|
|
worker_context = {
|
|
'PYTEST_WORKER_PG_RUN_ID': 'parent-run',
|
|
'PYTEST_WORKER_PG_RUN_MANIFEST': '/private/parent/manifest.json',
|
|
'PYTEST_WORKER_PG_STORAGE_ROOT': '/private/parent/storage',
|
|
'PYTEST_XDIST_WORKER': 'gw7',
|
|
'PYTEST_XDIST_TESTRUNUID': 'parent-run',
|
|
'PYTEST_XDIST_WORKER_COUNT': '16',
|
|
}
|
|
for name, value in worker_context.items():
|
|
monkeypatch.setenv(name, value)
|
|
monkeypatch.setenv('DATABASE_URL', 'postgresql://test.invalid/parent')
|
|
monkeypatch.setenv('PG_CONSUMER_CONNECTION_FILE', '/private/parent/descriptor.json')
|
|
|
|
child = _environment(tmp_path / 'evidence')
|
|
|
|
assert not worker_context.keys() & child.keys()
|
|
assert child['DATABASE_URL'] == 'postgresql://test.invalid/parent'
|
|
assert child['PG_CONSUMER_CONNECTION_FILE'] == '/private/parent/descriptor.json'
|
|
assert all(os.environ[name] == value for name, value in worker_context.items())
|
|
|
|
|
|
def _diagnostic_project(project):
|
|
"""Opt these controlled children into the diagnostic watchdog explicitly."""
|
|
(project / 'diagnostic_watchdog.py').write_text('''from pytest_watchdog import start_direct_watchdog, watchdog_plugins
|
|
watchdog = start_direct_watchdog()
|
|
def pytest_configure(config):
|
|
config.pluginmanager.register(watchdog_plugins(watchdog)[0], 'bounded_watchdog')
|
|
''')
|
|
(project / 'pytest.ini').write_text('[pytest]\naddopts = -p diagnostic_watchdog -p pytest_early\n')
|
|
|
|
|
|
def _run(command, *, cwd, env):
|
|
started = time.monotonic()
|
|
result = subprocess.run(command, cwd=cwd, env=env, capture_output=True, text=True, timeout=8)
|
|
assert time.monotonic() - started < 8
|
|
return result
|
|
|
|
|
|
# #region Test.PytestWatchdog.RealStages [C:3] [TYPE Function]
|
|
# @TEST_INVARIANT Actual pytest import/collection/setup/call/teardown and blocking thread join cannot outlive their independent deadlines.
|
|
@pytest.mark.parametrize('boundary', ['startup', 'collection', 'setup', 'call', 'teardown', 'join', 'shutdown'])
|
|
def test_direct_pytest_controlled_hangs_fail_with_private_all_thread_stacks(tmp_path, boundary):
|
|
project = tmp_path / 'project'
|
|
project.mkdir()
|
|
evidence = tmp_path / 'evidence'
|
|
_diagnostic_project(project)
|
|
source = '''import threading
|
|
import pytest
|
|
|
|
def block():
|
|
threading.Event().wait()
|
|
|
|
@pytest.fixture
|
|
def resource():
|
|
SETUP
|
|
yield
|
|
TEARDOWN
|
|
|
|
def test_owned(resource):
|
|
CALL
|
|
'''
|
|
source = source.replace('SETUP', 'block()' if boundary == 'setup' else 'pass')
|
|
source = source.replace('TEARDOWN', 'block()' if boundary == 'teardown' else 'pass')
|
|
source = source.replace('CALL', 'block()' if boundary == 'call' else (
|
|
'thread = threading.Thread(target=block); thread.start(); thread.join()' if boundary == 'join'
|
|
else 'threading.Thread(target=block).start()' if boundary == 'shutdown' else 'pass'))
|
|
if boundary == 'collection':
|
|
source += '\nblock()\n'
|
|
(project / 'test_owned.py').write_text(source)
|
|
command = [sys.executable, '-m', 'pytest', '--noconftest', '-q', 'test_owned.py']
|
|
if boundary == 'startup':
|
|
# A later plugin hangs after the explicitly loaded diagnostic plugin has armed.
|
|
(project / 'hang_plugin.py').write_text('import threading\nthreading.Event().wait()\n')
|
|
command += ['-p', 'hang_plugin']
|
|
result = _run(command, cwd=project, env=_environment(evidence, suite='0.6'))
|
|
assert result.returncode == -signal.SIGKILL
|
|
receipt = json.loads((evidence / 'timeout.json').read_text())
|
|
expected = 'call' if boundary == 'join' else boundary
|
|
assert receipt['error_code'] == 'FINAL_SUITE_OR_TEST_TIMEOUT' and receipt['completed'] is False
|
|
assert receipt['stage'] == expected and receipt['attempt_exit_code'] == 137
|
|
assert receipt['node_id'] == ('test_owned.py::test_owned' if expected in {'setup','call','teardown'} else None)
|
|
assert receipt['private_stacks_retained'] is True
|
|
stacks = evidence / receipt['private_stack_file']
|
|
assert stacks.stat().st_mode & 0o777 == 0o600
|
|
assert 'threading.py' in stacks.read_text() or 'Thread' in stacks.read_text()
|
|
assert sha256(stacks.read_bytes()).hexdigest() == receipt['private_stack_sha256']
|
|
summary = json.loads((evidence / 'summary.json').read_text())
|
|
armed = json.loads((evidence / 'watchdog.json').read_text())
|
|
assert summary['verification_session_id'] == receipt['verification_session_id'] == armed['verification_session_id']
|
|
assert summary['completed'] is False and summary['attempt_exit_code'] != 0
|
|
events = [json.loads(line) for line in (evidence / 'molecular.jsonl').read_text().splitlines()]
|
|
assert len(events) == 1 and events[0]['error_code'] == 'FINAL_SUITE_OR_TEST_TIMEOUT'
|
|
assert events[0]['payload']['verification_session_id'] == receipt['verification_session_id']
|
|
assert 'threading.py' not in json.dumps(events) and 'Event().wait' not in result.stdout + result.stderr
|
|
# #endregion Test.PytestWatchdog.RealStages
|
|
|
|
|
|
# #region Test.PytestWatchdog.NormalExit [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT Normal direct pytest exits with original PASS, closes its exact child and does not publish a timeout.
|
|
def test_normal_pytest_has_no_remaining_watchdog(tmp_path):
|
|
project, evidence = tmp_path / 'project', tmp_path / 'evidence'
|
|
project.mkdir()
|
|
_diagnostic_project(project)
|
|
(project / 'test_owned.py').write_text(
|
|
'def test_owned(pytestconfig):\n'
|
|
" assert not pytestconfig.pluginmanager.hasplugin('xdist')\n"
|
|
' assert 2 + 3 == 5\n'
|
|
)
|
|
result = _run([sys.executable, '-m', 'pytest', '--noconftest', '-q'], cwd=project,
|
|
env=_environment(evidence))
|
|
assert result.returncode == 0 and '1 passed' in result.stdout
|
|
status = json.loads((evidence / 'watchdog.json').read_text())
|
|
assert status['watchdog_closed'] is True and status['watchdog_exit_code'] == 0
|
|
assert not Path(f"/proc/{status['watchdog_pid']}").exists()
|
|
assert not (evidence / 'timeout.json').exists()
|
|
# #endregion Test.PytestWatchdog.NormalExit
|
|
|
|
|
|
# #region Test.PytestWatchdog.TransportIsolation [C:3] [TYPE Function]
|
|
# @TEST_INVARIANT Shared os.write faults cannot break the watchdog; actual transport refusal fails teardown after fixture cleanup and leaves the following test executable.
|
|
@pytest.mark.parametrize('fault', ['shared_os_write', 'private_transport'])
|
|
def test_transport_fault_isolation_and_teardown_cleanup(tmp_path, fault):
|
|
project, evidence = tmp_path / 'project', tmp_path / 'evidence'
|
|
project.mkdir()
|
|
_diagnostic_project(project)
|
|
source = '''import os
|
|
from pathlib import Path
|
|
import pytest
|
|
import pytest_watchdog
|
|
|
|
original_write = os.write
|
|
|
|
@pytest.fixture
|
|
def resource(monkeypatch):
|
|
yield monkeypatch
|
|
Path('finalized').write_text('fixture-finalized')
|
|
|
|
def test_fault(resource):
|
|
resource.setattr(FAULT_OWNER, FAULT_ATTRIBUTE, lambda *args: 0)
|
|
assert Path('finalized').exists() is False
|
|
|
|
def test_following():
|
|
assert Path('finalized').read_text() == 'fixture-finalized'
|
|
assert os.write is original_write
|
|
assert pytest_watchdog._transport_write is original_write
|
|
'''.replace('FAULT_OWNER', 'os' if fault == 'shared_os_write' else 'pytest_watchdog').replace(
|
|
'FAULT_ATTRIBUTE', repr('write' if fault == 'shared_os_write' else '_transport_write'))
|
|
(project / 'test_owned.py').write_text(source)
|
|
result = _run([sys.executable, '-m', 'pytest', '--noconftest', '-q', '--junitxml=report.xml'],
|
|
cwd=project, env=_environment(evidence, suite='5', stage='3'))
|
|
from xml.etree import ElementTree
|
|
cases = {case.attrib['name']: case for case in ElementTree.parse(project / 'report.xml').iter('testcase')}
|
|
assert set(cases) == {'test_fault', 'test_following'}
|
|
assert cases['test_following'].find('error') is None
|
|
assert cases['test_following'].find('failure') is None
|
|
if fault == 'shared_os_write':
|
|
assert result.returncode == 0 and cases['test_fault'].find('error') is None
|
|
assert 'FINAL_WATCHDOG_TRANSPORT_FAILED' not in result.stdout + result.stderr
|
|
else:
|
|
assert result.returncode == 1
|
|
assert 'FINAL_WATCHDOG_TRANSPORT_FAILED' in cases['test_fault'].find('error').attrib['message']
|
|
assert (project / 'finalized').read_text() == 'fixture-finalized'
|
|
status = json.loads((evidence / 'watchdog.json').read_text())
|
|
assert status['watchdog_closed'] is True and status['watchdog_exit_code'] == 0
|
|
assert not Path(f"/proc/{status['watchdog_pid']}").exists()
|
|
assert not (evidence / 'timeout.json').exists()
|
|
# #endregion Test.PytestWatchdog.TransportIsolation
|
|
|
|
|
|
# #region Test.PytestWatchdog.Burst [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT One thousand real phase messages followed by DONE reach the owned reader without transport loss or a surviving child.
|
|
def test_actual_phase_burst_completes_and_joins_owned_child(tmp_path):
|
|
evidence = tmp_path / 'evidence'
|
|
evidence.mkdir(mode=0o700)
|
|
code = '''from pathlib import Path
|
|
from pytest_watchdog import Watchdog
|
|
watchdog = Watchdog(Path(EVIDENCE), 'a'*32)
|
|
for number in range(1000):
|
|
watchdog.phase('call', 'literal::phase_burst')
|
|
watchdog.finish()
|
|
assert watchdog.child.returncode == 0
|
|
'''.replace('EVIDENCE', repr(str(evidence)))
|
|
result = _run([sys.executable, '-c', code], cwd=tmp_path,
|
|
env=_environment(evidence, suite='5', stage='3'))
|
|
assert result.returncode == 0
|
|
status = json.loads((evidence / 'watchdog.json').read_text())
|
|
assert status['watchdog_closed'] is True and status['watchdog_exit_code'] == 0
|
|
assert not Path(f"/proc/{status['watchdog_pid']}").exists()
|
|
assert not (evidence / 'timeout.json').exists()
|
|
# #endregion Test.PytestWatchdog.Burst
|
|
|
|
|
|
# #region Test.PytestWatchdog.Backpressure [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT A real full pipe with no reader progress fails within the transport bound and preserves its existing bytes.
|
|
def test_exhausted_pipe_refuses_after_bounded_wait_without_dropping_message(tmp_path):
|
|
code = '''import os, time
|
|
from pytest_watchdog import Watchdog
|
|
reader, writer = os.pipe()
|
|
os.set_blocking(writer, False)
|
|
filled = 0
|
|
try:
|
|
while True:
|
|
filled += os.write(writer, b'x'*4096)
|
|
except BlockingIOError:
|
|
pass
|
|
watchdog = Watchdog.__new__(Watchdog)
|
|
watchdog.writer = writer
|
|
started = time.monotonic()
|
|
try:
|
|
watchdog.send({'kind':'phase', 'stage':'call'})
|
|
except RuntimeError as exc:
|
|
assert str(exc) == 'FINAL_WATCHDOG_TRANSPORT_FAILED'
|
|
else:
|
|
raise AssertionError('full pipe was silently accepted')
|
|
assert 0.85 <= time.monotonic() - started < 2
|
|
os.close(writer)
|
|
assert os.read(reader, filled + 4096) == b'x'*filled
|
|
os.close(reader)
|
|
'''
|
|
result = _run([sys.executable, '-c', code], cwd=tmp_path,
|
|
env=_environment(tmp_path / 'unused-evidence'))
|
|
assert result.returncode == 0
|
|
# #endregion Test.PytestWatchdog.Backpressure
|
|
|
|
|
|
# #region Test.PytestWatchdog.InvalidDuration [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT Invalid explicit deadlines refuse before a test or watchdog child can start, never silently selecting defaults.
|
|
@pytest.mark.parametrize('value', ['0', '-1', 'nan', 'inf', '-inf', 'true', '', 'private-invalid'])
|
|
@pytest.mark.parametrize('field', ['PYTEST_WATCHDOG_STAGE_SECONDS', 'PYTEST_WATCHDOG_SUITE_SECONDS'])
|
|
def test_invalid_duration_refuses_before_collection(tmp_path, field, value):
|
|
project, evidence = tmp_path / 'project', tmp_path / 'evidence'
|
|
project.mkdir()
|
|
_diagnostic_project(project)
|
|
(project / 'test_owned.py').write_text('raise AssertionError("MUST_NOT_IMPORT")\n')
|
|
env = _environment(evidence)
|
|
env[field] = value
|
|
result = _run([sys.executable, '-m', 'pytest', '--noconftest', '-q'], cwd=project, env=env)
|
|
assert result.returncode != 0 and 'FINAL_WATCHDOG_DURATION_INVALID' in result.stderr
|
|
assert 'MUST_NOT_IMPORT' not in result.stdout + result.stderr and not evidence.exists()
|
|
# #endregion Test.PytestWatchdog.InvalidDuration
|
|
|
|
|
|
# #region Test.PytestWatchdog.SignalConflict [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT Existing Python or C-level faulthandler signal ownership is refused without changing its handler.
|
|
@pytest.mark.parametrize('owner', ['python', 'faulthandler'])
|
|
def test_existing_signal_owner_is_never_replaced(tmp_path, owner):
|
|
evidence = tmp_path / 'evidence'
|
|
evidence.mkdir(mode=0o700)
|
|
code = '''import faulthandler, signal
|
|
from pytest_watchdog import Watchdog
|
|
SIGNAL_OWNER
|
|
before = signal.getsignal(signal.SIGUSR2)
|
|
try:
|
|
Watchdog(EVIDENCE, 'a'*32)
|
|
except RuntimeError as exc:
|
|
assert str(exc) == 'FINAL_WATCHDOG_SIGNAL_CONFLICT'
|
|
else:
|
|
raise AssertionError('existing handler replaced')
|
|
assert signal.getsignal(signal.SIGUSR2) == before
|
|
'''.replace('SIGNAL_OWNER', 'signal.signal(signal.SIGUSR2, lambda *unused: None)' if owner == 'python'
|
|
else 'faulthandler.register(signal.SIGUSR2)').replace('EVIDENCE', repr(str(evidence)))
|
|
result = _run([sys.executable, '-c', code], cwd=tmp_path, env=_environment(evidence))
|
|
assert result.returncode == 0 and not (evidence / 'watchdog.json').exists()
|
|
# #endregion Test.PytestWatchdog.SignalConflict
|
|
|
|
|
|
# #region Test.PytestWatchdog.ParentEOF [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT A crashed parent closes the private pipe and the watcher exits rather than surviving to signal a reused PID.
|
|
def test_parent_crash_closes_pipe_and_watchdog_exits(tmp_path):
|
|
evidence = tmp_path / 'evidence'
|
|
evidence.mkdir(mode=0o700)
|
|
code = '''import os
|
|
from pytest_watchdog import Watchdog
|
|
Watchdog(EVIDENCE, 'b'*32)
|
|
os._exit(0)
|
|
'''.replace('EVIDENCE', repr(str(evidence)))
|
|
result = _run([sys.executable, '-c', code], cwd=tmp_path, env=_environment(evidence))
|
|
assert result.returncode == 0
|
|
status = json.loads((evidence / 'watchdog.json').read_text())
|
|
stat_path = Path(f"/proc/{status['watchdog_pid']}/stat")
|
|
def running():
|
|
try:
|
|
return stat_path.read_text().rsplit(')', 1)[1].split()[0] != 'Z'
|
|
except FileNotFoundError:
|
|
return False
|
|
deadline = time.monotonic() + 2
|
|
while running() and time.monotonic() < deadline:
|
|
time.sleep(0.025)
|
|
assert not running()
|
|
assert not (evidence / 'timeout.json').exists()
|
|
# #endregion Test.PytestWatchdog.ParentEOF
|
|
|
|
|
|
# #region Test.PytestWatchdog.WrongBirth [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT A mismatched birth token cannot signal even an existing PID after an expired deadline.
|
|
def test_expired_watchdog_never_signals_mismatched_parent_birth(tmp_path):
|
|
code = '''import json, os, subprocess, sys, time
|
|
from pathlib import Path
|
|
read, write=os.pipe()
|
|
child=subprocess.Popen([sys.executable, HELPER, '--watch', str(read)], pass_fds=(read,))
|
|
os.close(read)
|
|
os.write(write,(json.dumps({'parent_pid':os.getpid(), 'parent_birth':'not-this-process',
|
|
'started_at':time.monotonic()-10, 'suite_seconds':0.1})+'\\n').encode())
|
|
os.close(write)
|
|
assert child.wait(timeout=2)==0
|
|
'''.replace('HELPER', repr(str(BACKEND / 'pytest_watchdog.py')))
|
|
result = _run([sys.executable, '-c', code], cwd=tmp_path, env=_environment(tmp_path / 'unused'))
|
|
assert result.returncode == 0 and not (tmp_path / 'unused').exists()
|
|
# #endregion Test.PytestWatchdog.WrongBirth
|
|
|
|
|
|
# #region Test.PytestWatchdog.LateDone [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT Completing after an observed stage deadline cannot cancel timeout classification or leave a successful summary.
|
|
def test_late_done_cannot_convert_expired_deadline_to_pass(tmp_path):
|
|
evidence = tmp_path / 'evidence'
|
|
evidence.mkdir(mode=0o700)
|
|
code = '''import time
|
|
from pytest_watchdog import Watchdog
|
|
watchdog=Watchdog(EVIDENCE, 'c'*32)
|
|
watchdog.phase('call', 'literal::late_done')
|
|
time.sleep(0.2)
|
|
watchdog.finish()
|
|
'''.replace('EVIDENCE', repr(str(evidence)))
|
|
result = _run([sys.executable, '-c', code], cwd=tmp_path, env=_environment(evidence, stage='0.1'))
|
|
assert result.returncode == -signal.SIGKILL
|
|
receipt = json.loads((evidence / 'timeout.json').read_text())
|
|
assert receipt['error_code'] == 'FINAL_SUITE_OR_TEST_TIMEOUT'
|
|
assert receipt['stage'] == 'call' and receipt['node_id'] == 'literal::late_done'
|
|
# #endregion Test.PytestWatchdog.LateDone
|
|
|
|
|
|
# #region Test.PytestWatchdog.GIL [C:2] [TYPE Function]
|
|
# @TEST_INVARIANT The independent child enforces the deadline during a native call holding the parent GIL.
|
|
def test_native_gil_holding_wait_is_bounded_by_independent_process(tmp_path):
|
|
evidence = tmp_path / 'evidence'
|
|
evidence.mkdir(mode=0o700)
|
|
code = '''import ctypes, threading
|
|
from pytest_watchdog import Watchdog
|
|
watchdog=Watchdog(EVIDENCE, 'f'*32)
|
|
watchdog.phase('call', 'literal::native_gil_wait')
|
|
ctypes.PyDLL(None).sleep(30)
|
|
threading.Event().wait()
|
|
'''.replace('EVIDENCE', repr(str(evidence)))
|
|
result = _run([sys.executable, '-c', code], cwd=tmp_path, env=_environment(evidence))
|
|
assert result.returncode == -signal.SIGKILL
|
|
receipt = json.loads((evidence / 'timeout.json').read_text())
|
|
assert receipt['stage'] == 'call' and receipt['node_id'] == 'literal::native_gil_wait'
|
|
assert receipt['private_stacks_retained'] is True
|
|
# #endregion Test.PytestWatchdog.GIL
|
|
|
|
|
|
# #region Test.PytestWatchdog.StandardPytest [C:3] [TYPE Function]
|
|
# @TEST_INVARIANT The ordinary repository configuration loads official timeout/report plugins without importing or registering a project watchdog.
|
|
def test_standard_pytest_uses_official_plugins_without_project_watchdog(tmp_path):
|
|
project, evidence = tmp_path / 'project', tmp_path / 'unused-watchdog'
|
|
project.mkdir()
|
|
(project / 'test_owned.py').write_text('''import sys
|
|
def test_standard(pytestconfig):
|
|
assert pytestconfig.getini('timeout') == '180'
|
|
assert pytestconfig.getini('timeout_method') == 'signal'
|
|
assert pytestconfig.getini('timeout_func_only') is False
|
|
assert pytestconfig.getini('session_timeout') == '7200'
|
|
assert pytestconfig.pluginmanager.hasplugin('timeout')
|
|
assert pytestconfig.pluginmanager.hasplugin('pytest_reportlog')
|
|
assert not pytestconfig.pluginmanager.hasplugin('bounded_watchdog')
|
|
assert 'pytest_watchdog' not in sys.modules
|
|
''')
|
|
environment = _environment(evidence, suite='invalid', stage='invalid')
|
|
environment.pop('PYTEST_DISABLE_PLUGIN_AUTOLOAD')
|
|
result = _run([sys.executable, '-m', 'pytest', '--noconftest', '-q',
|
|
'-c', str(BACKEND / 'pyproject.toml'), str(project / 'test_owned.py')],
|
|
cwd=project, env=environment)
|
|
assert result.returncode == 0 and '1 passed' in result.stdout
|
|
assert not evidence.exists()
|
|
# #endregion Test.PytestWatchdog.StandardPytest
|
|
|
|
|
|
# #region Test.PytestWatchdog.StandardReports [C:3] [TYPE Function]
|
|
# @TEST_INVARIANT Official timeout fails a controlled call or fixture setup, runs cleanup/following tests, and writes native child reports without clobbering inherited parent evidence.
|
|
@pytest.mark.parametrize('boundary', ['setup', 'call'])
|
|
def test_standard_timeout_reports_are_owned_and_preserve_parent_evidence(tmp_path, monkeypatch, boundary):
|
|
from xml.etree import ElementTree
|
|
|
|
project, evidence = tmp_path / 'project', tmp_path / 'unused-watchdog'
|
|
project.mkdir()
|
|
parent_log, parent_junit = tmp_path / 'parent.jsonl', tmp_path / 'parent.xml'
|
|
parent_log.write_bytes(b'PARENT_REPORT_SENTINEL\n')
|
|
parent_junit.write_bytes(b'PARENT_JUNIT_SENTINEL\n')
|
|
parent_options = f'--report-log={parent_log} --junitxml={parent_junit}'
|
|
monkeypatch.setenv('PYTEST_ADDOPTS', parent_options)
|
|
environment = _environment(evidence)
|
|
assert 'PYTEST_ADDOPTS' not in environment and os.environ['PYTEST_ADDOPTS'] == parent_options
|
|
(project / 'pytest.ini').write_text('''[pytest]
|
|
addopts = -p pytest_early -p pytest_timeout -p pytest_reportlog.plugin
|
|
timeout = 0.2
|
|
timeout_method = signal
|
|
timeout_func_only = false
|
|
''')
|
|
source = '''from pathlib import Path
|
|
import threading
|
|
import pytest
|
|
|
|
@pytest.fixture
|
|
def resource(request):
|
|
request.addfinalizer(lambda: Path('finalized').write_text('closed'))
|
|
SETUP
|
|
|
|
def test_timeout(resource):
|
|
CALL
|
|
|
|
def test_following():
|
|
assert Path('finalized').read_text() == 'closed'
|
|
'''.replace('SETUP', 'threading.Event().wait()' if boundary == 'setup' else 'pass').replace(
|
|
'CALL', 'threading.Event().wait()' if boundary == 'call' else 'pass')
|
|
(project / 'test_owned.py').write_text(source)
|
|
report, junit = project / 'child.jsonl', project / 'child.xml'
|
|
result = _run([sys.executable, '-m', 'pytest', '--noconftest', '-q',
|
|
f'--report-log={report}', f'--junitxml={junit}'], cwd=project, env=environment)
|
|
assert result.returncode == 1 and 'pytest-timeout' in result.stdout
|
|
assert parent_log.read_bytes() == b'PARENT_REPORT_SENTINEL\n'
|
|
assert parent_junit.read_bytes() == b'PARENT_JUNIT_SENTINEL\n'
|
|
assert os.environ['PYTEST_ADDOPTS'] == parent_options
|
|
assert not evidence.exists()
|
|
events = [json.loads(line) for line in report.read_text().splitlines()]
|
|
assert events[0]['$report_type'] == 'SessionStart'
|
|
assert events[-1] == {'exitstatus': 1, '$report_type': 'SessionFinish'}
|
|
phases = {(event['nodeid'], event['when']): event['outcome'] for event in events
|
|
if event['$report_type'] == 'TestReport'}
|
|
assert phases['test_owned.py::test_timeout', boundary] == 'failed'
|
|
assert phases['test_owned.py::test_timeout', 'teardown'] == 'passed'
|
|
assert all(phases['test_owned.py::test_following', stage] == 'passed'
|
|
for stage in ('setup', 'call', 'teardown'))
|
|
cases = {case.attrib['name']: case for case in ElementTree.parse(junit).iter('testcase')}
|
|
assert set(cases) == {'test_timeout', 'test_following'}
|
|
assert cases['test_timeout'].find('error' if boundary == 'setup' else 'failure') is not None
|
|
assert not list(cases['test_following'])
|
|
# #endregion Test.PytestWatchdog.StandardReports
|
|
# #endregion Test.PytestWatchdog
|