-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathtest_framework.py
More file actions
162 lines (121 loc) · 4.53 KB
/
test_framework.py
File metadata and controls
162 lines (121 loc) · 4.53 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
from __future__ import print_function
class AssertException(Exception):
pass
def format_message(message):
return message.replace("\n", "<:LF:>")
def display(type, message, label="", mode=""):
print("\n<{0}:{1}:{2}>{3}".format(
type.upper(), mode.upper(), label, format_message(message)))
def expect(passed=None, message=None, allow_raise=False):
if passed:
display('PASSED', 'Test Passed')
else:
message = message or "Value is not what was expected"
display('FAILED', message)
if allow_raise:
raise AssertException(message)
def assert_equals(actual, expected, message=None, allow_raise=False):
equals_msg = "{0} should equal {1}".format(repr(actual), repr(expected))
if message is None:
message = equals_msg
else:
message += ": " + equals_msg
expect(actual == expected, message, allow_raise)
def assert_not_equals(actual, expected, message=None, allow_raise=False):
r_actual, r_expected = repr(actual), repr(expected)
equals_msg = "{0} should not equal {1}".format(r_actual, r_expected)
if message is None:
message = equals_msg
else:
message += ": " + equals_msg
expect(not (actual == expected), message, allow_raise)
def expect_error(message, function, exception=Exception):
passed = False
try:
function()
except exception:
passed = True
except Exception as e:
message = "{}: {} should be {}".format(message or "Unexpected exception", repr(e), repr(exception))
expect(passed, message)
def expect_no_error(message, function, exception=BaseException):
try:
function()
except exception as e:
fail("{}: {}".format(message or "Unexpected exception", repr(e)))
return
except:
pass
pass_()
def pass_(): expect(True)
def fail(message): expect(False, message)
def assert_approx_equals(
actual, expected, margin=1e-9, message=None, allow_raise=False):
msg = "{0} should be close to {1} with absolute or relative margin of {2}"
equals_msg = msg.format(repr(actual), repr(expected), repr(margin))
if message is None:
message = equals_msg
else:
message += ": " + equals_msg
div = max(abs(actual), abs(expected), 1)
expect(abs((actual - expected) / div) < margin, message, allow_raise)
'''
Usage:
@describe('describe text')
def describe1():
@it('it text')
def it1():
# some test cases...
'''
def _timed_block_factory(opening_text):
from timeit import default_timer as timer
from traceback import format_exception
from sys import exc_info
def _timed_block_decorator(s, before=None, after=None):
display(opening_text, s)
def wrapper(func):
if callable(before):
before()
time = timer()
try:
func()
except AssertionError as e:
display('FAILED', str(e))
except Exception:
fail('Unexpected exception raised')
tb_str = ''.join(format_exception(*exc_info()))
display('ERROR', tb_str)
display('COMPLETEDIN', '{:.2f}'.format((timer() - time) * 1000))
if callable(after):
after()
return wrapper
return _timed_block_decorator
describe = _timed_block_factory('DESCRIBE')
it = _timed_block_factory('IT')
def timeout(sec, user_msg=""):
def wrapper(func):
from multiprocessing import Process, Value
def wrapped(finished):
try:
func()
finished.value = 1.0
except BaseException as e:
finished.value = 1.0
fail("Should not throw any exceptions inside timeout: {}".format(repr(e)))
finished = Value('d',0.0)
# needed to know if the process crashed without any "feedback" and before any
# assertion has been done in the wrapped function or the wrapper (happens if
# the heap memory explodes)
process = Process(target=wrapped, args=(finished,))
process.start()
process.join(sec)
if process.is_alive():
msg = 'Exceeded time limit of {:.3f} seconds'.format(sec)
if user_msg:
msg += ': ' + user_msg
fail(msg)
process.terminate()
process.join()
elif not finished.value:
fail('Something went wrong: the process running the function crashed without feedback (probably saturating the available memory)')
return wrapper