Debian Codegraph @

tests/conftest.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (c) 2008-2026 Andrew Ziem.
3 #
4 # This work is licensed under the terms of the GNU GPL, version 3 or
5 # later. See the COPYING file in the top-level directory.
6
7 """
8 Under plain `pytest`, tests.TestAll's temp-dir wrapper never runs, so
9 subprocess-spawning tests (e.g. TestCLI.py) would otherwise inherit the
10 real BleachBit config dir. Set per-worker config and temporary directories
11 before any test module (and therefore bleachbit) is imported.
12
13 The worker-specific directory is also removed at interpreter exit
14 (pytest_sessionfinish is not called for --collect-only or when the session
15 is interrupted).
16 """
17
18 import atexit
19 import logging
20 import os
21 import shutil
22 import tempfile
23
24 # BleachBit's atexit handlers (delete-lock cleanup, GTK nonce cleanup) log
25 # after pytest has closed its capture streams, printing harmless
26 # "I/O operation on closed file" errors. Don't surface those.
27 logging.raiseExceptions = False
28
29 _worker = os.environ.get('PYTEST_XDIST_WORKER')
30 _options_dir = os.environ.get('BLEACHBIT_TEST_OPTIONS_DIR')
31 # The controller sets the env var before spawning workers, so every worker
32 # inherits it. Without keying on the worker id they would all share one
33 # config dir and race on the same bleachbit.ini.
34 if _worker:
35 if not _options_dir or _worker not in os.path.basename(_options_dir):
36 _options_dir = tempfile.mkdtemp(
37 prefix=f'bleachbit-test-{_worker}-', dir=_options_dir or None)
38 os.environ['BLEACHBIT_TEST_OPTIONS_DIR'] = _options_dir
39 # Give each worker a private temporary directory so that tests
40 # spawning subprocesses and Windows %TEMP%-based cleaners do
41 # not race on the shared system temp.
42 for _env_var in ('TEMP', 'TMP', 'TMPDIR'):
43 os.environ[_env_var] = _options_dir
44 tempfile.tempdir = _options_dir
45 elif not _options_dir:
46 _options_dir = tempfile.mkdtemp(prefix='bleachbit-test-master-')
47 os.environ['BLEACHBIT_TEST_OPTIONS_DIR'] = _options_dir
48
49
50 def _remove_options_dir():
51 """Remove the temporary directory created for this process."""
52 if _options_dir and os.path.isdir(_options_dir):
53 shutil.rmtree(_options_dir, ignore_errors=True)
54
55
56 # The interpreter exits without a session when pytest is interrupted or
57 # invoked with --collect-only, so sessionfinish alone would leak the
58 # directory. Clean up here as a fallback (sessionfinish below handles the
59 # normal case; a second removal is a no-op).
60 atexit.register(_remove_options_dir)
61
62
63 def pytest_sessionfinish(session, exitstatus):
64 """Clean up the temporary directory after the test session."""
65 _remove_options_dir()