forked from MPAS-Dev/compass
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_testcase.py
More file actions
executable file
·1870 lines (1552 loc) · 73 KB
/
setup_testcase.py
File metadata and controls
executable file
·1870 lines (1552 loc) · 73 KB
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
"""
This script is used to setup individual test cases. Available test cases
can be see using the list_testcases.py script.
Specifically, this script parses XML files that define cases (steps in test
cases) and driver scripts, and generates directories and scripts to run each
step in the process of creating a test case.
This script requires a setup configuration file. Configuration files are
specific to each core. Template configuration files for each core can be seen
in this directory named 'general.config.{core}'. Each core may have different
requirements as far as what is required within a configuration file.
"""
from __future__ import absolute_import, division, print_function, \
unicode_literals
import sys
import os
import fnmatch
import argparse
import xml.etree.ElementTree as ET
import subprocess
from six.moves import configparser
import textwrap
import netCDF4
import shutil
import errno
try:
from collections import defaultdict
except ImportError:
from utils import defaultdict
# *** Namelist setup functions *** # {{{
def generate_namelist_files(config_file, case_path, configs): # {{{
config_tree = ET.parse(config_file)
config_root = config_tree.getroot()
# Iterate over all namelists to be generated
for namelists in config_root.iter('namelist'):
# Determine the name of the namelist that will be generated
try:
namelist_file = '{}/{}'.format(case_path, namelists.attrib['name'])
except KeyError:
print("ERROR: <namelist> tag is missing the 'name' attribute")
print("Exiting...")
sys.exit(1)
try:
namelist_mode = namelists.attrib['mode']
except KeyError:
print("ERROR: <namelist> tag is missing the 'mode' attribute.")
print("Exiting...")
sys.exit(1)
if not configs.has_option("namelists", namelist_mode):
print("Error. Configuration file '{}' requires paths for "
"streams and namelist files for '{}' mode.".format(
config_file, namelist_mode))
print("Exiting...")
sys.exit(1)
template_namelist = configs.get("namelists", namelist_mode)
# Ingest namelist template into a dictionary
namelist_dict = defaultdict(lambda: defaultdict(list))
ingest_namelist(template_namelist, namelist_dict)
# Modify the dictionary to have the desired values
configure_namelist(namelist_dict, namelists, configs)
# Write the namelist using the template to determine the writing order.
write_namelist(namelist_dict, namelist_file, template_namelist)
del namelist_dict
del config_root
del config_tree
# }}}
def ingest_namelist(namelist_file, namelist_dict): # {{{
# Read the template file
namelistfile = open(namelist_file, 'r')
lines = namelistfile.readlines()
record_name = 'NONE!!!'
# Add each linke into the corresponding record / option entry in the
# dictionary.
for line in lines:
if line.find('&') >= 0:
record_name = line.strip().strip('&').strip('\n')
namelist_dict[record_name] = defaultdict(list)
elif line.find('=') >= 0:
opt, val = line.strip().strip('\n').split('=')
if record_name != "NONE!!!":
namelist_dict[record_name][opt].append(val)
# }}}
def set_namelist_val(namelist_dict, option_name, option_val): # {{{
# Set the value of the namelist option.
for record, opts in namelist_dict.items():
for opt, val in opts.items():
if opt.strip() == option_name:
val[0] = option_val
# }}}
def configure_namelist(namelist_dict, namelist_tag, configs): # {{{
# Iterate over all children within the namelist tag.
for child in namelist_tag:
# Process <option> tags
if child.tag == 'option':
option_name = child.attrib['name']
option_val = child.text
set_namelist_val(namelist_dict, option_name, option_val)
# Process <template> tags
elif child.tag == 'template':
apply_namelist_template(namelist_dict, child, configs)
# }}}
def apply_namelist_template(namelist_dict, template_tag, configs): # {{{
# Determine the template information, like it's path and the filename
template_info = get_template_info(template_tag, configs)
# Build the full filename for the template
template_file = '{}/{}'.format(template_info['template_path'],
template_info['template_file'])
# Parse the template
template_tree = ET.parse(template_file)
template_root = template_tree.getroot()
# Apply the template, by changing each option
for child in template_root:
if child.tag == 'namelist':
for grandchild in child:
if grandchild.tag == 'option':
option_name = grandchild.attrib['name']
option_val = grandchild.text
set_namelist_val(namelist_dict, option_name, option_val)
elif grandchild.tag == 'template':
apply_namelist_template(namelist_dict, grandchild, configs)
del template_root
del template_tree
del template_info
# }}}
def write_namelist(namelist_dict, outfilename, infilename): # {{{
# Write the namelist out, using the infilename as a template to determine
# the writing order.
in_namelist = open(infilename, 'r')
lines = in_namelist.readlines()
in_namelist.close()
out_namelist = open(outfilename, 'w+')
record_name = 'NONE!!!'
for line in lines:
if line.find('&') >= 0:
if record_name != "NONE!!!":
out_namelist.write('/\n')
record_name = line.strip().strip('&').strip('\n')
out_namelist.write(line)
elif line.find('=') >= 0:
opt, val = line.strip().strip('\n').split('=')
if record_name != "NONE!!!":
out_namelist.write(' {} = {}\n'.format(
opt.strip(),
namelist_dict[record_name][opt][0].strip()))
if record_name != "NONE!!!":
out_namelist.write('/\n')
out_namelist.close()
# }}}
# }}}
# *** Streams setup functions *** # {{{
def generate_streams_files(config_file, case_path, configs): # {{{
config_tree = ET.parse(config_file)
config_root = config_tree.getroot()
# Iterate over all sterams files to be generated
for streams in config_root:
if streams.tag == "streams":
# Determine the path to the template streams file
streams_filename = '{}/{}'.format(case_path,
streams.attrib['name'])
try:
streams_mode = streams.attrib['mode']
except KeyError:
print("ERROR: <streams> tag is missing the 'mode' attribute.")
print("Exiting...")
sys.exit(1)
if not configs.has_option("streams", streams_mode):
print("Error. Configuration file '{}' requires paths for "
"streams and namelist files for '{}' mode.".format(
config_file, streams_mode))
print("Exiting...")
sys.exit(1)
template_streams = configs.get("streams", streams_mode)
# Parse the template
streams_tree = ET.parse(template_streams)
streams_root = streams_tree.getroot()
# Configure the new streams file, using the template as a starting
# place.
configure_streams_file(streams_root, streams, configs)
# Write out the streams file
write_streams_file(streams_root, config_file, streams_filename,
'{}'.format(case_path))
del streams_root
del streams_tree
# }}}
def flush_streams(streams, remove_mutable, remove_immutable): # {{{
if remove_mutable:
# Remove all mutable streams from the template streams file
for stream in streams.findall('stream'):
streams.remove(stream)
if remove_immutable:
# Remove all immutable streams from the template streams file
for stream in streams.findall('immutable_stream'):
streams.remove(stream)
# }}}
def modify_stream_definition(streams_file, stream_conf): # {{{
# Determine the name of the stream to modify
name_to_modify = stream_conf.attrib['name']
found = False
# Check if stream already exists:
for stream in streams_file:
if stream.tag == 'stream' or stream.tag == 'immutable_stream':
name = stream.attrib['name']
if name.strip() == name_to_modify.strip():
if not found:
found = True
stream_to_modify = stream
else:
print("ERROR: Stream {} found multiple times in "
"template. Exiting...".format(name.strip()))
sys.exit(1)
# If not found, need to create it
if not found:
found = True
stream_to_modify = ET.SubElement(streams_file, 'stream')
stream_to_modify.set('name', name_to_modify)
# Make all of the modifications from the config file
for child in stream_conf:
# Process attribute changes
if child.tag == 'attribute':
attr_name = child.attrib['name']
attr_val = child.text
stream_to_modify.set(attr_name, attr_val)
# Process adding contents to the stream
elif child.tag == 'add_contents':
for member in child.findall('member'):
member_name = member.attrib['name']
member_type = member.attrib['type']
sub_member = ET.SubElement(stream_to_modify, member_type)
sub_member.set('name', member_name)
if 'packages' in member.attrib.keys():
member_packages = member.attrib['packages']
sub_member.set('packages', member_packages)
# Process removing contents from the stream
elif child.tag == 'remove_contents':
for member in child.findall('member'):
member_name = member.attrib['name']
for child in stream_to_modify.iter('*'):
try:
if child.attrib['name'] == member_name:
stream_to_modify.remove(child)
except KeyError:
print(" --- Tag: {} is missing a name "
"attribute".format(child.tag))
# }}}
def configure_streams_file(streams_file, streams_tag, configs): # {{{
keep_mode = streams_tag.attrib['keep']
remove_immutable = False
remove_mutable = False
if keep_mode.strip() == 'immutable':
remove_mutable = True
if keep_mode.strip() == 'mutable':
remove_immutable = True
if keep_mode.strip() == 'none':
remove_mutable = True
remove_immutable = True
# Flush requested streams
flush_streams(streams_file, remove_mutable, remove_immutable)
# Process all stream modifications
for child in streams_tag:
# Process all templates
if child.tag == 'template':
apply_stream_template(streams_file, child, configs)
# Process stream definitions / modifications
elif child.tag == 'stream':
modify_stream_definition(streams_file, child)
# }}}
def apply_stream_template(streams_file, template_tag, configs): # {{{
# Determine template information, like path and filename
template_info = get_template_info(template_tag, configs)
# Build full path to template file
template_file = '{}/{}'.format(template_info['template_path'],
template_info['template_file'])
# Parse the template
template_tree = ET.parse(template_file)
template_root = template_tree.getroot()
# Apply the streams portion of the template to the streams file
for child in template_root:
if child.tag == 'streams':
for grandchild in child:
if grandchild.tag == 'stream':
modify_stream_definition(streams_file, grandchild)
elif grandchild.tag == 'template':
apply_stream_template(streams_file, grandchild, configs)
del template_tree
del template_root
del template_info
# }}}
def write_streams_file(streams, config_file, filename, init_path): # {{{
config_tree = ET.parse(config_file)
config_root = config_tree.getroot()
stream_file = open(filename, 'w')
stream_file.write('<streams>\n')
# Write out all immutable streams first
for stream in streams.findall('immutable_stream'):
stream_name = stream.attrib['name']
stream_file.write('\n')
stream_file.write('<immutable_stream name="{}"'.format(stream_name))
# Process all attributes on the stream
for attr, val in stream.attrib.items():
if attr.strip() != 'name':
stream_file.write('\n {}="{}"'.format(attr,
val))
stream_file.write('/>\n')
# Write out all immutable streams
for stream in streams.findall('stream'):
stream_name = stream.attrib['name']
stream_file.write('\n')
stream_file.write('<stream name="{}"'.format(stream_name))
# Process all attributes
for attr, val in stream.attrib.items():
if attr.strip() != 'name':
stream_file.write('\n {}="{}"'.format(attr, val))
stream_file.write('>\n\n')
# Write out all streams included in this stream
for substream in stream.findall('stream'):
substream_name = substream.attrib['name']
if 'packages' in substream.attrib.keys():
package_name = substream.attrib['packages']
entry = ' <stream name="{}"'.format(substream_name) + \
' packages="{}" '.format(package_name) + '/>\n'
else:
entry = ' <stream name="{}"'.format(substream_name) + '/>\n'
stream_file.write(entry)
# Write out all var_structs included in this stream
for var_struct in stream.findall('var_struct'):
var_struct_name = var_struct.attrib['name']
if 'packages' in var_struct.attrib.keys():
package_name = var_struct.attrib['packages']
entry = ' <var_struct name="{}"'.format(var_struct_name) + \
' packages="{}" '.format(package_name) + '/>\n'
else:
entry = ' <var_struct name="{}"'.format(var_struct_name) + \
'/>\n'
stream_file.write(entry)
# Write out all var_arrays included in this stream
for var_array in stream.findall('var_array'):
var_array_name = var_array.attrib['name']
if 'packages' in var_array.attrib.keys():
package_name = var_array.attrib['packages']
entry = ' <var_array name="{}"'.format(var_array_name) + \
' packages="{}" '.format(package_name) + '/>\n'
else:
entry = ' <var_array name="{}"'.format(var_array_name) + \
'/>\n'
stream_file.write(entry)
# Write out all vars included in this stream
for var in stream.findall('var'):
var_name = var.attrib['name']
if 'packages' in var.attrib.keys():
package_name = var.attrib['packages']
entry = ' <var name="{}"'.format(var_name) + \
' packages="{}" '.format(package_name) + '/>\n'
else:
entry = ' <var name="{}"'.format(var_name) + '/>\n'
stream_file.write(entry)
stream_file.write('</stream>\n')
stream_file.write('\n')
stream_file.write('</streams>\n')
del config_tree
del config_root
# }}}
# }}}
# *** Script Generation Functions *** # {{{
def generate_run_scripts(config_file, init_path, configs): # {{{
config_tree = ET.parse(config_file)
config_root = config_tree.getroot()
dev_null = open('/dev/null', 'r+')
for run_script in config_root:
# Process run_script
if run_script.tag == 'run_script':
# Determine the name of the script, and create the file
script_name = run_script.attrib['name']
script_path = "{}/{}".format(init_path, script_name)
script = open(script_path, "w")
# Write the script header
script.write("#!/usr/bin/env python\n")
script.write("\n")
script.write("# This script was generated from "
"setup_testcases.py as part of a config file\n")
script.write("\n")
script.write('import sys\n')
script.write('import os\n')
script.write('import shutil\n')
script.write('import glob\n')
script.write("import subprocess\n\n\n")
script.write("dev_null = open('/dev/null', 'w')\n")
# Process each part of the run script
for child in run_script:
# Process each <step> tag
if child.tag == 'step':
process_script_step(child, configs, '', script)
# Process each <define_env_var> tag
elif child.tag == 'define_env_var':
process_env_define_step(child, configs, '', script)
elif child.tag == 'model_run':
process_model_run_step(child, configs, script)
# Finish writing the script
script.close()
# Make the script executable
subprocess.check_call(['chmod', 'a+x', '{}'.format(script_path)],
stdout=dev_null, stderr=dev_null)
dev_null.close()
del config_tree
del config_root
# }}}
def generate_driver_scripts(config_file, configs): # {{{
config_tree = ET.parse(config_file)
config_root = config_tree.getroot()
dev_null = open('/dev/null', 'r+')
# init_path is where the driver script will live after it's generated.
init_path = '{}/{}'.format(config.get('script_paths', 'work_dir'),
config.get('script_paths', 'config_path'))
# Ensure we're in a <driver_script> tag
if config_root.tag == 'driver_script':
name = config_root.attrib['name']
# Ensure work_dir exists before writing driver script there.
if not os.path.exists(init_path):
os.makedirs(init_path)
link_load_compass_env(init_path, configs)
# Create script file
script = open('{}/{}'.format(init_path, name), 'w')
# Write script header
script.write('#!/usr/bin/env python\n')
script.write('"""\n')
script.write('This script was generated as part of a driver_script '
'file by the\nsetup_testcases.py script.\n')
script.write('"""\n')
script.write('import sys\n')
script.write('import os\n')
script.write('import shutil\n')
script.write('import glob\n')
script.write('import subprocess\n')
script.write('import argparse\n')
script.write('\n\n')
script.write('# This script was generated by setup_testcases.py as '
'part of a driver_script\n'
'# file.\n')
script.write("os.environ['PYTHONUNBUFFERED'] = '1'\n")
script.write('parser = argparse.ArgumentParser(\n'
' description=__doc__, '
'formatter_class=argparse.RawTextHelpFormatter)\n')
case_dict = dict()
for child in config_root:
if child.tag == 'case':
case_name = child.attrib['name']
case_dict[case_name] = '1'
if child.tag == 'template':
print(" WARNING: use of templates outside of a case in a "
"driver_script is not supported!")
print(" (name of template file is {})".format(
child.attrib['file']))
for case_name in case_dict.keys():
script.write('parser.add_argument("--no_{}", dest="no_{}",\n'
' help="If set, {} case will not '
'be run during "\n'
' "execution of this script'
'.",\n'
' action="store_true")\n'.format(
case_name, case_name, case_name))
script.write('parser.add_argument("--finalize_{}", '
'dest="finalize_{}",\n'
' help="If set, {} case will have '
'symlinks replaced "\n'
' "with the files they point '
'to, this occurs after any "\n'
' "case runs that have been '
'requested.",\n'
' action="store_true")\n'.format(
case_name, case_name, case_name))
script.write('\n')
script.write('args = parser.parse_args()\n')
script.write('base_path = os.getcwd()\n')
script.write("dev_null = open('/dev/null', 'w')\n")
script.write('error = False\n')
script.write('\n')
# Process children of driver_script
for child in config_root:
# Process each case, by changing into that directory, and
# processing each step / define_env_var tag within it.
if child.tag == 'case':
case = child.attrib['name']
script.write('if not args.no_{}:\n'.format(case))
script.write(' os.chdir(base_path)\n')
script.write(' os.chdir(' + "'{}')\n".format(case))
# Process children of <case> tag
for grandchild in child:
# Process <step> tags
if grandchild.tag == 'step':
process_script_step(grandchild, configs, ' ',
script)
# Process <define_env_var> tags
elif grandchild.tag == 'define_env_var':
process_env_define_step(grandchild, configs, ' ',
script)
# Process <step> tags
elif child.tag == 'step':
script.write('os.chdir(base_path)\n')
process_script_step(child, configs, '', script)
# Process <compare_fields> tags
elif child.tag == 'validation':
script.write('os.chdir(base_path)\n')
process_validation_step(child, configs, script)
# Process <define_env_var> tags
elif child.tag == 'define_env_var':
script.write('os.chdir(base_path)\n')
process_env_define_step(child, configs, '', script)
# Write script footer, that ensures a 1 is returned if the script
# encountered an error. This happens before finalizing a case
# directory.
script.write('if error:\n')
script.write(' sys.exit(1)\n')
for case_name in case_dict.keys():
script.write('if args.finalize_{}:\n'.format(case_name))
script.write(' old_dir = os.getcwd()\n')
script.write(' os.chdir("{}")\n'.format(case_name))
script.write(' file_list = glob.glob("*")\n')
script.write(' for file in file_list:\n')
script.write(' if os.path.islink(file):\n')
script.write(' link_path = os.readlink(file)\n')
script.write(' os.unlink(file)\n')
script.write(' shutil.copyfile(link_path, file)\n')
script.write(' os.chdir(old_dir)\n')
script.write('\n')
script.write('sys.exit(0)\n')
script.close()
del case_dict
# Make script executable
subprocess.check_call(['chmod', 'a+x',
'{}/{}'.format(init_path, name)],
stdout=dev_null, stderr=dev_null)
# }}}
def process_env_define_step(var_tag, configs, indentation, script_file): # {{{
try:
var_name = var_tag.attrib['name']
except KeyError:
print("ERROR: <define_env_var> tag is missing 'name' attribte")
print('Exiting...')
sys.exit(1)
try:
var_val = var_tag.attrib['value']
except KeyError:
print("ERROR: <define_env_var> tag is missing 'value' attribute")
print('Exiting...')
sys.exit(1)
# Write line to define the environment variable
script_file.write("{}os.environ['{}'] = '{}'\n".format(indentation,
var_name,
var_val))
# }}}
def process_script_step(step, configs, indentation, script_file): # {{{
# Determine step attributes.
if 'executable_name' in step.attrib.keys() and 'executable' in \
step.attrib.keys():
print("ERROR: <step> tag has both an 'executable' and "
"'executable_name' attribute. Only one is allowed per step.")
print("Exiting...")
sys.exit(1)
try:
quiet_val = step.attrib['quiet']
if quiet_val == "true":
quiet = True
else:
quiet = False
except KeyError:
quiet = False
try:
step_pre_message = step.attrib['pre_message']
write_pre_message = True
except KeyError:
write_pre_message = False
try:
step_post_message = step.attrib['post_message']
write_post_message = True
except KeyError:
write_post_message = False
try:
executable_name = step.attrib['executable_name']
executable = configs.get('executables', executable_name)
except KeyError:
executable = step.attrib['executable']
# Write step header
script_file.write("\n")
# If a pre_message attribute was supplied, write it before adding the
# command.
if write_pre_message:
script_file.write('{}print("{}")\n'.format(indentation,
step_pre_message))
script_file.write("{}# Run command is:\n".format(indentation))
command_args = [executable]
# Process step arguments
for argument in step:
if argument.tag == 'argument':
flag = argument.attrib['flag']
val = argument.text
if flag.strip() != "":
command_args.append(flag)
if val is not None:
command_args.append(val)
# Build comment and command bases
comment = wrap_subprocess_comment(command_args, indentation)
command = wrap_subprocess_command(command_args, indentation, quiet)
# Write the comment, and the command. Also, ensure the command has the same
# environment as the calling script.
script_file.write("{}\n".format(comment))
script_file.write("{}\n".format(command))
# If a post_message attribute was supplied, write it after the command.
if write_post_message:
script_file.write('{}print("{}")\n'.format(indentation,
step_post_message))
# }}}
def process_validation_step(validation_tag, configs, script): # {{{
for child in validation_tag:
if child.tag == 'compare_fields':
process_compare_fields_step(child, configs, script)
if child.tag == 'compare_timers':
process_compare_timers_step(child, configs, script)
# }}}
# *** Field Comparison Functions *** ##{{{
def process_compare_fields_step(compare_tag, configs, script): # {{{
missing_file1 = False
missing_file2 = False
# Determine comparison attributes
try:
file1 = compare_tag.attrib['file1']
except KeyError:
missing_file1 = True
try:
file2 = compare_tag.attrib['file2']
except KeyError:
missing_file2 = True
if missing_file1 and missing_file2:
print("ERROR: <compare_fields> tag is missing both 'file1' and "
"'file2' tags. At least one is required.")
print("Exiting...")
sys.exit(1)
baseline_root = configs.get('script_paths', 'baseline_dir')
if baseline_root != 'NONE':
baseline_root = '{}/{}'.format(baseline_root,
configs.get('script_paths', 'test_dir'))
for child in compare_tag:
# Process field comparisons
if child.tag == 'field':
if not (missing_file1 or missing_file2):
process_field_definition(child, configs, script, file1, file2,
False)
if not missing_file1 and baseline_root != 'NONE':
process_field_definition(child, configs, script, file1,
'{}/{}'.format(baseline_root, file1),
True)
if not missing_file2 and baseline_root != 'NONE':
process_field_definition(child, configs, script, file2,
'{}/{}'.format(baseline_root, file2),
True)
# Process field comparison template
elif child.tag == 'template':
apply_compare_fields_template(child, compare_tag, configs, script)
# }}}
def apply_compare_fields_template(template_tag, compare_tag, configs, script):
# {{{
missing_file1 = False
missing_file2 = False
# Determine comparison attributes
try:
file1 = compare_tag.attrib['file1']
except KeyError:
missing_file1 = True
try:
file2 = compare_tag.attrib['file2']
except KeyError:
missing_file2 = True
if missing_file1 and missing_file2:
print("ERROR: <compare_fields> tag is missing both 'file1' and "
"'file2' tags. At least one is required.")
print("Exiting...")
sys.exit(1)
# Build the path to the baselines
baseline_root = configs.get('script_paths', 'baseline_dir')
if baseline_root != 'NONE':
baseline_root = '{}/{}'.format(baseline_root,
configs.get('script_paths', 'test_dir'))
# Determine template information, like path and filename
template_info = get_template_info(template_tag, configs)
template_file = '{}/{}'.format(template_info['template_path'],
template_info['template_file'])
# Parse the template
template_tree = ET.parse(template_file)
template_root = template_tree.getroot()
# Find a child tag that is validation->compare_fields->field, and add each
# field
for validation in template_root:
if validation.tag == 'validation':
for compare_fields in validation:
if compare_fields.tag == 'compare_fields':
for field in compare_fields:
if field.tag == 'field':
if not (missing_file1 or missing_file2):
process_field_definition(field, configs,
script, file1, file2,
False)
if not missing_file1 and baseline_root != 'NONE':
process_field_definition(
field, configs, script, file1,
'{}/{}'.format(baseline_root, file1), True)
if not missing_file2 and baseline_root != 'NONE':
process_field_definition(
field, configs, script, file2,
'{}/{}'.format(baseline_root, file2), True)
elif field.tag == 'template':
apply_compare_fields_template(field, compare_tag,
configs, script)
del template_root
del template_tree
del template_info
# }}}
def process_field_definition(field_tag, configs, script, file1, file2,
baseline_comp): # {{{
# Build the path to the comparison script.
compare_executable = '{}/compare_fields.py'.format(
configs.get('script_paths', 'utility_scripts'))
field_name = field_tag.attrib['name']
# Build the base command to compare the fields
command_args = [compare_executable, '-q', '-1', file1, '-2', file2, '-v',
field_name]
# Determine norm thresholds
if baseline_comp:
command_args.extend(['--l1', '0.0', '--l2', '0.0', '--linf', '0.0'])
else:
if 'l1_norm' in field_tag.attrib.keys():
command_args.extend(['--l1', field_tag.attrib['l1_norm']])
if 'l2_norm' in field_tag.attrib.keys():
command_args.extend(['--l2', field_tag.attrib['l2_norm']])
if 'linf_norm' in field_tag.attrib.keys():
command_args.extend(['--linf', field_tag.attrib['linf_norm']])
command = wrap_subprocess_command(command_args, indentation=' ',
quiet=False)
# Write the pass/fail logic.
script.write('try:\n')
script.write('{}\n'.format(command))
script.write(" print(' ** PASS Comparison of {} between {} and\\n'\n"
" ' {}')\n".format(field_name, file1, file2))
script.write('except subprocess.CalledProcessError:\n')
script.write(" print(' ** FAIL Comparison of {} between {} and\\n'\n"
" ' {}')\n".format(field_name, file1, file2))
script.write(' error = True\n')
# }}}
# }}}
# *** Timer Comparison Functions *** # {{{
def process_compare_timers_step(compare_tag, configs, script): # {{{
baseline_root = configs.get('script_paths', 'baseline_dir')
baseline_root = '{}/{}'.format(baseline_root,
configs.get('script_paths', 'test_dir'))
missing_rundir1 = True
missing_rundir2 = True
try:
rundir1 = compare_tag.attrib['rundir1']
missing_rundir1 = False
except KeyError:
missing_rundir1 = True
try:
rundir2 = compare_tag.attrib['rundir2']
missing_rundir2 = False
except KeyError:
missing_rundir2 = True
for child in compare_tag:
if child.tag == 'timer':
if not (missing_rundir1 or missing_rundir2):
process_timer_definition(child, configs, script, rundir1,
rundir2)
if not missing_rundir1:
process_timer_definition(
child, configs, script,
'{}/{}'.format(baseline_root, rundir1), rundir1)
if not missing_rundir2:
process_timer_definition(
child, configs, script,
'{}/{}'.format(baseline_root, rundir2), rundir2)
elif child.tag == 'template':
apply_compare_timers_template(child, compare_tag, configs, script)
# }}}
def apply_compare_timers_template(template_tag, compare_tag, configs, script):
# {{{
# Build the path to the baselines
baseline_root = configs.get('script_paths', 'baseline_dir')
baseline_root = '{}/{}'.format(baseline_root, configs.get('script_paths',
'test_dir'))
missing_rundir1 = True
missing_rundir2 = True
try:
rundir1 = compare_tag.attrib['rundir1']
missing_rundir1 = False
except KeyError:
missing_rundir1 = True
try:
rundir2 = compare_tag.attrib['rundir2']
missing_rundir2 = False
except KeyError:
missing_rundir2 = True
# Get the template information and build the template file
template_info = get_template_info(template_tag, configs)
template_file = '{}/{}'.format(template_info['template_path'],
template_info['template_file'])
# Parse template file
template_tree = ET.parse(template_file)
template_root = template_tree.getroot()
for validation in template_root:
if validation.tag == 'validation':
for compare_timers in validation:
if compare_timers.tag == 'compare_timers':
for timer in compare_timers:
if timer.tag == 'timer':
if not (missing_rundir1 or missing_rundir2):
process_timer_definition(
timer, configs, script, rundir1, rundir2)
if not missing_rundir1:
process_timer_definition(
timer, configs, script,
'{}/{}'.format(baseline_root, rundir1),
rundir1)
if not missing_rundir2:
process_timer_definition(