-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.py
2011 lines (1839 loc) · 104 KB
/
validator.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
import yaml, argparse, json, copy
from api_files.generator import ApiGenerator
from logger import LogLevel, Logger
from decouple import config
API_YAML = config('API_YAML')
STATE_YAML = config('STATE_YAML')
DEP_JSON = config('DEP_JSON')
# special loader with duplicate key checking (https://gist.github.com/pypt/94d747fe5180851196eb)
class UniqueKeyLoader(yaml.SafeLoader):
def construct_mapping(self, node, deep=False):
mapping = []
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
if key in mapping:
raise ValueError(f"Duplicate key {key!r} found in YAML.")
mapping.append(key)
return super().construct_mapping(node, deep)
PRIMITIVE_TYPE_MAP = {
'string': str,
'boolean': bool,
'number': float,
'int': int,
'integer': int
}
# state in scene should follow state_changes.yaml
class YamlValidator:
logger = Logger("yamlValidator")
file = None
dup_check_file = None
api_file = None
dep_file = None
state_change_file = None
loaded_yaml = None
api_yaml = None
state_changes_yaml = None
dep_json = None
missing_keys = 0
wrong_types = 0
invalid_values = 0
out_of_range = 0
invalid_keys = 0
empty_levels = 0
warning_count = 0
train_mode = False
allowed_supplies = []
def __init__(self, filename, train_mode=False):
'''
Load in the file and parse the yaml
'''
self.file = self.validate_file_location(filename)
try:
self.api_file = open(API_YAML, encoding='utf-8')
self.api_yaml = yaml.load(self.api_file, Loader=yaml.CLoader)
except Exception as e:
self.logger.log(LogLevel.FATAL, "Error while loading in api yaml. Please check the .env to make sure the location is correct and try again.\n\n" + str(e) + "\n")
try:
self.state_change_file = open(STATE_YAML, encoding='utf-8')
self.state_changes_yaml = yaml.load(self.state_change_file, Loader=yaml.CLoader)
except Exception as e:
self.logger.log(LogLevel.FATAL, "Error while loading in state api yaml. Please check the .env to make sure the location is correct and try again.\n\n" + str(e) + "\n")
try:
self.loaded_yaml = yaml.load(self.file, Loader=yaml.CLoader)
try:
dup_check_file = open(filename, 'r', encoding='utf-8')
yaml.load(dup_check_file, Loader=UniqueKeyLoader)
except Exception as e:
self.logger.log(LogLevel.FATAL, "Error while loading in yaml file -- " + str(e))
except Exception as e:
self.logger.log(LogLevel.FATAL, "Error while loading in yaml file. Please ensure the file is a valid yaml format and try again.\n\n" + str(e) + "\n")
try:
self.dep_file = open(DEP_JSON, encoding='utf-8')
self.dep_json = json.load(self.dep_file)
except Exception as e:
self.logger.log(LogLevel.FATAL, "Error while loading in json dependency file. Please check the .env to make sure the location is correct and try again.\n\n" + str(e) + "\n")
self.train_mode = train_mode
api = copy.deepcopy(self.api_yaml)
self.allowed_supplies = copy.deepcopy(api['components']['schemas']['SupplyTypeEnum']['enum'])
if not self.train_mode:
for x in self.dep_json['trainingOnlySupplies']:
self.allowed_supplies.remove(x)
for character in self.loaded_yaml.get('state', {'characters': []}).get('characters', []):
if character.get('has_blanket', False):
self.invalid_keys += 1
self.logger.log(LogLevel.ERROR, f"Blankets can't appear on characters at startup but '{character.get('id')}' has 'has_blanket' set to True.")
self.branches = self.find_all_branch_segments(copy.deepcopy(self.loaded_yaml))
def __del__(self):
'''
Basic cleanup: closing the file loaded in on close.
'''
self.logger.log(LogLevel.DEBUG, "Program closing...")
if (self.file):
self.file.close()
if (self.api_file):
self.api_file.close()
if (self.state_change_file):
self.state_change_file.close()
if (self.dep_file):
self.dep_file.close()
if (self.dup_check_file):
self.dup_check_file.close()
def remove_duplicate_sublists(self, lst_of_lsts):
'''
Given a list of lists, reduces it to only one of each sublist (same length, same order, same elements)
'''
def find_el_in_list(lst, el):
inds_where_found = []
for ind in range(len(lst)):
x = lst[ind]
if len(x) == len(el):
found_match = True
for i in range(len(x)):
if x[i] != el[i]:
found_match = False
break
if found_match:
inds_where_found.append(ind)
return inds_where_found
new_lst_of_lsts = []
for p in lst_of_lsts:
if len(p) > 0:
inds = find_el_in_list(lst_of_lsts, p)
try:
new_lst_of_lsts.index(lst_of_lsts[inds[0]])
except:
new_lst_of_lsts.append(lst_of_lsts[inds[0]])
return new_lst_of_lsts
def do_lists_match(self, lst1, lst2):
'''
Check if two lists have the same elements in the same order
'''
if len(lst1) == len(lst2):
for i in range(len(lst1)):
if lst1[i] != lst2[i]:
return False
return True
return False
def remove_covered_sublists(self, list_of_lists):
'''
We don't need every possible sublist in our branches. This function looks through all the branching lists
and removes any sublist that is already covered by a bigger list. This will also remove any duplicate branch paths
'''
list_of_lists.sort(key=len, reverse=True)
result = []
# go through the branches in descending length order
for sublist in list_of_lists:
# see if the list is already recorded in result. If not, add it!
if not any(self.do_lists_match(sublist, sublist_covered[:len(sublist)]) for sublist_covered in result):
result.append(sublist)
return result
def find_all_branch_segments(self, data):
'''
Creates and returns a list of all scene branches.
'''
paths = self.get_branches_from_scene(data, self.determine_first_scene(data)['id'])
scenes = data['scenes']
if len(scenes) == 1:
paths.append([scenes[0]['id']])
# remove duplicates (same order, same elements)
return self.remove_covered_sublists(paths)
def get_branches_from_scene(self, data, scene_id, path=[]):
'''
Given a starting scene_id, updates the path with branches
that can be taken from that scene
'''
paths = []
scene = self.get_scene_by_id(scene_id)
if scene is None:
self.logger.log(LogLevel.ERROR, f"Key 'next_scene' has value {scene_id}, which is not a valid scene.")
self.invalid_values += 1
return path
next_scene_id = None
if type(scene_id) is int and int(scene_id) >= 0:
next_scene_id = int(scene_id) + 1
if self.get_scene_by_id(next_scene_id) is None:
next_scene_id = None
default_next = scene.get('next_scene', next_scene_id)
scenes_to_investigate = []
for a in scene['action_mapping']:
next_scene = a.get('next_scene', default_next)
scenes_to_investigate.append(next_scene)
scenes_to_investigate = list(set(scenes_to_investigate))
for next_scene in scenes_to_investigate:
action_path = copy.deepcopy(path)
if action_path.count(next_scene) < 2 and (len(action_path) == 0 or action_path[-1] != next_scene):
if len(action_path) == 0:
# no two of the same scene in a row (doesn't affect anything logically)
if next_scene != scene_id:
action_path = [scene_id, next_scene]
else:
action_path = [scene_id]
else:
if action_path[-1] != next_scene:
action_path.append(next_scene)
paths.append(path)
if next_scene is not None:
paths += self.get_branches_from_scene(data, next_scene, action_path)
else:
paths.append(path)
if len(scenes_to_investigate) == 0:
paths.append(path)
return paths
def validate_field_names(self):
'''
Ensures all fields are supported by the API
'''
# start by checking the top level
schema = self.api_yaml['components']['schemas']
top_level = schema['Scenario']['properties']
required = schema['Scenario']['required'] if 'required' in schema['Scenario'] else []
self.validate_one_level('top', self.loaded_yaml, top_level, required, self.api_yaml)
def validate_one_level(self, level_name, to_validate, type_obj, required, api_yaml, persist_characters=False, override_required=False):
'''
Takes in an object to validate (to_validate) and the yaml schema describing the
expected types (type_obj)
'''
found_keys = []
# do not require characters if persist_characters is true
if level_name == 'scenes':
persist_characters = to_validate.get('persist_characters')
if level_name == 'Scenes/State' and persist_characters:
if 'characters' in required:
required.remove('characters')
if level_name == 'supplies':
if to_validate.get('type') not in self.allowed_supplies and to_validate.get('quantity') > 0:
self.logger.log(LogLevel.ERROR, f"Since eval mode is true, supplies must only be one of {self.allowed_supplies}, but '{to_validate.get('type')}' was found.")
self.invalid_values += 1
# see if an object is empty (and if it's allowed to be)
if to_validate == None and len(required) == 0:
return True
elif to_validate == None and len(required) > 0:
self.logger.log(LogLevel.ERROR, "Level '" + level_name + "' is empty but must contain keys " + str(required))
self.empty_levels += 1
return False
# loop through keys to check each value against expectations
for key in to_validate:
# make sure it is a valid key
if key not in type_obj:
self.logger.log(LogLevel.ERROR, "'" + key + "' is not a valid key at the '" + level_name + "' level of the yaml file. Allowed keys are " + str(list(type_obj.keys())))
self.invalid_keys += 1
else:
# begin type-checking
this_key_data = type_obj[key]
# check for the 'type' property - otherwise it might only have a $ref
if 'type' in this_key_data:
key_type = type_obj[key]['type']
# Basic types listed in PRIMITIVE_TYPE_MAP
if key_type in PRIMITIVE_TYPE_MAP:
self.validate_primitive(to_validate[key], key_type, key, level_name, type_obj[key], override_required=override_required)
# check for objects (key:value pairs)
elif key_type == 'object':
if 'additionalProperties' in type_obj[key]:
self.validate_additional_properties(type_obj[key], to_validate[key], key, level_name, api_yaml)
else:
self.logger.log(LogLevel.FATAL, "API error: Missing additionalProperties on '" + key + "' object at the '" + level_name + "' level. Please contact TA3 for assistance.")
return False
elif key_type == 'array':
self.validate_array(to_validate[key], key, level_name, key_type, type_obj, api_yaml)
else:
self.logger.log(LogLevel.FATAL, "API error: Unhandled validation for type '" + key_type + "' at the " + level_name + "' level. Please contact TA3 for assistance.")
return False
# check deep objects (more than simple key-value)
elif '$ref' in this_key_data:
# get the ref type and check that location (skip starting hashtag)
location = type_obj[key]['$ref'].split('/')[1:]
if level_name == 'scenes' and location[len(location)-1] == 'State':
# state at the scenes level should follow state_changes.yaml
self.validate_state_change(to_validate[key], persist_characters)
else:
ref_loc = api_yaml
# access the currect location to get the type map
for x in location:
ref_loc = ref_loc[x]
if 'enum' in ref_loc:
self.validate_enum(ref_loc, key, level_name, to_validate[key], override_required=override_required)
elif isinstance(to_validate[key], dict):
# if character's unseen property is True, vitals are not required
override_req_properties = False
if key == 'vitals':
override_req_properties = to_validate.get('unseen', False)
self.validate_object(to_validate[key], ref_loc, key, level_name, type_obj[key]['$ref'], api_yaml, override_req_properties)
else:
self.log_wrong_type(key, level_name, location[len(location)-1], type(to_validate[key]))
else:
self.logger.log(LogLevel.FATAL, "API Error: Key '" + key + "' at level '" + level_name + "' has no defined type or reference. Please contact TA3 for assistance.")
return False
found_keys.append(key)
# check for missing keys
for key in type_obj:
if key not in found_keys:
if not override_required and (key in required):
self.logger.log(LogLevel.ERROR, "Required key '" + key + "' at level '" + level_name + "' is missing in the yaml file.")
self.missing_keys += 1
else:
self.logger.log(LogLevel.DEBUG, "Optional key '" + key + "' at level '" + level_name + "' is missing in the yaml file.")
if level_name == 'characters':
if 'injuries' in to_validate:
injury_count = sum(1 for injury in to_validate['injuries'] if injury['name'] not in ['Ear Bleed', 'Asthmatic', 'Internal'] and 'Broken' not in injury['name'])
if injury_count > 12 and not self.train_mode:
self.logger.log(LogLevel.ERROR, f"Character '{to_validate.get('name')}' has {injury_count} 'masked' injuries (abrasions, punctures, lacerations, burns), which exceeds the maximum of 12 allowed in the simulation.")
def determine_first_scene(self, data):
'''
Determine the first scene, either from 'first_scene' or the first in the scenes list.
'''
scenes = data.get('scenes', [])
first_scene_id = data['first_scene'] if 'first_scene' in data else None
if first_scene_id is None:
return scenes[0]
else:
first_scene = self.get_scene_by_id(first_scene_id)
if first_scene is None:
return scenes[0]
return first_scene
def get_scene_by_id(self, scene_id):
data = copy.deepcopy(self.loaded_yaml)
scenes = data.get('scenes', [])
for x in scenes:
if x['id'] == scene_id:
return x
return None
def validate_state_change(self, obj_to_validate, persist_characters=False):
'''
Under Scenes in the API, state should be defined slightly differently.
Use state_changes.yaml and perform as before.
'''
schema = self.state_changes_yaml['components']['schemas']
top_level = schema['State']['properties']
required = schema['State']['required'] if 'required' in schema['State'] else []
return self.validate_one_level('Scenes/State', obj_to_validate, top_level, required, self.state_changes_yaml, persist_characters)
def validate_enum(self, type_obj, key, level, item, override_required=False):
'''
Accepts as parameters the object that describes expected types,
the key of the object, the level we're looking at, and the value
to check
'''
is_valid = True
# we are expecting a string here (will this ever be an int/float?)
if isinstance(item, str):
allowed = type_obj['enum']
if item not in allowed:
self.logger.log(LogLevel.ERROR, "Key '" + key + "' at level '" + level + "' must be one of the following values: " + str(allowed) + " but is '" + item + "' instead.")
self.invalid_values += 1
is_valid = False
else:
if not (override_required and type(item) == type(None)):
self.log_wrong_type(key, level, str(str), type(item))
is_valid = False
return is_valid
def validate_object(self, item, location, key, level, ref_name, api_yaml, override_required=False):
'''
Checks if an item matches the reference location. The reference location
may reference a full object, small object, or enum. Checks all 3 possibilities.
'''
# check large object
if 'properties' in location:
self.validate_one_level(key, item, location['properties'], location['required'] if 'required' in location else [], api_yaml, override_required=override_required)
# check small object
elif 'additionalProperties' in location:
self.validate_additional_properties(location, item, key, level, api_yaml)
# check enum
elif 'enum' in location:
self.validate_enum(location, key, level, item)
else:
self.logger.log(LogLevel.FATAL, "API missing enum, property, or additional properties for '" + ref_name + "'. Cannot parse. Please contact TA3 for assistance.")
def validate_additional_properties(self, type_obj, item, key, level, api_yaml):
'''
Accepts an object that describes the type we're looking for and an item to validate
'''
if 'type' in type_obj['additionalProperties']:
val_type = type_obj['additionalProperties']['type']
# two types of objects exist: 1. list of key-value
if isinstance(item, list):
for pair_set in item:
for k in pair_set:
if not self.do_types_match(pair_set[k], PRIMITIVE_TYPE_MAP[val_type]):
self.log_wrong_type(k, level, val_type, type(pair_set[k]))
# 2. object with key-value
else:
if isinstance(item, dict):
for k in item:
if not self.do_types_match(item[k], PRIMITIVE_TYPE_MAP[val_type]):
self.log_wrong_type(k, level, val_type, type(item[k]))
else:
self.log_wrong_type(key, level, 'object', type(item))
elif '$ref' in type_obj['additionalProperties']:
location = type_obj['additionalProperties']['$ref'].split('/')[1:]
ref_loc = api_yaml
for x in location:
ref_loc = ref_loc[x]
if isinstance(item, list):
for pair_set in item:
for k in pair_set:
self.validate_object(pair_set[k], ref_loc, key, level, type_obj['additionalProperties']['$ref'], api_yaml)
else:
if isinstance(item, dict):
for k in item:
self.validate_object(item[k], ref_loc, key, level, type_obj['additionalProperties']['$ref'], api_yaml)
else:
self.log_wrong_type(key, level, 'object', type(item))
else:
self.logger.log(LogLevel.FATAL, "API Error: Additional Properties must either have a type or ref, but at level '" + level + "' for property '" + key + "' it does not. Please contact TA3 for assistance.")
return
def validate_array(self, item, key, level, key_type, typed_keys, api_yaml):
'''
Looks at an array and ensures that each item in the array matches expectations
'''
if not isinstance(item, list):
self.log_wrong_type(key, level, key_type, type(item))
else:
# get type of item in array and check that each item matches
item_type = typed_keys[key]['items']
# check complex object types
if '$ref' in item_type:
location = item_type['$ref'].split('/')[1:]
ref_loc = api_yaml
for x in location:
ref_loc = ref_loc[x]
for i in item:
self.validate_object(i, ref_loc, key, level, typed_keys[key]['items']['$ref'], api_yaml)
# check basic types
elif 'type' in item_type:
expected = item_type['type']
if expected in PRIMITIVE_TYPE_MAP:
for i in item:
self.validate_primitive(i, expected, key, level, item_type)
else:
self.logger.log(LogLevel.FATAL, "API Error: Missing type definition or reference at level '" + level + "' for property '" + key + "'. Please contact TA3 for assistance.")
return
def validate_primitive(self, item, expected_type, key, level, type_obj, override_required=False):
'''
Looks at an object against an expected primitive type to see if it matches
'''
is_valid = True
# first validate enums
if PRIMITIVE_TYPE_MAP[expected_type] == str and 'enum' in type_obj:
if not self.validate_enum(type_obj, key, level, item, override_required=override_required):
is_valid = False
# then validate the rest
elif not self.do_types_match(item, PRIMITIVE_TYPE_MAP[expected_type]):
if not(type(item) == type(None) and override_required):
self.log_wrong_type(key, level, expected_type, type(item))
is_valid = False
if is_valid:
# check for min/max only if type is valid
if 'minimum' in type_obj:
if item < type_obj['minimum']:
self.logger.log(LogLevel.ERROR, "Key '" + key + "' at level '" + level + "' has a minimum of " + str(type_obj['minimum']) + " but is " + str(item) + ". (" + str(item) + " < " + str(type_obj['minimum']) + ")")
self.out_of_range += 1
if 'maximum' in type_obj:
if item > type_obj['maximum']:
self.logger.log(LogLevel.ERROR, "Key '" + key + "' at level '" + level + "' has a maximum of " + str(type_obj['maximum']) + " but is " + str(item) + ". (" + str(item) + " > " + str(type_obj['maximum']) + ")")
self.out_of_range += 1
def do_types_match(self, item, type):
'''
Checks the basic data types, allowing integers in place of floats and ints and floats in place of strings (think stringified numbers)
'''
return isinstance(item, type) or (type == float and isinstance(item, int)) or (type == str and (isinstance(item, float) or isinstance(item, int)))
def log_wrong_type(self, key, level, expected, actual):
'''
Logs when an incorrect type is found for a key
'''
self.logger.log(LogLevel.ERROR, "Key '" + key + "' at level '" + level + "' should be type '" + expected + "' but is " + str(actual) + " instead.")
self.wrong_types += 1
def validate_file_location(self, filename):
'''
Try to load in the yaml file. Checks that a path has been given, that the path leads to a yaml file,
and that the file is found. Returns the open binary file object.
'''
if not filename:
self.logger.log(LogLevel.FATAL, "No filename received. To run, please use 'python3 validator.py -f [filename]'")
if not filename.strip().endswith('.yaml'):
self.logger.log(LogLevel.FATAL, "File must be a yaml file.")
try:
f = open(filename, 'r', encoding='utf-8')
return f
except:
self.logger.log(LogLevel.FATAL, "Could not open file " + filename + ". Please make sure the path is valid and the file exists.")
def validate_dependencies(self):
'''
Checks the yaml file against the dependency requirements to check for
additional required/ignored fields and specific value requirements
'''
self.simple_requirements()
self.conditional_requirements()
self.conditional_forbid()
self.simple_value_matching()
self.deep_links()
self.value_follows_list()
self.require_unstructured()
self.scenes_with_state()
self.validate_action_params()
self.validate_mission_importance()
self.character_matching()
self.verify_uniqueness()
self.verify_allowed_actions()
self.check_first_scene()
self.is_pulse_oximeter_configured()
self.check_scene_env_type()
self.validate_pretreated_injuries()
self.validate_unseen_character_actions()
self.validate_aid_ids()
self.validate_events()
self.validate_messages()
self.are_all_scenes_reachable()
self.validate_quantized_support()
self.validate_treatments_have_injuries()
self.validate_injury_sets()
def validate_quantized_support(self):
'''
Flag if treatments_required > 1 for unsupported injures.
In general, these are injuries that aren't successfully treated by hemostatic gauze or pressure bandage.
'''
data = copy.deepcopy(self.loaded_yaml)
self.validate_quantized_support_in_characters(data['state']['characters'])
for scene in data['scenes']:
if 'state' in scene and 'characters' in scene['state']:
self.validate_quantized_support_in_characters(scene['state']['characters'])
def validate_quantized_support_in_characters(self, characters):
for character in characters:
for injury in character.get('injuries', []):
if 'treatments_required' in injury:
required = injury['treatments_required']
type = injury['name']
location = injury['location']
# look for an injury type that doesn't support quantized injuries
if required > 1 and not self.supports_quantized_injury(type, location):
self.logger.log(LogLevel.ERROR, f"Injuries requiring multiple treatments are only supported when the injury is treated by hemostatic gauze or pressure bandage, but not '{type}' injuries at '{location}' location in character '{character['id']}'.")
self.invalid_values += 1
def supports_quantized_injury(self, injury_type, location):
'''
Returns whether the specified injury/location combination is successfully treated by a hemostatic gauze or pressure bandage.
'''
if injury_type == 'Laceration' and 'thigh' in location:
return False # takes a Tourniquet
if injury_type == 'Shrapnel' and 'face' in location:
return False # take a Nasopharyngeal airway
if injury_type == 'Puncture' and ('bicep' in location or 'thigh' in location or 'calf' in location or 'chest' in location):
return False # takes a Vented Chest Seal (chest) or Tourniquet (others)
if injury_type not in ['Laceration', 'Shrapnel', 'Puncture']:
return False # cannot take Hemostatic Gauze or Pressure Bandage
return True
def simple_requirements(self):
'''
Checks the yaml file for simple required dependencies.
If field 1 is provided, then field2 is required
'''
for req in self.dep_json['simpleRequired']:
loc = req.split('.')
all_found = self.property_meets_conditions(loc, copy.deepcopy(self.loaded_yaml))
for x in all_found:
found = x.split('.')
if found[len(found)-1] != loc[len(loc)-1]:
# possible that we thought we found a key but didn't. if so, skip
continue
else:
# start searching for the key(s) that is/are required now that the first key has been found
self.search_for_key(True, found, self.dep_json['simpleRequired'][req], "has been provided")
def property_meets_conditions(self, first_key_list, data, value='', length=-1, exists=True, loc=[]):
'''
Accepts a list of deepening keys to search through, where
the last key is the key to find if it exists in data.
Then checks if certain conditions are met.
Returns the paths of the found keys that meet conditions.
'''
if len(loc) == 0:
loc = first_key_list
found_indices = []
skip = False
for i in range(len(first_key_list)):
k = first_key_list[i]
# check through each element of the array for keys
if '[]' in k:
simple_k = k.split('[]')[0]
if data is not None and simple_k in data:
data = data[simple_k]
data = data if data is not None else []
for j in range(len(data)):
# add in indices where keys were found
if (isinstance(data, object) and j in data) or isinstance(data, list):
detailed_k = simple_k + '[' + str(j) + ']'
found_indices += (self.property_meets_conditions(first_key_list[i+1:], data[j], value=value, length=length, exists=exists, loc='.'.join(loc).replace(k, detailed_k).split('.')))
else:
# key is not here, don't keep searching
skip = True
break
else:
if data is not None and k in data:
data = data[k]
else:
# key is not here, don't keep searching
skip = True
break
if not skip and exists:
valid = True
# check for specific value
if value != '':
if str(data) != str(value):
valid = False
# check for array length
if length > -1:
if len(data) < length:
valid = False
if valid:
found_indices.append('.'.join(loc))
elif skip and not exists:
# key did not exist and we didn't want it to
loc = '.'.join(loc)
if '[]' not in loc:
found_indices.append(loc)
return found_indices
def search_for_key(self, should_find, found, expected_required, explanation, expected_val=[], log_level='error'):
'''
Searches for a key that is either required or ignored based on the additional dependencies.
@param should_find is a boolean of if we need this key or don't need this key
@param found is the list of locations where the original key was found that
forced this key to be required or not.
@param expected_required is the list of locations where we expect to find
keys
@param explanation is a string explanation of why the key is expected (or not), in case of an error
@param expected_val is a list of possible/allowed expected values for each key found, if applicable
'''
for required in expected_required:
# go through the path to the location we found and the requirement
# side-by-side as long as possible
required = required.split('.')
data = copy.deepcopy(self.loaded_yaml)
earlyExit = False
for i in range(min(len(found), len(required))):
if found[i].split('[')[0] == required[i].split('[')[0]:
# they are the same!
if '[]' in required[i]:
# handle arrays
ind = int(found[i].split('[')[1].replace(']', ''))
data = data[required[i].split('[]')[0]][ind]
else:
# handle non-arrays
data = data[required[i]]
else:
# difference found, break
required = required[i:]
earlyExit = True
break
if not earlyExit:
required = required[i+1:]
# look through data for required
found_key = True
for k in required:
if '[]' in k:
self.logger.log(LogLevel.FATAL, "No index provided for required key '" + k + "'. Cannot proceed.")
return
if k in data:
data = data[k]
else:
if should_find:
# we expected to find this key, error
if log_level == 'error':
self.logger.log(LogLevel.ERROR, "Key '" + k + "' is required because '" + '.'.join(found) + "' " + explanation + ", but it is missing.")
self.missing_keys += 1
else:
self.logger.log(LogLevel.WARN, "Key '" + k + "' is recommended because '" + '.'.join(found) + "' " + explanation + ", but it is missing.")
self.warning_count += 1
else:
# otherwise, we did not want to find the key, so we're good here
found_key = False
break
if should_find is not None and not should_find and found_key:
if log_level == 'error':
self.logger.log(LogLevel.ERROR, "Key '" + k + "' is not allowed because '" + '.'.join(found) + "' " + explanation + ".")
self.invalid_keys += 1
else:
self.logger.log(LogLevel.WARN, "Key '" + k + "' is not expected because '" + '.'.join(found) + "' " + explanation + ".")
self.warning_count += 1
elif found_key and len(expected_val) > 0:
if data not in expected_val:
if log_level == 'error':
self.logger.log(LogLevel.ERROR, "Key '" + k + "' must have one of the following values " + str(expected_val) + " because '" + '.'.join(found) + "' " + explanation + ", but instead value is '" + str(data) + "'")
self.invalid_values += 1
else:
self.logger.log(LogLevel.WARN, "Key '" + k + "' was expected have one of the following values " + str(expected_val) + " because '" + '.'.join(found) + "' " + explanation + ", but instead value is '" + str(data) + "'")
self.warning_count += 1
def conditional_requirements(self):
'''
Checks the yaml file for simple required dependencies.
If field 1 is provided and meets a set of conditions, then field 2 is required
'''
for req in self.dep_json['conditionalRequired']:
loc = req.split('.')
# there may be more than one if-else for each key, look through each
for entry in self.dep_json['conditionalRequired'][req]:
value = entry['conditions']['value'] if 'value' in entry['conditions'] else ''
length = entry['conditions']['length'] if 'length' in entry['conditions'] else -1
exists = bool(entry['conditions']['exists']) if 'exists' in entry['conditions'] else True
log_level = entry.get('logLevel', 'error')
all_found = self.property_meets_conditions(loc, copy.deepcopy(self.loaded_yaml), value=value, exists=exists, length=length)
for x in all_found:
found = x.split('.')
if found[len(found)-1] != loc[len(loc)-1]:
# possible that we thought we found a key but didn't. if so, skip
continue
else:
# start searching for the key(s) that is/are required now that the first key has been found
self.search_for_key(True, found, entry['required'], "meets conditions " + str(entry['conditions']), log_level=log_level)
def conditional_forbid(self):
'''
Checks the yaml file for simple required dependencies.
If field 1 is provided and meets a set of conditions, then field 2 should not be provided
'''
for req in self.dep_json['conditionalForbid']:
loc = req.split('.')
# there may be more than one if-else for each key, look through each
for entry in self.dep_json['conditionalForbid'][req]:
value = entry['conditions']['value'] if 'value' in entry['conditions'] else ''
length = entry['conditions']['length'] if 'length' in entry['conditions'] else -1
exists = bool(entry['conditions']['exists']) if 'exists' in entry['conditions'] else True
log_level = entry.get('logLevel', 'error')
all_found = self.property_meets_conditions(loc, copy.deepcopy(self.loaded_yaml), value=value, length=length, exists=exists)
for x in all_found:
found = x.split('.')
if found[len(found)-1] != loc[len(loc)-1]:
# possible that we thought we found a key but didn't. if so, skip
continue
else:
# start searching for the key(s) that is/are required now that the first key has been found
self.search_for_key(False, found, entry['forbid'], "meets conditions " + str(entry['conditions']), log_level=log_level)
def simple_value_matching(self):
'''
Checks the yaml file for value-matching dependencies.
If field1 equals value1, then field2 must be one of [...values]
'''
for field in self.dep_json['simpleAllowedValues']:
loc = field.split('.')
# there may be more than one value for each key, look through each
for val in self.dep_json['simpleAllowedValues'][field]:
# find every place where the field matches the value
all_found = self.property_meets_conditions(loc, copy.deepcopy(self.loaded_yaml), value=val)
for x in all_found:
found = x.split('.')
if found[len(found)-1] != loc[len(loc)-1]:
# possible that we thought we found a key but didn't. if so, skip
continue
else:
# start searching for the key(s) that need to match one of the provided values
for key in self.dep_json['simpleAllowedValues'][field][val]:
self.search_for_key(None, found, [key], "is '" + val + "'", self.dep_json['simpleAllowedValues'][field][val][key])
def require_unstructured(self):
'''
Within every scenes[].state, at least one unstructured field must be provided.
'''
data = copy.deepcopy(self.loaded_yaml)
i = 0
for scene in data['scenes']:
if 'state' in scene:
state = scene['state']
# look for an unstructured field
found = self.find_unstructured(state)
if not found:
# unstructured not found - error
self.logger.log(LogLevel.ERROR, "At least one 'unstructured' key must be provided within each scenes[].state but is missing at scene[" + scene['id'] + "]")
self.missing_keys += 1
i += 1
def find_unstructured(self, obj):
'''
Looks through obj for an unstructured field
'''
found = False
if obj is None:
return found
for k in obj:
if isinstance(obj[k], dict):
found = found or self.find_unstructured(obj[k])
if k == 'unstructured':
found = True
return found
def deep_links(self):
'''
Checks the yaml file for "if field1 is one of [a, b,...] and field2 is one of [c, d,...],
then field3 must be one of [e, f,...]"
'''
for parent_key in self.dep_json['deepLinks']:
# get all possible parents for the keys
possible_parents = self.property_meets_conditions(parent_key.split('.'), copy.deepcopy(self.loaded_yaml))
for p in possible_parents:
if '[]' in p:
# no index given for an array, skip this key
continue
# look for matching keys using possibleParents
for req_set in self.dep_json['deepLinks'][parent_key]:
conditions = True
# check if the conditions are true
explanation = "key-value pairs "
for c in req_set['condition']:
singleCondition = False
values = req_set['condition'][c]
if not isinstance(values, list):
values = [values]
for v in values:
singleCondition = singleCondition or self.does_key_have_value(p.split('.')+c.split('.'), v, copy.deepcopy(self.loaded_yaml))
if singleCondition:
explanation += "('" + c + "': '" + str(v) + "'); "
break
conditions = conditions and singleCondition
# remove extra semicolon
explanation = explanation[:-2]
if conditions:
# if the conditions match at this parent level, check if the required keys also match
for x in req_set['requirement']:
self.search_for_key(None, p.split('.'), [parent_key+'.'+x], 'has ' + explanation, expected_val=req_set['requirement'][x])
def does_key_have_value(self, key, value, yaml):
'''
Looks through the yaml file to see if a key at a specific location has the given value
'''
val = self.get_value_at_key(key, yaml)
if val is not None:
# if we made it to here, we found the key - check the value!
return val == value
return False
def get_value_at_key(self, key, yaml):
'''
Given a key, returns the value matching
'''
data = yaml
for k in key:
if '[' in k:
loc = k.split('[')[0]
inside_brackets = k.split('[')[1].split(']')[0]
if inside_brackets is not None and inside_brackets != '':
ind = int(k.split('[')[1].split(']')[0])
if loc in data:
data = data[loc]
if len(data) > ind:
data = data[ind]
else:
return None
elif k in data:
data = data[k]
else:
# key not found
return None
return data
def value_follows_list(self):
'''
Checks the yaml file for "field1 value must match one of the values from field2"
'''
for key in self.dep_json['valueMatch']:
# start by compiling a list of all allowed values by using the value of the k-v pair
allowed_loc = self.dep_json['valueMatch'][key].split('.')
locations = self.property_meets_conditions(allowed_loc, copy.deepcopy(self.loaded_yaml))
# gather allowed values
allowed_values = []
for l in locations:
loc = l.split('.')
val = self.get_value_at_key(loc, copy.deepcopy(self.loaded_yaml))
if val is not None:
allowed_values.append(val)
# check if the location matches one of the allowed values
locations = self.property_meets_conditions(key.split('.'), copy.deepcopy(self.loaded_yaml))
for loc in locations:
if loc[-2:] == '[]':
continue
v = self.get_value_at_key(loc.split('.'), copy.deepcopy(self.loaded_yaml))
if not isinstance(v, list):
v = [v]
for v_element in v:
if v_element not in allowed_values:
self.logger.log(LogLevel.ERROR, "Key '" + loc.split('.')[-1] + "' at '" + str(loc) + "' must have one of the following values " + str(allowed_values) + " to match one of " + str('.'.join(allowed_loc)) + ", but instead value is '" + str(v_element) + "'")
self.invalid_values += 1
def character_matching(self):
'''
Checks the yaml file for character matches: "characters at scene level 0 must match state characters.
characters at other scene levels must match the characters within that scene"
'''
# get all locations that have character ids
allowed_loc_0 = "state.characters[].id".split('.') # general location of character ids that are allowed in scene 0
allowed_loc_other = "scenes[].state.characters[].id".split('.') # general location of characters listed in all other scenes
removed_chars_loc = "scenes[].removed_characters[]".split('.') # general location of removed characters throughout the yaml
data = copy.deepcopy(self.loaded_yaml)
locations_0 = self.property_meets_conditions(allowed_loc_0, data) # specific locations of character ids that are allowed in scene 0
locations_other = self.property_meets_conditions(allowed_loc_other, data) # specific locations of character ids that are listed in other scenes
locations_removed = self.property_meets_conditions(removed_chars_loc, data) # specific locations of removed characters
scenes = data['scenes']
first_scene_id = self.determine_first_scene(data)['id']
allowed_vals = {}
allowed_vals[first_scene_id] = []
all_chars = [] # store all characters found anywhere in the character definitions
removed_chars = [] # store all removed characters that are found anywhere in the character definitions
# get all allowed values, organizing by the scene index where those values will be allowed
for l in locations_0:
# getting allowed characters for the first scene
loc = l.split('.')
val = self.get_value_at_key(loc, data)
if val is not None:
allowed_vals[first_scene_id].append(val)
all_chars.append(val)
for l in locations_other:
# getting characters listed in all the other scenes
ind = int(l.split('cenes[')[1].split(']')[0])
if ind not in allowed_vals:
allowed_vals[ind] = []
loc = l.split('.')
val = self.get_value_at_key(loc, data)
if val is not None:
allowed_vals[ind].append(val)
all_chars.append(val)
for l in locations_removed:
# get all characters removed at some point in the yaml
val = self.get_value_at_key(l.split('.'), data)