blob: 57ae62cc778a5edec003864efa9ea59778c0ece0 [file] [log] [blame]
Eli Benderskyb9223602011-12-28 10:06:55 +02001#-------------------------------------------------------------------------------
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#-------------------------------------------------------------------------------
Eli Benderskyccdb5542013-03-31 14:19:21 -07009import os, sys, subprocess, tempfile
Eli Bendersky79271e92012-01-27 10:25:47 +020010from elftools.common.py3compat import bytes2str
Eli Bendersky26e41c42011-12-28 09:21:14 +020011
12
Eli Benderskyd32d7112013-04-06 07:00:00 -070013def setup_syspath():
14 """ Setup sys.path so that tests pick up local pyelftools before the
15 installed one when run from development directory.
16 """
17 if sys.path[0] != '.':
18 sys.path.insert(0, '.')
19
20
Eli Bendersky26e41c42011-12-28 09:21:14 +020021def run_exe(exe_path, args):
22 """ Runs the given executable as a subprocess, given the
23 list of arguments. Captures its return code (rc) and stdout and
24 returns a pair: rc, stdout_str
25 """
26 popen_cmd = [exe_path] + args
27 if os.path.splitext(exe_path)[1] == '.py':
Eli Benderskyccdb5542013-03-31 14:19:21 -070028 popen_cmd.insert(0, sys.executable)
Eli Bendersky26e41c42011-12-28 09:21:14 +020029 proc = subprocess.Popen(popen_cmd, stdout=subprocess.PIPE)
30 proc_stdout = proc.communicate()[0]
Eli Bendersky79271e92012-01-27 10:25:47 +020031 return proc.returncode, bytes2str(proc_stdout)
Eli Benderskyd32d7112013-04-06 07:00:00 -070032
Eli Bendersky26e41c42011-12-28 09:21:14 +020033
34def is_in_rootdir():
35 """ Check whether the current dir is the root dir of pyelftools
36 """
37 dirstuff = os.listdir('.')
38 return 'test' in dirstuff and 'elftools' in dirstuff
Eli Benderskyd32d7112013-04-06 07:00:00 -070039
Eli Benderskyb9223602011-12-28 10:06:55 +020040
41def dump_output_to_temp_files(testlog, *args):
42 """ Dumps the output strings given in 'args' to temp files: one for each
43 arg.
44 """
45 for i, s in enumerate(args):
46 fd, path = tempfile.mkstemp(
47 prefix='out' + str(i + 1) + '_',
48 suffix='.stdout')
49 file = os.fdopen(fd, 'w')
50 file.write(s)
51 file.close()
52 testlog.info('@@ Output #%s dumped to file: %s' % (i + 1, path))
Eli Benderskyd32d7112013-04-06 07:00:00 -070053