-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtestsuite.py
executable file
·1691 lines (1348 loc) · 58.7 KB
/
testsuite.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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""./testsuite.py [OPTIONS] [RE_TEST_PATH]
Run the GNATcoverage testsuite
See ./testsuite.py -h for more help
"""
import time
import os
import re
import sys
import itertools
from e3.fs import mkdir, rm, cp
from e3.os.fs import which, unixpath
from e3.os.process import Run, quote_arg
import e3.testsuite
from e3.testsuite.control import AdaCoreLegacyTestControlCreator
from e3.testsuite.driver import TestDriver
from e3.testsuite.driver.classic import TestAbortWithError
from e3.testsuite.result import Log, TestResult, TestStatus
from e3.testsuite.testcase_finder import ParsedTest, TestFinder
import SUITE.cutils as cutils
from SUITE.cutils import strip_prefix, contents_of, lines_of
from SUITE.cutils import FatalError, exit_if
from SUITE.cutils import version
from SUITE.dutils import pdump_to, pload_from
from SUITE.dutils import jdump_to
from SUITE.dutils import time_string_from, host_string_from
from SUITE.qdata import stdf_in, qdaf_in, treeref_at
from SUITE.qdata import QLANGUAGES, QROOTDIR
from SUITE.qdata import QSTRBOX_DIR, CTXDATA_FILE
from SUITE.qdata import SUITE_context, TC_status, TOOL_info, OPT_info_from
import SUITE.control as control
from SUITE.control import BUILDER, _runtime_info
from SUITE.control import altrun_opt_for, altrun_attr_for
from SUITE.control import cargs_opt_for, cargs_attr_for
VALGRIND_TIMEOUT_FACTOR = 2
"""
When the testsuite runs with Valgrind (--enable-valgrind), the default timeout
is multiplied by this number to get the actual default timeout. This is used to
compensate the slowdown that Valgrind incurs.
"""
# ==========================================
# == Qualification principles and control ==
# ==========================================
# The testsuite tree features particular subdirectories hosting TOR and
# qualification testcases. These are all hosted down a single root directory,
# and we designate the whole piece as the qualification subtree.
# These tests may be run as part of a regular testing activity or for an
# actual qualification process. The latter is indicated by passing
# --qualif-level on the command line, in which case the testsuite is said to
# run in qualification mode.
# The qualification mode aims at producing a test-results qualification report
# for the provided target level.
# Beyond the production of a qualification report, --qualif-level has several
# effects of note:
#
# * The set of tests exercised is restricted to the set of qualification
# tests relevant for the target level,
#
# * The coverage analysis tool is called with a --level corresponding to the
# target qualification level for all the tests, whatever the criterion the
# test was designed to assess. For example, for a target level A we will
# invoke gnatcov --level=stmt+mcdc even for tests designed to verify
# statement coverage only.
#
# * For criteria with variants (e.g. unique-cause and masking mcdc),
# exercise only the default one.
#
# * Even if empty, an explicit set of GNAT configuration pragmas shall be
# provided by way of a -gnatec= compilation switch, typically enforcing
# what the Operational Conditions of Use mandate.
#
# * Tests only are only run with --annotate=report, not --annotate=xcov,
# as only the former is claimed to be qualified.
# A dictionary of information of interest for each qualification level:
class QlevelInfo(object):
def __init__(self, levelid, subtrees, xcovlevel):
self.levelid = levelid # string identifier
# regexp of directory subtrees: testdirs that match this
# hold qualification tests for this level
self.subtrees = subtrees
# --level argument to pass to xcov when running such tests when in
# qualification mode
self.xcovlevel = xcovlevel
def hosts(self, test_dir):
"""
Whether the subtrees covered by this Qlevel encompass the
provided test directory, which may be relative to a testsuite
root or absolute.
"""
# Expect filtering subtrees using forward slashes, so make
# sure the provided test_dir is amenable so such patterns.
return re.search(pattern=self.subtrees, string=unixpath(test_dir))
RE_QCOMMON = "(Common|Appendix)"
RE_QLANG = "(%s)" % "|".join(QLANGUAGES)
# A regular expression that matches subdirs of qualification tests
# that should apply for coverage criteria RE_CRIT.
def RE_SUBTREE(re_crit):
return "%(root)s/((%(common)s)|(%(lang)s/(%(crit)s)))" % {
"root": QROOTDIR,
"common": RE_QCOMMON,
"lang": RE_QLANG,
"crit": re_crit,
}
# Note that we expect test directory names to be in unix form here.
# This is easy to achieve, will have obvious observable effects if not
# respected, and simplifies the regexp overall.
QLEVEL_INFO = {
"doA": QlevelInfo(
levelid="doA",
subtrees=RE_SUBTREE(re_crit="stmt|decision|mcdc"),
xcovlevel="stmt+mcdc",
),
"doB": QlevelInfo(
levelid="doB",
subtrees=RE_SUBTREE(re_crit="stmt|decision"),
xcovlevel="stmt+decision",
),
"doC": QlevelInfo(
levelid="doC", subtrees=RE_SUBTREE(re_crit="stmt"), xcovlevel="stmt"
),
}
# ===============================
# == Compilation Flags Control ==
# ===============================
# The --cargs family of options controls the compilation options used to
# compile all the tests, part of the qualification tree or not. This allows
# exercising all the tests with nightly variants, not only qualification
# tests.
# --cargs options are conveyed as CARGS_ discriminants, with leading dashes
# stripped and without language indication. For example --cargs="-O1"
# --cargs:Ada="-gnatp" translates as CARGS_O1 + CARGS_gnatp discriminants.
# Individual tests that really depend on particular options might of course
# request so, via:
#
# - The "extracargs" argument to the gprbuild function in tutils, for
# tests that invoke this function directly from test.py, or
#
# - The "extracargs" initializer argument of TestCase instances
#
# This is not allowed for qualifcation tests though, because we need simple
# and reliable ways to determine the set of options we support and too many
# possible sources for options is unwelcome.
# On top of this user level control, we add a couple of flags such as -g or
# -fdump-scos automatically (depending on command line options, in particular
# on the requested kind of trace mode). Below is a sketch of the internal
# compilation flags flow:
#
# SUITE.control.BUILDER.SCOV_CARGS(options) (-g -fdump-scos ...)
# |
# | gprfor ()
# | template.gpr
# | % Switches (main) += "-fno-inline" as needed
# | |
# | | direct calls to gprbuild() from test.py,
# | | or via TestCase(extracargs)
# | | |
# | v v testsuite.py
# | gprbuild (gpr, extracargs) [--cargs=<>] [--cargs:Ada=<>] [--cargs:C=<>]
# | | |
# o--------------------o--------------o
# |
# v
# run "gprbuild -Pgpr -cargs=... [-cargs:Ada=<>] [-cargs:C=<>]
# In addition to the SUITE.control bits, the only default option we enforce is
# -gnat05 for Ada.
# =============================
# == Setup specific controls ==
# =============================
# This toplevel driver supports various command line options allowing
# customization of the test execution process:
#
# * --gnatcov_<cmd> allows providing alternate programs to execute instead of
# "gnatcov <cmd>" when a test normally needs it. A typical use is
#
# --gnatcov_run=</path/to/program_execution_driver>
#
# to provide a replacement to "gnatcov run" for execution trace production,
# e.g. running the program on hardware through a probe.
#
# The replacement programs may be python scripts or native executables for
# the host on which the testsuite runs. They need to support the command
# line interface of the facility they replace, at least the subset used by
# the tests.
#
# When the alternate command is called, the current directory is that of
# the context at the point of the call. We don't switch to the directory
# which holds the alternate implementation prio to calling it.
#
# The control.ALTRUN_GNATCOV_PAIRS variable contains the list of ('gnatcov',
# <cmd>) pairs we support. See the altrun/example subdir for implementation
# examples.
#
# * --pre/post-testsuite/testcase allows providing programs to execute as
# hooks within the testsuite process:
#
# - Before the complete test sequence starts (--pre-testsuite)
# - After the complete test sequence has finished (--post-testsuite)
# - Before each testcase executes (--pre-testcase)
# - After each testcase executes (--post-testcase)
#
# A typical use is with environments requiring on-board execution through a
# probe, which might need some service to startup before any program loading
# may take place, some shutdown operation afterwards (once done with all the
# tests), and possibly some preliminary local cleanup before each test can
# start or after each test has run.
#
# When pre/post-testcase is called, the current directory is set to the
# testcase location. When pre/post-testsuite is called the current directory
# is set to the location where the hook script or binary resides.
#
# The control.ALTRUN_HOOK_PAIRS variable contains the list of
# ('pre|post', 'testsuite|testcase') pairs we support.
# For environments that need combinations of the aforedescribed facilities,
# the --altrun=<path> command line option provides a convenient way to
# wrap everything together.
#
# It instructs this driver to look in the <path> subdirectory as part
# of the testsuite run preparation, and then:
#
# * If there is a "setup" binary (exe or .py) there, run it with the
# current directory set to <path>; then:
#
# * If there are binaries (exe or .py) matching the pre/post command option
# names, use each as if the corresponding option had been passed
#
# * Likewise if there are binaries corresponding to the gnatcov_<cmd> option
# names, except a "c<cmd>" binary is searched to match each "gnatcov_<cmd>"
# option.
def maybe_exec(log, binfile, args=None, edir=None):
"""
Execute the provided BINFILE program file, if any.
Run this program in the current working directory EDIR is None. Otherwise,
run it in the location where BINFILE resides if EDIR is "...", or in EDIR's
value otherwise.
Pass the provided list of ARGS, if any, on the command line. Skip possible
empty or None arg values there.
Log the execution of this program in LOG, with possible output if the
command fails.
Return the process object.
"""
if not binfile:
return
to_run = (
[sys.executable, binfile] if binfile.endswith(".py") else [binfile]
)
if args:
to_run.extend([arg for arg in args if arg])
if edir == "...":
edir = os.path.dirname(binfile)
p = Run(to_run, cwd=edir)
log += "\nRunning hook: {}\n".format(binfile)
log += p.out
return p
class TestPyRunner:
"""Helper to run a "test.py" test script."""
filename = "test.py"
def __init__(self, driver, result, test_prefix, working_prefix):
"""
Common test driver initialization.
:param driver: TestDriver instance that owns `self`.
:param result: TestResult instance to fill in.
:param test_prefix: Directory in the sources where this testcase was
found. This is the directory that contains the "test.py" to run.
:param working_prefix: Temporary directory to run this test.
"""
self.driver = driver
self.result = result
self.test_prefix = test_prefix
self.working_prefix = working_prefix
# Convenience shortcut
self.env = driver.env
# Create an empty working directory. Even if testcases are ran in the
# original tree, there are still some temporaries that we generate
# elsewhere.
os.mkdir(self.working_dir())
# Create a "canonical" directory name for this testcase, useful to
# simplify some platform-independent processings.
self.unix_test_dir = unixpath(self.test_dir())
# Load all relevant *.opt files to control the execution of this test
self.test_control_creator = self.parse_opt()
# Shortcuts to build paths, similar to
# TestDriver.test_dir/TestDriver.working_dir.
def test_dir(self, *args):
return os.path.join(self.test_prefix, *args)
def working_dir(self, *args):
return os.path.join(self.working_prefix, *args)
# ---------------------------
# -- Testcase output files --
# ---------------------------
def outf(self):
"""
Name of the file where outputs of the provided test object should go.
Same location as the test source script, with same name + a .out extra
suffix extension.
"""
return self.test_dir(self.filename + ".out")
def logf(self):
"""
Similar to outfile, for the file where logs of the commands executed by
the provided test object should go.
"""
return self.test_dir(self.filename + ".log")
def errf(self):
"""
Similar to outf, for the file where diffs of the provided test object
should go.
"""
return self.test_dir(self.filename + ".err")
def qdaf(self):
return qdaf_in(self.test_dir())
def ctxf(self):
"""
The file containing a SUITE_context describing the testcase run (the
file is in pickle format).
"""
return self.test_dir("ctx.dump")
# --------------------------------------
# -- Testscase specific discriminants --
# --------------------------------------
def discriminants(self):
"""
List of discriminants for this particular test. Might include
LANG_<lang> if path to test contains /<lang>/ for any of the languages
we know about.
"""
discs = []
lang = self.lang()
if lang:
discs.append("LANG_%s" % lang.upper())
return discs
def lang(self):
"""The language specific subtree SELF pertains to."""
for lang in control.KNOWN_LANGUAGES:
if "/{}/".format(lang) in self.unix_test_dir:
return lang
return None
def lookup_extra_opt(self):
"""Look for all "extra.opt" files that apply to this testcase.
The result is in bottom up order (deepest files in the tree first).
"""
result = []
# Determine the directory under which all tests reside. In an ideal
# world, this would be the tessuite root directory, but in practice we
# often run the testsuite on "Qualif/ ../extra/tests/", so if there is
# an "extra" directory above the root directory, allow one level up.
root_dir = self.driver.test_env["testsuite_root_dir"]
up_root = os.path.abspath(os.path.join(root_dir, ".."))
if os.path.exists(os.path.join(up_root, "extra")):
root_dir = up_root
# Climb up from the testcase directory to the testsuite root directory
# and gather all extra.opt files found in the way.
d = self.test_dir("..")
while d.startswith(root_dir):
extra_opt = os.path.join(d, "extra.opt")
if os.path.exists(extra_opt):
result.append(extra_opt)
d = os.path.dirname(d)
return result
def parse_opt(self):
"""
Parse the local test.opt + possible extra.opt uptree in accordance with
the testsuite discriminants + the test specific discriminants, if any.
The deeper .opt file prevails.
"""
# Build a list of strings corresponding to the catenation of
# test.opt/extra.opt files for this test, fetched bottom up in
# directory tree order, then feed that to the opt file parser.
opt_files = []
test_opt = self.test_dir("test.opt")
if os.path.exists(test_opt):
opt_files.append(test_opt)
opt_files.extend(self.lookup_extra_opt())
opt_lines = sum((lines_of(f) for f in opt_files), [])
# Create a single "control.opt" file to contain all control directives
control_opt = self.working_dir("control.opt")
with open(control_opt, "w") as f:
for line in opt_lines:
f.write(line + "\n")
return AdaCoreLegacyTestControlCreator(
system_tags=self.env.suite_discriminants + self.discriminants(),
opt_filename=control_opt,
)
def set_up(self):
mopt = self.env.main_options
# Setup test execution related files. Clear them upfront to prevent
# accumulation across executions and bogus reuse of old contents if
# running the test raises a premature exception, before the execution
# script gets a chance to initialize the file itself.
outf = self.outf()
logf = self.logf()
errf = self.errf()
qdaf = self.qdaf()
for f in (outf, logf, errf, qdaf):
cutils.clear(f)
# Save a copy of the context data in case the user wants to
# re-run the testsuite with --skip-if-* later on. Since
# this context data is only generated when in Qualification
# mode, only make that copy when in that mode, too.
if mopt.qualif_level:
cp(CTXDATA_FILE, self.ctxf())
# Construct the test command line
testcase_cmd = [
sys.executable,
self.test_dir(self.filename),
"--report-file=" + outf,
"--log-file=" + logf,
]
if mopt.enable_valgrind:
testcase_cmd.append("--enable-valgrind=" + mopt.enable_valgrind)
# Propagate our command line arguments as testcase options.
#
# Beware that we're not using 'is not None' on purpose, to prevent
# propagating empty arguments.
# In qualification mode, pass the target qualification level to
# qualification tests and enforce the proper xcov-level. Note that
# if we reach here, we already know that this test is relevant to
# the requested level (validated by GNATcovTestFinder.probe):
if mopt.qualif_level:
testcase_cmd.append("--qualif-level=%s" % mopt.qualif_level)
testcase_cmd.append(
"--xcov-level=%s" % QLEVEL_INFO[mopt.qualif_level].xcovlevel
)
if mopt.build:
testcase_cmd.append("--build=%s" % mopt.build)
if mopt.target:
testcase_cmd.append("--target=%s" % mopt.target)
if mopt.board:
testcase_cmd.append("--board=%s" % mopt.board)
if mopt.gprmode:
testcase_cmd.append("--gprmode")
if mopt.trace_mode:
testcase_cmd.append("--trace-mode=%s" % mopt.trace_mode)
if mopt.kernel:
testcase_cmd.append("--kernel=%s" % mopt.kernel)
if mopt.trace_size_limit:
testcase_cmd.append(
"--trace-size-limit=%s" % mopt.trace_size_limit
)
if mopt.RTS:
testcase_cmd.append("--RTS=%s" % mopt.RTS)
if mopt.largs:
testcase_cmd.append("--largs=%s" % mopt.largs.strip())
testcase_cmd.append("--tags=@%s" % self.env.discr_file)
if mopt.auto_arch:
testcase_cmd.append("--auto-arch")
if mopt.consolidate:
testcase_cmd.append("--consolidate=%s" % mopt.consolidate)
if mopt.pretty_print:
testcase_cmd.append("--pretty-print")
if mopt.spark_tests:
testcase_cmd.append("--spark-tests=%s" % mopt.spark_tests)
if mopt.all_warnings:
testcase_cmd.append("--all-warnings")
if mopt.default_dump_trigger:
testcase_cmd.append(
f"--default-dump-trigger={mopt.default_dump_trigger}"
)
if mopt.default_dump_channel:
testcase_cmd.append(
f"--default-dump-channel={mopt.default_dump_channel}"
)
if mopt.block:
testcase_cmd.append("--block")
# --gnatcov_<cmd> family
for pgm, cmd in control.ALTRUN_GNATCOV_PAIRS:
if getattr(mopt, altrun_attr_for(pgm, cmd)) is None:
continue
testcase_cmd.append(
"--%(opt)s=%(val)s"
% {
"opt": altrun_opt_for(pgm, cmd),
"val": getattr(mopt, altrun_attr_for(pgm, cmd)),
}
)
# --gpr<tool> family
for pgm in control.ALTRUN_GPR:
if getattr(mopt, altrun_attr_for(pgm)) is None:
continue
testcase_cmd.append(
f"--{altrun_opt_for(pgm)}="
f"{getattr(mopt, altrun_attr_for(pgm))}"
)
# --cargs family
for lang in [None] + control.KNOWN_LANGUAGES:
testcase_cmd.append(
"--%(opt)s=%(val)s"
% {
"opt": cargs_opt_for(lang),
"val": getattr(mopt, cargs_attr_for(lang)),
}
)
# Compute the testcase timeout, whose default vary depending on whether
# we use Valgrind.
timeout = int(self.test_control.opt_results["RLIMIT"])
if mopt.enable_valgrind:
timeout = VALGRIND_TIMEOUT_FACTOR * timeout
if mopt.rewrite and not self.test_control.xfail:
testcase_cmd.append("--rewrite")
self.testcase_cmd = testcase_cmd
self.testcase_timeout = timeout
def maybe_exec(self, binfile, args=None, edir=None):
"""
Shortcut for the global maybe_exec. Log the result in
``self.result.log`` and abort the testcase on failure.
"""
if not binfile:
return
if maybe_exec(self.result.log, binfile, args, edir).status != 0:
raise TestAbortWithError("Altrun hook failed ({})".format(binfile))
def run(self):
mopt = self.env.main_options
self.maybe_exec(
mopt.pre_testcase, args=[mopt.altrun], edir=self.test_dir()
)
# Run the "test.py" script in the testsuite root directory (as
# expected: the script will change its own CWD later).
start_time = time.time()
self.test_py_process = Run(
self.testcase_cmd,
cwd=self.env.root_dir,
timeout=self.testcase_timeout,
)
end_time = time.time()
self.result.time = end_time - start_time
# To ease debugging, copy the consolidated standard outputs (stdout +
# stderr) to the "test.py.err" file.
with open(self.errf(), "w") as f:
f.write(self.test_py_process.out)
# If the script exitted with an error status code, consider that the
# testcase failed.
self.test_py_failed = self.test_py_process.status != 0
if self.test_py_failed:
# Make --show-error-output display the consolidated standard
# outputs, which likely contains relevant information for
# debugging.
self.result.log = Log(self.test_py_process.out)
else:
# Otherwise, load the test actual output from the "test.py.out"
# file to the result, for --show-error-output.
with open(self.outf()) as f:
self.result.log = Log(f.read())
def tear_down(self):
args = self.env.main_options
# Execute a post-testcase action if requested so, before the test
# artifacts might be cleared by a post-run cleanup:
self.maybe_exec(
args.post_testcase, args=[args.altrun], edir=self.test_dir()
)
# Perform post-run cleanups if requested so. Note that this may
# alter the test execution status to make sure that unexpected cleanup
# failures get visibility:
if self.result.status != TestStatus.FAIL and args.do_post_run_cleanups:
self.do_post_run_cleanups(ts_options=args)
if args.qualif_level:
self.latch_status()
def analyze(self):
if self.test_py_failed:
self.push_failure(
"test.py exitted with status code {}".format(
self.test_py_process.status
)
)
elif cutils.match("==== PASSED ==================", self.outf()):
self.push_success()
else:
self.push_failure("Missing PASSED tag in output file")
def run_test(self, previous_values, slot):
"""Run the testcase, analyze its result and push the result."""
try:
self.test_control = self.test_control_creator.create(self.driver)
except ValueError as exc:
return self.push_error(
"Error while interpreting control: {}".format(exc)
)
# If test control tells us to skip the test, stop right here
if self.test_control.skip:
return self.push_skip(self.test_control.message)
try:
self.set_up()
self.run()
self.analyze()
self.tear_down()
except TestAbortWithError as exc:
self.push_error(str(exc))
return
def push_success(self):
"""Set status to consider that the test passed."""
# Given that we skip execution right after the test control evaluation,
# there should be no way to call push_success in this case.
assert not self.test_control.skip
if self.test_control.xfail:
self.result.set_status(TestStatus.XPASS)
else:
self.result.set_status(TestStatus.PASS)
self.driver.push_result(self.result)
def push_skip(self, message):
"""
Consider that we skipped the test, set status accordingly.
:param message: Label to explain the skipping.
"""
self.result.set_status(TestStatus.SKIP, message)
self.driver.push_result(self.result)
def push_error(self, message):
"""
Set status to consider that something went wrong during test execution.
:param message: Message to explain what went wrong.
"""
self.result.set_status(TestStatus.ERROR, message)
self.driver.push_result(self.result)
def push_failure(self, message):
"""
Consider that the test failed and set status according to test control.
:param message: Test failure description.
"""
if self.test_control.xfail:
status = TestStatus.XFAIL
if self.test_control.message:
message = "{} ({})".format(message, self.test_control.message)
else:
status = TestStatus.FAIL
self.result.set_status(status, message)
self.driver.push_result(self.result)
def stdf(self):
return stdf_in(self.test_dir())
def latch_status(self):
r = self.result
pdump_to(
self.stdf(),
o=TC_status(
passed=r.status in (TestStatus.PASS, TestStatus.XPASS),
xfail=self.test_control.xfail,
status=r.status.name,
comment=self.test_control.message,
),
)
def latched_status(self):
return pload_from(self.stdf())
def _handle_info_for(self, path):
"""Return a string describing file handle information related to
the provided PATH, such as the output of the "handle" sysinternal
on Windows."""
if sys.platform != "win32":
return "No handle info on non-windows platform"
# Adjust the provided path to something
path = re.sub("^[a-zA-Z]:(.*)", r"\1", path).replace("/", "\\")
gpdir = os.path.dirname(sys.executable)
handle_path = os.path.abspath(
os.path.join(
gpdir,
"Lib",
"site-packages",
"gnatpython",
"internal",
"data",
"libexec",
"x86-windows",
"handle.exe",
)
)
return Run([handle_path, "/AcceptEULA", "-a", "-u", path]).out
def do_post_run_cleanups(self, ts_options):
"""Cleanup temporary artifacts from the testcase directory.
Append removal failure info to the test error log. TS_OPTIONS
are the testsuite command line options."""
comments = []
# In principle, most of this is the spawned test.py responsibilty,
# because _it_ knows what it creates etc. We have artifacts of our
# own though (dump files for qualif runs, for example), and removing
# these correctly can only be done from here. Doing the rest as well
# is just simpler and more efficient.
# Beware that some artifacts need to be preserved for qualification
# runs. In particular, test execution logs and coverage reports which
# might reside in temporary directories.
# List of paths to filesystem entities we will want to remove, which
# may hold file or directory names (to be removed entirely):
cleanup_q = []
def cleanup_on_match(subdirs, prefixes, parent):
"""
Helper for the filesystem walking code below, to facilitate the
processing of subdirectories. Queue for removal the subdirectories
of ``parent`` in ``subdirs`` which have a name starting with one
of the provided ``prefixes``, removing them from ``subdirs``.
"""
to_clear = []
for sd in subdirs:
for prefix in prefixes:
if sd.startswith(prefix):
to_clear.append(sd)
break
for sd in to_clear:
cleanup_q.append(os.path.join(parent, sd))
subdirs.remove(sd)
# Perform a filesystem walk to craft the list of items we
# can/should remove. Make it topdown so we can arrange not to
# recurse within subirectories we cleanup as a whole.
for dirpath, dirnames, filenames in os.walk(
self.test_dir(), topdown=True
):
# Nothing in "obj" dirs ever needs to be preserved
cleanup_on_match(
subdirs=dirnames, prefixes=["tmp", "obj"], parent=dirpath
)
# We can also always get rid of all the pure binary artifacts,
# wherever they are produced. Files without extension, most often
# executables, are considered never of interest.
for fn in filenames:
if (
fn.endswith(".trace")
or fn.endswith(".obj")
or fn.endswith(".o")
or fn.endswith(".exe")
or "." not in fn
):
cleanup_q.append(os.path.join(dirpath, fn))
# Then for regular runs, we can remove test execution logs and the
# scov test temp dirs as a whole. We can't remove these dirs in
# qualification runs because they hold subcommand execution logs
# and coverage reports which need to be preserved in qualification
# packages.
if not ts_options.qualif_level:
for fn in filenames:
if fn == "test.py.log":
cleanup_q.append(os.path.join(dirpath, fn))
cleanup_on_match(
subdirs=dirnames,
prefixes=["st_", "dc_", "mc_", "uc_"],
parent=dirpath,
)
# Deal with occasional removal failures presumably caused by stray
# handles. Expand glob patterns locally, issue separate rm requests
# for distinct filesystem entries and turn exceptions from rm into
# test failures.
for path in set(cleanup_q):
try:
rm(path, recursive=True)
except Exception:
handle_comment = self._handle_info_for(path)
self.passed = False
self.status = "RMFAILED"
comments.append(
"Removal of %s failed\nHandle info follows:" % path
)
comments.append(handle_comment)
with open(self.errf(), "a") as f:
f.write("\n".join(comments))
class TestPyDriver(TestDriver):
"""
Test driver that runs "test.py" scripts.
"""
def add_test(self, dag):
self.runner = TestPyRunner(
self, self.result, self.test_dir(), self.working_dir()
)
self.add_fragment(dag, "run", self.runner.run_test)
class GroupPyDriver(TestDriver):
"""
Test driver that runs "group.py" scripts.
"""
def add_test(self, dag):
# Generator of unique indexes for generated testcases
indexes = itertools.count(1)
# Run the "group.py" script, to generate testcases
p = Run([sys.executable, "group.py"], cwd=self.test_dir(), timeout=20)
if p.status != 0:
raise RuntimeError(
"Execution of group.py failed ({}):"
"\nOutput:"
"\n{}".format(self.test_dir("group.py"), p.out)
)
# Look for all "test.py" that were generated under this test directory
for dirpath, _, filenames in os.walk(self.test_dir()):
if "test.py" in filenames:
self.add_test_py_run(dag, dirpath, next(indexes))
def add_test_py_run(self, dag, test_dir, index):
# Create a dedicated name for this generated test, with the same rules
# as for regular tests.
test_rel_dir = os.path.relpath(test_dir, self.test_dir())
test_name = "{}-{}".format(
self.test_name, unixpath(test_rel_dir).replace("/", "-")
)
# For debuggability, derive the group.py test environment
test_env = dict(self.test_env)
test_env["generated_test_dir"] = test_dir
# Plan for a dedicated working directory
working_dir = os.path.join(self.env.working_dir, test_name)
result = TestResult(test_name, test_env)
runner = TestPyRunner(self, result, test_dir, working_dir)
self.add_fragment(dag, "run_{}".format(index), runner.run_test)
class GNATcovTestFinder(TestFinder):
def probe(self, testsuite, dirpath, dirnames, filenames):
# If we are running in qualification mode, punt if this test
# is not within the subtrees attached to the requested level.
qlevel = testsuite.main.args.qualif_level
if qlevel and not QLEVEL_INFO[qlevel].hosts(dirpath):
return None
# If directory contains a "test.py" file *and* not a ".generated"
# one, this this is a regular testcase.
if "test.py" in filenames and ".generated" not in filenames:
driver_cls = TestPyDriver
# If it contains a "group.py" file, then this is a special test that
# generates several actual testcases.
elif "group.py" in filenames:
driver_cls = GroupPyDriver
# Otherwise, there is no testcase
else:
driver_cls = None