]> arthur.barton.de Git - bup.git/blob - buptest.py
Move exc, exo, and logcmd to buptest.py
[bup.git] / buptest.py
1
2 from __future__ import print_function
3 from contextlib import contextmanager
4 from os.path import basename, dirname, realpath
5 from pipes import quote
6 from subprocess import PIPE, Popen, check_call
7 from traceback import extract_stack
8 import subprocess, sys, tempfile
9
10 from wvtest import WVPASSEQ, wvfailure_count
11
12 from bup import helpers
13
14
15 @contextmanager
16 def no_lingering_errors():
17     def fail_if_errors():
18         if helpers.saved_errors:
19             bt = extract_stack()
20             src_file, src_line, src_func, src_txt = bt[-4]
21             msg = 'saved_errors ' + repr(helpers.saved_errors)
22             print('! %-70s %s' % ('%s:%-4d %s' % (basename(src_file),
23                                                   src_line,
24                                                   msg),
25                                   'FAILED'))
26             sys.stdout.flush()
27     fail_if_errors()
28     helpers.clear_errors()
29     yield
30     fail_if_errors()
31     helpers.clear_errors()
32
33
34 # Assumes (of course) this file is at the top-level of the source tree
35 _bup_tmp = realpath(dirname(__file__) + '/t/tmp')
36 helpers.mkdirp(_bup_tmp)
37
38
39 @contextmanager
40 def test_tempdir(prefix):
41     initial_failures = wvfailure_count()
42     tmpdir = tempfile.mkdtemp(dir=_bup_tmp, prefix=prefix)
43     yield tmpdir
44     if wvfailure_count() == initial_failures:
45         subprocess.call(['chmod', '-R', 'u+rwX', tmpdir])
46         subprocess.call(['rm', '-rf', tmpdir])
47
48
49 def logcmd(cmd):
50     if isinstance(cmd, basestring):
51         print(cmd, file=sys.stderr)
52     else:
53         print(' '.join(map(quote, cmd)), file=sys.stderr)
54
55 def exc(cmd, shell=False):
56     logcmd(cmd)
57     check_call(cmd, shell=shell)
58
59 def exo(cmd, stdin=None, stdout=True, stderr=False, shell=False, check=True):
60     logcmd(cmd)
61     p = Popen(cmd,
62               stdin=None,
63               stdout=(PIPE if stdout else None),
64               stderr=PIPE,
65               shell=shell)
66     out, err = p.communicate()
67     if check and p.returncode != 0:
68         raise Exception('subprocess %r failed with status %d, stderr: %r'
69                         % (' '.join(map(quote, cmd)), p.returncode, err))
70     return out, err, p