]> arthur.barton.de Git - bup.git/blob - test/lib/buptest/__init__.py
Update base_version to 0.34~ for 0.34 development
[bup.git] / test / lib / buptest / __init__.py
1
2 from __future__ import absolute_import, print_function
3 from collections import namedtuple
4 from os.path import abspath, basename, dirname, realpath
5 from pipes import quote
6 from subprocess import PIPE, Popen
7 from traceback import extract_stack
8 import errno, os, subprocess, sys, tempfile
9
10 from bup import helpers
11 from bup.compat import fsencode
12 from bup.io import byte_stream
13
14
15 ex_res = namedtuple('SubprocResult', ['out', 'err', 'proc', 'rc'])
16
17 def run(cmd, check=True, input=None, **kwargs):
18     """Run a subprocess as per subprocess.Popen(cmd, **kwargs) followed by
19     communicate(input=input).  If check is true, then throw an
20     exception if the subprocess exits with non-zero status.  Return a
21     SubprocResult tuple.
22
23     """
24     if input:
25         assert 'stdin' not in kwargs
26         kwargs['stdin'] = PIPE
27     p = Popen(cmd, **kwargs)
28     out, err = p.communicate(input=input)
29     if check and p.returncode != 0:
30         raise Exception('subprocess %r failed with status %d%s'
31                         % (cmd, p.returncode,
32                            (', stderr: %r' % err) if err else ''))
33     return ex_res(out=out, err=err, proc=p, rc=p.returncode)
34
35 def logcmd(cmd):
36     s = helpers.shstr(cmd)
37     if isinstance(cmd, str):
38         print(s, file=sys.stderr)
39     else:
40         # bytes - for now just escape it
41         print(s.decode(errors='backslashreplace'), file=sys.stderr)
42
43 def ex(cmd, **kwargs):
44     """Print cmd to stderr and then run it as per ex(...).
45     Print the subprocess stderr to stderr if stderr=PIPE and there's
46     any data.
47     """
48     logcmd(cmd)
49     result = run(cmd, **kwargs)
50     if result.err:
51         sys.stderr.flush()
52         byte_stream(sys.stderr).write(result.err)
53     return result
54
55 def exo(cmd, **kwargs):
56     """Print cmd to stderr and then run it as per ex(..., stdout=PIPE).
57     Print the subprocess stderr to stderr if stderr=PIPE and there's
58     any data.
59
60     """
61     assert 'stdout' not in kwargs
62     kwargs['stdout'] = PIPE
63     return ex(cmd, **kwargs)