forked from csvoss/onelinerizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntests.py
70 lines (60 loc) · 1.99 KB
/
runtests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import unittest
import os
import random
import sys
from StringIO import StringIO
from main import to_one_line
TEST_DIRECTORY = 'tests'
DEBUG = False
class TestOneLine(unittest.TestCase):
def runTest(self):
pass
def make_test(filename):
"""Return a function that verifies that the file and its onelined version
both output the same."""
def new_test(self):
with open(filename, 'r') as fi:
self.longMessage = True
original = fi.read().strip()
onelined = to_one_line(original)
self.assertEqual(capture_exec(original),
capture_exec(onelined),
msg="\n\nOnelined: "+onelined)
return new_test
class FakeStdin(object):
"""Sometimes tests use raw_input; this feeds those deterministically."""
def __init__(self):
self.counter = 0
def readline(self):
self.counter += 1
return str(self.counter)
def capture_exec(code_string):
"""Run the code with FakeStdin as stdin, return its stdout."""
random.seed(4) # for RFC 1149.5 compliance
new_stdout = StringIO()
old_stdout = sys.stdout
old_stdin = sys.stdin
sys.stdout = new_stdout
sys.stdin = FakeStdin()
namespace = {}
try:
exec code_string in namespace
except Exception as e:
import traceback
exc = traceback.format_exc()
if DEBUG:
old_stdout.write("\nFYI: test threw error %s\n" % str(type(e)(code_string + ', ' + exc)))
new_stdout.write("Error thrown.")
sys.stdout = old_stdout
sys.stdin = old_stdin
return new_stdout.getvalue()
## Monkey-patch
for subdir, dirs, files in os.walk(TEST_DIRECTORY):
for filename in files:
root, ext = os.path.splitext(filename)
if ext == '.py' and 'unimplemented' not in subdir:
setattr(TestOneLine,
'test_%s' % root,
make_test(os.path.join(subdir, filename)))
if __name__ == '__main__':
unittest.main()