forked from datacamp/pythonwhat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprobe.py
More file actions
252 lines (214 loc) · 8.62 KB
/
probe.py
File metadata and controls
252 lines (214 loc) · 8.62 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import pprint as pp
import itertools
import inspect
from functools import partial
from collections import OrderedDict
TEST_NAMES = [
"test_mc",
"test_or",
"test_with",
"test_list_comp",
"test_dict_comp",
"test_generator_exp",
"test_import",
"test_object",
"test_correct",
"test_if_else",
"test_if_exp",
"test_for_loop",
"test_function",
"test_print",
"test_function_v2",
"test_operator",
"test_try_except",
"test_data_frame",
"test_dictionary",
"test_while_loop",
"test_student_typed",
"test_object_accessed",
"test_output_contains",
"test_lambda_function",
"test_expression_result",
"test_expression_output",
"test_function_definition",
"test_object_after_expression"
]
SUB_TESTS = {
"test_if_else": ['test', 'body', 'orelse'],
"test_if_exp": ['test', 'body', 'orelse'],
"test_list_comp": ['comp_iter', 'body', 'ifs'],
"test_dict_comp": ['comp_iter', 'key', 'value', 'ifs'],
"test_correct": ['check', 'diagnose'],
"test_generator_exp": ['comp_iter', 'body', 'ifs'],
"test_for_loop": ['for_iter', 'body', 'orelse'],
"test_try_except": ['body', 'handlers', 'orelse', 'finalbody'],
"test_while_loop": ['test', 'body', 'orelse'],
"test_with": ['context_tests', 'body'],
"test_function_definition": ['body'],
"test_or": ['tests'],
"test_lambda_function": ['body']
}
class Tree(object):
def __init__(self):
"""
Represent a tree of nodes, by holding the currently active node.
This class is necessary to put sub-tests onto a graph, because they may
exist inside of function calls. By getting the currently active node
from the tree, Probe instances may add subtests as children on that node,
and update it when recursing over sub-tests.
"""
self.root = Node(name="root")
self.crnt_node = self.root
@classmethod
def str_branch(cls, node, str_func=lambda s: ""):
f = node.data.get('func')
this_node = " "*node.depth + getattr(f, '__name__', node.name) + str_func(node) + "\n"
return this_node + "".join(map(lambda x: cls.str_branch(x, str_func), node.child_list))
def __str__(self):
return self.str_branch(self.crnt_node)
def descend(self, node=None):
node = self.crnt_node if node is None else node
children = map(self.descend, node.child_list)
base = [node] if node.name != "root" else []
return sum(children, base)
def __iter__(self):
for ii in self.descend(self.crnt_node): yield ii
class Node(object):
def __init__(self, child_list = None, data = None, name="unnamed", arg_name=""):
"""
Hold a function call with its bound arguments, along with child nodes.
"""
self.parent = None
self.name = name
self.arg_name = arg_name
self.child_list = [] if child_list is None else child_list
self.data = {} if data is None else data
self.updated = False
# hacky way to add their argument name when a function of tests was given
def __call__(self, state=None):
"""Call original function with its arguments, and optional state"""
ba = self.data['bound_args']
if state:
self.data['func'](state=state, *ba.args, **ba.kwargs)
return state
else:
self.data['func'](*ba.args, **ba.kwargs)
ba.apply_defaults()
return ba.arguments['state']
def __iter__(self):
return iter(self.child_list)
def partial(self):
"""Return partial of original function call"""
ba = self.data['bound_args']
return partial(self.data['func'], *ba.args, **ba.kwargs)
def update_child_calls(self):
"""Replace child nodes on original function call with their partials"""
for node in filter(lambda n: len(n.arg_name), self.child_list):
self.data['bound_args'].arguments[node.arg_name] = node.partial()
self.updated = True
def remove_child(self, node):
indx = self.child_list.index(node)
del self.child_list[indx]
return indx
def add_child(self, child):
# since it is a tree, there is only one parent
# note this means we do not allow edges between same layer units
if child.parent: child.parent.remove_child(child)
child.parent = self
self.child_list.append(child)
def descend(self, include_me=True):
"""Descend depth first into all child nodes"""
if include_me: yield self
for child in self.child_list:
yield child
yield from child.descend()
@property
def depth(self):
if self.parent: return self.parent.depth + 1
else: return 0
def __str__(self):
# TODO print function signature without defaults (or with)
return pp.pformat(self.data)
def __iter__(self):
for c in self.child_list: yield c
class NodeList(Node):
def partial(self):
return [node.partial() for node in self.child_list]
def update_child_calls(self):
pass
class NodeDict(Node):
def partial(self):
return OrderedDict((node.arg_name, node.partial()) for node in self.child_list)
def update_child_calls(self):
pass
class Probe(object):
def __init__(self, tree, f, eval_on_call=False):
self.tree = tree
self.f = f
self.test_name = f.__name__
self.eval_on_call = eval_on_call
# TODO: auto sub_test detection
self.sub_tests = SUB_TESTS.get(self.test_name) or []
def __call__(self, *args, **kwargs):
"""Bind arguments to original function signature, and store in a Node
This is used to discover what tests and sub-tests the SCT would like to
call, and defer them for later execution via their node instance. Node
instances are assembled into a tree.
"""
bound_args = inspect.signature(self.f).bind(*args, **kwargs)
data = dict(
bound_args = bound_args,
func = self.f)
this_node = Node(data=data, name=self.test_name)
if self.tree is not None:
self.tree.crnt_node.add_child(this_node)
# First pass to set up branches off node
da = bound_args.arguments
for st in self.sub_tests: # TODO: auto sub test detection
if st in da and da[st]:
self.build_sub_test_nodes(da[st], self.tree, this_node, st)
# Second pass to build node and all its children into a subtest
for n in this_node.descend(include_me=True):
if n.updated: # already built, e.g. node used multiple times
continue
else:
n.update_child_calls()
if self.eval_on_call: return this_node()
else: return this_node
@staticmethod
def build_sub_test_nodes(test, tree, node, arg_name):
# note that I've made the strong assumption that
# if not a function, then test is a dict, list or tuple of them
if isinstance(test, dict):
nd = NodeDict(name = "Dict", arg_name = arg_name)
node.add_child(nd)
for k, f in test.items(): Probe.build_sub_test_nodes(f, tree, nd, k)
elif isinstance(test, (list, tuple)):
nl = NodeList(name = "List", arg_name = arg_name)
node.add_child(nl)
for ii, f in enumerate(test): Probe.build_sub_test_nodes(f, tree, nl, str(ii))
elif isinstance(test, Node):
# test was a lambdaless subtest call, which produced a node
# so need to tell it what its arg_name was on parent test
test.arg_name = arg_name
node.add_child(test)
elif callable(test):
# test was inside a lambda or function containing subtests
# since either may contain multiple subtests, we put them in a node list
nl = NodeList(name = "ListDeferred", arg_name = arg_name)
node.add_child(nl)
if tree is not None:
prev_node, tree.crnt_node = tree.crnt_node, nl
test()
tree.crnt_node = prev_node
else:
test()
elif test is not None:
raise Exception("Expected a function or list/tuple/dict of functions")
def create_test_probes(context):
tree = Tree()
all_tests = [context[s] for s in TEST_NAMES]
new_context = {f.__name__: Probe(tree, f) for f in all_tests}
new_context.update({k:v for k,v in context.items() if k not in new_context})
#new_context['success_msg'] = lambda s: s
return tree, new_context