-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest_cli.py
426 lines (377 loc) · 12.8 KB
/
test_cli.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import argparse
import collections
import os
import pathlib
import re
import subprocess
import sys
import imagehash
import pytest
from PIL import Image
# Define variables used by all tests (will be filled in by pre-test fixture)
READY = False
UPDATE = False
OUTPUT_DIR = None
DATA_DIR = None
NEXTPLOT_PATH = None
# Define CLI test parameters
MapTest = collections.namedtuple(
"Test",
[
"name",
"args",
"out_img",
"out_plot",
"out_map",
"golden_log",
"golden_img",
"golden_plot",
"golden_map",
],
)
ProgressionTest = collections.namedtuple(
"Test",
[
"name",
"args",
"out_img",
"out_html",
"golden_log",
"golden_img",
"golden_html",
],
)
def _prepare_tests() -> None:
global READY, UPDATE, OUTPUT_DIR, DATA_DIR, NEXTPLOT_PATH
# If it's the first test, setup all variables
if not READY:
# Read arguments
parser = argparse.ArgumentParser(description="nextplot golden file tests")
parser.add_argument(
"--update",
dest="update",
action="store_true",
default=False,
help="updates the golden files",
)
args, _ = parser.parse_known_args() # Ignore potentially forwarded pytest args
UPDATE = args.update
# Update if requested by env var
if os.environ.get("UPDATE", "0") == "1":
UPDATE = True
# Set paths
OUTPUT_DIR = str(pathlib.Path(__file__).parent.joinpath("./output").resolve())
DATA_DIR = str(pathlib.Path(__file__).parent.joinpath("./testdata").resolve(strict=True))
NEXTPLOT_PATH = str(pathlib.Path(__file__).parent.joinpath("../plot.py").resolve(strict=True))
# Prepare output directory
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Mark as ready
READY = True
@pytest.fixture(autouse=True)
def run_around_tests() -> None:
"""
Prepare tests and clean up.
"""
_prepare_tests()
# Run a test
yield
# Clean up
# - nothing to do, we keep the output for manual inspection
def _remove_guids(data: str) -> str:
"""
Remove any GUID from an arbitrary string.
"""
return re.sub(r"[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}", "", data)
def _remove_folium_ids(data: str) -> str:
"""
Remove any folium ID from an arbitrary string.
"""
return re.sub(r"[a-f0-9]{32}", "", data)
def _run_map_test(test: MapTest) -> None:
# Clear old results
if os.path.isfile(test.out_img):
os.remove(test.out_img)
if os.path.isfile(test.out_map):
os.remove(test.out_map)
# Assemble command and arguments
base = [sys.executable, NEXTPLOT_PATH]
cmd = [*base, *test.args]
cmd.extend(
[
"--output_image",
test.out_img,
"--output_plot",
test.out_plot,
"--output_map",
test.out_map,
]
)
# Log
cmd_string = " ".join(test.args)
print(f"Invoking: {cmd_string}")
# Run command
result = subprocess.run(cmd, stdout=subprocess.PIPE)
# Expect no errors
assert result.returncode == 0
# Compare log output
output = result.stdout.decode("utf-8")
if UPDATE:
with open(test.golden_log, "w") as file:
file.write(output)
else:
expected = ""
with open(test.golden_log) as file:
expected = file.read()
assert output == expected
# Compare plot file against expectation
if UPDATE:
# Copy plot file, but replace any GUIDs
with open(test.out_plot) as fr:
with open(test.golden_plot, "w") as fw:
fw.write(_remove_guids(fr.read()))
else:
# Compare plot file
expected, got = "", ""
with open(test.golden_plot) as f:
expected = f.read()
with open(test.out_plot) as f:
got = _remove_guids(f.read())
assert got == expected
# Compare map file against expectation
if UPDATE:
# Copy map file, but replace any GUIDs
with open(test.out_map) as fr:
with open(test.golden_map, "w") as fw:
fw.write(_remove_folium_ids(fr.read()))
else:
# Compare map file
expected, got = "", ""
with open(test.golden_map) as f:
expected = f.read()
with open(test.out_map) as f:
got = _remove_folium_ids(f.read())
assert got == expected
# Compare image file against expectation
# (we cannot compare the html file, as it is not deterministic)
hash_gotten = imagehash.phash(Image.open(test.out_img))
if UPDATE:
# Update expected hash
with open(test.golden_img, "w") as f:
f.write(str(hash_gotten) + "\n")
else:
# Compare image similarity via imagehash library
hash_expected = None
with open(test.golden_img) as f:
hash_expected = imagehash.hex_to_hash(f.read().strip())
distance = hash_gotten - hash_expected
assert distance < 7, (
f"hash distance too large: {distance},\n" + f"got:\t{hash_gotten}\n" + f"want:\t{hash_expected}"
)
def _run_progression_test(test: ProgressionTest) -> None:
# Clear old results
if os.path.isfile(test.out_img):
os.remove(test.out_img)
if os.path.isfile(test.out_html):
os.remove(test.out_html)
# Assemble command and arguments
base = [sys.executable, NEXTPLOT_PATH]
cmd = [*base, *test.args]
cmd.extend(
[
"--output_png",
test.out_img,
"--output_html",
test.out_html,
]
)
# Log
cmd_string = " ".join(test.args)
print(f"Invoking: {cmd_string}")
# Run command
result = subprocess.run(cmd, stdout=subprocess.PIPE)
# Expect no errors
assert result.returncode == 0
# Compare log output
output = result.stdout.decode("utf-8")
if UPDATE:
with open(test.golden_log, "w") as file:
file.write(output)
else:
expected = ""
with open(test.golden_log) as file:
expected = file.read()
assert output == expected
# Compare html file against expectation
if UPDATE:
# Copy html file, but replace any GUIDs
with open(test.out_html) as fr:
with open(test.golden_html, "w") as fw:
fw.write(_remove_guids(fr.read()))
else:
# Compare html file
expected, got = "", ""
with open(test.golden_html) as f:
expected = f.read()
with open(test.out_html) as f:
got = _remove_guids(f.read())
assert got == expected
# Compare image file against expectation
# (we cannot compare the html file, as it is not deterministic)
hash_gotten = imagehash.phash(Image.open(test.out_img))
if UPDATE:
# Update expected hash
with open(test.golden_img, "w") as f:
f.write(str(hash_gotten) + "\n")
else:
# Compare image similarity via imagehash library
hash_expected = None
with open(test.golden_img) as f:
hash_expected = imagehash.hex_to_hash(f.read().strip())
distance = hash_gotten - hash_expected
assert distance < 7, (
f"hash distance too large: {distance},\n" + f"got:\t{hash_gotten}\n" + f"want:\t{hash_expected}"
)
def test_map_plot_cli_paris_route():
test = MapTest(
"paris-route",
[
"route",
"--input_route",
os.path.join(DATA_DIR, "paris-route.json"),
"--jpath_route",
"state.tours[*].route",
"--jpath_x",
"location[1]",
"--jpath_y",
"location[0]",
"--omit_start",
"--omit_end",
"--custom_map_tile",
'https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png,DarkMatter no labels,<a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
"--weight_route",
"4",
"--weight_points",
"4",
],
os.path.join(OUTPUT_DIR, "paris-route.plot.png"),
os.path.join(OUTPUT_DIR, "paris-route.plot.html"),
os.path.join(OUTPUT_DIR, "paris-route.html"),
os.path.join(DATA_DIR, "paris-route.json.golden"),
os.path.join(DATA_DIR, "paris-route.plot.png.golden"),
os.path.join(DATA_DIR, "paris-route.plot.html.golden"),
os.path.join(DATA_DIR, "paris-route.map.html.golden"),
)
_run_map_test(test)
def test_map_plot_cli_paris_cluster():
test = MapTest(
"paris-cluster",
[
"cluster",
"--input_cluster",
os.path.join(DATA_DIR, "paris-cluster.json"),
"--jpath_cluster",
"state.tours[*].route",
"--jpath_x",
"location[1]",
"--jpath_y",
"location[0]",
"--no_points",
"--custom_map_tile",
'https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png,DarkMatter no labels,<a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
"--weight_points",
"4",
],
os.path.join(OUTPUT_DIR, "paris-cluster.plot.png"),
os.path.join(OUTPUT_DIR, "paris-cluster.plot.html"),
os.path.join(OUTPUT_DIR, "paris-cluster.html"),
os.path.join(DATA_DIR, "paris-cluster.json.golden"),
os.path.join(DATA_DIR, "paris-cluster.plot.png.golden"),
os.path.join(DATA_DIR, "paris-cluster.plot.html.golden"),
os.path.join(DATA_DIR, "paris-cluster.map.html.golden"),
)
_run_map_test(test)
def test_map_plot_cli_paris_point():
test = MapTest(
"paris-point",
[
"point",
"--input_point",
os.path.join(DATA_DIR, "paris-point.json"),
"--jpath_point",
"state[*].tours[*].route",
"--jpath_x",
"location[1]",
"--jpath_y",
"location[0]",
"--weight_points",
"4",
],
os.path.join(OUTPUT_DIR, "paris-point.plot.png"),
os.path.join(OUTPUT_DIR, "paris-point.plot.html"),
os.path.join(OUTPUT_DIR, "paris-point.html"),
os.path.join(DATA_DIR, "paris-point.json.golden"),
os.path.join(DATA_DIR, "paris-point.plot.png.golden"),
os.path.join(DATA_DIR, "paris-point.plot.html.golden"),
os.path.join(DATA_DIR, "paris-point.map.html.golden"),
)
_run_map_test(test)
def test_map_plot_cli_paris_route_indexed():
test = MapTest(
"paris-route-indexed",
[
"route",
"--input_route",
os.path.join(DATA_DIR, "paris-route-indexed.json"),
"--jpath_route",
"state.tours[*].route",
"--input_pos",
os.path.join(DATA_DIR, "paris-pos.json"),
"--jpath_pos",
"positions",
"--jpath_x",
"",
"--jpath_y",
"",
"--custom_map_tile",
'https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png,DarkMatter no labels,<a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
"--weight_route",
"1.5",
"--weight_points",
"2",
"--swap",
],
os.path.join(OUTPUT_DIR, "paris-route-indexed.plot.png"),
os.path.join(OUTPUT_DIR, "paris-route-indexed.plot.html"),
os.path.join(OUTPUT_DIR, "paris-route-indexed.html"),
os.path.join(DATA_DIR, "paris-route-indexed.json.golden"),
os.path.join(DATA_DIR, "paris-route-indexed.plot.png.golden"),
os.path.join(DATA_DIR, "paris-route-indexed.plot.html.golden"),
os.path.join(DATA_DIR, "paris-route-indexed.map.html.golden"),
)
_run_map_test(test)
def test_progression_plot_cli_fleet_cloud_comparison():
test = ProgressionTest(
"fleet-cloud-comparison",
[
"progression",
"--input_progression",
"0.7.3," + os.path.join(DATA_DIR, "fleet-cloud-all-0.7.3.json"),
"0.8," + os.path.join(DATA_DIR, "fleet-cloud-all-0.8.json"),
"--title",
"Fleet cloud comparison",
],
os.path.join(OUTPUT_DIR, "fleet-cloud-comparison.png"),
os.path.join(OUTPUT_DIR, "fleet-cloud-comparison.html"),
os.path.join(DATA_DIR, "fleet-cloud-comparison.golden"),
os.path.join(DATA_DIR, "fleet-cloud-comparison.png.golden"),
os.path.join(DATA_DIR, "fleet-cloud-comparison.html.golden"),
)
_run_progression_test(test)
if __name__ == "__main__":
_prepare_tests()
test_map_plot_cli_paris_route()
test_map_plot_cli_paris_cluster()
test_map_plot_cli_paris_point()
test_map_plot_cli_paris_route_indexed()
test_progression_plot_cli_fleet_cloud_comparison()
print("Everything passed")