Commit b22b36c53aab1fac8d392dbc67b3f33e08ba9009

Authored by Christian Herdtweck
1 parent 06c591af

tests: Move code to "run and capture" to utils

tests/olevba/test_crypto.py
... ... @@ -2,13 +2,11 @@
2 2  
3 3 import sys
4 4 import unittest
5   -import os
6 5 from os.path import join as pjoin
7   -from subprocess import check_output, CalledProcessError
8 6 import json
9 7 from collections import OrderedDict
10 8  
11   -from tests.test_utils import DATA_BASE_DIR, SOURCE_BASE_DIR
  9 +from tests.test_utils import DATA_BASE_DIR, call_and_capture
12 10  
13 11 from oletools import crypto
14 12  
... ... @@ -34,25 +32,11 @@ class OlevbaCryptoWriteProtectTest(unittest.TestCase):
34 32 """
35 33 def test_autostart(self):
36 34 """Check that autostart macro is found in xls[mb] sample file."""
37   - # create a PYTHONPATH environment var to prefer our olevba
38   - env = os.environ
39   - try:
40   - env['PYTHONPATH'] = SOURCE_BASE_DIR + os.pathsep + \
41   - os.environ['PYTHONPATH']
42   - except KeyError:
43   - env['PYTHONPATH'] = SOURCE_BASE_DIR
44   -
45 35 for suffix in 'xlsm', 'xlsb':
46 36 example_file = pjoin(
47 37 DATA_BASE_DIR, 'encrypted',
48 38 'autostart-encrypt-standardpassword.' + suffix)
49   - try:
50   - output = check_output([sys.executable, '-m', 'olevba', '-j',
51   - example_file],
52   - universal_newlines=True, env=env)
53   - except CalledProcessError as err:
54   - print(err.output)
55   - raise
  39 + output, _ = call_and_capture('olevba', args=('-j', example_file))
56 40 data = json.loads(output, object_pairs_hook=OrderedDict)
57 41 # debug: json.dump(data, sys.stdout, indent=4)
58 42 self.assertEqual(len(data), 4)
... ...
tests/test_utils/utils.py
... ... @@ -2,8 +2,10 @@
2 2  
3 3 """Utils generally useful for unittests."""
4 4  
  5 +import sys
5 6 import os
6 7 from os.path import dirname, join, abspath
  8 +from subprocess import check_output, STDOUT, CalledProcessError
7 9  
8 10  
9 11 # Base dir of project, contains subdirs "tests" and "oletools" and README.md
... ... @@ -14,3 +16,48 @@ DATA_BASE_DIR = join(PROJECT_ROOT, 'tests', 'test-data')
14 16  
15 17 # Directory with source code
16 18 SOURCE_BASE_DIR = join(PROJECT_ROOT, 'oletools')
  19 +
  20 +
  21 +def call_and_capture(module, args=None, accept_nonzero_exit=False):
  22 + """
  23 + Run module as script, capturing and returning output and return code.
  24 +
  25 + This is the best way to capture a module's stdout and stderr; trying to
  26 + modify sys.stdout/sys.stderr to StringIO-Buffers frequently causes trouble.
  27 +
  28 + Only drawback sofar: stdout and stderr are merged into one (which is
  29 + what users see on their shell as well).
  30 +
  31 + :param str module: name of module to test, e.g. `olevba`
  32 + :param args: arguments for module's main function
  33 + :param bool fail_nonzero: Raise error if command returns non-0 return code
  34 + :returns: ret_code, output
  35 + :rtype: int, str
  36 + """
  37 + # create a PYTHONPATH environment var to prefer our current code
  38 + env = os.environ.copy()
  39 + try:
  40 + env['PYTHONPATH'] = SOURCE_BASE_DIR + os.pathsep + \
  41 + os.environ['PYTHONPATH']
  42 + except KeyError:
  43 + env['PYTHONPATH'] = SOURCE_BASE_DIR
  44 +
  45 + # ensure args is a tuple
  46 + my_args = tuple(args) if args else ()
  47 +
  48 + ret_code = -1
  49 + try:
  50 + output = check_output((sys.executable, '-m', module) + my_args,
  51 + universal_newlines=True, env=env,
  52 + stderr=STDOUT)
  53 + ret_code = 0
  54 +
  55 + except CalledProcessError as err:
  56 + if accept_nonzero_exit:
  57 + ret_code = err.returncode
  58 + output = err.output
  59 + else:
  60 + print(err.output)
  61 + raise
  62 +
  63 + return output, ret_code
... ...