4669cf8458a96dc4a02a31a333270b1946931211
[pyelftools.git] / test / utils.py
1 #-------------------------------------------------------------------------------
2 # test/utils.py
3 #
4 # Some common utils for tests
5 #
6 # Eli Bendersky (eliben@gmail.com)
7 # This code is in the public domain
8 #-------------------------------------------------------------------------------
9 from __future__ import print_function
10 import os, sys, subprocess, tempfile
11
12
13 def run_exe(exe_path, args=[], echo=False):
14 """ Runs the given executable as a subprocess, given the
15 list of arguments. Captures its return code (rc) and stdout and
16 returns a pair: rc, stdout_str
17 """
18 popen_cmd = [exe_path] + args
19 if os.path.splitext(exe_path)[1] == '.py':
20 popen_cmd.insert(0, sys.executable)
21 if echo:
22 print('[cmd]', ' '.join(popen_cmd))
23 proc = subprocess.Popen(popen_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
24 proc_stdout = proc.communicate()[0]
25 from elftools.common.py3compat import bytes2str
26 return proc.returncode, bytes2str(proc_stdout)
27
28
29 def is_in_rootdir():
30 """ Check whether the current dir is the root dir of pyelftools
31 """
32 return os.path.isdir('test') and os.path.isdir('elftools')
33
34
35 def dump_output_to_temp_files(testlog, filename, option, *args):
36 """ Dumps the output strings given in 'args' to temp files: one for each
37 arg. The filename and option arguments contribute to the file name,
38 so that one knows which test did the output dump come from.
39 """
40 for i, s in enumerate(args):
41 fd, path = tempfile.mkstemp(
42 prefix='out-%d-%s-%s-' % (i + 1, os.path.split(filename)[-1], option),
43 suffix='.stdout')
44 file = os.fdopen(fd, 'w')
45 file.write(s)
46 file.close()
47 testlog.info('@@ Output #%s dumped to file: %s' % (i + 1, path))