-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathrules.py
executable file
·4522 lines (3806 loc) · 146 KB
/
rules.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
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Validation rules for the NIST CDF XML validator."""
from __future__ import print_function
import collections
import datetime
import enum
import hashlib
import re
from civics_cdf_validator import base
from civics_cdf_validator import gpunit_rules
from civics_cdf_validator import loggers
from civics_cdf_validator import office_utils
from frozendict import frozendict
import language_tags
from lxml import etree
import networkx
import pycountry
from six.moves.urllib.parse import urlparse
_PARTY_LEADERSHIP_TYPES = ["party-leader-id", "party-chair-id"]
_INDEPENDENT_PARTY_NAMES = frozenset(["independent", "nonpartisan"])
# The set of external identifiers that contain references to other entities.
_IDREF_EXTERNAL_IDENTIFIERS = frozenset(
["jurisdiction-id"] + _PARTY_LEADERSHIP_TYPES
)
_IDENTIFIER_TYPES = frozenset(
["local-level", "national-level", "ocd-id", "state-level"]
)
_CONTEST_STAGE_TYPES = frozenset([
"exit-polls",
"estimates",
"projections",
"preliminary",
"official",
"unnamed",
])
_INTERNATIONALIZED_TEXT_ELEMENTS = [
# go/keep-sorted start
"BallotName",
"BallotSubTitle",
"BallotText",
"BallotTitle",
"ConStatement",
"Directions",
"EffectOfAbstain",
"FullName",
"FullText",
"InternationalizedAbbreviation",
"InternationalizedName",
"Name",
"PassageThreshold",
"ProStatement",
"Profession",
"Selection",
"SummaryText",
"Title",
# go/keep-sorted end
]
_EXECUTIVE_OFFICE_ROLES = frozenset([
"head of state",
"head of government",
"president",
"vice president",
"state executive",
"deputy state executive",
"deputy head of government",
])
_VALID_FEED_LONGEVITY_BY_FEED_TYPE = frozendict({
"committee": ["evergreen"],
"election-dates": ["evergreen"],
"election-results": ["limited", "yearly"],
"officeholder": ["evergreen"],
"pre-election": ["limited", "yearly"],
})
def _is_executive_office(office_roles):
return not _EXECUTIVE_OFFICE_ROLES.isdisjoint(office_roles)
def _get_government_body(element):
governmental_body = get_entity_info_for_value_type(
element,
"governmental-body",
)
government_body = get_entity_info_for_value_type(element, "government-body")
return governmental_body or government_body
def get_external_id_values(element, value_type, return_elements=False):
"""Helper to gather all Values of external ids for a given type."""
external_ids = element.findall(".//ExternalIdentifier")
values = []
for extern_id in external_ids:
id_type = extern_id.find("Type")
if id_type is None or not id_type.text:
continue
matches_type = False
id_text = id_type.text.strip()
if id_text in _IDENTIFIER_TYPES and id_text == value_type:
matches_type = True
elif id_text == "other":
other_type = extern_id.find("OtherType")
if (
other_type is not None
and other_type.text
and other_type.text.strip() == value_type
and value_type not in _IDENTIFIER_TYPES
):
matches_type = True
if matches_type:
value = extern_id.find("Value")
# Could include empty text; check in calling function.
# Not checked here because errors should be raised in some cases.
if value is not None and value.text:
if return_elements:
values.append(value)
else:
values.append(value.text)
return values
def get_additional_type_values(element, value_type, return_elements=False):
"""Helper to gather all nested additional type values for a given type."""
elements = element.findall(".//AdditionalData[@type='{}']".format(value_type))
if not return_elements:
return [
val.text
for val in elements
if val is not None and val.text and val.text.strip()
]
return elements
def extract_person_fullname(person):
"""Extracts the person's fullname or builds it if needed."""
full_name_elt = person.find("FullName")
if full_name_elt is None:
return []
full_name_list = set()
for name in full_name_elt.findall("Text"):
if name.text:
full_name_list.add(name.text)
return full_name_list
return []
def get_entity_info_for_value_type(element, info_type, return_elements=False):
info_collection = get_additional_type_values(
element, info_type, return_elements
)
info_collection.extend(
list(get_external_id_values(element, info_type, return_elements))
)
return info_collection
def get_language_to_text_map(element):
"""Return a map of languages to text in an InternationalizedText element."""
language_map = {}
if element is None:
return language_map
intl_strings = element.findall("Text")
for intl_string in intl_strings:
text = intl_string.text
if text is None or not text:
continue
language = intl_string.get("language")
if language is None or not language:
continue
if language not in language_map:
language_map[language] = [text]
else:
language_map[language].append(text)
return language_map
def element_has_text(element):
return (
element is not None
and element.text is not None
and not element.text.isspace()
)
def country_code_is_valid(country_code):
# EU is part of ISO 3166/MA
return (
country_code.lower() == "eu"
or pycountry.countries.get(alpha_2=country_code.upper()) is not None
)
class Schema(base.TreeRule):
"""Checks if election file validates against the provided schema."""
def check(self):
try:
schema = etree.XMLSchema(etree=self.schema_tree)
except etree.XMLSchemaParseError as e:
raise loggers.ElectionError.from_message(
"The schema file could not be parsed correctly %s" % str(e)
)
valid_xml = True
try:
schema.assertValid(self.election_tree)
except etree.DocumentInvalid as e:
valid_xml = False
if not valid_xml:
errors = []
for error in schema.error_log:
errors.append(
loggers.LogEntry(
lines=[error.line],
message=(
"The election file didn't validate "
"against schema : {0}".format(error.message.encode("utf-8"))
),
)
)
raise loggers.ElectionError(errors)
class OptionalAndEmpty(base.BaseRule):
"""Checks for optional and empty fields."""
def __init__(self, election_tree, schema_tree, **kwargs):
super(OptionalAndEmpty, self).__init__(election_tree, schema_tree, **kwargs)
self.previous = None
def elements(self):
eligible_elements = []
for _, element in etree.iterwalk(self.schema_tree):
tag = self.strip_schema_ns(element)
if tag and tag == "element" and element.get("minOccurs") == "0":
eligible_elements.append(element.get("name"))
return eligible_elements
# pylint: disable=g-explicit-length-test
def check(self, element):
if element == self.previous:
return
self.previous = element
if (element.text is None or not element.text.strip()) and not len(element):
raise loggers.ElectionWarning.from_message(
"This optional element included although it is empty.", [element]
)
class Encoding(base.TreeRule):
"""Checks that the file provided uses UTF-8 encoding."""
def check(self):
docinfo = self.election_tree.docinfo
if docinfo.encoding != "UTF-8":
raise loggers.ElectionError.from_message("Encoding on file is not UTF-8")
class HungarianStyleNotation(base.BaseRule):
"""Check that element identifiers use Hungarian style notation.
Hungarian style notation is used to maintain uniqueness and provide context
for the identifiers.
"""
# Add a prefix when there is a specific entity in the xml.
elements_prefix = {
"BallotMeasureContest": "bmc",
"BallotMeasureSelection": "bms",
"BallotStyle": "bs",
"Candidate": "can",
"CandidateContest": "cc",
"CandidateSelection": "cs",
"Coalition": "coa",
"ContactInformation": "ci",
"Hours": "hours",
"Office": "off",
"OfficeGroup": "og",
"Party": "par",
"PartyContest": "pc",
"PartySelection": "ps",
"Person": "per",
"ReportingDevice": "rd",
"ReportingUnit": "ru",
"RetentionContest": "rc",
"Schedule": "sched",
}
def elements(self):
return self.elements_prefix.keys()
def check(self, element):
object_id = element.get("objectId")
tag = self.get_element_class(element)
if object_id:
if not object_id.startswith(self.elements_prefix[tag]):
raise loggers.ElectionInfo.from_message(
(
"%s ID %s is not in Hungarian Style Notation. Should start"
" with %s" % (tag, object_id, self.elements_prefix[tag])
),
[element],
)
class LanguageCode(base.BaseRule):
"""Check that Text elements have a valid language code."""
def elements(self):
return ["Text"]
def check(self, element):
if "language" not in element.attrib:
return
elem_lang = element.get("language")
if not elem_lang.strip() or not language_tags.tags.check(elem_lang):
raise loggers.ElectionError.from_message(
"%s is not a valid language code" % elem_lang, [element]
)
class PercentSum(base.BaseRule):
"""Check that Contest elements have percents summing to 0 or 100."""
def elements(self):
return ["Contest"]
@staticmethod
def fuzzy_equals(a, b, epsilon=1e-6):
return abs(a - b) < epsilon
def check(self, element):
sum_percents = 0.0
for ballot_selection in element.findall("BallotSelection"):
for vote_counts in ballot_selection.find("VoteCountsCollection").findall(
"VoteCounts"
):
other_type = vote_counts.find("OtherType")
if other_type is not None and other_type.text == "total-percent":
sum_percents += float(vote_counts.find("Count").text)
if not PercentSum.fuzzy_equals(
sum_percents, 0
) and not PercentSum.fuzzy_equals(sum_percents, 100):
raise loggers.ElectionError.from_message(
"Contest percents do not sum to 0 or 100: %f" % sum_percents,
[element],
)
class EmptyText(base.BaseRule):
"""Check that Text elements are not strictly whitespace."""
def elements(self):
return ["Text"]
def check(self, element):
if (element.text is None or not element.text.strip()) or (
element.text is None and element.get("language") is not None
):
raise loggers.ElectionError.from_message("Text is empty", element)
class DuplicateID(base.TreeRule):
"""Check that the file does not contain duplicate object IDs."""
def check(self):
all_object_ids = set()
error_log = []
for _, element in etree.iterwalk(self.election_tree, events=("end",)):
if "objectId" not in element.attrib:
continue
else:
obj_id = element.get("objectId")
if not obj_id:
continue
if obj_id in all_object_ids:
error_log.append(loggers.LogEntry("duplicate object ID", element))
else:
all_object_ids.add(obj_id)
if error_log:
raise loggers.ElectionError(error_log)
class ValidIDREF(base.BaseRule):
"""Check that IDREFs are valid.
Every field of type IDREF should actually reference a value that exists in a
field of type ID. Additionaly the referenced value should be an objectId
of the proper reference type for the given field.
"""
def __init__(self, election_tree, schema_tree, **kwargs):
super(ValidIDREF, self).__init__(election_tree, schema_tree, **kwargs)
self.object_id_mapping = {}
self.element_reference_mapping = {}
_REFERENCE_TYPE_OVERRIDES = {
"ElectoralDistrictId": "GpUnit",
"ElectionScopeId": "GpUnit",
"ScopeLevel": "GpUnit",
"AuthorityId": "Person",
"AuthorityIds": "Person",
"PartyLeaderId": "Person",
}
def setup(self):
object_id_map = self._gather_object_ids_by_type()
self.object_id_mapping = object_id_map
element_reference_map = self._gather_reference_mapping()
self.element_reference_mapping = element_reference_map
def _gather_object_ids_by_type(self):
"""Create a mapping of element types to set of objectIds of same type."""
type_obj_id_mapping = dict()
for _, element in etree.iterwalk(self.election_tree, events=("end",)):
if "objectId" in element.attrib:
obj_type = element.tag
obj_id = element.get("objectId")
if obj_id:
type_obj_id_mapping.setdefault(obj_type, set([])).add(obj_id)
return type_obj_id_mapping
def _gather_reference_mapping(self):
"""Create a mapping of each IDREF(S) element to their reference type."""
reference_mapping = dict()
for _, element in etree.iterwalk(self.schema_tree):
tag = self.strip_schema_ns(element)
if (
tag
and tag == "element"
and element.get("type") in ("xs:IDREF", "xs:IDREFS")
):
elem_name = element.get("name")
reference_type = self._determine_reference_type(elem_name)
reference_mapping[elem_name] = reference_type
return reference_mapping
def _determine_reference_type(self, name):
"""Determines the XML type being referenced by an IDREF(S) element."""
for elem_type in self.object_id_mapping.keys():
type_id = elem_type + "Id"
if name.endswith(type_id) or name.endswith(type_id + "s"):
return elem_type
if name in self._REFERENCE_TYPE_OVERRIDES:
return self._REFERENCE_TYPE_OVERRIDES[name]
return None
def elements(self):
return list(self.element_reference_mapping.keys())
def check(self, element):
error_log = []
element_name = element.tag
element_reference_type = self.element_reference_mapping[element_name]
reference_object_ids = self.object_id_mapping.get(
element_reference_type, []
)
if element.text:
id_references = element.text.split()
for id_ref in id_references:
if id_ref not in reference_object_ids:
error_log.append(
loggers.LogEntry(
(
"{} is not a valid IDREF. {} should contain an "
"objectId from a {} element."
).format(id_ref, element_name, element_reference_type),
element,
)
)
if error_log:
raise loggers.ElectionError(error_log)
class ValidStableID(base.BaseRule):
"""Ensure stable-ids are in the correct format."""
def __init__(self, election_tree, schema_tree, **kwargs):
super(ValidStableID, self).__init__(election_tree, schema_tree, **kwargs)
regex = r"^[a-zA-Z0-9_-]+$"
self.stable_id_matcher = re.compile(regex, flags=re.U)
def elements(self):
return ["ExternalIdentifiers"]
def check(self, element):
stable_ids = get_external_id_values(element, "stable")
error_log = []
for s_id in stable_ids:
if not self.stable_id_matcher.match(s_id):
error_log.append(
loggers.LogEntry(
"Stable id '{}' is not in the correct format.".format(s_id),
[element],
)
)
if error_log:
raise loggers.ElectionError(error_log)
class ElectoralDistrictOcdId(base.BaseRule):
"""GpUnit referred to by ElectoralDistrictId MUST have a valid OCD-ID."""
def __init__(self, election_tree, schema_tree, **kwargs):
super(ElectoralDistrictOcdId, self).__init__(
election_tree, schema_tree, **kwargs
)
self._all_gpunits = {}
def setup(self):
gp_units = self.election_tree.findall(".//GpUnit")
for gp_unit in gp_units:
if "objectId" not in gp_unit.attrib:
continue
self._all_gpunits[gp_unit.attrib["objectId"]] = gp_unit
def elements(self):
return ["ElectoralDistrictId"]
def check(self, element):
error_log = []
referenced_gpunit = self._all_gpunits.get(element.text)
if referenced_gpunit is None:
msg = (
"The ElectoralDistrictId element not refer to a GpUnit. Every "
"ElectoralDistrictId MUST reference a GpUnit"
)
error_log.append(loggers.LogEntry(msg, [element]))
else:
ocd_ids = get_external_id_values(referenced_gpunit, "ocd-id")
if not ocd_ids:
error_log.append(
loggers.LogEntry(
"The referenced GpUnit %s does not have an ocd-id"
% element.text,
[element],
[referenced_gpunit.sourceline],
)
)
else:
for ocd_id in ocd_ids:
if not self.ocd_id_validator.is_valid_ocd_id(ocd_id):
error_log.append(
loggers.LogEntry(
"The ElectoralDistrictId refers to GpUnit %s "
"that does not have a valid OCD ID (%s)"
% (element.text, ocd_id),
[element],
[referenced_gpunit.sourceline],
)
)
if error_log:
raise loggers.ElectionError(error_log)
class GpUnitOcdId(base.BaseRule):
"""Any GpUnit that is a geographic district SHOULD have a valid OCD-ID."""
districts = [
"borough",
"city",
"county",
"municipality",
"state",
"town",
"township",
"village",
]
validate_ocd_file = True
def elements(self):
return ["ReportingUnit"]
def check(self, element):
gpunit_type = element.find("Type")
if gpunit_type is not None and gpunit_type.text in self.districts:
external_id_elements = get_external_id_values(
element, "ocd-id", return_elements=True
)
for extern_id in external_id_elements:
if not self.ocd_id_validator.is_valid_ocd_id(extern_id.text):
msg = "The OCD ID %s is not valid" % extern_id.text
raise loggers.ElectionWarning.from_message(
msg, [element], [extern_id.sourceline]
)
class DuplicatedGpUnitOcdId(base.BaseRule):
"""2 GPUnits should not have same OCD-ID."""
def elements(self):
return ["GpUnitCollection"]
def check(self, element):
error_log = []
gp_ocdid = dict()
gpunits = element.findall("GpUnit")
for gpunit in gpunits:
ocd_ids = get_external_id_values(gpunit, "ocd-id")
for ocd_id in ocd_ids:
if ocd_id not in gp_ocdid.keys():
gp_ocdid[ocd_id] = gpunit.get("objectId")
else:
msg = "GpUnits %s and %s have the same ocd-id %s" % (
gp_ocdid[ocd_id],
gpunit.get("objectId"),
ocd_id,
)
error_log.append(loggers.LogEntry(msg, [gpunit]))
if error_log:
raise loggers.ElectionError(error_log)
class DuplicateGpUnits(base.BaseRule):
"""Detect GpUnits which are effectively duplicates of each other."""
def elements(self):
return ["GpUnitCollection"]
def check(self, element):
children = {}
object_ids = set()
error_log = []
for gpunit in element.findall("GpUnit"):
object_id = gpunit.get("objectId")
if not object_id:
continue
elif object_id in object_ids:
error_log.append(loggers.LogEntry("GpUnit is duplicated", [gpunit]))
continue
object_ids.add(object_id)
composing_gpunits = gpunit.find("ComposingGpUnitIds")
if composing_gpunits is None or not composing_gpunits.text:
continue
composing_ids = frozenset(composing_gpunits.text.split())
if children.get(composing_ids):
error_log.append(
loggers.LogEntry(
"GpUnits {} are duplicates".format(
str((children[composing_ids], object_id))
)
)
)
continue
children[composing_ids] = object_id
if error_log:
raise loggers.ElectionError(error_log)
class GpUnitsHaveSingleRoot(base.TreeRule):
"""Ensure that GpUnits form a single-rooted tree."""
def __init__(self, election_tree, schema_tree, **kwargs):
super(GpUnitsHaveSingleRoot, self).__init__(
election_tree, schema_tree, **kwargs
)
self.error_log = []
def check(self):
# Make sure there's at most one GpUnit as a root.
# The root is defined as having ComposingGpUnitIds but
# is not in the ComposingGpUnitIds of any other GpUnit.
gpunit_ids = dict()
composing_gpunits = set()
for element in self.get_elements_by_class(self.election_tree, "GpUnit"):
object_id = element.get("objectId")
if object_id is not None:
gpunit_ids[object_id] = element
composing_gpunit = element.find("ComposingGpUnitIds")
if composing_gpunit is not None and composing_gpunit.text is not None:
composing_gpunits.update(composing_gpunit.text.split())
roots = gpunit_ids.keys() - composing_gpunits
if not roots:
self.error_log.append(
loggers.LogEntry(
"GpUnits have no geo district root. "
"There should be one or more root geo district."
)
)
else:
for object_id in roots:
element = gpunit_ids.get(object_id)
ocd_ids = get_external_id_values(element, "ocd-id")
for ocd_id in ocd_ids:
if not gpunit_rules.GpUnitOcdIdValidator.is_country_or_region_ocd_id(
ocd_id
):
msg = (
"GpUnits tree roots needs to be either a country or the EU"
" region, please check the value %s." % (ocd_id)
)
self.error_log.append(loggers.LogEntry(msg, [element]))
if self.error_log:
raise loggers.ElectionError(self.error_log)
class GpUnitsCyclesRefsValidation(base.TreeRule):
"""Ensure that GpUnits form a valid tree and no cycles are present."""
def __init__(self, election_tree, schema_tree, **kwargs):
super(GpUnitsCyclesRefsValidation, self).__init__(
election_tree, schema_tree, **kwargs
)
self.edges = dict() # Used to maintain the record of connected edges
self.visited = {} # Used to store status of the nodes as visited or not.
self.error_log = []
self.bad_nodes = []
def build_tree(self, gpunit):
# Check if the node is already visited
if gpunit in self.visited:
if gpunit not in self.bad_nodes:
self.error_log.append(
loggers.LogEntry("Cycle detected at node {0}".format(gpunit))
)
self.bad_nodes.append(gpunit)
return
self.visited[gpunit] = 1
# Check each composing_gpunit and its edges if any.
for child_unit in self.edges[gpunit]:
if child_unit in self.edges:
self.build_tree(child_unit)
else:
self.error_log.append(
loggers.LogEntry(
"Node {0} is not present in the file as a GpUnit element."
.format(child_unit)
)
)
def check(self):
for element in self.get_elements_by_class(self.election_tree, "GpUnit"):
object_id = element.get("objectId")
if object_id is None:
continue
self.edges[object_id] = []
composing_gp_unit = element.find("ComposingGpUnitIds")
if composing_gp_unit is None or composing_gp_unit.text is None:
continue
composing_gp_unit_ids = composing_gp_unit.text.split()
self.edges[object_id] = composing_gp_unit_ids
for gpunit in self.edges:
self.build_tree(gpunit)
self.visited.clear()
if self.error_log:
raise loggers.ElectionError(self.error_log)
class OtherType(base.BaseRule):
"""Elements with an "other" enum should set OtherType.
Elements that have enumerations which include a value named other should
-- when that enumeration value is other -- set the corresponding field
OtherType within the containing element.
"""
def elements(self):
eligible_elements = []
for element in self.schema_tree.iterfind(
"{%s}complexType" % self._XSCHEMA_NAMESPACE
):
for elem in element.iter():
tag = self.strip_schema_ns(elem)
if tag == "element":
elem_name = elem.get("name")
if elem_name and elem_name == "OtherType":
eligible_elements.append(element.get("name"))
return eligible_elements
def check(self, element):
type_element = element.find("Type")
other_type_element = element.find("OtherType")
if type_element is not None and type_element.text == "other":
if other_type_element is None:
msg = (
"Type on this element is set to 'other' but OtherType element "
"is not defined"
)
raise loggers.ElectionError.from_message(msg, [element])
if type_element is not None and type_element.text != "other":
if other_type_element is not None:
msg = (
"Type on this element is not set to 'other' but OtherType "
"element is defined"
)
raise loggers.ElectionError.from_message(msg, [element])
class PartisanPrimary(base.BaseRule):
"""Partisan elections should link to the correct political party.
For an Election element of Election type primary, partisan-primary-open,
or partisan-primary-closed, the Contests in that ContestCollection should
have a PrimartyPartyIds that is present and non-empty.
"""
election_type = None
def __init__(self, election_tree, schema_tree, **kwargs):
super(PartisanPrimary, self).__init__(election_tree, schema_tree, **kwargs)
# There can only be one election element in a file.
election_elem = self.election_tree.find("Election")
if election_elem is not None:
election_type_elem = election_elem.find("Type")
if election_type_elem is not None:
self.election_type = election_type_elem.text.strip()
def elements(self):
return ["Election"]
def check(self, election_elem):
election_type_elem = election_elem.find("Type")
election_type = None
if element_has_text(election_type_elem):
election_type = election_type_elem.text.strip()
if not election_type or election_type not in (
"partisan-primary-open",
"partisan-primary-closed",
):
return
contests = self.get_elements_by_class(election_elem, "CandidateContest")
for contest_elem in contests:
primary_party_ids = contest_elem.find("PrimaryPartyIds")
if not element_has_text(primary_party_ids):
msg = (
"Election is of ElectionType %s but PrimaryPartyIds is not present"
" or is empty" % (self.election_type)
)
raise loggers.ElectionWarning.from_message(msg, [election_elem])
class PartisanPrimaryHeuristic(base.BaseRule):
"""Attempts to identify partisan primaries not marked up as such."""
# Add other strings that imply this is a primary contest.
party_text = ["(dem)", "(rep)", "(lib)"]
def elements(self):
return ["Election"]
def check(self, election_elem):
election_type_elem = election_elem.find("Type")
election_type = None
if element_has_text(election_type_elem):
election_type = election_type_elem.text.strip()
if election_type is not None and election_type in (
"primary",
"partisan-primary-open",
"partisan-primary-closed",
):
return
contests = self.get_elements_by_class(election_elem, "CandidateContest")
for contest_elem in contests:
contest_name = contest_elem.find("Name")
if element_has_text(contest_name):
c_name = contest_name.text.replace(" ", "").lower()
for p_text in self.party_text:
if p_text in c_name:
msg = (
"Name of contest - %s, contains text that implies it is a "
"partisan primary but is not marked up as such."
% (contest_name.text)
)
raise loggers.ElectionWarning.from_message(msg, [contest_elem])
class CoalitionParties(base.BaseRule):
"""Coalitions should always define the Party IDs."""
def elements(self):
return ["Coalition"]
def check(self, element):
party_id = element.find("PartyIds")
if party_id is None or not party_id.text or not party_id.text.strip():
raise loggers.ElectionError.from_message(
"Coalition must define PartyIDs", [element]
)
class UniqueLabel(base.BaseRule):
"""Labels should be unique within a file."""
def __init__(self, election_tree, schema_tree, **kwargs):
super(UniqueLabel, self).__init__(election_tree, schema_tree, **kwargs)
self.labels = set()
def elements(self):
eligible_elements = []
for _, element in etree.iterwalk(self.schema_tree):
tag = self.strip_schema_ns(element)
if tag == "element":
elem_type = element.get("type")
if elem_type == "InternationalizedText":
if element.get("name") not in eligible_elements:
eligible_elements.append(element.get("name"))
return eligible_elements
def check(self, element):
element_label = element.get("label")
if element_label:
if element_label in self.labels:
msg = "Duplicate label '%s'. Label already defined" % element_label
raise loggers.ElectionError.from_message(msg, [element])
else:
self.labels.add(element_label)
class CandidatesReferencedInRelatedContests(base.BaseRule):
"""Candidate should not be referred to by multiple unrelated contests.
A Candidate object should only be referenced from one contest, unless the
contests are related (connected by SubsequentContestId). If a Person is
running in multiple unrelated Contests, then that Person is a Candidate
several times over, but a Candida(te|cy) can't span unrelated contests.
"""
def __init__(self, election_tree, schema_tree, **kwargs):
super(CandidatesReferencedInRelatedContests, self).__init__(
election_tree, schema_tree, **kwargs
)
self.error_log = []
self.contest_graph = networkx.Graph()
def elements(self):
return ["ElectionReport"]
def _register_person_to_candidate_to_contests(self, election_report):
person_candidate_contest_mapping = {}
candidate_to_contest_mapping = {}
contests = self.get_elements_by_class(election_report, "Contest")
for contest in contests:
contest_id = contest.get("objectId", None)
candidate_ids_elements = self.get_elements_by_class(
contest, "CandidateIds"
)
candidate_id_elements = self.get_elements_by_class(contest, "CandidateId")
id_elements = candidate_ids_elements + candidate_id_elements
for id_element in id_elements:
if element_has_text(id_element):
for candidate_id in id_element.text.split():
candidate_to_contest_mapping.setdefault(candidate_id, []).append(
contest_id
)
candidates = self.get_elements_by_class(election_report, "Candidate")
for candidate in candidates:
candidate_id = candidate.get("objectId", None)
person_id = candidate.find("PersonId")
if element_has_text(person_id):
if candidate_id not in candidate_to_contest_mapping.keys():
raise loggers.ElectionError.from_message(
(
"A Candidate should be referenced in a Contest. Candidate {} "
"is not referenced."
).format(candidate_id)
)
contest_list = candidate_to_contest_mapping[candidate_id]
person_candidate_contest_mapping.setdefault(person_id.text, {})[
candidate_id
] = contest_list
return person_candidate_contest_mapping
def _construct_contest_graph(self, election_report):
contests = self.get_elements_by_class(election_report, "Contest")
# create a node for each contest