Files
wine-access/tests/wine_test_environment_test.py

144 lines
7.3 KiB
Python

"""Check test-file retention, saved evidence, space guards and cancellation."""
from contextlib import redirect_stderr, redirect_stdout
import io
import os
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch
from wine_test_environment import run_wine_test, stop_wine_prefixes
class WineTestEnvironmentTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="wine-test-runner-check-")
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.buildDir = self.root / "build"
def run_fixture(self, source, **options):
output = io.StringIO()
with patch("wine_test_environment.tempfile.gettempdir", return_value=str(self.root)), \
redirect_stdout(output), redirect_stderr(output):
code = run_wine_test([sys.executable, "-c", source], self.buildDir,
"runner-check", minFreeMiB=0, **options)
lines = output.getvalue().splitlines()
testRoot = Path(next(line.removeprefix("Wine test directory: ")
for line in lines if line.startswith("Wine test directory: ")))
logPath = Path(next(line.removeprefix("Wine test log: ")
for line in lines if line.startswith("Wine test log: ")))
return code, testRoot, logPath.read_text()
def test_success_removes_files_but_preserves_log(self):
code, testRoot, log = self.run_fixture("print('fixture diagnostic')")
self.assertEqual(code, 0)
self.assertFalse(testRoot.exists())
self.assertIn("fixture diagnostic", log)
self.assertIn("Removed Wine test directory:", log)
def test_failure_retains_original_fixture_and_log_by_default(self):
source = "import os, pathlib; pathlib.Path(os.environ['WINE_ACCESS_TEST_ROOT'], 'evidence').write_text('fixture'); print('failure detail'); raise SystemExit(7)"
code, testRoot, log = self.run_fixture(source)
self.assertEqual(code, 7)
self.assertEqual((testRoot / "evidence").read_text(), "fixture")
self.assertIn("failure detail", log)
self.assertIn("Retained Wine test directory:", log)
def test_fixture_log_survives_successful_cleanup(self):
source = "import os, pathlib; pathlib.Path(os.environ['WINE_ACCESS_TEST_ROOT'], 'helper.log').write_text('saved helper detail')"
code, testRoot, _ = self.run_fixture(source)
self.assertEqual(code, 0)
self.assertFalse(testRoot.exists())
saved = list((self.buildDir / "Testing/WineAccessLogs").rglob("helper.log"))
self.assertEqual(len(saved), 1)
self.assertEqual(saved[0].read_text(), "saved helper detail")
def test_keep_preserves_success_and_clean_option_preserves_failure_status(self):
code, testRoot, _ = self.run_fixture("pass", keep=True)
self.assertEqual(code, 0)
self.assertTrue(testRoot.exists())
code, testRoot, log = self.run_fixture("raise SystemExit(9)", keepOnFailure=False)
self.assertEqual(code, 9)
self.assertFalse(testRoot.exists())
self.assertIn("exit status: 9", log)
def test_cli_retention_switches(self):
runner = Path(__file__).with_name("run_wine_test.py")
env = dict(os.environ, TMPDIR=str(self.root), WINE_ACCESS_TEST_KEEP="0",
WINE_ACCESS_TEST_KEEP_ON_FAILURE="1")
for flags, exitCode, retained in (([], 7, True), (["--clean-on-failure"], 7, False),
(["--keep"], 0, True)):
result = subprocess.run([sys.executable, str(runner), "--build-dir", str(self.buildDir),
"--name", "cli-check", "--min-free-mib", "0", *flags,
"--", sys.executable, "-c", f"raise SystemExit({exitCode})"],
env=env, capture_output=True, text=True, timeout=5)
self.assertEqual(result.returncode, exitCode, result.stdout + result.stderr)
root = Path(next(line.removeprefix("Wine test directory: ")
for line in result.stdout.splitlines() if line.startswith("Wine test directory: ")))
self.assertEqual(root.exists(), retained, result.stdout)
def test_timeout_stops_fixture_and_retains_its_log(self):
code, testRoot, log = self.run_fixture("import time; print('before stall', flush=True); time.sleep(60)", timeout=.2)
self.assertEqual(code, 124)
self.assertTrue(testRoot.exists())
self.assertIn("before stall", log)
self.assertIn("timed out", log)
def test_sigterm_retains_files_and_restores_signal_handlers(self):
before = signal.getsignal(signal.SIGTERM)
code, testRoot, log = self.run_fixture("import os, signal; os.kill(os.getppid(), signal.SIGTERM)")
self.assertEqual(code, 143)
self.assertTrue(testRoot.exists())
self.assertIn("interrupted", log)
self.assertEqual(signal.getsignal(signal.SIGTERM), before)
def test_descendant_holding_output_does_not_hang_runner(self):
code, testRoot, log = self.run_fixture("import subprocess; subprocess.Popen(['sleep', '60']); print('parent finished')")
self.assertEqual(code, 0)
self.assertFalse(testRoot.exists())
self.assertIn("parent finished", log)
def test_failed_teardown_overrides_cleanup_and_success(self):
with patch("wine_test_environment.stop_wine_prefixes", return_value=False):
code, testRoot, log = self.run_fixture("pass", keepOnFailure=False)
self.assertEqual(code, 1)
self.assertTrue(testRoot.exists())
self.assertIn("teardown did not finish", log)
def test_low_space_stops_before_starting_or_creating_files(self):
output = io.StringIO()
with patch("wine_test_environment.shutil.disk_usage", return_value=SimpleNamespace(free=0)), \
patch("wine_test_environment.subprocess.Popen") as launch, \
redirect_stderr(output):
code = run_wine_test(["unused"], self.buildDir, "low-space", minFreeMiB=1024)
self.assertEqual(code, 2)
launch.assert_not_called()
self.assertEqual(list(self.root.iterdir()), [])
self.assertIn("at least 1024 MiB", output.getvalue())
def test_teardown_is_limited_to_owned_prefixes(self):
testRoot = self.root / "test"
testRoot.mkdir()
ownPrefix = testRoot / "fixture" / "prefix"
ownPrefix.mkdir(parents=True)
(ownPrefix / "system.reg").touch()
with patch("wine_test_environment.subprocess.run") as run:
self.assertTrue(stop_wine_prefixes(testRoot, {"WINEPREFIX": "/unrelated-prefix"}, io.BytesIO()))
self.assertEqual(run.call_count, 2)
for call in run.call_args_list:
self.assertEqual(call.kwargs["env"]["WINEPREFIX"], str(ownPrefix))
(testRoot / "prefix").symlink_to(self.root, target_is_directory=True)
with patch("wine_test_environment.subprocess.run") as run:
self.assertFalse(stop_wine_prefixes(testRoot, {}, io.BytesIO()))
self.assertTrue(all(call.kwargs["env"]["WINEPREFIX"] == str(ownPrefix)
for call in run.call_args_list))
if __name__ == "__main__":
unittest.main()