-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdocpipeline.py
662 lines (590 loc) · 19.5 KB
/
docpipeline.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# FIXME: combine with same thing in Mathics Django
"""
Does 2 things which can either be done independently or
as a pipeline:
1. Extracts tests and runs them from static mdoc files and docstrings from Mathics
built-in functions
2. Creates/updates internal documentation data
"""
import os
import os.path as osp
import pickle
import re
import sys
from argparse import ArgumentParser
from datetime import datetime
import mathics
from mathics import version_string
from mathics.core.definitions import Definitions
from mathics.core.evaluation import Evaluation, Output
from mathics.core.load_builtin import (
builtins_by_module,
builtins_dict,
import_and_load_builtins,
)
from mathics.core.parser import MathicsSingleLineFeeder
from mathics.eval.pymathics import PyMathicsLoadException, eval_LoadModule
from mathics_django.doc import MathicsDjangoDocumentation
from mathics_django.settings import get_doctest_html_data_path
builtins = builtins_dict(builtins_by_module)
class TestOutput(Output):
def max_stored_size(self):
return None
sep = "-" * 70 + "\n"
# Global variables
definitions = None
documentation = None
check_partial_enlapsed_time = False
logfile = None
MAX_TESTS = 100000 # Number than the total number of tests
def print_and_log(*args):
a = [a.decode("utf-8") if isinstance(a, bytes) else a for a in args]
string = "".join(a)
print(string)
if logfile:
logfile.write(string)
def compare(result, wanted) -> bool:
if result == wanted:
return True
if result is None or wanted is None:
return False
result = result.splitlines()
wanted = wanted.splitlines()
if result == [] and wanted == ["#<--#"]:
return True
if len(result) != len(wanted):
return False
for r, w in zip(result, wanted):
wanted_re = re.escape(w.strip())
wanted_re = wanted_re.replace("\\.\\.\\.", ".*?")
wanted_re = "^%s$" % wanted_re
if not re.match(wanted_re, r.strip()):
return False
return True
stars = "*" * 10
def test_case(test, tests, index=0, subindex=0, quiet=False, section=None) -> bool:
global check_partial_enlapsed_time
test, wanted_out, wanted = test.test, test.outs, test.result
def fail(why):
part, chapter, section = tests.part, tests.chapter, tests.section
print_and_log(
f"""{sep}Test failed: {section} in {part} / {chapter}
{part}
{why}
""".encode(
"utf-8"
)
)
return False
if not quiet:
if section:
print(f"{stars} {tests.chapter} / {section} {stars}".encode("utf-8"))
print(f"{index:4d} ({subindex:2d}): TEST {test}".encode("utf-8"))
feeder = MathicsSingleLineFeeder(test, "<test>")
evaluation = Evaluation(definitions, catch_interrupt=False, output=TestOutput())
try:
time_parsing = datetime.now()
query = evaluation.parse_feeder(feeder)
if check_partial_enlapsed_time:
print(" parsing took", datetime.now() - time_parsing)
if query is None:
# parsed expression is None
result = None
out = evaluation.out
else:
result = evaluation.evaluate(query)
if check_partial_enlapsed_time:
print(" evaluation took", datetime.now() - time_parsing)
out = result.out
result = result.result
except Exception as exc:
fail("Exception %s" % exc)
info = sys.exc_info()
sys.excepthook(*info)
return False
time_comparing = datetime.now()
comparison_result = compare(result, wanted)
if check_partial_enlapsed_time:
print(" comparison took ", datetime.now() - time_comparing)
if not comparison_result:
print("result =!=wanted")
fail_msg = "Result: %s\nWanted: %s" % (result, wanted)
if out:
fail_msg += "\nAdditional output:\n"
fail_msg += "\n".join(str(o) for o in out)
return fail(fail_msg)
output_ok = True
time_comparing = datetime.now()
if len(wanted_out) == 1 and wanted_out[0].text == "...":
# If we have ... don't check
pass
elif len(out) != len(wanted_out):
# Mismatched number of output lines and we don't have "..."
output_ok = False
else:
# Need to check all output line by line
for got, wanted in zip(out, wanted_out):
if not got == wanted and wanted.text != "...":
output_ok = False
break
if check_partial_enlapsed_time:
print(" comparing messages took ", datetime.now() - time_comparing)
if not output_ok:
return fail(
"Output:\n%s\nWanted:\n%s"
% ("\n".join(str(o) for o in out), "\n".join(str(o) for o in wanted_out))
)
return True
def test_tests(
tests,
index,
quiet=False,
stop_on_failure=False,
start_at=0,
max_tests=MAX_TESTS,
excludes=[],
):
definitions.reset_user_definitions()
total = failed = skipped = 0
failed_symbols = set()
section = tests.section
if section in excludes:
return total, failed, len(tests.tests), failed_symbols, index
count = 0
for subindex, test in enumerate(tests.tests):
index += 1
if test.ignore:
continue
if index < start_at:
skipped += 1
continue
elif count >= max_tests:
break
total += 1
count += 1
if not test_case(test, tests, index, subindex + 1, quiet, section):
failed += 1
failed_symbols.add((tests.part, tests.chapter, tests.section))
if stop_on_failure:
break
section = None
return total, failed, skipped, failed_symbols, index
# FIXME: move this to common routine
def create_output(tests, doc_data, format="xml"):
definitions.reset_user_definitions()
for test in tests.tests:
if test.private:
continue
key = test.key
evaluation = Evaluation(
definitions, format=format, catch_interrupt=True, output=TestOutput()
)
try:
result = evaluation.parse_evaluate(test.test)
except: # noqa
result = None
if result is None:
result = []
else:
result = [result.get_data()]
doc_data[key] = {
"query": test.test,
"results": result,
}
def test_chapters(
chapters: set,
quiet=False,
stop_on_failure=False,
generate_output=False,
reload=False,
want_sorting=False,
):
if documentation is None:
print_and_log("documentation is not loaded.")
return
failed = 0
index = 0
chapter_names = ", ".join(chapters)
print(f"Testing chapter(s): {chapter_names}")
output_data = load_doc_data() if reload else {}
prev_key = []
for tests in documentation.get_tests():
if tests.chapter in sorted(chapters):
for test in tests.tests:
key = list(test.key)[1:-1]
if prev_key != key:
prev_key = key
print(f'Testing section: {" / ".join(key)}')
index = 0
if test.ignore:
continue
index += 1
if not test_case(test, tests, index, quiet=quiet):
failed += 1
if stop_on_failure:
break
if generate_output and failed == 0:
create_output(tests, output_data)
print()
if index == 0:
print_and_log(f"No chapters found named {chapter_names}.")
elif failed > 0:
if not (keep_going and format == "xml"):
print_and_log("%d test%s failed." % (failed, "s" if failed != 1 else ""))
else:
print_and_log("All tests passed.")
def test_sections(
sections: set,
quiet=False,
stop_on_failure=False,
generate_output=False,
reload=False,
want_sorting=False,
):
if documentation is None:
print_and_log("documentation is not loaded.")
return
failed = 0
index = 0
section_names = ", ".join(sections)
print(f"Testing section(s): {section_names}")
sections |= {"$" + s for s in sections}
output_data = load_doc_data() if reload else {}
prev_key = []
for tests in documentation.get_tests():
if tests.section in sections:
for test in tests.tests:
key = list(test.key)[1:-1]
if prev_key != key:
prev_key = key
print(f'Testing section: {" / ".join(key)}')
index = 0
if test.ignore:
continue
index += 1
if not test_case(test, tests, index, quiet=quiet):
failed += 1
if stop_on_failure:
break
if generate_output and failed == 0:
create_output(tests, output_data)
print()
if index == 0:
print_and_log(f"No sections found named {section_names}.")
elif failed > 0:
if not (keep_going and format == "xml"):
print_and_log("%d test%s failed." % (failed, "s" if failed != 1 else ""))
else:
print_and_log("All tests passed.")
if generate_output and (failed == 0 or keep_going):
save_doctest_data(output_data)
def open_ensure_dir(f, *args, **kwargs):
try:
return open(f, *args, **kwargs)
except (IOError, OSError):
d = osp.dirname(f)
if d and not osp.exists(d):
os.makedirs(d)
return open(f, *args, **kwargs)
def test_all(
quiet=False,
generate_output=False,
stop_on_failure=False,
start_at=0,
count=MAX_TESTS,
texdatafolder=None,
doc_even_if_error=False,
excludes=[],
want_sorting=False,
):
if not quiet:
print(f"Testing {version_string}")
if documentation is None:
print_and_log("documentation is not loaded.")
return
try:
index = 0
total = failed = skipped = 0
failed_symbols = set()
output_data = {}
for tests in documentation.get_tests():
sub_total, sub_failed, sub_skipped, symbols, index = test_tests(
tests,
index,
quiet=quiet,
stop_on_failure=stop_on_failure,
start_at=start_at,
max_tests=count,
excludes=excludes,
)
if generate_output:
create_output(tests, output_data)
total += sub_total
failed += sub_failed
skipped += sub_skipped
failed_symbols.update(symbols)
if sub_failed and stop_on_failure:
break
if total >= count:
break
builtin_total = len(builtins)
except KeyboardInterrupt:
print("\nAborted.\n")
return
if failed > 0:
print(sep)
if count == MAX_TESTS:
print_and_log(
"%d Tests for %d built-in symbols, %d passed, %d failed, %d skipped."
% (total, builtin_total, total - failed - skipped, failed, skipped)
)
else:
print_and_log(
"%d Tests, %d passed, %d failed, %d skipped."
% (total, total - failed, failed, skipped)
)
if failed_symbols:
if stop_on_failure:
print_and_log("(not all tests are accounted for due to --stop-on-failure)")
print_and_log("Failed:")
for part, chapter, section in sorted(failed_symbols):
print_and_log(" - %s in %s / %s" % (section, part, chapter))
if generate_output and (failed == 0 or doc_even_if_error):
save_doctest_data(output_data)
return True
if failed == 0:
print("\nOK")
else:
print("\nFAILED")
return sys.exit(1) # Travis-CI knows the tests have failed
def load_doc_data():
doc_html_data_path = get_doctest_html_data_path(should_be_readable=True)
print(f"Loading internal document data from {doc_html_data_path}")
with open_ensure_dir(doc_html_data_path, "rb") as doc_data_file:
return pickle.load(doc_data_file)
def save_doctest_data(output_data):
"""
Save doctest tests and test results to a Python PCL file.
``output_data`` is a dictionary of test results. The key is a tuple
of:
* Part name,
* Chapter name,
* [Guide Section name],
* Section name,
* Subsection name,
* test number
and the value is a dictionary of a Result.getdata() dictionary.
"""
doctest_html_data_path = get_doctest_html_data_path(
should_be_readable=False, create_parent=True
)
print(f"Writing internal document data to {doctest_html_data_path}")
with open_ensure_dir(doctest_html_data_path, "wb") as output_file:
pickle.dump(output_data, output_file, 4)
def write_doctest_data(quiet=False, reload=False):
"""
Write internal (pickled) doc files and example data in docstrings.
"""
if documentation is None:
print_and_log("documentation is not loaded.")
return
if not quiet:
print(f"Extracting internal doc data for {version_string}")
print("This may take a while...")
try:
output_data = load_doc_data() if reload else {}
for tests in documentation.get_tests():
create_output(tests, output_data)
except KeyboardInterrupt:
print("\nAborted.\n")
return
print("done.\n")
save_doctest_data(output_data)
def main():
global check_partial_enlapsed_time
global definitions
import_and_load_builtins()
definitions = Definitions(add_builtin=True)
parser = ArgumentParser(description="Mathics test suite.", add_help=False)
parser.add_argument(
"--help", "-h", help="show this help message and exit", action="help"
)
parser.add_argument(
"--version", "-v", action="version", version="%(prog)s " + mathics.__version__
)
parser.add_argument(
"--chapters",
"-c",
dest="chapters",
metavar="CHAPTER",
help="only test CHAPTER(s). "
"You can list multiple chapters by adding a comma (and no space) in between chapter names.",
)
parser.add_argument(
"--sections",
"-s",
dest="sections",
metavar="SECTION",
help="only test SECTION(s). "
"You can list multiple sections by adding a comma (and no space) in between section names.",
)
parser.add_argument(
"--exclude",
"-X",
default="",
dest="exclude",
metavar="SECTION",
help="excude SECTION(s). "
"You can list multiple sections by adding a comma (and no space) in between section names.",
)
parser.add_argument(
"--load-module",
"-l",
dest="pymathics",
metavar="MATHIC3-MODULES",
help="load Mathics3 module MATHICS3-MODULES. "
"You can list multiple Mathics3 Modules by adding a comma (and no space) in between "
"module names.",
)
parser.add_argument(
"--logfile",
"-f",
dest="logfilename",
metavar="LOGFILENAME",
help="stores the output in [logfilename]. ",
)
parser.add_argument(
"--time-each",
"-d",
dest="enlapsed_times",
action="store_true",
help="check the time that take each test to parse, evaluate and compare.",
)
parser.add_argument(
"--output",
"-o",
dest="output",
action="store_true",
help="generate pickled internal document data",
)
parser.add_argument(
"--reload",
"-r",
dest="reload",
action="store_true",
help="reload pickled internal data, before possibly adding to it",
)
parser.add_argument(
"--doc-only",
dest="doc_only",
action="store_true",
help="reload pickled internal document data, before possibly adding to it",
)
parser.add_argument(
"--quiet", "-q", dest="quiet", action="store_true", help="hide passed tests"
)
parser.add_argument(
"--keep-going",
"-k",
dest="keep_going",
action="store_true",
help="create documentation even if there is a test failure",
)
parser.add_argument(
"--stop-on-failure", "-x", action="store_true", help="stop on failure"
)
parser.add_argument(
"--skip",
metavar="N",
dest="skip",
type=int,
default=0,
help="skip the first N tests",
)
parser.add_argument(
"--count",
metavar="N",
dest="count",
type=int,
default=MAX_TESTS,
help="run only N tests",
)
# FIXME: there is some weird interacting going on with
# mathics when tests in sorted order. Some of the Plot
# show a noticeable 2 minute delay in processing.
# I think the problem is in Mathics itself rather than
# sorting, but until we figure that out, use
# sort as an option only. For normal testing we don't
# want it for speed. But for document building which is
# rarely done, we do want sorting of the sections and chapters.
parser.add_argument(
"--want-sorting",
dest="want_sorting",
action="store_true",
help="Sort chapters and sections",
)
global logfile
args = parser.parse_args()
if args.enlapsed_times:
check_partial_enlapsed_time = True
# If a test for a specific section is called
# just test it
if args.logfilename:
logfile = open(args.logfilename, "wt")
# LoadModule Mathics3 modules
if args.pymathics:
for module_name in args.pymathics.split(","):
try:
eval_LoadModule(module_name, definitions)
except PyMathicsLoadException:
print(f"Python module {module_name} is not a Mathics3 module.")
except ImportError:
print(f"Python module {module_name} does not exist")
else:
print(f"Mathics3 Module {module_name} loaded")
# MathicsDjangoDocumentation load the documentation automatically.
# It must be loaded after loading modules.
global documentation
documentation = MathicsDjangoDocumentation()
if args.sections:
sections = set(args.sections.split(","))
test_sections(
sections,
stop_on_failure=args.stop_on_failure,
generate_output=args.output,
reload=args.reload,
)
elif args.chapters:
chapters = set(args.chapters.split(","))
test_chapters(
chapters, stop_on_failure=args.stop_on_failure, reload=args.reload
)
else:
if args.doc_only:
write_doctest_data(
quiet=args.quiet,
reload=args.reload,
want_sorting=args.want_sorting,
)
else:
excludes = set(args.exclude.split(","))
start_at = args.skip + 1
start_time = datetime.now()
test_all(
quiet=args.quiet,
generate_output=args.output,
stop_on_failure=args.stop_on_failure,
start_at=start_at,
count=args.count,
doc_even_if_error=args.keep_going,
excludes=excludes,
want_sorting=args.want_sorting,
)
end_time = datetime.now()
print("Tests took ", end_time - start_time)
if logfile:
logfile.close()
if __name__ == "__main__":
main()