forked from amanzi/ats-demos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregression_tests.py
1599 lines (1340 loc) · 60.8 KB
/
regression_tests.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
#!/bin/env python
"""
Program to manage and run ATS regression tests.
With inspiration, and in some places just stolen, from Ben Andre's
PFloTran regression test suite.
Author: Ethan Coon ([email protected])
"""
from __future__ import print_function
from __future__ import division
import sys
if sys.hexversion < 0x02070000:
print(70*"*")
print("ERROR: The regression test manager requires python >= 2.7.x. ")
print("It appears that you are running python {0}.{1}.{2}".format(
sys.version_info[0], sys.version_info[1], sys.version_info[2]))
print(70*"*")
sys.exit(1)
import argparse
import datetime
import os
#import pprint
import shutil
import subprocess
import textwrap
import time
import traceback
import distutils.spawn
import numpy
sys.path.append("scripts")
import ats_h5
class NoCatchException(Exception):
def __init__(self,*args,**kwargs):
Exception.__init__(self,*args,**kwargs)
if sys.version_info[0] == 2:
from ConfigParser import SafeConfigParser as config_parser
else:
from configparser import ConfigParser as config_parser
class TestStatus(object):
"""
Simple class to hold status info.
"""
def __init__(self):
self.fail = 0
self.warning = 0
self.error = 0
self.skipped = 0
self.test_count = 0
def __str__(self):
message = "fail = {0}\n".format(self.fail)
message += "warning = {0}\n".format(self.warning)
message += "error = {0}\n".format(self.error)
message += "skipped = {0}\n".format(self.skipped)
message += "test_count = {0}\n".format(self.test_count)
return message
class RegressionTest(object):
"""
Class to collect data about a test problem, run the problem, and
compare the results to a known result.
"""
# things to compare
_TIME = "time"
_TIMESTEPS = "timesteps"
_DEFAULT = "default" # compare a variable
# ways to compare it
_ABSOLUTE = "absolute"
_RELATIVE = "relative"
_PERCENT = "percent"
_DISCRETE = "discrete"
# ways to measure what to compare
_NORM = numpy.inf
def __init__(self):
self._EXECUTABLE = "ats"
self._SUCCESS = 0
self._RESERVED = [self._TIME, self._TIMESTEPS]
# misc test parameters
# self._pprint = pprint.PrettyPrinter(indent=2)
self._txtwrap = textwrap.TextWrapper(width=78, subsequent_indent=4*" ")
self._executable = None
self._input_arg = "--xml_file="
self._input_suffix = "xml"
self._np = None
self._timeout = 162.0
self._skip_check_gold = False
self._check_performance = False
self._num_failed = 0
self._test_name = None
# assign default tolerances for different classes of variables
# absolute min and max thresholds for determining whether to
# compare to baseline, i.e. if (min_threshold <= abs(value) <=
# max_threshold) then compare values. By default we use the
# python definitions for this platform
self._default_tolerance = {}
self._default_tolerance[self._TIME] = [5.0, self._PERCENT, \
0.0, sys.float_info.max]
self._default_tolerance[self._TIMESTEPS] = [5, self._RELATIVE, \
0, sys.maxsize]
self._default_tolerance[self._DISCRETE] = [0, self._ABSOLUTE, 0, sys.maxsize]
self._default_tolerance[self._DEFAULT] = [1.0e-12, self._RELATIVE, \
0.0, sys.float_info.max]
self._eps = 1.e-14
self._checkpoint = None
# dictionary indexed by domain, each of which is a dictionary of
# (key, tolerance) pairs
self._criteria = {}
self._file_format_with_domain = "visdump_{0}_data.h5"
self._file_format_no_domain = "visdump_data.h5"
def __str__(self):
message = " {0} :\n".format(self.name())
message += " timeout = {0}\n".format(self._timeout)
message += " np = {0}\n".format(self._np)
message += " ATS args :\n"
message += " exec : {0}\n".format(self._executable)
message += " input : {0}../{1}.{2}\n".format(
self._input_arg,self._test_name,self._input_suffix)
for domain,criteria in self._criteria.iteritems():
message += " test criteria on \"{0}\" :\n".format(domain)
for key,tol in criteria.iteritems():
message += " {0} : {1} [{2}] : {3} <= abs(value) <= {4}\n".format(
key, tol[0], tol[1], tol[2], tol[3])
return message
def setup(self, cfg_criteria, test_data,
timeout, check_performance, testlog):
"""
Setup the test object
cfg_criteria - dict from cfg file, all tests in file
test_data - dict from cfg file, test specific
timeout - list(?) from command line option
check_performance - bool from command line option
"""
self._test_name = test_data.pop('name')
self._np = test_data.pop('np', None)
self._skip_check_gold = test_data.pop('skip_check_gold', None)
self._check_performance = check_performance
# timeout : preference (1) command line (2) test data (3) class default
self._timeout = float(cfg_criteria.pop('timeout', self._timeout))
self._timeout = float(test_data.pop('timeout', self._timeout))
if timeout is not None:
self._timeout = float(timeout[0])
# check whether this is a checkpoint
checkpoint = test_data.pop('checkpoint',
cfg_criteria.pop('checkpoint', None))
if checkpoint is not None:
self._checkpoint = checkpoint
# pop a default and/or default discrete
default = test_data.pop(self._DEFAULT,
cfg_criteria.pop(self._DEFAULT, None))
if default is not None:
tol = self._validate_tolerance(self._DEFAULT, self._DEFAULT, default)
self._default_tolerance[self._DEFAULT] = tol
discrete = test_data.pop(self._DISCRETE,
cfg_criteria.pop(self._DISCRETE, None))
if discrete is not None:
tol = self._validate_tolerance(self._DISCRETE, self._DISCRETE, discrete)
self._default_tolerance[self._DISCRETE] = tol
# requested criteria, skipping time and timesteps
for key in set(cfg_criteria.keys() + test_data.keys()):
if key != self._TIME and key != self._TIMESTEPS:
self._set_criteria(key, cfg_criteria, test_data)
# criteria defaults
# - time exists on all domains, but must make sure it is on a valid one
if self._check_performance:
self._set_criteria("({0})".format(self._criteria.keys()[0])+self._TIME,
cfg_criteria, test_data)
# - timestep exists on all domains, but must make sure it is on a valid one
if self._checkpoint is None:
self._set_criteria("({0})".format(self._criteria.keys()[0])+self._TIMESTEPS,
cfg_criteria, test_data)
def name(self):
return self._test_name
def dirname(self, gold=False):
suffix = ".regression"
if gold:
suffix += ".gold"
return self.name() + suffix
def filename(self, domain, gold=False):
if self._checkpoint is not None:
return os.path.join(self.dirname(gold),
self._checkpoint)
else:
if domain == "":
return os.path.join(self.dirname(gold),
self._file_format_no_domain)
else:
return os.path.join(self.dirname(gold),
self._file_format_with_domain.format(domain))
def run(self, mpiexec, executable, dry_run, status, testlog):
"""
Run the test.
"""
self._cleanup_generated_files()
self._run_test(mpiexec, executable, self.name(), dry_run, status,
testlog)
def _run_test(self, mpiexec, executable, test_name, dry_run, status, testlog):
"""
Build up the run command, including mpiexec, np, ats,
input file, output file. Then run the job as a subprocess.
* NOTE(bja) - starting in python 3.3, we can use:
subprocess.Popen(...).wait(timeout)
to catch hanging jobs, but for python < 3.3 we have to
manually manage the timeout...?
"""
command = []
if self._np is not None:
if mpiexec:
command.append(mpiexec)
command.append("-np")
command.append(self._np)
else:
# parallel test, but don't have mpiexec, we mark the
# test as skipped and bail....
message = self._txtwrap.fill(
"WARNING : mpiexec was not provided for a parallel test '{0}'.\n"
"This test was skipped!".format(self.name()))
print(message, file=testlog)
status.skipped = 1
return None
command.append(executable)
command.append("{0}../{1}.{2}".format(self._input_arg,test_name,self._input_suffix))
test_directory = os.getcwd()
run_directory = os.path.join(test_directory, self.dirname())
os.mkdir(run_directory)
os.chdir(run_directory)
print(" cd {0}".format(run_directory), file=testlog)
print(" {0}".format(" ".join(command)), file=testlog)
if not dry_run:
run_stdout = open(test_name + ".stdout", 'w')
start = time.time()
proc = subprocess.Popen(command,
shell=False,
stdout=run_stdout,
stderr=subprocess.STDOUT)
while proc.poll() is None:
time.sleep(0.1)
if time.time() - start > self._timeout:
proc.kill()
time.sleep(0.1)
message = self._txtwrap.fill(
"ERROR: job '{0}' has exceeded timeout limit of "
"{1} seconds.".format(test_name, self._timeout))
print(''.join(['\n', message, '\n']), file=testlog)
finish = time.time()
print(" # {0} : run time : {1:.2f} seconds".format(test_name, finish - start), file=testlog)
ierr_status = abs(proc.returncode)
run_stdout.close()
if ierr_status != self._SUCCESS:
status.fail = 1
message = self._txtwrap.fill(
"FAIL : {name} : {execute} return an error "
"code ({status}) indicating the simulation may have "
"failed. Please check '{name}.stdout' "
"for error messages (included below).".format(
execute=self._EXECUTABLE, name=test_name, status=ierr_status))
print("".join(['\n', message, '\n']), file=testlog)
print("~~~~~ {0}.stdout ~~~~~".format(test_name), file=testlog)
try:
with open("{0}.stdout".format(test_name), 'r') as tempfile:
shutil.copyfileobj(tempfile, testlog)
except Exception as e:
print(" Error opening file: {0}.stdout\n {1}".format(test_name, e))
print("~~~~~~~~~~", file=testlog)
os.chdir(test_directory)
def _cleanup_generated_files(self):
"""Cleanup old generated files that may be hanging around from a
previous run.
"""
run_dir = self.dirname(False)
shutil.rmtree(run_dir, ignore_errors=True)
def check(self, status, testlog):
"""
Check the test results against the gold standard
"""
for domain in self._criteria.keys():
self._check_gold(status, domain, testlog)
def update(self, status, testlog):
"""
Update the gold standard test results to the current
output. Both the current regression output and a gold file
must exist.
"""
gold_dir = self.dirname(True)
run_dir = self.dirname(False)
old_gold_dir = gold_dir+".old"
# verify that the gold file exists
if not os.path.isdir(gold_dir):
print("ERROR: test '{0}' results cannot be updated "
"because a gold directory does not "
"exist!".format(self.name()), file=testlog)
status.error = 1
# verify that the regression directory exists
if not os.path.isdir(run_dir):
print("ERROR: test '{0}' results cannot be updated "
"because no regression run directory "
"exists!".format(self.name()), file=testlog)
status.error = 1
# check that the regression file was created in the regression directory
if (not status.error and not status.fail):
for domain in self._criteria.keys():
reg_name = self.filename(domain, False)
if not os.path.isfile(reg_name):
print("ERROR: run for "
"test '{0}' did not create the needed regression file "
"'{1}', not updating!".format(self.name(),
reg_name), file=testlog)
status.fail = 1
if not status.error and not status.fail:
# remove old-old gold
if os.path.isdir(old_gold_dir):
try:
shutil.rmtree(old_gold_dir)
except Exception as error:
message = str(error)
message += "\nFAIL : Could not remove old gold '{0}'. ".format(old_gold_dir)
message += "Please remove the directory manually!"
message += " rm -rf {0}".format(old_gold_dir)
print(message, file=testlog)
status.fail = 1
# move gold -> old_gold
if not status.fail:
try:
os.rename(gold_dir, old_gold_dir)
except Exception as error:
message = str(error)
message += "\nFAIL : Could not back up gold '{0}' as '{1}'. ".format(
gold_dir, old_gold_dir)
message += "Please rename or remove the gold directory manually!"
message += " mv {0} {1}".format(gold_dir, old_gold_dir)
print(message, file=testlog)
status.fail = 1
if not status.fail:
# move run -> gold
try:
os.rename(run_dir, gold_dir)
except Exception as error:
message = str(error)
message += "\nFAIL : Could not move '{0}' to '{1}'. ".format(
run_dir, gold_dir)
message += "Please rename the directory manually!"
message += " mv {0} {1}".format(run_dir, gold_dir)
print(message, file=testlog)
status.fail = 1
print("done", file=testlog)
def new_test(self, status, testlog):
"""
A new test does not have a gold standard regression test. We
will check to see if a gold standard file exists (an error),
then create the gold file by copying the current regression
file to gold.
"""
gold_dir = self.dirname(True)
run_dir = self.dirname(False)
# verify that the gold file does not exisit
if os.path.isdir(gold_dir) or os.path.isfile(gold_dir):
print("ERROR: test '{0}' was classified as new, "
"but a gold file already "
"exists!".format(self.name()), file=testlog)
status.error = 1
# verify that the run directory exists
if not os.path.isdir(run_dir):
print("ERROR: test '{0}' results cannot be new "
"because no run directory "
"exists!".format(self.name()), file=testlog)
status.error = 1
# verify that the run directory created good files
if (not status.error and not status.fail):
for domain in self._criteria.keys():
reg_name = self.filename(domain, False)
if not os.path.isfile(reg_name):
print("ERROR: run for "
"test '{0}' did not create the needed regression file "
"'{1}', not making new gold!".format(self.name(),
reg_name), file=testlog)
status.fail = 1
# move the run to gold
if not status.error and not status.fail:
print(" creating gold directory '{0}'... ".format(self.name()),
file=testlog)
try:
os.rename(run_dir, gold_dir)
except Exception as error:
message = str(error)
message += "\nFAIL : Could not move '{0}' to '{1}'. ".format(
run_dir, gold_dir)
message += "Please rename the directory manually!"
message += " mv {0} {1}".format(run_dir, gold_dir)
print(message, file=testlog)
status.fail = 1
print("done", file=testlog)
def _check_gold(self, status, domain, testlog):
"""
Test the output from the run against the known "gold standard"
output and determine if the test succeeded or failed.
We return zero on success, one on failure so that the test
manager can track how many tests succeeded and failed.
"""
if self._skip_check_gold:
message = " Skipping comparison to regression gold file (only test if model runs to completion)."
print("".join(['\n', message, '\n']), file=testlog)
return
gold_filename = self.filename(domain, True)
if not os.path.isfile(gold_filename):
message = self._txtwrap.fill(
"FAIL: could not find regression test gold file "
"'{0}'. If this is a new test, please create "
"it with '--new-test'.".format(gold_filename))
print("".join(['\n', message, '\n']), file=testlog)
status.fail = 1
return
current_filename = self.filename(domain, False)
if not os.path.isfile(current_filename):
message = self._txtwrap.fill(
"FAIL: could not find regression test file '{0}'."
" Please check the standard output file for "
"errors.".format(current_filename))
print("".join(['\n', message, '\n']), file=testlog)
status.fail = 1
return
try:
h5_current = ats_h5.File(current_filename)
except Exception as e:
print(" FAIL: Could not open file: '{0}'".format(current_filename), file=testlog)
status.fail = 1
h5_current = None
try:
h5_gold = ats_h5.File(gold_filename)
except Exception as e:
print(" FAIL: Could not open file: '{0}'".format(gold_filename), file=testlog)
status.fail = 1
h5_gold = None
if h5_gold is not None and h5_current is not None:
self._compare(h5_current, h5_gold, domain, status, testlog)
h5_gold.close()
h5_current.close()
def _compare(self, h5_current, h5_gold, domain, status, testlog):
"""Check that output hdf5 file has not changed from the baseline.
"""
for key, tolerance in self._criteria[domain].iteritems():
if key == self._TIME:
self._compare_time(h5_current, h5_gold, tolerance,
status, testlog)
elif key == self._TIMESTEPS:
self._compare_timesteps(h5_current, h5_gold, tolerance,
status, testlog)
else:
self._compare_values(h5_current, h5_gold, key, tolerance,
status, testlog)
if status.fail == 0:
print(" Passed tests.", file=testlog)
def _compare_time(self, h5_current, h5_gold, tolerance, status, testlog):
self._check_tolerance(h5_current.simulationTime(), h5_gold.simulationTime(),
self._TIME, tolerance, status, testlog)
def _compare_timesteps(self, h5_current, h5_gold, tolerance, status, testlog):
self._check_tolerance(h5_current.numSteps(), h5_gold.numSteps(),
self._TIMESTEPS, tolerance, status, testlog)
def _compare_values(self, h5_current, h5_gold, key, tolerance, status, testlog):
if set(h5_current.matches(key)) != set(h5_gold.matches(key)):
status.fail = 1
print(" FAIL: {0} : {1} :".format(self.name(), key), file=testlog)
print(" gold matches: {1}".format(";".join(h5_gold.matches(key))),
file=testlog)
print(" current matches: {1}".format(";".join(h5_current.matches(key))),
file=testlog)
else:
if self._checkpoint is not None:
for k in h5_gold.matches(key):
self._check_tolerance(h5_current[k][:], h5_gold[k][:],
k, tolerance, status, testlog)
else:
for k in h5_gold.matches(key):
for i_current, i_gold in zip(h5_current.steps(), h5_gold.steps()):
key_with_index = "{0} [{1}]".format(k, i_gold)
self._check_tolerance(h5_current[k][i_current][:],
h5_gold[k][i_gold][:],
key_with_index, tolerance,
status, testlog)
def _norm(self, diff):
"""
Determine the difference between two values
"""
if type(diff) is numpy.ndarray:
delta = numpy.linalg.norm(diff.flatten(), self._NORM)
else:
delta = abs(diff)
return delta
def _check_tolerance(self, current, gold, key, tolerance, status, testlog):
"""
Compare the values using the appropriate tolerance and criteria.
"""
my_status = 0
# unpack the tolerance
tol, tol_type, min_threshold, max_threshold = tuple(tolerance)
if tol_type == self._ABSOLUTE:
delta = self._norm(current-gold)
elif (tol_type == self._RELATIVE or
tol_type == self._PERCENT):
if type(gold) is numpy.ndarray:
rel_to = numpy.where(gold > self._eps, gold, current)
filter = numpy.where(rel_to > self._eps)[0]
if filter.shape[0] == 0:
delta = 0
else:
delta = self._norm((gold[filter] - current[filter]) / rel_to[filter])
else:
if gold > self._eps:
delta = self._norm((gold - current) / gold)
elif current > self._eps:
delta = self._norm((gold - current) / current)
else:
delta = 0
if tol_type == self._PERCENT:
delta *= 100.0
else:
# should never get here....
raise RuntimeError("ERROR: unknown test tolerance_type '{0}' for "
"variable '{1}, {2}.'".format(tol_type,
self.name(), key))
if delta > tol:
status.fail = 1
print(" FAIL: {0} : {1} : {2} > {3} [{4}]".format(
self.name(), key, delta, tol, tol_type), file=testlog)
else:
print(" PASS: {0} : {1} : {2} <= {3} [{4}]".format(
self.name(), key, delta, tol, tol_type), file=testlog)
return
def _set_criteria(self, key, cfg_criteria, test_data):
"""
Our preferred order for selecting test criteria is:
(1) test data section of the config file
(2) config-file wide defaults
(3) hard coded class default
"""
# strip the domain prefix
if key.startswith("("):
domain,varname = key[1:].split(")")
elif "-" in key:
domain = key.split("-")[0]
varname = key
else:
domain = ""
varname = key
# parse the criteria
if key in test_data:
criteria = domain, varname, self._validate_tolerance(key, varname, test_data[key])
elif key in cfg_criteria:
criteria = domain, varname, self._validate_tolerance(key, varname, cfg_criteria[key])
elif varname == self._TIME:
criteria = domain, self._TIME, self._default_tolerance[self._TIME]
elif varname == self._TIMESTEPS:
criteria = domain, self._TIMESTEPS, self._default_tolerance[self._TIMESTEPS]
else:
criteria = domain, varname, self._default_tolerance[self._DEFAULT]
if criteria is not None:
domain,varname,tol = criteria
if tol is not None:
domain_dict = self._criteria.setdefault(domain,dict())
domain_dict[varname] = tol
def _validate_tolerance(self, key, varname, test_data):
"""
Validate the tolerance string from a config file.
Valid input configurations are:
* (domain)varname =
* (domain)varname = default
* (domain)varname = no
* (domain)varname = tolerance type
* (domain)varname = tolerance type [, min_threshold value] [, max_threshold value]
where the first two use defaults, the third turns the test
off, and the last two specify the tolerance explicitly, where
min_threshold and max_threshold are optional
"""
# deal with defaults first
if test_data.lower() == "none" or test_data.lower() == "no" or test_data.lower() == "n":
return None
if test_data == "" or test_data.lower() == self._DEFAULT:
return self._default_tolerance[self._DEFAULT]
if test_data == self._DISCRETE:
return self._default_tolerance[self._DISCRETE]
# if we get here, parse the string
criteria = 4*[None]
test_data = test_data.split(",")
test_criteria = test_data[0]
value = test_criteria.split()[0]
try:
value = float(value)
except Exception:
raise RuntimeError("ERROR : Could not convert '{0}' test criteria "
"value '{1}' into a float!".format(key, value))
criteria[0] = value
criteria_type = test_criteria.split()[1]
if (criteria_type.lower() != self._PERCENT and
criteria_type.lower() != self._ABSOLUTE and
criteria_type.lower() != self._RELATIVE):
raise RuntimeError("ERROR : invalid test criteria string '{0}' "
"for '{1}'".format(criteria_type, key))
criteria[1] = criteria_type
thresholds = {}
for t in range(1, len(test_data)):
name = test_data[t].split()[0].strip()
value = test_data[t].split()[1].strip()
try:
value = float(value)
except Exception:
raise RuntimeError(
"ERROR : Could not convert '{0}' test threshold '{1}'"
"value '{2}' into a float!".format(key, name, value))
thresholds[name] = value
value = thresholds.pop("min_threshold", None)
criteria[2] = value
value = thresholds.pop("max_threshold", None)
criteria[3] = value
if len(thresholds) > 0:
raise RuntimeError("ERROR: test {0} : unknown criteria threshold: {1}",
key, thresholds)
return criteria
class RegressionTestManager(object):
"""
Class to open a configuration file, process it into a group of
tests, and manage running the tests.
Notes:
* The ConfigParser class converts all section names and key
names into lower case. This means we need to preprocess user
input names to lower case.
"""
def __init__(self):
self._debug = False
self._file_status = TestStatus()
self._config_filename = None
self._default_test_criteria = {}
self._available_tests = {}
self._available_suites = {}
self._tests = []
self._txtwrap = textwrap.TextWrapper(width=78, subsequent_indent=4*" ")
# self._pprint = pprint.PrettyPrinter(indent=2)
def __str__(self):
data = "Regression Test Manager :\n"
data += " configuration file : {0}\n".format(self._config_filename)
data += " default test criteria :\n"
data += self._dict_to_string(self._default_test_criteria)
data += " suites :\n"
data += self._dict_to_string(self._available_suites)
data += " available tests :\n"
data += self._dict_to_string(self._available_tests)
data += "Tests :\n"
for test in self._tests:
data += test.__str__()
return data
def debug(self, debug):
self._debug = debug
def num_tests(self):
return len(self._tests)
def generate_tests(self, config_file, user_suites, user_tests,
timeout, check_performance, testlog):
"""
Read the config file, validate the input and generate the test objects.
"""
self._read_config_file(config_file)
self._validate_suites()
user_suites, user_tests = self._validate_user_lists(user_suites,
user_tests, testlog)
self._create_tests(user_suites, user_tests, timeout, check_performance,
testlog)
def run_tests(self, mpiexec, executable,
dry_run, update, new_test, check_only, testlog):
"""
Run the tests specified in the config file.
* dry_run - flag indicates that the test is setup then print
the command that would be used, but don't actually run
anything or compare results.
* new_test - flag indicates that the test is a new test, and
there should not be a gold standard regression file
present. Run the executable and create the gold file.
* update - flag indicates that the output from ats has
changed, and we want to update the gold standard regression
file to reflect this. Run the executable and replace the
gold file.
* check_only - flag to indicate just diffing the existing
regression files without rerunning ats.
"""
if self.num_tests() > 0:
if new_test:
self._run_new(mpiexec, executable, dry_run, testlog)
elif update:
self._run_update(mpiexec, executable, dry_run, testlog)
elif check_only:
self._check_only(dry_run, testlog)
else:
self._run_check(mpiexec, executable, dry_run, testlog)
else:
self._file_status.test_count = 0
def _run_check(self, mpiexec, executable, dry_run, testlog):
"""
Run the test and check the results.
"""
if dry_run:
print("Dry run:")
print("Running tests from '{0}':".format(self._config_filename), file=testlog)
print(50 * '-', file=testlog)
for test in self._tests:
status = TestStatus()
self._test_header(test.name(), testlog)
test.run(mpiexec, executable, dry_run, status, testlog)
if not dry_run and status.skipped == 0:
test.check(status, testlog)
self._add_to_file_status(status)
self._test_summary(test.name(), status, dry_run,
"passed", "failed", testlog)
self._print_file_summary(dry_run, "passed", "failed", testlog)
def _check_only(self, dry_run, testlog):
"""
Recheck the regression files from a previous run.
"""
if dry_run:
print("Dry run:")
print("Checking existing test results from '{0}':".format(
self._config_filename), file=testlog)
print(50 * '-', file=testlog)
for test in self._tests:
status = TestStatus()
self._test_header(test.name(), testlog)
if not dry_run and status.skipped == 0:
test.check(status, testlog)
self._add_to_file_status(status)
self._test_summary(test.name(), status, dry_run,
"passed", "failed", testlog)
self._print_file_summary(dry_run, "passed", "failed", testlog)
def _run_new(self, mpiexec, executable, dry_run, testlog):
"""
Run the tests and create new gold files.
"""
if dry_run:
print("Dry run:")
print("New tests from '{0}':".format(self._config_filename), file=testlog)
print(50 * '-', file=testlog)
for test in self._tests:
status = TestStatus()
self._test_header(test.name(), testlog)
test.run(mpiexec, executable, dry_run, status, testlog)
if not dry_run and status.skipped == 0:
test.new_test(status, testlog)
self._add_to_file_status(status)
self._test_summary(test.name(), status, dry_run,
"created", "error creating new test files.", testlog)
self._print_file_summary(dry_run, "created", "could not be created", testlog)
def _run_update(self, mpiexec, executable, dry_run, testlog):
"""
Run the tests and update the gold file with the current output
"""
if dry_run:
print("Dry run:")
print("Updating tests from '{0}':".format(self._config_filename), file=testlog)
print(50 * '-', file=testlog)
for test in self._tests:
status = TestStatus()
self._test_header(test.name(), testlog)
test.run(mpiexec, executable, dry_run, status, testlog)
if not dry_run and status.skipped == 0:
test.update(status, testlog)
self._add_to_file_status(status)
self._test_summary(test.name(), status, dry_run,
"updated", "error updating test.", testlog)
self._print_file_summary(dry_run, "updated", "could not be updated", testlog)
def _test_header(self, name, testlog):
"""
Write a header to the log file to separate tests.
"""
print(40 * '-', file=testlog)
print("{0}... ".format(name), file=testlog)
def _test_summary(self, name, status, dry_run,
success_message, fail_message, testlog):
"""
Write the test status information to stdout and the test log.
"""
if dry_run:
print("D", end='', file=sys.stdout)
print(" dry run.", file=testlog)
else:
if (status.fail == 0 and
status.warning == 0 and
status.error == 0 and
status.skipped == 0):
print(".", end='', file=sys.stdout)
print("{0}... {1}.".format(name, success_message), file=testlog)
elif status.fail != 0:
print("F", end='', file=sys.stdout)
print("{0}... {1}.".format(name, fail_message), file=testlog)
elif status.warning != 0:
print("W", end='', file=sys.stdout)
elif status.error != 0:
print("E", end='', file=sys.stdout)
elif status.skipped != 0:
print("S", end='', file=sys.stdout)
print("{0}... skipped.".format(name), file=testlog)
else:
print("?", end='', file=sys.stdout)
sys.stdout.flush()
def _print_file_summary(self, dry_run, success_message, fail_message, testlog):
"""
Print a summary of the results for this config file
"""
print("", file=sys.stdout)
print(50 * '-', file=testlog)
if dry_run:
print("{0} : dry run.".format(self._config_filename), file=testlog)
elif self._file_status.test_count == 0:
print("{0} : no tests run.".format(self._config_filename), file=testlog)
else:
line = "{0} : {1} tests : ".format(self._config_filename,
self._file_status.test_count)
if self._file_status.fail > 0:
line = "{0} {1} tests {2}, ".format(
line, self._file_status.fail, fail_message)
if self._file_status.skipped > 0:
line = "{0} {1} tests {2}, ".format(
line, self._file_status.skipped, "skipped")
num_passed = (self._file_status.test_count -
self._file_status.fail - self._file_status.skipped)
line = "{0} {1} tests {2}".format(line, num_passed, success_message)
print(line, file=testlog)
def _add_to_file_status(self, status):
"""
Add the current test status to the overall status for the file.
"""
self._file_status.fail += status.fail
self._file_status.warning += status.warning
self._file_status.error += status.error
self._file_status.skipped += status.skipped
self._file_status.test_count += 1
def run_status(self):
return self._file_status
def display_available_tests(self):
print("Available tests: ")
for test in sorted(self._available_tests.keys()):
print(" {0}".format(test))
def display_available_suites(self):
print("Available test suites: ")
for suite in self._available_suites:
print(" {0} :".format(suite))
for test in self._available_suites[suite].split():
print(" {0}".format(test))
def _read_config_file(self, config_file):
"""
Read the configuration file.
Sections : The config file will have known sections:
"suites", "default-test-criteria".
All other sections are assumed to be test names.
"""
if config_file is None: