From: Rob Browning Date: Tue, 17 Nov 2020 04:41:09 +0000 (-0600) Subject: Use pytest item results to preserve tmpdirs on failure X-Git-Tag: 0.32~21^2~2 X-Git-Url: https://arthur.barton.de/gitweb/?p=bup.git;a=commitdiff_plain;h=fd450e8563c7dc7945a1e79f2c1f4b17642dd456 Use pytest item results to preserve tmpdirs on failure Signed-off-by: Rob Browning --- diff --git a/conftest.py b/conftest.py index 0507a79..9045072 100644 --- a/conftest.py +++ b/conftest.py @@ -1,12 +1,15 @@ -from __future__ import absolute_import -from os.path import basename, dirname, realpath +from __future__ import absolute_import, print_function +from os.path import basename, dirname, realpath, relpath from time import tzset from traceback import extract_stack +import errno import os import pytest +import re import subprocess import sys +import tempfile sys.path[:0] = ['lib'] @@ -27,7 +30,7 @@ def pytest_runtest_makereport(item, call): other_hooks = yield report = other_hooks.get_result() bup = item.__dict__.setdefault('bup', {}) - bup[report.when + '_report'] = report # setup, call, teardown + bup[report.when + '-report'] = report # setup, call, teardown item.bup = bup def bup_test_sort_order(item): @@ -72,11 +75,32 @@ def ephemeral_env_changes(): tzset() os.chdir(_bup_src_top) +# Assumes (of course) this file is at the top-level of the source tree +_bup_test_dir = realpath(dirname(fsencode(__file__))) + b'/test' +_bup_tmp = _bup_test_dir + b'/tmp' +try: + os.makedirs(_bup_tmp) +except OSError as e: + if e.errno != errno.EEXIST: + raise + +_safe_path_rx = re.compile(br'[^a-zA-Z0-9_-]') + @pytest.fixture() -def tmpdir(tmp_path): - try: - yield bytes(tmp_path) - finally: - subprocess.call([b'chmod', b'-R', b'u+rwX', bytes(tmp_path)]) - # FIXME: delete only if there are no errors - #subprocess.call(['rm', '-rf', tmpdir]) +def tmpdir(request): + if sys.version_info[0] > 2: + rp = realpath(fsencode(request.fspath)) + else: + rp = realpath(str(request.fspath)) + rp = relpath(rp, _bup_test_dir) + if request.function: + rp += b'-' + fsencode(request.function.__name__) + safe = _safe_path_rx.sub(b'-', rp) + tmpdir = tempfile.mkdtemp(dir=_bup_tmp, prefix=safe) + yield tmpdir + if request.node.bup['call-report'].failed: + print('\nPreserving:', b'test/' + relpath(tmpdir, _bup_test_dir), + file=sys.stderr) + else: + subprocess.call(['chmod', '-R', 'u+rwX', tmpdir]) + subprocess.call(['rm', '-rf', tmpdir])