-
Notifications
You must be signed in to change notification settings - Fork 40
/
equality_test_runs.py
249 lines (212 loc) · 7.61 KB
/
equality_test_runs.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
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
from __future__ import annotations
import typing
import flood
from . import equality_test_sets
def run_equality_test(
test_name: str,
nodes: flood.NodesShorthand,
*,
verbose: bool | int = True,
random_seed: flood.RandomSeed | None = None,
) -> None:
import json
import requests
import toolstr
nodes = flood.parse_nodes(nodes)
for node in nodes.values():
if node['remote'] is not None:
raise Exception('remote not supported for equality test')
if len(nodes) != 2:
raise Exception('should use two nodes in equality test')
# get tests
if test_name != 'all':
raise NotImplementedError('must use test_name="all" for equality test')
equality_tests = equality_test_sets.get_all_equality_tests()
# print preamble
flood.print_text_box('Running equality test')
flood.print_bullet(key='nodes', value='')
for n, node in enumerate(nodes.values()):
toolstr.print(
toolstr.add_style(str(n + 1), flood.styles['metavar'])
+ '. '
+ str(node),
indent=4,
style=flood.styles['description'],
)
flood.print_bullet(key='methods', value='')
for test in equality_tests:
flood.print_bullet(key=test[0], value='', colon_str='', indent=4)
successful = []
headers = {'Content-Type': 'application/json', 'User-Agent': 'flood'}
for test in equality_tests:
# create call
test_name, constructor, args, kwargs = test
call = constructor(*args, **kwargs)
# dispatch call
results = []
responses = []
for node in nodes.values():
response = None
try:
response = requests.post(
url=node['url'], data=json.dumps(call), headers=headers
)
response_data = response.json()
if 'result' in response_data:
result = response_data['result']
else:
result = None
except Exception:
result = None
responses.append(response)
results.append(result)
# print summary
success = _summarize_result(
responses=responses,
results=results,
nodes=nodes,
test=test,
call=call,
)
if success:
successful.append(test_name)
print()
flood.print_text_box('Equality Test Summary')
print()
flood.print_header(
'No differences detected (n = ' + str(len(successful)) + ')'
)
if len(successful) == 0:
print('[none]')
else:
for name in sorted(successful):
flood.print_bullet(key=name, value='', colon_str='')
print()
failed = [test[0] for test in equality_tests if test[0] not in successful]
flood.print_header('Differences detected (n = ' + str(len(failed)) + ')')
if len(failed) == 0:
print('[none]')
else:
for name in sorted(failed):
flood.print_bullet(key=name, value='', colon_str='')
def json_equal(lhs: typing.Any, rhs: typing.Any) -> bool:
import json
return json.dumps(lhs, sort_keys=True) == json.dumps(rhs, sort_keys=True)
def _summarize_result(
responses: typing.Sequence[typing.Any],
results: typing.Sequence[typing.Any],
nodes: flood.Nodes,
test: flood.EqualityTest,
call: typing.Mapping[str, typing.Any],
) -> bool:
import toolstr
test_name, constructor, args, kwargs = test
if not json_equal(results[0], results[1]):
print()
flood.print_text_box('Discrepancies in ' + test_name)
print()
flood.print_header('args')
if len(args) > 0:
for arg in args:
flood.print_bullet(key=arg, value='', colon_str='')
if len(kwargs) > 0:
for key, value in kwargs.items():
flood.print_bullet(key=key, value=value)
print()
flood.print_header('call')
print(call)
if any(result is None for result in results):
print()
for node, result, response in zip(nodes.values(), results, responses):
if result is None:
toolstr.print(
node['name'] + ' failed', style=flood.styles['title']
)
if response.status_code == 200:
print('response:', response.json())
else:
print('response: status code ', response.status_code)
if results[0] is None or results[1] is None:
return False
_print_result_diff(results=results, nodes=list(nodes.values()))
return False
else:
return True
def _print_result_diff(
results: typing.Sequence[typing.Any],
nodes: typing.Sequence[flood.Node],
) -> None:
import toolstr
result0 = results[0]
result1 = results[1]
if type(result0) is not type(result1):
for node, result in zip(nodes, results):
print(node['name'], 'type:', type(result))
return
if isinstance(result0, dict):
keys0 = set(result0.keys())
keys1 = set(result1.keys())
if keys0 != keys1:
only_in_0 = keys0 - keys1
only_in_1 = keys1 - keys0
print()
flood.print_header('different fields in results')
if len(only_in_0) > 0:
print(
'- present only in',
nodes[0]['name'] + ':',
', '.join(only_in_0),
)
if len(only_in_1) > 0:
print(
'- present only in',
nodes[1]['name'] + ':',
', '.join(only_in_1),
)
rows = []
for key in keys0 & keys1:
if not json_equal(result0[key], result1[key]):
row = [key, result0[key], result1[key]]
rows.append(row)
if len(rows) > 0:
print()
flood.print_header('differences in values')
flood.print_table(
rows,
labels=['field', nodes[0]['name'], nodes[1]['name']],
compact=3,
max_column_widths=[20, 30, 30],
indent=4,
)
elif isinstance(result0, list):
if len(result1) != len(result0):
print()
flood.print_header('different number of results')
for node, result in zip(nodes, results):
flood.print_bullet(
key=node['name'], value=str(len(result)) + ' results'
)
else:
import json
print('differences:')
n_printed = 0
for i, (item0, item1) in enumerate(zip(result0, result1)):
if not json_equal(item0, item1):
if n_printed >= 10:
print('...')
break
item0_str = json.dumps(item0)
if len(item0_str) > 20:
item0_str = item0_str[:17] + '...'
item1_str = json.dumps(item1)
if len(item1_str) > 20:
item1_str = item1_str[:17] + '...'
print('- item at index', i)
print(' -', nodes[0]['name'] + ':', item0_str)
print(' -', nodes[1]['name'] + ':', item1_str)
n_printed += 1
else:
if result1 != result0:
flood.print_header('differences in values')
for node, result in zip(nodes, results):
flood.print_bullet(key=node['name'], value=result)