civics-cdf-validator 1.67.dev2__py3-none-any.whl → 1.67.dev4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,2732 +15,28 @@
15
15
 
16
16
  from __future__ import print_function
17
17
 
18
- import collections
19
18
  import datetime
20
19
  import enum
21
- import hashlib
22
20
  import re
23
21
 
24
22
  from botocore import utils as botocore_utils
25
23
  from civics_cdf_validator import base
26
- from civics_cdf_validator import gpunit_rules
27
24
  from civics_cdf_validator import loggers
28
25
  from civics_cdf_validator.rulesets import common_rules
26
+ from civics_cdf_validator.rulesets import election_rules
27
+ from civics_cdf_validator.rulesets import officeholder_rules
29
28
  from civics_cdf_validator.rulesets import rule_util
30
29
  import dateutil
31
30
  from frozendict import frozendict
32
- import networkx
33
-
34
-
35
- _CONTEST_STAGE_TYPES = frozenset([
36
- "exit-polls",
37
- "estimates",
38
- "projections",
39
- "preliminary",
40
- "official",
41
- "unnamed",
42
- ])
43
- _INTERNATIONALIZED_TEXT_ELEMENTS_WITH_ONLY_ONE_TEXT_PER_LANGUAGE = [
44
- # go/keep-sorted start
45
- "BallotName",
46
- "BallotSubTitle",
47
- "BallotText",
48
- "BallotTitle",
49
- "ConStatement",
50
- "Directions",
51
- "DisplayName",
52
- "EffectOfAbstain",
53
- "FullName",
54
- "FullText",
55
- "InternationalizedAbbreviation",
56
- "InternationalizedName",
57
- "Name",
58
- "PartyLabel",
59
- "PassageThreshold",
60
- "ProStatement",
61
- "Profession",
62
- "Selection",
63
- "SummaryText",
64
- "Title",
65
- # go/keep-sorted end
66
- ]
67
-
68
-
69
- _VALID_FEED_LONGEVITY_BY_FEED_TYPE = frozendict({
70
- "committee": ["evergreen"],
71
- "election-dates": ["evergreen"],
72
- "election-results": ["limited"],
73
- "officeholder": ["evergreen"],
74
- "pre-election": ["limited", "yearly"],
75
- })
76
-
77
-
78
- _WINNER_POST_ELECTION_STATUSES = frozenset([
79
- "winner",
80
- "projected-winner",
81
- ])
82
-
83
-
84
- def _get_type_or_other_type(element):
85
- """Returns the OtherType text if Type is "other", else the Type text."""
86
- type_element = element.find("Type")
87
- other_type_element = element.find("OtherType")
88
- type_text = (
89
- type_element.text.strip()
90
- if rule_util.element_has_text(type_element)
91
- else ""
92
- )
93
- other_type_text = (
94
- other_type_element.text.strip()
95
- if rule_util.element_has_text(other_type_element)
96
- else ""
97
- )
98
- return other_type_text if type_text == "other" else type_text
99
-
100
-
101
- class PercentSum(base.BaseRule):
102
- """Check that Contest elements have percents summing to 0 or 100."""
103
-
104
- def elements(self):
105
- return ["Contest"]
106
-
107
- @staticmethod
108
- def fuzzy_equals(a, b, epsilon=1e-6):
109
- return abs(a - b) < epsilon
110
-
111
- def check(self, element):
112
- sum_percents = 0.0
113
- for ballot_selection in element.findall("BallotSelection"):
114
- for vote_counts in ballot_selection.find("VoteCountsCollection").findall(
115
- "VoteCounts"
116
- ):
117
- other_type = vote_counts.find("OtherType")
118
- if other_type is not None and other_type.text == "total-percent":
119
- sum_percents += float(vote_counts.find("Count").text)
120
- if not PercentSum.fuzzy_equals(
121
- sum_percents, 0
122
- ) and not PercentSum.fuzzy_equals(sum_percents, 100):
123
- raise loggers.ElectionError.from_message(
124
- "Contest percents do not sum to 0 or 100: %f" % sum_percents,
125
- [element],
126
- )
127
-
128
-
129
- class GpUnitsHaveSingleRoot(base.TreeRule):
130
- """Ensure that GpUnits form a single-rooted tree."""
131
-
132
- def __init__(self, election_tree, schema_tree, **kwargs):
133
- super(GpUnitsHaveSingleRoot, self).__init__(
134
- election_tree, schema_tree, **kwargs
135
- )
136
- self.error_log = []
137
-
138
- def check(self):
139
- # Make sure there's at most one GpUnit as a root.
140
- # The root is defined as having ComposingGpUnitIds but
141
- # is not in the ComposingGpUnitIds of any other GpUnit.
142
-
143
- gpunit_ids = dict()
144
- composing_gpunits = set()
145
- for element in self.get_elements_by_class(self.election_tree, "GpUnit"):
146
- object_id = element.get("objectId")
147
- if object_id is not None:
148
- gpunit_ids[object_id] = element
149
- composing_gpunit = element.find("ComposingGpUnitIds")
150
- if composing_gpunit is not None and composing_gpunit.text is not None:
151
- composing_gpunits.update(composing_gpunit.text.split())
152
-
153
- roots = gpunit_ids.keys() - composing_gpunits
154
-
155
- if not roots:
156
- self.error_log.append(
157
- loggers.LogEntry(
158
- "GpUnits have no geo district root. "
159
- "There should be one or more root geo district."
160
- )
161
- )
162
- else:
163
- for object_id in roots:
164
- element = gpunit_ids.get(object_id)
165
- ocd_ids = rule_util.get_external_id_values(element, "ocd-id")
166
- for ocd_id in ocd_ids:
167
- if not gpunit_rules.GpUnitOcdIdValidator.is_country_or_region_ocd_id(
168
- ocd_id
169
- ):
170
- msg = (
171
- "GpUnits tree roots needs to be either a country or the EU"
172
- " region, please check the value %s." % (ocd_id)
173
- )
174
- self.error_log.append(loggers.LogEntry(msg, [element]))
175
-
176
- if self.error_log:
177
- raise loggers.ElectionError(self.error_log)
178
-
179
-
180
- class PartisanPrimary(base.BaseRule):
181
- """Partisan elections should link to the correct political party.
182
-
183
- For an Election element of Election type primary, partisan-primary-open,
184
- or partisan-primary-closed, the Contests in that ContestCollection should
185
- have a PrimartyPartyIds that is present and non-empty.
186
- """
187
-
188
- election_type = None
189
-
190
- def __init__(self, election_tree, schema_tree, **kwargs):
191
- super(PartisanPrimary, self).__init__(election_tree, schema_tree, **kwargs)
192
- # There can only be one election element in a file.
193
- election_elem = self.election_tree.find("Election")
194
- if election_elem is not None:
195
- election_type_elem = election_elem.find("Type")
196
- if election_type_elem is not None:
197
- self.election_type = election_type_elem.text.strip()
198
-
199
- def elements(self):
200
- return ["Election"]
201
-
202
- def check(self, election_elem):
203
- election_type_elem = election_elem.find("Type")
204
- election_type = None
205
- if rule_util.element_has_text(election_type_elem):
206
- election_type = election_type_elem.text.strip()
207
-
208
- if not election_type or election_type not in (
209
- "partisan-primary-open",
210
- "partisan-primary-closed",
211
- ):
212
- return
213
-
214
- contests = self.get_elements_by_class(election_elem, "CandidateContest")
215
- for contest_elem in contests:
216
- primary_party_ids = contest_elem.find("PrimaryPartyIds")
217
- if not rule_util.element_has_text(primary_party_ids):
218
- msg = (
219
- "Election is of ElectionType %s but PrimaryPartyIds is not present"
220
- " or is empty" % (self.election_type)
221
- )
222
- raise loggers.ElectionWarning.from_message(msg, [election_elem])
223
-
224
-
225
- class PartisanPrimaryHeuristic(base.BaseRule):
226
- """Attempts to identify partisan primaries not marked up as such."""
227
-
228
- # Add other strings that imply this is a primary contest.
229
- party_text = ["(dem)", "(rep)", "(lib)"]
230
-
231
- def elements(self):
232
- return ["Election"]
233
-
234
- def check(self, election_elem):
235
- election_type_elem = election_elem.find("Type")
236
- election_type = None
237
- if rule_util.element_has_text(election_type_elem):
238
- election_type = election_type_elem.text.strip()
239
-
240
- if election_type is not None and election_type in (
241
- "primary",
242
- "partisan-primary-open",
243
- "partisan-primary-closed",
244
- ):
245
- return
246
-
247
- contests = self.get_elements_by_class(election_elem, "CandidateContest")
248
- for contest_elem in contests:
249
- contest_name = contest_elem.find("Name")
250
- if rule_util.element_has_text(contest_name):
251
- c_name = contest_name.text.replace(" ", "").lower()
252
- for p_text in self.party_text:
253
- if p_text in c_name:
254
- msg = (
255
- "Name of contest - %s, contains text that implies it is a "
256
- "partisan primary but is not marked up as such."
257
- % (contest_name.text)
258
- )
259
- raise loggers.ElectionWarning.from_message(msg, [contest_elem])
260
-
261
-
262
- class CoalitionParties(base.BaseRule):
263
- """Coalitions should always define the Party IDs."""
264
-
265
- def elements(self):
266
- return ["Coalition"]
267
-
268
- def check(self, element):
269
- party_id = element.find("PartyIds")
270
- if party_id is None or not party_id.text or not party_id.text.strip():
271
- raise loggers.ElectionError.from_message(
272
- "Coalition must define PartyIDs", [element]
273
- )
274
-
275
-
276
- class CandidatesReferencedInRelatedContests(base.BaseRule):
277
- """Candidate should not be referred to by multiple unrelated contests.
278
-
279
- A Candidate object should only be referenced from one contest, unless the
280
- contests are related (connected by ComposingContestIds or
281
- SubsequentContestId). If a Person is running in multiple unrelated Contests,
282
- then that Person is a Candidate several times over, but a Candida(te|cy)
283
- can't span unrelated contests.
284
- """
285
-
286
- def __init__(self, election_tree, schema_tree, **kwargs):
287
- super(CandidatesReferencedInRelatedContests, self).__init__(
288
- election_tree, schema_tree, **kwargs
289
- )
290
- self.error_log = []
291
- self.contest_graph = networkx.Graph()
292
-
293
- def elements(self):
294
- return ["ElectionReport"]
295
-
296
- def _register_person_to_candidate_to_contests(self, election_report):
297
- person_candidate_contest_mapping = {}
298
-
299
- candidate_to_contest_mapping = {}
300
- contests = self.get_elements_by_class(election_report, "Contest")
301
- for contest in contests:
302
- contest_id = contest.get("objectId", None)
303
- candidate_ids_elements = self.get_elements_by_class(
304
- contest, "CandidateIds"
305
- )
306
- candidate_id_elements = self.get_elements_by_class(contest, "CandidateId")
307
- id_elements = candidate_ids_elements + candidate_id_elements
308
- for id_element in id_elements:
309
- if rule_util.element_has_text(id_element):
310
- for candidate_id in id_element.text.split():
311
- candidate_to_contest_mapping.setdefault(candidate_id, []).append(
312
- contest_id
313
- )
314
-
315
- candidates = self.get_elements_by_class(election_report, "Candidate")
316
- for candidate in candidates:
317
- candidate_id = candidate.get("objectId", None)
318
- person_id = candidate.find("PersonId")
319
- if rule_util.element_has_text(person_id):
320
- if candidate_id not in candidate_to_contest_mapping.keys():
321
- raise loggers.ElectionError.from_message(
322
- (
323
- "A Candidate should be referenced in a Contest. Candidate {} "
324
- "is not referenced."
325
- ).format(candidate_id)
326
- )
327
- contest_list = candidate_to_contest_mapping[candidate_id]
328
- person_candidate_contest_mapping.setdefault(person_id.text, {})[
329
- candidate_id
330
- ] = contest_list
331
-
332
- return person_candidate_contest_mapping
333
-
334
- def _construct_contest_graph(self, election_report):
335
- contests = self.get_elements_by_class(election_report, "Contest")
336
- # create a node for each contest
337
- for contest in contests:
338
- self.contest_graph.add_node(contest.get("objectId"))
339
-
340
- for contest in contests:
341
- subsequent_contest = contest.find("SubsequentContestId")
342
- if rule_util.element_has_text(subsequent_contest):
343
- subsequent_contest_id = subsequent_contest.text
344
- # subsequent contest id is not valid if it isn't in the graph
345
- if not self.contest_graph.has_node(subsequent_contest_id):
346
- raise loggers.ElectionError.from_message(
347
- (
348
- "Contest {} contains a subsequent Contest Id ({}) that does "
349
- "not exist."
350
- ).format(contest.get("objectId"), subsequent_contest_id),
351
- [subsequent_contest],
352
- )
353
- self.contest_graph.add_edge(
354
- contest.get("objectId"), subsequent_contest_id
355
- )
356
- # Add the composing contest if it exists
357
- composing_contests = contest.find("ComposingContestIds")
358
- if rule_util.element_has_text(composing_contests):
359
- children = composing_contests.text.split()
360
- for child in children:
361
- # composing contest id is not valid if it isn't in the graph
362
- if not self.contest_graph.has_node(child):
363
- raise loggers.ElectionError.from_message(
364
- (
365
- "Contest {} contains a composing Contest Id ({}) that does "
366
- "not exist."
367
- ).format(contest.get("objectId"), child),
368
- [composing_contests],
369
- )
370
- self.contest_graph.add_edge(contest.get("objectId"), child)
371
-
372
- def _check_candidate_contests_are_related(self, contest_id_list):
373
- for i in range(len(contest_id_list) - 1):
374
- contest_one = contest_id_list[i]
375
- contest_two = contest_id_list[i + 1]
376
- # every unique contest should be related, but since paths are transitive
377
- # checking each subsequent pair is enough to ensure this
378
- if not networkx.has_path(self.contest_graph, contest_one, contest_two):
379
- return False
380
-
381
- return True
382
-
383
- def _check_separate_candidates_not_related(self, candidate_contest_mapping):
384
- for contests in candidate_contest_mapping.values():
385
- for other_contests in [
386
- con for con in candidate_contest_mapping.values() if con != contests
387
- ]:
388
- for contest in contests:
389
- for other_contest in other_contests:
390
- if networkx.has_path(self.contest_graph, contest, other_contest):
391
- return False
392
- return True
393
-
394
- def check(self, election_report):
395
- self._construct_contest_graph(election_report)
396
- person_candidate_to_contest_map = (
397
- self._register_person_to_candidate_to_contests(election_report)
398
- )
399
- for person, cand_con_mapping in person_candidate_to_contest_map.items():
400
- for cand, contests in cand_con_mapping.items():
401
- related_contests = self._check_candidate_contests_are_related(contests)
402
- if not related_contests:
403
- error_message = (
404
- "Candidate {} appears in the following contests "
405
- "which are not all related: {}"
406
- ).format(cand, ", ".join(contests))
407
- self.error_log.append(
408
- loggers.LogEntry(error_message, [election_report])
409
- )
410
-
411
- sep_cand_not_related = self._check_separate_candidates_not_related(
412
- cand_con_mapping
413
- )
414
- if not sep_cand_not_related:
415
- error_message = (
416
- "Person {} has separate candidates in contests that "
417
- "are related.".format(person)
418
- )
419
- self.error_log.append(
420
- loggers.LogEntry(error_message, [election_report])
421
- )
422
-
423
- if self.error_log:
424
- raise loggers.ElectionError(self.error_log)
425
-
426
-
427
- class ProperBallotSelection(base.BaseRule):
428
- """BallotSelections should be correct for that type of contest.
429
-
430
- Ensure that the BallotSelection elements in a CandidateContest are
431
- CandidateSelections, PartyContests have PartySelections, etc, etc.
432
- """
433
-
434
- con_sel_mapping = {
435
- "BallotMeasureContest": "BallotMeasureSelection",
436
- "CandidateContest": "CandidateSelection",
437
- "PartyContest": "PartySelection",
438
- "RetentionContest": "BallotMeasureSelection",
439
- }
440
-
441
- def elements(self):
442
- return self.con_sel_mapping.keys()
443
-
444
- def check(self, element):
445
- tag = self.get_element_class(element)
446
- selections = []
447
- for c in self.con_sel_mapping:
448
- selections += self.get_elements_by_class(element, self.con_sel_mapping[c])
449
- for selection in selections:
450
- selection_tag = self.get_element_class(selection)
451
- if selection_tag != self.con_sel_mapping[tag]:
452
- contest_id = element.get("objectId")
453
- selection_id = selection.get("objectId")
454
- msg = (
455
- "The Contest does not contain the right BallotSelection. %s "
456
- "must have a %s but contains a %s, %s"
457
- % (tag, self.con_sel_mapping[tag], selection_tag, selection_id)
458
- )
459
- raise loggers.ElectionError.from_message(msg, [element])
460
-
461
-
462
- class CorrectCandidateSelectionCount(base.BaseRule):
463
- """CandidateSelections should only reference one candidate.
464
-
465
- This rule will throw a warning if a CandidateSelection references multiple
466
- candidates or does not reference any candidates at all. We currently do not
467
- support tickets (i.e. CandidateSelections with multiple candidates) except for
468
- party list elections.
469
- """
470
-
471
- def elements(self):
472
- return ["CandidateSelection"]
473
-
474
- def check(self, element):
475
- selection_id = element.get("objectId")
476
- candidate_ids = element.findall("CandidateIds")
477
- if not candidate_ids:
478
- msg = (
479
- f"The CandidateSelection {selection_id} does not reference any"
480
- " candidates."
481
- )
482
- raise loggers.ElectionWarning.from_message(msg, [element])
483
- if len(candidate_ids) > 1:
484
- msg = (
485
- f"The CandidateSelection {selection_id} is expected to have one"
486
- f" CandidateIds but {len(candidate_ids)} were found."
487
- )
488
- raise loggers.ElectionWarning.from_message(msg, [element])
489
- candidates = candidate_ids[0].text.split()
490
- if len(candidates) != 1:
491
- msg = (
492
- f"CandidateIds for CandidateSelection {selection_id} is expected to"
493
- f" reference one candidate but {len(candidates)} candidates were"
494
- " found. This warning can be ignored for party list elections."
495
- )
496
- raise loggers.ElectionWarning.from_message(msg, [element])
497
-
498
-
499
- class SingularPartySelection(base.BaseRule):
500
- """Each PartySelection should have exactly one Party in the PartyIds.
501
-
502
- While technically the schema allows multiple IDs, currently our pipeline does
503
- not support this. Having multiple parties can cause undefined behavior.
504
- """
505
-
506
- def elements(self):
507
- return ["PartySelection"]
508
-
509
- def check(self, element):
510
- party_ids = element.find("PartyIds")
511
- if party_ids is None or not party_ids.text or not party_ids.text.strip():
512
- raise loggers.ElectionError.from_message(
513
- "PartySelection has no associated parties.", [element]
514
- )
515
- elif len(party_ids.text.split()) != 1:
516
- raise loggers.ElectionError.from_message(
517
- "PartySelection has more than one associated party.", [element]
518
- )
519
-
520
-
521
- class ValidatePartyCollection(base.BaseRule):
522
- """Generic party collection validation rule.
523
-
524
- All partyCollection validation rules can inherit from this class since it
525
- contains basic checks.
526
- """
527
-
528
- def elements(self):
529
- return ["PartyCollection"]
530
-
531
- def check_specific(self, parties):
532
- """Return a list of info log to be raised."""
533
- raise NotImplementedError
534
-
535
- def check(self, element):
536
- info_log = []
537
- parties = element.findall("Party")
538
- if len(parties) < 1:
539
- info_message = "<PartyCollection> does not have <Party> objects"
540
- info_log.append(loggers.LogEntry(info_message, element))
541
- info_log.extend(self.check_specific(parties))
542
- if info_log:
543
- raise loggers.ElectionInfo(info_log)
544
-
545
-
546
- class ValidateDuplicateColors(base.TreeRule):
547
- """Parties under the same contest should have unique color.
548
-
549
- A Party object that has duplicate color and referenced under the same contest
550
- should be picked up within this class and returned to the user as a warning
551
- message.
552
- """
553
-
554
- def check(self):
555
- party_colors_by_id = {}
556
- party_objects = {}
557
- for party in self.get_elements_by_class(self.election_tree, "Party"):
558
- party_id = party.get("objectId")
559
- party_objects[party_id] = party
560
- party_colors_by_id[party_id] = {}
561
- color_element = party.find("Color")
562
- if rule_util.element_has_text(color_element):
563
- party_colors_by_id[party_id]["Color"] = color_element.text.lower()
564
- colors_element = party.find("Colors")
565
- if colors_element is not None:
566
- for color_field in ("DarkThemeColor", "LightThemeColor"):
567
- sub_color_element = colors_element.find(color_field)
568
- if rule_util.element_has_text(sub_color_element):
569
- party_colors_by_id[party_id][
570
- color_field
571
- ] = sub_color_element.text.lower()
572
-
573
- warning_log = []
574
- for party_contest in self.get_elements_by_class(
575
- element=self.election_tree, element_name="PartyContest"
576
- ):
577
- contest_colors = {
578
- "Color": collections.defaultdict(list),
579
- "DarkThemeColor": collections.defaultdict(list),
580
- "LightThemeColor": collections.defaultdict(list),
581
- }
582
- for party_ids_element in self.get_elements_by_class(
583
- element=party_contest, element_name="PartyIds"
584
- ):
585
- for party_id in party_ids_element.text.split():
586
- if party_id not in party_colors_by_id:
587
- continue
588
- party_colors = party_colors_by_id[party_id]
589
- party_element = party_objects[party_id]
590
-
591
- has_party_colors = "Color" in party_colors or (
592
- "DarkThemeColor" in party_colors
593
- and "LightThemeColor" in party_colors
594
- )
595
- if not has_party_colors:
596
- warning_log.append(
597
- loggers.LogEntry(
598
- f"Party ({party_id}) in PartyContest should have either"
599
- " Color or Colors.DarkThemeColor and Colors.LightThemeColor"
600
- " set.",
601
- [party_element],
602
- )
603
- )
604
-
605
- for color_field in ("Color", "DarkThemeColor", "LightThemeColor"):
606
- if color_field in party_colors:
607
- color_val = party_colors[color_field]
608
- contest_colors[color_field][color_val].append(party_element)
609
-
610
- for color_field in ("Color", "DarkThemeColor", "LightThemeColor"):
611
- for color, parties in contest_colors[color_field].items():
612
- if len(parties) > 1:
613
- warning_log.append(
614
- loggers.LogEntry(
615
- f"Parties have the same {color_field} {color}.",
616
- parties,
617
- )
618
- )
619
- if warning_log:
620
- raise loggers.ElectionWarning(warning_log)
621
-
622
-
623
- class DuplicatedPartyAbbreviation(ValidatePartyCollection):
624
- """Party abbreviation should be used once in a given language.
625
-
626
- If an abbreviation is duplicated, the corresponding party should be picked up
627
- within this class and returned to the user as an Info message.
628
- """
629
-
630
- def check_specific(self, parties):
631
- info_log = []
632
- party_abbrs_by_language = {}
633
- for party in parties:
634
- abbr_element = party.find("InternationalizedAbbreviation")
635
- if abbr_element is None:
636
- info_message = (
637
- "<Party> does not have <InternationalizedAbbreviation> objects"
638
- )
639
- info_log.append(loggers.LogEntry(info_message, [party]))
640
- continue
641
- party_abbrs = abbr_element.findall("Text")
642
- for party_abbr in party_abbrs:
643
- language = party_abbr.get("language")
644
- abbr = party_abbr.text
645
- if language not in party_abbrs_by_language:
646
- party_abbrs_by_language[language] = {}
647
- if abbr in party_abbrs_by_language[language]:
648
- party_abbrs_by_language[language][abbr].append(party)
649
- else:
650
- party_abbrs_by_language[language][abbr] = [party]
651
-
652
- for language, abbrs in party_abbrs_by_language.items():
653
- for abbr, parties in abbrs.items():
654
- if len(parties) > 1:
655
- info_message = "Parties have the same abbreviation in %s." % language
656
- info_log.append(loggers.LogEntry(info_message, parties))
657
- return info_log
658
-
659
-
660
- class DuplicatedPartyName(ValidatePartyCollection):
661
- """Party name should be used once in a given language.
662
-
663
- If a party name is duplicated, the corresponding party should be picked up
664
- within this class and returned to the user as an Info message.
665
- """
666
-
667
- def check_specific(self, parties):
668
- info_log = []
669
- party_names_by_language = {}
670
- for party in parties:
671
- name_element = party.find("Name")
672
- if name_element is None:
673
- info_message = "<Party> does not have <Name> objects"
674
- info_log.append(loggers.LogEntry(info_message, [party]))
675
- continue
676
- party_names = name_element.findall("Text")
677
- for party_name in party_names:
678
- language = party_name.get("language")
679
- name = party_name.text
680
- if language not in party_names_by_language:
681
- party_names_by_language[language] = {}
682
- if name in party_names_by_language[language]:
683
- party_names_by_language[language][name].append(party)
684
- else:
685
- party_names_by_language[language][name] = [party]
686
-
687
- for language, names in party_names_by_language.items():
688
- for name, parties in names.items():
689
- if len(parties) > 1:
690
- info_message = "Parties have the same name in %s." % language
691
- info_log.append(loggers.LogEntry(info_message, parties))
692
- return info_log
693
-
694
-
695
- class MissingPartyNameTranslation(ValidatePartyCollection):
696
- """All Parties should have their name translated to the same languages.
697
-
698
- If there is a party name that is not translated to all the feed languages,
699
- the party should be picked up within this class and returned to the user as
700
- an Info message.
701
- """
702
-
703
- def check_specific(self, parties):
704
- info_log = []
705
- feed_languages, feed_party_ids = set(), set()
706
- for party in parties:
707
- party_object_id = party.get("objectId")
708
- name_element = party.find("Name")
709
- if name_element is None:
710
- info_message = "<Party> does not have <Name> objects"
711
- info_log.append(loggers.LogEntry(info_message, [party]))
712
- continue
713
- party_names = name_element.findall("Text")
714
- party_languages = set()
715
- for party_name in party_names:
716
- language = party_name.get("language")
717
- if language not in feed_languages:
718
- feed_languages.add(language)
719
- if feed_party_ids:
720
- info_message = (
721
- "The feed is missing names translation to %s for parties : %s."
722
- % (language, feed_party_ids)
723
- )
724
- info_log.append(loggers.LogEntry(info_message))
725
- party_languages.add(language)
726
- feed_party_ids.add(party_object_id)
727
- if len(party_languages) != len(feed_languages):
728
- info_message = (
729
- "The party name is not translated to all feed languages %s. You "
730
- "did it only for the following languages : %s."
731
- % (feed_languages, party_languages)
732
- )
733
- info_log.append(loggers.LogEntry(info_message, [party]))
734
- return info_log
735
-
736
-
737
- class MissingPartyAbbreviationTranslation(ValidatePartyCollection):
738
- """Every party's abbreviation should be translated to the same languages.
739
-
740
- If a party is missing a name translation, it should be picked up within this
741
- class and returned to the user as an Info message.
742
- """
743
-
744
- def check_specific(self, parties):
745
- info_log = []
746
- feed_languages, feed_party_ids = set(), set()
747
- for party in parties:
748
- party_object_id = party.get("objectId")
749
- abbr_element = party.find("InternationalizedAbbreviation")
750
- if abbr_element is None:
751
- info_message = (
752
- "<Party> does not have <InternationalizedAbbreviation> objects"
753
- )
754
- info_log.append(loggers.LogEntry(info_message, [party]))
755
- continue
756
- party_abbrs = abbr_element.findall("Text")
757
- party_languages = set()
758
- for party_abbr in party_abbrs:
759
- language = party_abbr.get("language")
760
- if language not in feed_languages:
761
- feed_languages.add(language)
762
- if feed_party_ids:
763
- info_message = (
764
- "The feed is missing abbreviation translation to %s for parties"
765
- " : %s." % (language, feed_party_ids)
766
- )
767
- info_log.append(loggers.LogEntry(info_message))
768
- party_languages.add(language)
769
- feed_party_ids.add(party_object_id)
770
- if len(party_languages) != len(feed_languages):
771
- info_message = (
772
- "The party abbreviation is not translated to all feed languages %s."
773
- " You only did it for the following languages : %s."
774
- % (feed_languages, party_languages)
775
- )
776
- info_log.append(loggers.LogEntry(info_message, [party]))
777
- return info_log
778
-
779
-
780
- class DuplicateContestNames(base.BaseRule):
781
- """Check that an election contains unique ContestNames.
782
-
783
- Add Warning if duplicate ContestName found.
784
- """
785
-
786
- def elements(self):
787
- return ["ContestCollection"]
788
-
789
- def check(self, election_elt):
790
- # Mapping for <Name> and its Contest ObjectId.
791
- error_log = []
792
- name_contest_id = {}
793
- contest_elts = election_elt.findall("Contest")
794
- if contest_elts is None:
795
- error_message = "ContestCollection is Empty."
796
- error_log.append(loggers.LogEntry(error_message, [election_elt]))
797
- for element in contest_elts:
798
- name = element.find("Name")
799
- if name is None or not name.text:
800
- error_message = "The contest is missing a <Name> "
801
- error_log.append(loggers.LogEntry(error_message, [element]))
802
- continue
803
- name_contest_id.setdefault(name.text, []).append(element)
804
-
805
- for name, contests in name_contest_id.items():
806
- if len(contests) > 1:
807
- error_log.append(
808
- loggers.LogEntry("Contests have the same name %s." % name, contests)
809
- )
810
- if error_log:
811
- raise loggers.ElectionError(error_log)
812
-
813
-
814
- class DuplicateBallotTitleSeatPair(base.BaseRule):
815
- """Checks that each English (BallotTitle, Seat) combination is unique.
816
-
817
- Adds Warning/Error if duplicate English (BallotTitle, Seat) combinations are
818
- found.
819
- """
820
-
821
- def elements(self):
822
- return ["ContestCollection"]
823
-
824
- def check(self, element):
825
- error_log = []
826
- contest_elements = element.findall("Contest")
827
- contests_by_title_and_seat = collections.defaultdict(list)
828
-
829
- for contest in contest_elements:
830
- ballot_title_element = rule_util.get_language_to_text_map(
831
- contest.find("BallotTitle")
832
- )
833
- english_title = ballot_title_element.get("en")
834
- seat_element = contest.find("Seat")
835
-
836
- ballot_title = english_title[0].strip() if english_title else ""
837
- seat = (
838
- seat_element.text.strip()
839
- if rule_util.element_has_text(seat_element)
840
- else ""
841
- )
842
-
843
- if not ballot_title:
844
- continue
845
-
846
- ballot_title_and_seat = (ballot_title, seat)
847
- contests_by_title_and_seat[ballot_title_and_seat].append(contest)
848
-
849
- for ballot_title_and_seat, contests in contests_by_title_and_seat.items():
850
- if len(contests) > 1:
851
- ballot_title, seat = ballot_title_and_seat
852
- error_message = (
853
- "Multiple Contests found with the same BallotTitle"
854
- f" ('{ballot_title}') and Seat ('{seat}')."
855
- )
856
- error_log.append(loggers.LogEntry(error_message, contests))
857
-
858
- if error_log:
859
- raise loggers.ElectionError(error_log)
860
-
861
-
862
- class MultipleCandidatesPointToTheSamePersonInTheSameContest(base.TreeRule):
863
- """Raise an error when multiple candidates point to the same person in the same contest."""
864
-
865
- def check(self):
866
- # Keep track of rule violations
867
- error_log = []
868
- rule_violations = []
869
- # Get all Candidate objects in the feed
870
- candidates = self.get_elements_by_class(self.election_tree, "Candidate")
871
- # Store link between candidate_id and person_id for each Candidate object
872
- person_id_by_candidate_id = {
873
- candidate.get("objectId"): candidate.find("PersonId").text
874
- for candidate in candidates
875
- }
876
- # Get all Contest objects in the feed
877
- contests = self.get_elements_by_class(self.election_tree, "Contest")
878
- for contest in contests:
879
- rule_violations.extend(
880
- self._check_for_bad_candidates(person_id_by_candidate_id, contest)
881
- )
882
- # Combine rule violations into one error message
883
- if rule_violations:
884
- for rule_violation in rule_violations:
885
- contest_id = rule_violation[0]
886
- person_id = rule_violation[1]
887
- candidate_list = rule_violation[2]
888
- error_message = (
889
- "Multiple candidates in Contest {} reference the same Person "
890
- "{}. Candidates: {}"
891
- ).format(contest_id, person_id, candidate_list)
892
- error_log.append(loggers.LogEntry((error_message), [contest_id]))
893
- if error_log:
894
- raise loggers.ElectionError(error_log)
895
-
896
- def _check_for_bad_candidates(self, person_id_by_candidate_id, contest):
897
- candidate_ids_by_person_id = dict()
898
- rule_violating_person_ids = []
899
- contest_id = contest.get("objectId")
900
- for candidate_id in self._get_candidate_ids_for_contest(contest):
901
- person_id = person_id_by_candidate_id[candidate_id]
902
- if person_id not in candidate_ids_by_person_id:
903
- candidate_ids_by_person_id[person_id] = [candidate_id]
904
- else:
905
- candidate_ids_by_person_id[person_id].append(candidate_id)
906
- rule_violating_person_ids.append(person_id)
907
- return [
908
- (contest_id, person_id, str(candidate_ids_by_person_id[person_id]))
909
- for person_id in rule_violating_person_ids
910
- ]
911
-
912
- def _get_candidate_ids_for_contest(self, contest):
913
- candidate_id_elements = self.get_elements_by_class(contest, "CandidateIds")
914
- candidate_ids = []
915
- for candidate_id_element in candidate_id_elements:
916
- candidate_ids.extend(candidate_id_element.text.split())
917
- return candidate_ids
918
-
919
-
920
- class SelfDeclaredCandidateMethod(base.BaseRule):
921
- """A self declared candidate cannot have an "electoral-commission" id.
922
-
923
- Please update the candidate Pre election Status.
924
- """
925
-
926
- def elements(self):
927
- return ["Candidate"]
928
-
929
- def check(self, element):
930
- status = element.find("PreElectionStatus")
931
- if status is not None and status.text == "self-declared":
932
- externalidvalues = rule_util.get_external_id_values(
933
- element, "electoral-commission"
934
- )
935
- length = len(externalidvalues)
936
- if length > 0:
937
- msg = (
938
- "A self declared candidate cannot have an electoral-commission"
939
- " id. Please update the candidate Pre election Status."
940
- )
941
- raise loggers.ElectionWarning.from_message(msg, [element])
942
-
943
-
944
- class ContestHasMultipleOffices(base.BaseRule):
945
- """Ensure that each contest has exactly one Office."""
946
-
947
- def elements(self):
948
- return ["CandidateContest", "PartyContest"]
949
-
950
- def check(self, element):
951
- # for each contest, get the <officeids> entity
952
- office_ids = element.find("OfficeIds")
953
- if office_ids is not None and office_ids.text:
954
- ids = office_ids.text.split()
955
- if len(ids) > 1:
956
- raise loggers.ElectionWarning.from_message(
957
- "Contest has more than one associated office.", [element]
958
- )
959
- else:
960
- raise loggers.ElectionWarning.from_message(
961
- "Contest has no associated offices.", [element]
962
- )
963
-
964
-
965
- class PersonHasOffice(base.ValidReferenceRule):
966
- """Ensure that each non-party-leader Person object linked to one Office."""
967
-
968
- def _gather_reference_values(self):
969
- root = self.election_tree.getroot()
970
-
971
- person_ids = set()
972
- person_collection = root.find("PersonCollection")
973
- if person_collection is not None:
974
- person_ids = {p.attrib["objectId"] for p in person_collection}
975
- return person_ids
976
-
977
- def _gather_defined_values(self):
978
- root = self.election_tree.getroot()
979
-
980
- person_reference_ids = set()
981
- # Add party leaders provided in the External Identifier
982
- for external_id in root.findall(".//Party//ExternalIdentifier"):
983
- other_type = external_id.find("OtherType")
984
- if (
985
- other_type is not None
986
- and other_type.text in rule_util.PARTY_LEADERSHIP_TYPES
987
- ):
988
- person_reference_ids.add(external_id.find("Value").text)
989
- # Add party leaders provided in the Leadership entity
990
- for leader_id in root.findall(".//Party//PartyLeaderId"):
991
- if leader_id.text:
992
- person_reference_ids.add(leader_id.text)
993
-
994
- office_holder_tenure_collection = root.find("OfficeHolderTenureCollection")
995
- if office_holder_tenure_collection is not None:
996
- for office_holder_tenure in office_holder_tenure_collection.findall(
997
- "OfficeHolderTenure"
998
- ):
999
- id_obj = office_holder_tenure.find("OfficeHolderPersonId")
1000
- if id_obj is not None and id_obj.text:
1001
- person_reference_ids.add(id_obj.text.strip())
1002
-
1003
- office_collection = root.find("OfficeCollection")
1004
- if (
1005
- office_holder_tenure_collection is None
1006
- and office_collection is not None
1007
- ):
1008
- for office in office_collection.findall("Office"):
1009
- id_obj = office.find("OfficeHolderPersonIds")
1010
- if id_obj is not None and id_obj.text:
1011
- ids = id_obj.text.strip().split()
1012
- if len(ids) > 1:
1013
- msg = "Office has {} OfficeHolders. Must have exactly one.".format(
1014
- str(len(ids))
1015
- )
1016
- raise loggers.ElectionError.from_message(msg, [office])
1017
- person_reference_ids.update(ids)
1018
-
1019
- return person_reference_ids
1020
-
1021
-
1022
- class VoteCountTypesCoherency(base.BaseRule):
1023
- """Ensure VoteCount types describe the appropriate votable."""
1024
-
1025
- PARTY_VC_TYPES = {
1026
- "seats-won",
1027
- "seats-leading",
1028
- "party-votes",
1029
- "seats-no-election",
1030
- "seats-total",
1031
- "seats-delta",
1032
- "seats-delta-mandate",
1033
- "seats-delta-institutional",
1034
- }
1035
- # Ibid.
1036
- CAND_VC_TYPES = {"candidate-votes"}
1037
-
1038
- def elements(self):
1039
- return ["Contest"]
1040
-
1041
- def check(self, element):
1042
- invalid_vc_types = None
1043
- contest_type = ""
1044
- if element.get("type", "") == "CandidateContest":
1045
- invalid_vc_types = self.PARTY_VC_TYPES
1046
- contest_type = "Candidate"
1047
- elif element.get("type", "") == "PartyContest":
1048
- invalid_vc_types = self.CAND_VC_TYPES
1049
- contest_type = "Party"
1050
- if invalid_vc_types:
1051
- errors = []
1052
- for ballot_selection in element.findall("BallotSelection"):
1053
- for vote_counts in ballot_selection.find(
1054
- "VoteCountsCollection"
1055
- ).findall("VoteCounts"):
1056
- vc_type = vote_counts.find("OtherType").text
1057
- if vc_type in invalid_vc_types:
1058
- errors.append(vc_type)
1059
- if errors:
1060
- msg = "VoteCount types {0} should not be nested in {1} Contest".format(
1061
- ", ".join(errors), contest_type
1062
- )
1063
- raise loggers.ElectionError.from_message(msg, [element])
1064
-
1065
-
1066
- class VoteCountValidSeatsDeltaTypes(base.BaseRule):
1067
- """Ensure VoteCount seats delta types are valid."""
1068
-
1069
- def elements(self):
1070
- return ["BallotSelection"] + list(
1071
- self.get_element_names_for_type("SpecialBallotSelection")
1072
- )
1073
-
1074
- def check(self, element):
1075
- vote_count_types = set()
1076
- vote_counts_collection = element.find("VoteCountsCollection")
1077
- if vote_counts_collection is None:
1078
- return
1079
- for vote_counts in vote_counts_collection.findall("VoteCounts"):
1080
- vote_count_types.add(_get_type_or_other_type(vote_counts))
1081
- if "seats-delta" in vote_count_types:
1082
- raise loggers.ElectionError.from_message(
1083
- "Legacy VoteCounts type seats-delta is no longer supported as of"
1084
- " July 1, 2026. Please update your implementation to use"
1085
- " seats-delta-mandate and/or seats-delta-institutional.",
1086
- [element],
1087
- )
1088
-
1089
-
1090
- class OfficeHasjurisdictionSameAsElectoralDistrict(base.BaseRule):
1091
- """In election feeds, office has the electoral district same as jurisdiction."""
1092
-
1093
- def elements(self):
1094
- return ["Office"]
1095
-
1096
- def check(self, element):
1097
- jurisdiction_values = rule_util.get_entity_info_for_value_type(
1098
- element, "jurisdiction-id"
1099
- )
1100
- jurisdiction_values = [
1101
- j_id.strip() for j_id in jurisdiction_values if j_id.strip()
1102
- ]
1103
- if not jurisdiction_values or len(jurisdiction_values) > 1:
1104
- return
1105
-
1106
- electoral_district = element.find(".//ElectoralDistrictId")
1107
- if electoral_district is None:
1108
- return
1109
- if electoral_district.text.strip() != jurisdiction_values[0]:
1110
- raise loggers.ElectionInfo.from_message(
1111
- "Office has electoral district different from jurisdiction.",
1112
- [element],
1113
- )
1114
-
1115
-
1116
- class ContestHasValidContestStage(base.BaseRule):
1117
- """Each Contest must have a valid contest-stage."""
1118
-
1119
- def elements(self):
1120
- return ["CandidateContest", "PartyContest", "BallotMeasureContest"]
1121
-
1122
- def check(self, element):
1123
- contest_stage_values = [
1124
- contest_stage_value.strip()
1125
- for contest_stage_value in rule_util.get_external_id_values(
1126
- element, "contest-stage"
1127
- )
1128
- ]
1129
- for contest_stage_value in contest_stage_values:
1130
- if contest_stage_value not in _CONTEST_STAGE_TYPES:
1131
- raise loggers.ElectionError.from_message(
1132
- "The contest has invalid contest-stage '{}'.".format(
1133
- contest_stage_value
1134
- ),
1135
- [element],
1136
- )
1137
-
1138
-
1139
- class DateOfBirthIsInPast(base.DateRule):
1140
- """Date of Birth should not be in the future."""
1141
-
1142
- def elements(self):
1143
- return ["PersonCollection"]
1144
-
1145
- def check(self, element):
1146
- for person_element in element:
1147
- date_of_birthday = person_element.find("DateOfBirth")
1148
- if date_of_birthday is not None and date_of_birthday.text:
1149
- date_of_birthday = base.PartialDate.init_partial_date(
1150
- date_of_birthday.text
1151
- )
1152
- self.check_for_date_in_past(date_of_birthday, person_element)
1153
- if self.error_log:
1154
- raise loggers.ElectionError(self.error_log)
1155
-
1156
-
1157
- class ElectionContainsStartAndEndDates(base.DateRule):
1158
- """Election elements should have start and end dates populated."""
1159
-
1160
- def elements(self):
1161
- return ["Election"]
1162
-
1163
- def check(self, element):
1164
- self.reset_instance_vars()
1165
- self.gather_dates(element)
1166
-
1167
- if self.start_elem is None:
1168
- self.error_log.append(
1169
- loggers.LogEntry(
1170
- "Election {} is missing a start date.".format(
1171
- element.get("objectId")
1172
- )
1173
- )
1174
- )
1175
-
1176
- if self.end_elem is None:
1177
- self.error_log.append(
1178
- loggers.LogEntry(
1179
- "Election {} is missing an end date.".format(
1180
- element.get("objectId")
1181
- )
1182
- )
1183
- )
1184
-
1185
- if self.error_log:
1186
- raise loggers.ElectionError(self.error_log)
1187
-
1188
-
1189
- class ElectionStartDates(base.DateRule):
1190
- """Election elements should contain valid start dates.
1191
-
1192
- Start dates in the past should raise a warning. This is not an error
1193
- as validator could conceivably be run during an ongoing election.
1194
- """
1195
-
1196
- def elements(self):
1197
- return ["Election"]
1198
-
1199
- def check(self, element):
1200
- self.reset_instance_vars()
1201
- self.gather_dates(element)
1202
-
1203
- if self.start_date:
1204
- self.check_for_date_not_in_past(self.start_date, self.start_elem)
1205
-
1206
- if self.error_log:
1207
- raise loggers.ElectionWarning(self.error_log)
1208
-
1209
-
1210
- class ElectionEndDatesInThePast(base.DateRule):
1211
- """Election elements would be in the present or in the future.
1212
-
1213
- Using a past end date needs to be notified. The warning is useful to prevent
1214
- using a wrong date.
1215
-
1216
- A bounded election with a past end date is an error since the date should be
1217
- confirmed. The only exception to this is elections that are postponed or
1218
- canceled.
1219
- """
1220
-
1221
- def elements(self):
1222
- return ["Election"]
1223
-
1224
- def check(self, element):
1225
- self.reset_instance_vars()
1226
- self.gather_dates(element)
1227
- date_type = element.find("ElectionDateType")
1228
- if date_type is not None and date_type.text.lower() == "bounded":
1229
- if self.end_date:
1230
- self.check_for_date_not_in_past(self.end_date, self.end_elem)
1231
- if self.error_log:
1232
- date_status = element.find("ElectionDateStatus")
1233
- if date_status is None or date_status.text.lower() not in [
1234
- "postponed",
1235
- "canceled",
1236
- ]:
1237
- raise loggers.ElectionError.from_message(
1238
- "A bounded election should not have an end date in the past.",
1239
- [element],
1240
- )
1241
- self.reset_instance_vars()
1242
- for contest in self.get_elements_by_class(element, "Contest"):
1243
- subsequent_contest_id_element = contest.find("SubsequentContestId")
1244
- if subsequent_contest_id_element is not None:
1245
- continue
1246
- else:
1247
- if self.end_date:
1248
- self.check_for_date_not_in_past(self.end_date, self.end_elem)
1249
- if self.error_log:
1250
- raise loggers.ElectionWarning(self.error_log)
1251
-
1252
-
1253
- class ElectionEndDatesOccurAfterStartDates(base.DateRule):
1254
- """Election elements should contain a coherent start and end dates.
1255
-
1256
- End dates should not occur before the start date.
1257
- """
1258
-
1259
- def elements(self):
1260
- return ["Election"]
1261
-
1262
- def check(self, element):
1263
- self.reset_instance_vars()
1264
- self.gather_dates(element)
1265
-
1266
- if self.end_date and self.start_date:
1267
- self.check_end_after_start()
1268
- if self.error_log:
1269
- raise loggers.ElectionError(self.error_log)
1270
-
1271
-
1272
- class ElectionDatesSpanContestDates(base.DateRule):
1273
- """Election start/end dates should span the Contest start/end dates.
1274
-
1275
- The start date of the Election should be on or before the start date of every
1276
- included Contest. The end date of the Election should be on or after the end
1277
- date of every included Contest. Only Contests that have the dates populated
1278
- will be considered.
1279
- """
1280
-
1281
- def elements(self):
1282
- return ["ElectionReport"]
1283
-
1284
- def _validate_contest_dates_within_election(self, election, contest):
1285
- self.reset_instance_vars()
1286
- self.gather_dates(election)
1287
- election_start_date = self.start_date
1288
- election_end_date = self.end_date
1289
- election_id = election.get("objectId")
1290
- self.reset_instance_vars()
1291
- self.gather_dates(contest)
1292
- contest_id = contest.get("objectId")
1293
- contest_date_status = contest.find("ContestDateStatus")
1294
- if (
1295
- election_end_date is not None
1296
- and self.end_date is not None
1297
- and election_end_date < self.end_date
1298
- # Only compare election end date to contests that are not canceled
1299
- and (
1300
- contest_date_status is None
1301
- or contest_date_status.text.lower() != "canceled"
1302
- )
1303
- ):
1304
- self.error_log.append(
1305
- loggers.LogEntry(
1306
- "Contest {} with end date {} occurs after Election {} with"
1307
- " end date {}. Election end date should be on or after any"
1308
- " Contest end date.".format(
1309
- contest_id,
1310
- self.end_date,
1311
- election_id,
1312
- election_end_date,
1313
- )
1314
- )
1315
- )
1316
- if (
1317
- election_start_date is not None
1318
- and self.start_date is not None
1319
- and self.start_date < election_start_date
1320
- ):
1321
- self.error_log.append(
1322
- loggers.LogEntry(
1323
- "Contest {} with start date {} occurs before Election {} with"
1324
- " start date {}. Election start date should be on or before"
1325
- " any Contest start date.".format(
1326
- contest_id,
1327
- self.start_date,
1328
- election_id,
1329
- election_start_date,
1330
- )
1331
- )
1332
- )
1333
-
1334
- def check(self, election_report_element):
1335
- for election in self.get_elements_by_class(
1336
- election_report_element, "Election"
1337
- ):
1338
- for contest in self.get_elements_by_class(election, "Contest"):
1339
- self._validate_contest_dates_within_election(election, contest)
1340
-
1341
- if self.error_log:
1342
- raise loggers.ElectionError(self.error_log)
1343
-
1344
-
1345
- class ElectionTypesAreCompatible(base.BaseRule):
1346
- """Election element Type values cannot be both a general and primary type."""
1347
-
1348
- def elements(self):
1349
- return ["Election"]
1350
-
1351
- def check(self, element):
1352
- election_types = element.findall("Type")
1353
- if election_types:
1354
- for i in range(len(election_types)):
1355
- election_types[i] = election_types[i].text
1356
- if "general" in election_types and (
1357
- "primary" in election_types
1358
- or "partisan-primary-open" in election_types
1359
- or "partisan-primary-closed" in election_types
1360
- ):
1361
- raise loggers.ElectionError.from_message(
1362
- "Election element has incompatible election-type values.", [element]
1363
- )
1364
-
1365
-
1366
- class ElectionTypesAndCandidateContestTypesAreCompatible(base.BaseRule):
1367
- """Election elements should contain CandidateContests with compatible types.
1368
-
1369
- Elections with the general type should not have any CandidateContests with the
1370
- primary types. Elections with the primary types should not have any
1371
- CandidateContests with the general type.
1372
- """
1373
-
1374
- def _extract_text_from_elements(self, elements):
1375
- return {
1376
- element.text.strip().lower()
1377
- for element in elements
1378
- if rule_util.element_has_text(element)
1379
- }
1380
-
1381
- def elements(self):
1382
- return ["Election"]
1383
-
1384
- def check(self, element):
1385
- errors = []
1386
- contests = self.get_elements_by_class(element, "CandidateContest")
1387
- election_types = self._extract_text_from_elements(element.findall("Type"))
1388
- primary_types = {
1389
- "primary",
1390
- "partisan-primary-open",
1391
- "partisan-primary-closed",
1392
- }
1393
- for contest in contests:
1394
- contest_types = self._extract_text_from_elements(contest.findall("Type"))
1395
- if "general" in election_types and primary_types.intersection(
1396
- contest_types
1397
- ):
1398
- errors.append(
1399
- loggers.LogEntry(
1400
- "Election %s includes CandidateContest %s with incompatible"
1401
- " type(s). General elections cannot include primary contests."
1402
- % (element.get("objectId"), contest.get("objectId")),
1403
- element,
1404
- )
1405
- )
1406
- elif (
1407
- primary_types.intersection(election_types)
1408
- and "general" in contest_types
1409
- ):
1410
- errors.append(
1411
- loggers.LogEntry(
1412
- "Election %s includes CandidateContest %s with incompatible"
1413
- " type(s). Primary elections cannot include general contests."
1414
- % (element.get("objectId"), contest.get("objectId")),
1415
- element,
1416
- )
1417
- )
1418
-
1419
- if errors:
1420
- raise loggers.ElectionError(errors)
1421
-
1422
-
1423
- class DateStatusMatches(base.DateRule):
1424
- """In most cases, ContestDateStatus should match ElectionDateStatus.
1425
-
1426
- If all contests contained in an election have the same status, and this status
1427
- does not match the status on the election, it is probably incorrect - raise
1428
- warning. Differing values among ContestDateStatus in an election are possible
1429
- but uncommon - raise Info level message.
1430
- """
1431
-
1432
- def elements(self):
1433
- return ["Election"]
1434
-
1435
- def check(self, election_elem):
1436
- election_date_status = "confirmed" # default value
1437
- election_status_elem = election_elem.find("ElectionDateStatus")
1438
-
1439
- if rule_util.element_has_text(election_status_elem):
1440
- election_date_status = election_status_elem.text.strip()
1441
-
1442
- contest_statuses = set()
1443
- for contest_elem in self.get_elements_by_class(election_elem, "Contest"):
1444
- contest_status_elem = contest_elem.find("ContestDateStatus")
1445
- if rule_util.element_has_text(contest_status_elem):
1446
- contest_statuses.add(contest_status_elem.text.strip())
1447
- else:
1448
- contest_statuses.add("confirmed")
1449
-
1450
- if len(contest_statuses) == 1:
1451
- contest_status = contest_statuses.pop()
1452
- if contest_status != election_date_status:
1453
- msg = (
1454
- "All contests on election {} have a date status of {}, but the "
1455
- "election has a date status of {}.".format(
1456
- election_elem.get("objectId"),
1457
- contest_status,
1458
- election_date_status,
1459
- )
1460
- )
1461
- raise loggers.ElectionWarning.from_message(msg, [election_elem])
1462
- elif len(contest_statuses) > 1:
1463
- msg = (
1464
- "There are multiple date statuses present for the contests on "
1465
- "election {}. This may be correct, but is an unusal case. Please "
1466
- "confirm.".format(election_elem.get("objectId"))
1467
- )
1468
- raise loggers.ElectionInfo.from_message(msg, [election_elem])
1469
-
1470
-
1471
- class OfficeSelectionMethodMatch(base.BaseRule):
1472
- """Office and OfficeHolderTenure need to have matching selection methods.
1473
-
1474
- Ensure that the OfficeSelectionMethod of a given OfficeHolderTenure is
1475
- also
1476
- present in the list of SelectionMethods of the Office it points to.
1477
- """
1478
-
1479
- def __init__(self, election_tree, schema_tree, **kwargs):
1480
- self.office_selection_methods = {}
1481
- officeholder_tenure_elements = self.get_elements_by_class(
1482
- election_tree, "OfficeHolderTenure"
1483
- )
1484
- office_elements = self.get_elements_by_class(election_tree, "Office")
1485
- if officeholder_tenure_elements:
1486
- for element in office_elements:
1487
- office_id = element.get("objectId")
1488
- selection_methods = {
1489
- selection_method.text
1490
- for selection_method in element.findall("SelectionMethod")
1491
- }
1492
- self.office_selection_methods[office_id] = selection_methods
1493
-
1494
- def elements(self):
1495
- return ["OfficeHolderTenure"]
1496
-
1497
- def check(self, element):
1498
- office_id = element.find("OfficeId").text
1499
- office_selection_method = element.find("OfficeSelectionMethod").text
1500
- if (
1501
- office_id not in self.office_selection_methods
1502
- or office_selection_method
1503
- not in self.office_selection_methods[office_id]
1504
- ):
1505
- raise loggers.ElectionError.from_message(
1506
- "OfficeSelectionMethod does not have a matching SelectionMethod"
1507
- " in the corresponding Office element.",
1508
- [element],
1509
- )
1510
-
1511
-
1512
- class OfficeHolderTenureTermDates(base.DateRule):
1513
- """OfficeHolderTenure elements should contain valid term dates."""
1514
-
1515
- def elements(self):
1516
- return ["OfficeHolderTenure"]
1517
-
1518
- def check(self, element):
1519
- start_date = element.find("StartDate")
1520
- end_date = element.find("EndDate")
1521
- if rule_util.element_has_text(start_date) and rule_util.element_has_text(
1522
- end_date
1523
- ):
1524
- start_date_obj = base.PartialDate.init_partial_date(start_date.text)
1525
- end_date_obj = base.PartialDate.init_partial_date(end_date.text)
1526
- if end_date_obj < start_date_obj:
1527
- raise loggers.ElectionError.from_message(
1528
- "OfficeHolderTenure element has an EndDate that is before the"
1529
- " StartDate.",
1530
- [element],
1531
- )
1532
-
1533
-
1534
- class OfficeTermDates(base.DateRule):
1535
- """Office elements should contain valid term dates.
1536
-
1537
- Offices with OfficeHolderPersonIds should have a Term declared. Given
1538
- term should have a start date. If term also has an end date then end date
1539
- should come after start date. Post Office split feed office objects should
1540
- not have a Term element.
1541
- """
1542
-
1543
- def __init__(self, election_tree, schema_tree, **kwargs):
1544
- self.is_post_office_split_feed = False
1545
- officeholder_tenure_collection_element = self.get_elements_by_class(
1546
- election_tree, "OfficeHolderTenureCollection"
1547
- )
1548
- if officeholder_tenure_collection_element:
1549
- self.is_post_office_split_feed = True
1550
-
1551
- def elements(self):
1552
- return ["Office"]
1553
-
1554
- def check(self, element):
1555
- self.reset_instance_vars()
1556
- if self.is_post_office_split_feed:
1557
- term = element.find("Term")
1558
- if term is not None:
1559
- raise loggers.ElectionError.from_message(
1560
- "Office should not contain Term data in post Office split feed.",
1561
- [element],
1562
- )
1563
- if self.error_log:
1564
- raise loggers.ElectionError(self.error_log)
1565
- else:
1566
- off_per_id = element.find("OfficeHolderPersonIds")
1567
- if rule_util.element_has_text(off_per_id):
1568
- term = element.find("Term")
1569
- if term is None:
1570
- raise loggers.ElectionWarning.from_message(
1571
- "The Office is missing a Term.", [element]
1572
- )
1573
-
1574
- self.gather_dates(term)
1575
- if self.start_date is None:
1576
- raise loggers.ElectionWarning.from_message(
1577
- "The Office is missing a Term > StartDate.", [element]
1578
- )
1579
- elif self.end_date is not None:
1580
- self.check_end_after_start()
1581
-
1582
- if self.error_log:
1583
- raise loggers.ElectionError(self.error_log)
1584
-
1585
-
1586
- class RemovePersonAndOfficeHolderId60DaysAfterEndDate(base.TreeRule):
1587
- """Office elements should contain valid term dates.
1588
-
1589
- Check if 60 days after the specified office term EndDate,
1590
- the associated Person and OfficeholderId may be removed from the feed.
1591
- However, if the Person is elected to another office,
1592
- they will be kept in the feed with the same stable ID.
1593
- """
1594
-
1595
- def check(self):
1596
- info_log = []
1597
- persons = self.get_elements_by_class(self.election_tree, "Person")
1598
- offices = self.get_elements_by_class(self.election_tree, "Office")
1599
- officeholder_tenure_collection = self.get_elements_by_class(
1600
- self.election_tree, "OfficeHolderTenureCollection"
1601
- )
1602
- is_post_office_split_feed = bool(officeholder_tenure_collection)
1603
- person_office_dict = dict()
1604
- outdated_offices = []
1605
- outdated_officeholder_tenures = []
1606
- outdated_officetenure_persons = dict()
1607
- if is_post_office_split_feed:
1608
- officeholder_tenures = self.get_elements_by_class(
1609
- self.election_tree, "OfficeHolderTenure"
1610
- )
1611
- for officeholder_tenure in officeholder_tenures:
1612
- office_holder_person_elem = officeholder_tenure.find(
1613
- "OfficeHolderPersonId"
1614
- )
1615
- person_id = office_holder_person_elem.text
1616
- date_validator = base.DateRule(None, None)
1617
- date_validator.gather_dates(officeholder_tenure)
1618
- end_date = date_validator.end_date
1619
- if end_date is not None:
1620
- sixty_days_earlier = datetime.datetime.now() + datetime.timedelta(
1621
- days=-60
1622
- )
1623
- partial_date_sixty_days = base.PartialDate(
1624
- sixty_days_earlier.year,
1625
- sixty_days_earlier.month,
1626
- sixty_days_earlier.day,
1627
- )
1628
- if end_date < partial_date_sixty_days:
1629
- outdated_officeholder_tenures.append(officeholder_tenure)
1630
- if person_id in outdated_officetenure_persons.keys():
1631
- outdated_officetenure_persons[person_id].append(
1632
- (office_holder_person_elem, end_date)
1633
- )
1634
- else:
1635
- outdated_officetenure_persons[person_id] = [
1636
- (office_holder_person_elem, end_date)
1637
- ]
1638
- for outdated_officeholder_tenure in outdated_officeholder_tenures:
1639
- info_message = (
1640
- "The officeholder tenure end date is more than 60 days"
1641
- " in the past; this OfficeHolderTenure element can be removed"
1642
- " from the feed."
1643
- )
1644
- info_log.append(
1645
- loggers.LogEntry(info_message, [outdated_officeholder_tenure])
1646
- )
1647
- for person_id, value_list in outdated_officetenure_persons.items():
1648
- has_recent_tenure = False
1649
- office_holder_person_elem = None
1650
- for value in value_list:
1651
- office_holder_person_elem = value[0]
1652
- end_date = value[1]
1653
- sixty_days_earlier = datetime.datetime.now() + datetime.timedelta(
1654
- days=-60
1655
- )
1656
- partial_date_sixty_days = base.PartialDate(
1657
- sixty_days_earlier.year,
1658
- sixty_days_earlier.month,
1659
- sixty_days_earlier.day,
1660
- )
1661
- if end_date > partial_date_sixty_days:
1662
- has_recent_tenure = True
1663
- if not has_recent_tenure and office_holder_person_elem is not None:
1664
- info_message = (
1665
- "All officeholder tenures ended more than 60 days ago. "
1666
- "Therefore, you can remove the person and the "
1667
- "related officeholder tenures from the feed."
1668
- )
1669
- info_log.append(
1670
- loggers.LogEntry(info_message, [office_holder_person_elem])
1671
- )
1672
- else:
1673
- for office in offices:
1674
- person_id = office.find("OfficeHolderPersonIds").text
1675
- if person_id in person_office_dict:
1676
- person_office_dict[person_id].append(office.get("objectId"))
1677
- else:
1678
- person_office_dict[person_id] = [office.get("objectId")]
1679
- term = office.find(".//Term")
1680
- if term is not None:
1681
- date_validator = base.DateRule(None, None)
1682
- date_validator.gather_dates(term)
1683
- end_date_person = date_validator.end_date
1684
- if end_date_person is not None:
1685
- sixty_days_earlier = datetime.datetime.now() + datetime.timedelta(
1686
- days=-60
1687
- )
1688
- partial_date_sixty_days = base.PartialDate(
1689
- sixty_days_earlier.year,
1690
- sixty_days_earlier.month,
1691
- sixty_days_earlier.day,
1692
- )
1693
- if end_date_person < partial_date_sixty_days:
1694
- outdated_offices.append(office.get("objectId"))
1695
- for person in persons:
1696
- pid = person.get("objectId")
1697
- if person_office_dict.get(pid) is not None:
1698
- check_person_outdated = all(
1699
- item in outdated_offices for item in person_office_dict.get(pid)
1700
- )
1701
- if check_person_outdated:
1702
- info_message = (
1703
- "The officeholder mandates ended more than 60 days ago. "
1704
- "Therefore, you can remove the person and the related offices "
1705
- "from the feed."
1706
- )
1707
- info_log.append(loggers.LogEntry(info_message, [person]))
1708
- if info_log:
1709
- raise loggers.ElectionInfo(info_log)
1710
-
1711
-
1712
- class UniqueStartDatesForOfficeRoleAndJurisdiction(base.BaseRule):
1713
- """Office StartDates should be unique within a certain group.
1714
-
1715
- Office StartDates should be unique amongst a group of Office entries
1716
- with the same jurisdiction-id and office-role.
1717
- """
1718
-
1719
- def elements(self):
1720
- return ["OfficeCollection"]
1721
-
1722
- def _filter_out_past_end_dates(self, offices):
1723
- valid_offices = []
1724
- for office in offices:
1725
- term = office.find(".//Term")
1726
- if term is not None:
1727
- date_validator = base.DateRule(None, None, ocd_id_validator=None)
1728
- try:
1729
- date_validator.gather_dates(term)
1730
- if date_validator.end_date is not None:
1731
- date_validator.check_for_date_not_in_past(
1732
- date_validator.end_date, date_validator.end_elem
1733
- )
1734
- if not date_validator.error_log:
1735
- valid_offices.append(office)
1736
- except loggers.ElectionError:
1737
- continue
1738
- return valid_offices
1739
-
1740
- def _count_start_dates_by_jurisdiction_role(self, element):
1741
- offices = element.findall("Office")
1742
- offices = self._filter_out_past_end_dates(offices)
1743
- jurisdiction_role_mapping = {}
1744
- for office in offices:
1745
- office_role = ""
1746
- jurisdiction_id = ""
1747
- start_date = ""
1748
-
1749
- start_date_elem = office.find(".//Term//StartDate")
1750
- if not rule_util.element_has_text(start_date_elem):
1751
- continue
1752
- start_date = start_date_elem.text
1753
-
1754
- office_roles = rule_util.get_entity_info_for_value_type(
1755
- office, "office-role"
1756
- )
1757
- if office_roles:
1758
- office_role = office_roles[0]
1759
-
1760
- jurisdiction_ids = rule_util.get_entity_info_for_value_type(
1761
- office, "jurisdiction-id"
1762
- )
1763
- if jurisdiction_ids:
1764
- jurisdiction_id = jurisdiction_ids[0]
1765
-
1766
- office_hash = hashlib.sha256(
1767
- (office_role + jurisdiction_id).encode("utf-8")
1768
- ).hexdigest()
1769
- if office_hash not in jurisdiction_role_mapping.keys():
1770
- jurisdiction_role_mapping[office_hash] = dict({
1771
- "jurisdiction_id": jurisdiction_id,
1772
- "office_role": office_role,
1773
- "start_dates": dict({}),
1774
- })
1775
-
1776
- office_date_info = jurisdiction_role_mapping[office_hash]
1777
- if start_date not in office_date_info["start_dates"].keys():
1778
- office_date_info["start_dates"][start_date] = set()
1779
-
1780
- office_date_info["start_dates"][start_date].add(office)
1781
-
1782
- return jurisdiction_role_mapping
1783
-
1784
- def check(self, element):
1785
- warning_log = []
1786
-
1787
- start_counts = self._count_start_dates_by_jurisdiction_role(element)
1788
- for start_info in start_counts.values():
1789
- start_date_map = start_info["start_dates"]
1790
- if len(start_date_map.keys()) == 1:
1791
- start_date = list(start_date_map.keys())[0]
1792
- # this accounts for offices with only one entry (i.e. US Pres)
1793
- if len(start_date_map[start_date]) > 1:
1794
- warning_log.append(
1795
- loggers.LogEntry(
1796
- (
1797
- "Only one unique StartDate found for each"
1798
- " jurisdiction-id: {} and office-role: {}. {} appears {}"
1799
- " times."
1800
- ).format(
1801
- start_info["jurisdiction_id"],
1802
- start_info["office_role"],
1803
- start_date,
1804
- len(start_date_map[start_date]),
1805
- ),
1806
- start_date_map[start_date],
1807
- )
1808
- )
1809
-
1810
- if warning_log:
1811
- raise loggers.ElectionWarning(warning_log)
1812
-
1813
-
1814
- class ValidateInfoUriAnnotation(base.BaseRule):
1815
- """InfoUri is an annotated Uri that accepts the following annotations.
1816
-
1817
- wikipedia, ballotpedia, official-website, fulltext.
1818
- Adding a check for this.
1819
- """
1820
-
1821
- info_array = [
1822
- "wikipedia",
1823
- "ballotpedia",
1824
- "official-website",
1825
- "fulltext",
1826
- "logo-uri",
1827
- ]
1828
-
1829
- def elements(self):
1830
- return ["InfoUri"]
1831
-
1832
- def check(self, element):
1833
- error_log = []
1834
- annotation = element.attrib["Annotation"]
1835
- if annotation not in self.info_array:
1836
- error_log.append(
1837
- loggers.LogEntry(annotation + " is an invalid annotation.", [element])
1838
- )
1839
- if error_log:
1840
- raise loggers.ElectionError(error_log)
1841
-
1842
-
1843
- class FullTextMaxLength(base.BaseRule):
1844
- """FullText field should not be longer than MAX_LENGTH."""
1845
-
1846
- MAX_LENGTH = 30000 # about 8-10 pages of text, 4500-5000 words
1847
-
1848
- def elements(self):
1849
- return ["FullText"]
1850
-
1851
- def check(self, element):
1852
- intl_text_list = element.findall("Text")
1853
- for intl_text in intl_text_list:
1854
- if len(intl_text.text) > self.MAX_LENGTH:
1855
- msg = (
1856
- "FullText is longer than %s characters. Please remove and "
1857
- "include a link to the full text via InfoUri with Annotation "
1858
- "'fulltext'." % (self.MAX_LENGTH)
1859
- )
1860
- raise loggers.ElectionWarning.from_message(msg, [element])
1861
-
1862
-
1863
- class FullTextOrBallotText(base.BaseRule):
1864
- """Warn if BallotText is missing and FullText is short."""
1865
-
1866
- SUGGESTION_CUTOFF_LENGTH = 2500 # about 3 paragraphs, 250-300 words
1867
-
1868
- def elements(self):
1869
- return ["BallotMeasureContest"]
1870
-
1871
- def check(self, element):
1872
- full_text_map = rule_util.get_language_to_text_map(element.find("FullText"))
1873
- if not full_text_map:
1874
- return
1875
-
1876
- ballot_text_map = rule_util.get_language_to_text_map(
1877
- element.find("BallotText")
1878
- )
1879
- for language, full_text_strings in full_text_map.items():
1880
- full_text_string = full_text_strings[0]
1881
- if (
1882
- language not in ballot_text_map.keys()
1883
- and len(full_text_string) < self.SUGGESTION_CUTOFF_LENGTH
1884
- ):
1885
- msg = (
1886
- "Language: %s. BallotText is missing but FullText is present "
1887
- "for the same language. Please confirm that FullText contains "
1888
- "only supplementary text and not text on the ballot itself."
1889
- % (language)
1890
- )
1891
- raise loggers.ElectionWarning.from_message(msg, [element])
1892
-
1893
-
1894
- class BallotTitle(base.BaseRule):
1895
- """BallotTitle must exist and should usually be shorter than BallotText."""
1896
-
1897
- def elements(self):
1898
- return ["BallotMeasureContest"]
1899
-
1900
- def check(self, element):
1901
- ballot_title_map = rule_util.get_language_to_text_map(
1902
- element.find("BallotTitle")
1903
- )
1904
- if not ballot_title_map:
1905
- raise loggers.ElectionError.from_message(
1906
- "BallotMeasureContest is missing BallotTitle.", [element]
1907
- )
1908
-
1909
- ballot_text_map = rule_util.get_language_to_text_map(
1910
- element.find("BallotText")
1911
- )
1912
- if not ballot_text_map:
1913
- msg = (
1914
- "BallotText is missing. Please confirm that the ballot "
1915
- "text/question is not in BallotTitle."
1916
- )
1917
- raise loggers.ElectionWarning.from_message(msg, [element])
1918
-
1919
- for language, ballot_title_strings in ballot_title_map.items():
1920
- ballot_title_string = ballot_title_strings[0]
1921
- if language not in ballot_text_map.keys() or len(
1922
- ballot_text_map[language][0]
1923
- ) < len(ballot_title_string):
1924
- msg = (
1925
- "Language: %s. BallotText is missing or shorter than "
1926
- " Please confirm that the ballot text/question is not "
1927
- "in BallotTitle." % (language)
1928
- )
1929
- raise loggers.ElectionWarning.from_message(msg, [element])
1930
-
1931
-
1932
- class ImproperCandidateContest(base.TreeRule):
1933
- """Detect CandidateContest elements that should be a BallotMeasureContest."""
1934
-
1935
- _BALLOT_SELECTION_OPTIONS = frozenset({"yes", "no", "for", "against"})
1936
-
1937
- def _gather_contest_candidates(self, contest):
1938
- """Return candidate ids for given contest element."""
1939
- candidate_ids = []
1940
- cand_id_elems = contest.findall("BallotSelection//CandidateIds")
1941
- for cand_id_elem in cand_id_elems:
1942
- for cand_id in cand_id_elem.text.split():
1943
- candidate_ids.append(cand_id)
1944
- return candidate_ids
1945
-
1946
- def _gather_invalid_candidates(self):
1947
- """Return candidate ids that appear to be BallotMeasureSelections."""
1948
- invalid_candidates = []
1949
- candidates = self.get_elements_by_class(
1950
- self.election_tree, "CandidateCollection//Candidate"
1951
- )
1952
- for candidate in candidates:
1953
- ballot_name = candidate.find(".//BallotName/Text[@language='en']")
1954
- if ballot_name is not None:
1955
- if ballot_name.text.lower() in self._BALLOT_SELECTION_OPTIONS:
1956
- invalid_candidates.append(candidate.get("objectId"))
1957
- return invalid_candidates
1958
-
1959
- def check(self):
1960
- candidate_contest_mapping = {}
1961
- candidate_contests = self.get_elements_by_class(
1962
- self.election_tree, "CandidateContest"
1963
- )
1964
- for cc in candidate_contests:
1965
- cand_ids = self._gather_contest_candidates(cc)
1966
- contest_id = cc.get("objectId")
1967
- candidate_contest_mapping[contest_id] = cand_ids
1968
-
1969
- invalid_candidates = self._gather_invalid_candidates()
1970
-
1971
- warning_log = []
1972
- for contest_id, cand_ids in candidate_contest_mapping.items():
1973
- flagged_candidates = []
1974
- for cand_id in cand_ids:
1975
- if cand_id in invalid_candidates:
1976
- flagged_candidates.append(cand_id)
1977
- if flagged_candidates:
1978
- warning_message = (
1979
- "Candidates {} should be BallotMeasureSelection "
1980
- "elements. Similarly, Contest {} should be changed "
1981
- "to a BallotMeasureContest instead of a "
1982
- "CandidateContest."
1983
- ).format(", ".join(flagged_candidates), contest_id)
1984
- warning_log.append(loggers.LogEntry(warning_message))
1985
- if invalid_candidates:
1986
- warning_message = (
1987
- "There are CandidateContests that appear to be "
1988
- "BallotMeasureContests based on the "
1989
- "BallotName values."
1990
- )
1991
- raise loggers.ElectionWarning(warning_log)
1992
-
1993
-
1994
- class WinnerCountLimit(base.BaseRule):
1995
- """Number of winners must be less than or equal to NumberElected."""
1996
-
1997
- def setup(self):
1998
- self.candidate_post_election_status_by_object_id = (
1999
- self._get_candidate_post_election_status_by_object_id()
2000
- )
2001
-
2002
- def _get_candidate_post_election_status_by_object_id(self):
2003
- candidate_post_election_status_by_object_id = {}
2004
- candidates = self.get_elements_by_class(
2005
- self.election_tree, "CandidateCollection//Candidate"
2006
- )
2007
- for candidate in candidates:
2008
- object_id = candidate.get("objectId")
2009
- post_election_status = candidate.find("PostElectionStatus")
2010
- if object_id and rule_util.element_has_text(post_election_status):
2011
- candidate_post_election_status_by_object_id[object_id] = (
2012
- post_election_status.text.strip()
2013
- )
2014
- return candidate_post_election_status_by_object_id
2015
-
2016
- def elements(self):
2017
- return ["CandidateContest"]
2018
-
2019
- def check(self, element):
2020
- number_elected_element = element.find("NumberElected")
2021
- number_elected = (
2022
- int(number_elected_element.text)
2023
- if rule_util.element_has_text(number_elected_element)
2024
- else 1
2025
- )
2026
-
2027
- candidate_ids_elements = element.findall("BallotSelection//CandidateIds")
2028
- candidate_ids = set()
2029
- for candidate_ids_element in candidate_ids_elements:
2030
- if rule_util.element_has_text(candidate_ids_element):
2031
- candidate_ids.update(candidate_ids_element.text.split())
2032
-
2033
- winner_count = 0
2034
- for candidate_id in candidate_ids:
2035
- status = self.candidate_post_election_status_by_object_id.get(
2036
- candidate_id
2037
- )
2038
- if status in _WINNER_POST_ELECTION_STATUSES:
2039
- winner_count += 1
2040
-
2041
- if winner_count > number_elected:
2042
- raise loggers.ElectionError.from_message(
2043
- f"Contest {element.get('objectId')} has {winner_count} candidates"
2044
- " with PostElectionStatus of 'winner' or 'projected-winner',"
2045
- f" which exceeds NumberElected: {number_elected}.",
2046
- [element],
2047
- )
2048
-
2049
-
2050
- class SubsequentContestIdIsValidRelatedContest(base.DateRule):
2051
- """Check that SubsequentContests are valid.
2052
-
2053
- Conditions for a valid SubsequentContest:
2054
- - OfficeId, if present, must match the original contest.
2055
- - PrimaryPartyIds, if present, must match the original contest.
2056
- - EndDate, if present, must not be after EndDate of the original contest.
2057
- - ComposingContestIds must not contain the original contest.
2058
- """
2059
-
2060
- def elements(self):
2061
- return ["ElectionReport"]
2062
-
2063
- def check(self, election_report_element):
2064
- error_log = []
2065
- contest_by_id = {}
2066
- contest_end_date_by_id = {}
2067
-
2068
- for election in self.get_elements_by_class(
2069
- election_report_element, "Election"
2070
- ):
2071
- self.gather_dates(election)
2072
- election_end_date = self.end_date
2073
- for contest in self.get_elements_by_class(election, "Contest"):
2074
- self.reset_instance_vars()
2075
- self.gather_dates(contest)
2076
- contest_by_id[contest.get("objectId")] = contest
2077
- contest_end_date_by_id[contest.get("objectId")] = (
2078
- self.end_date or election_end_date
2079
- )
2080
-
2081
- for contest_id, contest in contest_by_id.items():
2082
- element = contest.find("SubsequentContestId")
2083
- if not rule_util.element_has_text(element):
2084
- continue
2085
- subsequent_contest_id = element.text.strip()
2086
-
2087
- # Check that subsequent contest exists
2088
- if subsequent_contest_id not in contest_by_id:
2089
- error_log.append(
2090
- loggers.LogEntry(
2091
- "Could not find SubsequentContest"
2092
- f" {subsequent_contest_id} referenced by Contest {contest_id}."
2093
- )
2094
- )
2095
- continue
2096
-
2097
- subsequent_contest = contest_by_id[subsequent_contest_id]
2098
- # Check that the subsequent contest has a later end date
2099
- if subsequent_contest is not None and contest is not None:
2100
- contest_end_date = contest_end_date_by_id[contest_id]
2101
- subsequent_contest_end_date = contest_end_date_by_id[
2102
- subsequent_contest_id
2103
- ]
2104
- if subsequent_contest_end_date < contest_end_date:
2105
- error_log.append(
2106
- loggers.LogEntry(
2107
- f"Contest {contest_id} references a subsequent contest with"
2108
- " an earlier end date.",
2109
- [contest],
2110
- [contest.sourceline],
2111
- )
2112
- )
2113
-
2114
- # Check that office ids match
2115
- contest_office_id = None
2116
- subsequent_contest_office_id = None
2117
- element = contest.find("OfficeIds")
2118
- if rule_util.element_has_text(element):
2119
- contest_office_id = element.text
2120
- element = subsequent_contest.find("OfficeIds")
2121
- if rule_util.element_has_text(element):
2122
- subsequent_contest_office_id = element.text
2123
-
2124
- if contest_office_id != subsequent_contest_office_id:
2125
- error_log.append(
2126
- loggers.LogEntry(
2127
- f"Contest {contest_id} references a subsequent contest with a"
2128
- " different office id.",
2129
- [contest],
2130
- [contest.sourceline],
2131
- )
2132
- )
2133
-
2134
- # Check that primary party ids match or that the subsequent contest does
2135
- # not have a primary party (e.g. primary -> general election)
2136
- contest_primary_party_ids = None
2137
- subsequent_contest_primary_party_ids = None
2138
- element = contest.find("PrimaryPartyIds")
2139
- if rule_util.element_has_text(element):
2140
- contest_primary_party_ids = set(element.text.split())
2141
- element = subsequent_contest.find("PrimaryPartyIds")
2142
- if rule_util.element_has_text(element):
2143
- subsequent_contest_primary_party_ids = set(element.text.split())
2144
-
2145
- if (
2146
- subsequent_contest_primary_party_ids is not None
2147
- and contest_primary_party_ids != subsequent_contest_primary_party_ids
2148
- ):
2149
- error_log.append(
2150
- loggers.LogEntry(
2151
- "Contest %s references a subsequent contest with different "
2152
- "primary party ids." % contest_id,
2153
- [contest],
2154
- [contest.sourceline],
2155
- )
2156
- )
2157
-
2158
- # Check that there is not a subsequent contest <-> composing contest loop
2159
- element = subsequent_contest.find("ComposingContestIds")
2160
- if rule_util.element_has_text(element):
2161
- subsequent_composing_ids = element.text.split()
2162
- if contest_id in subsequent_composing_ids:
2163
- error_log.append(
2164
- loggers.LogEntry(
2165
- f"Contest {contest_id} is listed as a composing contest for"
2166
- " its subsequent contest. Two contests can be linked by"
2167
- " SubsequentContestId or ComposingContestId, but not both.",
2168
- [contest],
2169
- [contest.sourceline],
2170
- )
2171
- )
2172
-
2173
- if error_log:
2174
- raise loggers.ElectionError(error_log)
2175
-
2176
-
2177
- class ComposingContestIdsAreValidRelatedContests(base.BaseRule):
2178
- """Check that ComposingContestIds are valid.
2179
-
2180
- Conditions for a valid ComposingContest:
2181
- - OfficeId, if present, must match the parent contest.
2182
- - PrimaryPartyIds, if present, must match the parent contest.
2183
- - ComposingContests must not be referenced by more than one parent contest.
2184
- - ComposingContests must not reference each other.
2185
- """
2186
-
2187
- def elements(self):
2188
- return ["ElectionReport"]
2189
-
2190
- def check(self, election_report_element):
2191
- error_log = []
2192
-
2193
- contests = self.get_elements_by_class(election_report_element, "Contest")
2194
- contest_ids = {cc.get("objectId"): cc for cc in contests}
2195
- composing_contests = {}
2196
- for contest_id, contest in contest_ids.items():
2197
- element = contest.find("ComposingContestIds")
2198
- if not rule_util.element_has_text(element):
2199
- continue
2200
- composing_contests[contest_id] = element.text.split()
2201
-
2202
- # Check for composing contests that appear more than once
2203
- unique_contests = set()
2204
- for contest_list in composing_contests.values():
2205
- for contest_id in contest_list:
2206
- if contest_id not in unique_contests:
2207
- unique_contests.add(contest_id)
2208
- else:
2209
- error_log.append(
2210
- loggers.LogEntry(
2211
- "Contest %s is listed as a ComposingContest for more "
2212
- "than one parent contest. ComposingContests should be a "
2213
- "strict hierarchy." % contest_id
2214
- )
2215
- )
2216
-
2217
- for contest_id, composing_contest_ids in composing_contests.items():
2218
- contest = contest_ids[contest_id]
2219
- for cc_id in composing_contest_ids:
2220
- # Check that the composing contests exist
2221
- if cc_id not in contest_ids.keys():
2222
- error_log.append(
2223
- loggers.LogEntry(
2224
- "Could not find ComposingContest % referenced by Contest %s."
2225
- % (contest_id, cc_id)
2226
- )
2227
- )
2228
- continue
2229
-
2230
- composing_contest = contest_ids[cc_id]
2231
- # Check that the office ids match
2232
- c_office_id = None
2233
- cc_office_id = None
2234
- element = contest.find("OfficeIds")
2235
- if rule_util.element_has_text(element):
2236
- c_office_id = element.text
2237
- element = composing_contest.find("OfficeIds")
2238
- if rule_util.element_has_text(element):
2239
- cc_office_id = element.text
2240
-
2241
- if c_office_id != cc_office_id:
2242
- error_log.append(
2243
- loggers.LogEntry(
2244
- "Contest %s and composing contest %s have different office "
2245
- "ids." % (contest_id, cc_id)
2246
- )
2247
- )
2248
-
2249
- # Check that primary party ids match
2250
- c_primary_party_ids = None
2251
- cc_primary_party_ids = None
2252
- element = contest.find("PrimaryPartyIds")
2253
- if rule_util.element_has_text(element):
2254
- c_primary_party_ids = set(element.text.split())
2255
- element = composing_contest.find("PrimaryPartyIds")
2256
- if rule_util.element_has_text(element):
2257
- cc_primary_party_ids = set(element.text.split())
2258
-
2259
- if c_primary_party_ids != cc_primary_party_ids:
2260
- error_log.append(
2261
- loggers.LogEntry(
2262
- "Contest %s and composing contest %s have different primary "
2263
- "party ids." % (contest_id, cc_id)
2264
- )
2265
- )
2266
-
2267
- # Check that composing contests don't reference each other
2268
- if (
2269
- cc_id in composing_contests
2270
- and contest_id in composing_contests[cc_id]
2271
- ):
2272
- error_log.append(
2273
- loggers.LogEntry(
2274
- "Contest %s and contest %s reference each other as composing "
2275
- "contests." % (contest_id, cc_id)
2276
- )
2277
- )
2278
-
2279
- if error_log:
2280
- raise loggers.ElectionError(error_log)
2281
-
2282
-
2283
- class MultipleInternationalizedTextWithSameLanguageCode(base.BaseRule):
2284
- """Checks for multiple InternationalizedText with the same language code."""
2285
-
2286
- def elements(self):
2287
- return _INTERNATIONALIZED_TEXT_ELEMENTS_WITH_ONLY_ONE_TEXT_PER_LANGUAGE
2288
-
2289
- def check(self, element):
2290
- language_map = rule_util.get_language_to_text_map(element)
2291
-
2292
- for language, texts in language_map.items():
2293
- if len(texts) > 1:
2294
- raise loggers.ElectionError.from_message(
2295
- 'Multiple "%s" texts found for "%s"' % (language, texts[0].strip())
2296
- )
2297
-
2298
-
2299
- class ContestContainsValidStartDate(base.DateRule):
2300
- """Contest elements should contain valid start dates.
2301
-
2302
- A warning will be raised for start dates in the past. These dates are still
2303
- valid because the validator could be run during an ongoing election.
2304
- """
2305
-
2306
- def elements(self):
2307
- return ["Contest"]
2308
-
2309
- def check(self, element):
2310
- self.reset_instance_vars()
2311
- self.gather_dates(element)
2312
-
2313
- if self.start_date:
2314
- self.check_for_date_not_in_past(self.start_date, self.start_elem)
2315
-
2316
- if self.error_log:
2317
- raise loggers.ElectionWarning(self.error_log)
2318
-
2319
-
2320
- class ContestContainsValidEndDate(base.DateRule):
2321
- """Contest elements should contain valid end dates.
2322
-
2323
- A warning will be raised for end dates in the past. These dates are still
2324
- valid because the validator could be run during an ongoing election.
2325
- """
2326
-
2327
- def elements(self):
2328
- return ["Contest"]
2329
-
2330
- def check(self, element):
2331
- self.reset_instance_vars()
2332
- self.gather_dates(element)
2333
-
2334
- if self.end_date:
2335
- self.check_for_date_not_in_past(self.end_date, self.end_elem)
2336
-
2337
- if self.error_log:
2338
- raise loggers.ElectionWarning(self.error_log)
2339
-
2340
-
2341
- class ContestEndDateOccursAfterStartDate(base.DateRule):
2342
- """Contest elements should have end dates that occur after the start dates."""
2343
-
2344
- def elements(self):
2345
- return ["Contest"]
2346
-
2347
- def check(self, element):
2348
- self.reset_instance_vars()
2349
- self.gather_dates(element)
2350
-
2351
- if self.end_date and self.start_date:
2352
- self.check_end_after_start()
2353
- if self.error_log:
2354
- raise loggers.ElectionError(self.error_log)
2355
-
2356
-
2357
- class ContestEndDateOccursBeforeSubsequentContestStartDate(base.DateRule):
2358
- """Contest end dates should occur before subsequent contest start dates.
2359
-
2360
- This rule will trigger if a Contest has a valid Subsequent Contest and both
2361
- Contests have dates.
2362
- """
2363
-
2364
- def elements(self):
2365
- return ["ElectionReport"]
2366
-
2367
- def check(self, election_report_element):
2368
- contest_by_contest_id = {}
2369
- dates_by_contest_id = {}
2370
-
2371
- for election in self.get_elements_by_class(
2372
- election_report_element, "Election"
2373
- ):
2374
- for contest in self.get_elements_by_class(election, "Contest"):
2375
- contest_id = contest.get("objectId")
2376
- self.reset_instance_vars()
2377
- self.gather_dates(contest)
2378
- contest_by_contest_id[contest_id] = contest
2379
- dates_by_contest_id[contest_id] = (self.start_date, self.end_date)
2380
-
2381
- for contest_id, contest in contest_by_contest_id.items():
2382
- # ignore contests that don't have a subsequent contest
2383
- subsequent_element = contest.find("SubsequentContestId")
2384
- if not rule_util.element_has_text(subsequent_element):
2385
- continue
2386
- # ignore invalid subsequent contest ids
2387
- subsequent_contest_id = subsequent_element.text.strip()
2388
- if subsequent_contest_id not in contest_by_contest_id:
2389
- continue
2390
- # compare contest end date with subsequent contest start date
2391
- _, contest_end = dates_by_contest_id[contest_id]
2392
- subsequent_contest_start, _ = dates_by_contest_id[subsequent_contest_id]
2393
- if contest_end is not None and subsequent_contest_start is not None:
2394
- if subsequent_contest_start < contest_end:
2395
- self.error_log.append(
2396
- loggers.LogEntry(
2397
- "Contest {} with end date {} does not occur before"
2398
- " subsequent contest {} with start date {}".format(
2399
- contest_id,
2400
- contest_end,
2401
- subsequent_contest_id,
2402
- subsequent_contest_start,
2403
- )
2404
- )
2405
- )
2406
-
2407
- if self.error_log:
2408
- raise loggers.ElectionError(self.error_log)
2409
-
2410
-
2411
- class ContestStartDateContainsCorrespondingEndDate(base.DateRule):
2412
- """Contest start dates must always have corresponding end dates.
2413
-
2414
- A Contest can either have both StartDate and EndDate populated or neither at
2415
- all.
2416
- """
2417
-
2418
- def elements(self):
2419
- return ["Contest"]
2420
-
2421
- def check(self, element):
2422
- self.reset_instance_vars()
2423
- self.gather_dates(element)
2424
-
2425
- if self.start_elem is None and self.end_elem is not None:
2426
- raise loggers.ElectionError.from_message(
2427
- "Contest has an EndDate but is missing a StartDate. Every EndDate"
2428
- " must have a corresponding StartDate.",
2429
- [element],
2430
- )
2431
-
2432
- if self.start_elem is not None and self.end_elem is None:
2433
- raise loggers.ElectionError.from_message(
2434
- "Contest has a StartDate but is missing an EndDate. Every StartDate"
2435
- " must have a corresponding EndDate.",
2436
- [element],
2437
- )
2438
-
2439
-
2440
- class ValidatePollsCloseDatetimes(base.BaseRule):
2441
- """Checks that LatestPollsClose is not before EarliestPollsClose."""
2442
-
2443
- def elements(self):
2444
- return ["Contest"]
2445
-
2446
- def check(self, element):
2447
- earliest_polls_close_element = element.find("EarliestPollsClose")
2448
- latest_polls_close_element = element.find("LatestPollsClose")
2449
-
2450
- if not rule_util.element_has_text(
2451
- earliest_polls_close_element
2452
- ) or not rule_util.element_has_text(latest_polls_close_element):
2453
- return
2454
-
2455
- earliest_polls_close_text = earliest_polls_close_element.text.strip()
2456
- latest_polls_close_text = latest_polls_close_element.text.strip()
2457
-
2458
- try:
2459
- earliest_polls_close = datetime.datetime.fromisoformat(
2460
- earliest_polls_close_text
2461
- )
2462
- latest_polls_close = datetime.datetime.fromisoformat(
2463
- latest_polls_close_text
2464
- )
2465
-
2466
- if latest_polls_close < earliest_polls_close:
2467
- raise loggers.ElectionError.from_message(
2468
- f"LatestPollsClose ({latest_polls_close_text}) must not be before"
2469
- f" EarliestPollsClose ({earliest_polls_close_text}) for Contest"
2470
- f" {element.get('objectId')}.",
2471
- [element],
2472
- )
2473
- except ValueError as e:
2474
- raise loggers.ElectionError.from_message(
2475
- "Invalid PollsClose datetime format in Contest"
2476
- f" {element.get('objectId')}: {e}",
2477
- [element],
2478
- )
2479
-
2480
-
2481
- class ValidateResultsExpected(base.BaseRule):
2482
- """Checks that ResultsExpected is not before the first ResultsReportingStage.
2483
-
2484
- The ResultsExpected datetime must not be before the ExpectedStartDateTime
2485
- of the earliest ResultsReportingStage excluding the no-results stage.
2486
- """
2487
-
2488
- def elements(self):
2489
- return ["Contest"]
2490
-
2491
- def check(self, element):
2492
- results_expected_element = element.find("ResultsExpected")
2493
- if not rule_util.element_has_text(results_expected_element):
2494
- return
2495
-
2496
- results_expected_text = results_expected_element.text.strip()
2497
-
2498
- try:
2499
- results_expected = datetime.datetime.fromisoformat(results_expected_text)
2500
- except ValueError as e:
2501
- raise loggers.ElectionError.from_message(
2502
- "Invalid ResultsExpected datetime format in Contest"
2503
- f" {element.get('objectId')}: {e}",
2504
- [element],
2505
- )
2506
-
2507
- stage_collection = element.find("ResultsReportingStageCollection")
2508
- if stage_collection is None:
2509
- return
2510
-
2511
- earliest_start = None
2512
- earliest_start_text = None
2513
- for stage in stage_collection.findall("ResultsReportingStage"):
2514
- stage_type_element = stage.find("StageType")
2515
- if (
2516
- rule_util.element_has_text(stage_type_element)
2517
- and stage_type_element.text.strip() == "no-results"
2518
- ):
2519
- continue
2520
-
2521
- start_element = stage.find("ExpectedStartDateTime")
2522
- if not rule_util.element_has_text(start_element):
2523
- continue
2524
-
2525
- start_text = start_element.text.strip()
2526
- try:
2527
- start = datetime.datetime.fromisoformat(start_text)
2528
- if earliest_start is None or start < earliest_start:
2529
- earliest_start = start
2530
- earliest_start_text = start_text
2531
- except ValueError as e:
2532
- raise loggers.ElectionError.from_message(
2533
- "Invalid ExpectedStartDateTime datetime format for the"
2534
- f" '{stage_type_element.text.strip()}' ResultsReportingStage in"
2535
- f" Contest {element.get('objectId')}: {e}",
2536
- [element],
2537
- )
2538
-
2539
- if earliest_start and results_expected < earliest_start:
2540
- raise loggers.ElectionError.from_message(
2541
- f"ResultsExpected ({results_expected_text}) must not be before the"
2542
- f" ExpectedStartDateTime ({earliest_start_text}) of the earliest"
2543
- f" ResultsReportingStage for Contest {element.get('objectId')}.",
2544
- [element],
2545
- )
2546
-
2547
-
2548
- class ValidateResultsEmbargoEnd(base.BaseRule):
2549
- """Checks that ResultsEmbargoEnd is not after the official ResultsReportingStage start."""
2550
-
2551
- def elements(self):
2552
- return ["Contest"]
2553
-
2554
- def check(self, element):
2555
- results_embargo_end_element = element.find("ResultsEmbargoEnd")
2556
- if not rule_util.element_has_text(results_embargo_end_element):
2557
- return
2558
-
2559
- results_embargo_end_text = results_embargo_end_element.text.strip()
2560
-
2561
- try:
2562
- results_embargo_end = datetime.datetime.fromisoformat(
2563
- results_embargo_end_text
2564
- )
2565
- except ValueError as e:
2566
- raise loggers.ElectionError.from_message(
2567
- "Invalid ResultsEmbargoEnd datetime format in Contest"
2568
- f" {element.get('objectId')}: {e}",
2569
- [element],
2570
- )
2571
-
2572
- stage_collection = element.find("ResultsReportingStageCollection")
2573
- if stage_collection is None:
2574
- return
2575
-
2576
- official_start = None
2577
- official_start_text = None
2578
- for stage in stage_collection.findall("ResultsReportingStage"):
2579
- stage_type_element = stage.find("StageType")
2580
- if (
2581
- rule_util.element_has_text(stage_type_element)
2582
- and stage_type_element.text.strip() == "official"
2583
- ):
2584
- start_element = stage.find("ExpectedStartDateTime")
2585
- if not rule_util.element_has_text(start_element):
2586
- continue
2587
-
2588
- start_text = start_element.text.strip()
2589
- try:
2590
- official_start = datetime.datetime.fromisoformat(start_text)
2591
- official_start_text = start_text
2592
- break
2593
- except ValueError as e:
2594
- raise loggers.ElectionError.from_message(
2595
- "Invalid ExpectedStartDateTime datetime format for the"
2596
- " 'official' ResultsReportingStage in Contest"
2597
- f" {element.get('objectId')}: {e}",
2598
- [element],
2599
- )
2600
-
2601
- if official_start and official_start < results_embargo_end:
2602
- raise loggers.ElectionError.from_message(
2603
- f"ResultsEmbargoEnd ({results_embargo_end_text}) must not be after"
2604
- f" the ExpectedStartDateTime ({official_start_text}) of the official"
2605
- f" ResultsReportingStage for Contest {element.get('objectId')}.",
2606
- [element],
2607
- )
2608
-
2609
-
2610
- class ResultsReportingStagesMustHaveUniqueType(base.BaseRule):
2611
- """Checks that each ResultsReportingStage has a unique StageType per Contest."""
2612
-
2613
- def elements(self):
2614
- return ["ResultsReportingStageCollection"]
2615
-
2616
- def check(self, element):
2617
- stages_by_type = collections.defaultdict(list)
2618
- for stage in element.findall("ResultsReportingStage"):
2619
- stage_type_element = stage.find("StageType")
2620
- if rule_util.element_has_text(stage_type_element):
2621
- stage_type = stage_type_element.text.strip()
2622
- stages_by_type[stage_type].append(stage)
2623
-
2624
- errors = []
2625
- for stage_type, stages in stages_by_type.items():
2626
- if len(stages) > 1:
2627
- errors.append(
2628
- loggers.LogEntry(
2629
- f"Duplicate ResultsReportingStage StageType '{stage_type}'"
2630
- " found in the same ResultsReportingStageCollection.",
2631
- stages,
2632
- )
2633
- )
2634
- if errors:
2635
- raise loggers.ElectionError(errors)
2636
-
2637
-
2638
- class ValidateResultReportingStages(base.BaseRule):
2639
- """Validates ResultsReportingStage elements in a stage collection."""
2640
-
2641
- def setup(self):
2642
- self.composing_contest_ids = self._get_composing_contest_ids()
2643
-
2644
- def _get_composing_contest_ids(self):
2645
- composing_contest_ids = set()
2646
- for contest in self.get_elements_by_class(self.election_tree, "Contest"):
2647
- composing_contest_ids_element = contest.find("ComposingContestIds")
2648
- if rule_util.element_has_text(composing_contest_ids_element):
2649
- composing_contest_ids.update(composing_contest_ids_element.text.split())
2650
- return composing_contest_ids
2651
-
2652
- def elements(self):
2653
- return ["ResultsReportingStageCollection"]
2654
-
2655
- def check(self, element):
2656
- inherit_from_composed = rule_util.is_xml_true(
2657
- element.find("InheritFromComposedContest")
2658
- )
2659
- stages = element.findall("ResultsReportingStage")
2660
-
2661
- if inherit_from_composed:
2662
- error_log = []
2663
- if stages:
2664
- error_log.append(
2665
- loggers.LogEntry(
2666
- "ResultsReportingStageCollection must not contain any"
2667
- " ResultsReportingStage elements when"
2668
- " InheritFromComposedContest is true.",
2669
- [element],
2670
- )
2671
- )
2672
- contest = element.getparent()
2673
- contest_id = contest.get("objectId") if contest is not None else None
2674
- if contest_id not in self.composing_contest_ids:
2675
- error_log.append(
2676
- loggers.LogEntry(
2677
- f"Contest {contest_id} sets InheritFromComposedContest to"
2678
- " true but is not listed in the ComposingContestIds of any"
2679
- " other Contest.",
2680
- [contest],
2681
- )
2682
- )
2683
- if error_log:
2684
- raise loggers.ElectionError(error_log)
2685
- return
2686
-
2687
- if not stages:
2688
- raise loggers.ElectionError.from_message(
2689
- "ResultsReportingStageCollection must contain at least one"
2690
- " ResultsReportingStage element when InheritFromComposedContest is"
2691
- " not true.",
2692
- [element],
2693
- )
2694
-
2695
- stage_types = set()
2696
- for stage in stages:
2697
- stage_type_element = stage.find("StageType")
2698
- if rule_util.element_has_text(stage_type_element):
2699
- stage_types.add(stage_type_element.text.strip())
2700
-
2701
- if (
2702
- len(stages) < 2
2703
- or "no-results" not in stage_types
2704
- or stage_types.isdisjoint({"preliminary", "official"})
2705
- ):
2706
- raise loggers.ElectionWarning.from_message(
2707
- "ResultsReportingStageCollection should contain at least two"
2708
- " ResultsReportingStage elements, including one of StageType"
2709
- " 'no-results' and at least one of StageType 'preliminary' or"
2710
- " 'official', when InheritFromComposedContest is not true.",
2711
- [element],
2712
- )
2713
-
2714
31
 
2715
- class CandidateContestTypesAreCompatible(base.BaseRule):
2716
- """CandidateContest Type values cannot have both a general and primary type."""
2717
32
 
2718
- def elements(self):
2719
- return ["CandidateContest"]
2720
-
2721
- def check(self, element):
2722
- primary_types = {
2723
- "primary",
2724
- "partisan-primary-open",
2725
- "partisan-primary-closed",
2726
- }
2727
- contest_type_elements = element.findall("Type")
2728
- if contest_type_elements:
2729
- contest_types = {
2730
- type_element.text.strip().lower()
2731
- for type_element in contest_type_elements
2732
- if rule_util.element_has_text(type_element)
2733
- }
2734
- if "general" in contest_types and primary_types.intersection(
2735
- contest_types
2736
- ):
2737
- raise loggers.ElectionError.from_message(
2738
- "CandidateContest {} has incompatible type values. A contest cannot"
2739
- " have both a general and primary type.".format(
2740
- element.get("objectId")
2741
- ),
2742
- [element],
2743
- )
33
+ _VALID_FEED_LONGEVITY_BY_FEED_TYPE = frozendict({
34
+ "committee": ["evergreen"],
35
+ "election-dates": ["evergreen"],
36
+ "election-results": ["limited"],
37
+ "officeholder": ["evergreen"],
38
+ "pre-election": ["limited", "yearly"],
39
+ })
2744
40
 
2745
41
 
2746
42
  class CommitteeClassificationEndDateOccursAfterStartDate(base.DateRule):
@@ -3209,33 +505,6 @@ class UnreferencedEntitiesElectionDates(common_rules.UnreferencedEntitiesBase):
3209
505
  )
3210
506
 
3211
507
 
3212
- class UnreferencedEntitiesOfficeholders(common_rules.UnreferencedEntitiesBase):
3213
- """CDF offices and party leadership entities are top-level in officeholders feeds.
3214
-
3215
- This rule is a warning for CDF parties since we ask for all parties for some
3216
- LatAm feeds.
3217
- """
3218
-
3219
- def __init__(self, election_tree, schema_tree, **kwargs):
3220
- office_holder_tenure_collection = self.get_elements_by_class(
3221
- election_tree, "OfficeHolderTenure"
3222
- )
3223
- is_post_office_split = False
3224
- if office_holder_tenure_collection:
3225
- is_post_office_split = True
3226
- super(UnreferencedEntitiesOfficeholders, self).__init__(
3227
- election_tree,
3228
- schema_tree,
3229
- (
3230
- frozenset(["OfficeHolderTenure", "Leadership"])
3231
- if is_post_office_split
3232
- else frozenset(["Office", "Leadership"])
3233
- ),
3234
- frozenset(["Party"]),
3235
- **kwargs,
3236
- )
3237
-
3238
-
3239
508
  class ElectoralCommissionCollectionExists(base.BaseRule):
3240
509
  """ElectoralCommissionCollection should exist."""
3241
510
 
@@ -3387,235 +656,6 @@ class FeedElementsShouldHaveSubElementsBasedOnType(base.BaseRule):
3387
656
  )
3388
657
 
3389
658
 
3390
- class NotEmptyUniqueDataSourceUris(base.BaseRule):
3391
- """Checks that DataSource entities have globally unique URIs and they are not empty."""
3392
-
3393
- def elements(self):
3394
- return ["DataSourceCollection"]
3395
-
3396
- def check(self, element):
3397
- data_source_ids_by_uri = collections.defaultdict(set)
3398
- error_log = []
3399
-
3400
- for data_source in element.findall("DataSource"):
3401
- datasource_id = data_source.get("objectId")
3402
- for uri_element in data_source.findall("Uri"):
3403
- if not rule_util.element_has_text(uri_element):
3404
- error_log.append(
3405
- loggers.LogEntry(
3406
- "DataSource {} has an empty Uri.".format(datasource_id),
3407
- [data_source],
3408
- )
3409
- )
3410
- continue
3411
- uri = uri_element.text.strip()
3412
- data_source_ids_by_uri[uri].add(data_source)
3413
-
3414
- for uri, data_sources in data_source_ids_by_uri.items():
3415
- if len(data_sources) <= 1:
3416
- continue
3417
- sorted_data_sources = sorted(
3418
- data_sources, key=lambda ds: ds.get("objectId")
3419
- )
3420
- data_source_ids = [
3421
- data_source.get("objectId") for data_source in sorted_data_sources
3422
- ]
3423
- error_log.append(
3424
- loggers.LogEntry(
3425
- "DataSource entities {} have duplicate Uri '{}'.".format(
3426
- ", ".join(data_source_ids), uri
3427
- ),
3428
- sorted_data_sources,
3429
- )
3430
- )
3431
-
3432
- if error_log:
3433
- raise loggers.ElectionError(error_log)
3434
-
3435
-
3436
- class UniqueDataSourceLanguages(base.BaseRule):
3437
- """Checks that Uri elements have unique languages within a DataSource."""
3438
-
3439
- def elements(self):
3440
- return ["DataSourceCollection"]
3441
-
3442
- def check(self, element):
3443
- error_log = []
3444
-
3445
- for data_source in element.findall("DataSource"):
3446
- data_source_id = data_source.get("objectId")
3447
- seen_uri_languages = set()
3448
- for uri_element in data_source.findall("Uri"):
3449
- language = uri_element.get("language")
3450
- if not language:
3451
- error_log.append(
3452
- loggers.LogEntry(
3453
- "DataSource {} has a Uri element without a language.".format(
3454
- data_source_id
3455
- ),
3456
- [uri_element],
3457
- )
3458
- )
3459
- continue
3460
- language = language.strip()
3461
- if language in seen_uri_languages:
3462
- error_log.append(
3463
- loggers.LogEntry(
3464
- "DataSource {} has multiple Uri elements with the same"
3465
- " language '{}'.".format(data_source_id, language),
3466
- [element],
3467
- )
3468
- )
3469
- else:
3470
- seen_uri_languages.add(language)
3471
-
3472
- if error_log:
3473
- raise loggers.ElectionError(error_log)
3474
-
3475
-
3476
- class UniqueDataSourceDisplayNames(base.BaseRule):
3477
- """Checks that DataSource entities have globally unique DisplayNames."""
3478
-
3479
- def elements(self):
3480
- return ["DataSourceCollection"]
3481
-
3482
- def check(self, element):
3483
- data_source_ids_by_name = collections.defaultdict(set)
3484
- error_log = []
3485
-
3486
- for data_source in element.findall("DataSource"):
3487
- data_source_id = data_source.get("objectId")
3488
- display_name_element = data_source.find("DisplayName")
3489
- for text_element in display_name_element.findall("Text"):
3490
- if not rule_util.element_has_text(text_element):
3491
- error_log.append(
3492
- loggers.LogEntry(
3493
- "DataSource {} has a DisplayName element without"
3494
- " text.".format(data_source_id),
3495
- [data_source],
3496
- )
3497
- )
3498
- continue
3499
- name_text = text_element.text.strip()
3500
- data_source_ids_by_name[name_text].add(data_source)
3501
-
3502
- for name_text, data_sources in data_source_ids_by_name.items():
3503
- if len(data_sources) <= 1:
3504
- continue
3505
- sorted_data_sources = sorted(
3506
- data_sources, key=lambda ds: ds.get("objectId")
3507
- )
3508
- datasource_ids = [ds.get("objectId") for ds in sorted_data_sources]
3509
- error_log.append(
3510
- loggers.LogEntry(
3511
- "DataSource entities {} have duplicate DisplayName '{}'.".format(
3512
- ", ".join(datasource_ids), name_text
3513
- ),
3514
- sorted_data_sources,
3515
- )
3516
- )
3517
-
3518
- if error_log:
3519
- raise loggers.ElectionError(error_log)
3520
-
3521
-
3522
- def _get_attribution_depth(element):
3523
- """Helper to recursively get the maximum depth of an Attribution tree."""
3524
- children = element.findall("Attribution")
3525
- if not children:
3526
- return 1
3527
- return 1 + max(_get_attribution_depth(child) for child in children)
3528
-
3529
-
3530
- def _get_datasource_id(element):
3531
- """Helper to safely extract and strip the text of the DataSourceId child."""
3532
- ds_element = element.find("DataSourceId")
3533
- return (
3534
- ds_element.text.strip() if rule_util.element_has_text(ds_element) else ""
3535
- )
3536
-
3537
-
3538
- class AttributionDepthLimit(base.BaseRule):
3539
- """Checks that each top-level Attribution in a ResultsReportingStage has at most three levels of depth."""
3540
-
3541
- def elements(self):
3542
- return ["ResultsReportingStage"]
3543
-
3544
- def check(self, element):
3545
- error_log = []
3546
- # This findall query is non-recursive and only returns direct children.
3547
- for attribution in element.findall("Attribution"):
3548
- depth = _get_attribution_depth(attribution)
3549
- if depth > 3:
3550
- data_source_id = _get_datasource_id(attribution)
3551
- error_log.append(
3552
- loggers.LogEntry(
3553
- f"Attribution starting with DataSourceId '{data_source_id}'"
3554
- f" has a depth of {depth}, exceeding the limit of 3.",
3555
- [attribution],
3556
- )
3557
- )
3558
- if error_log:
3559
- raise loggers.ElectionError(error_log)
3560
-
3561
-
3562
- def _canonicalize_cycle(cycle):
3563
- """Canonicalizes a cycle by rotating it to start with the min element."""
3564
- if not cycle:
3565
- return []
3566
- min_node = min(cycle)
3567
- min_idx = cycle.index(min_node)
3568
- return cycle[min_idx:] + cycle[:min_idx]
3569
-
3570
-
3571
- class AttributionContainsNoCycles(base.TreeRule):
3572
- """Checks that there are no cycles between Attribution elements."""
3573
-
3574
- def check(self):
3575
- graph = networkx.DiGraph()
3576
-
3577
- attributions = self.get_elements_by_class(self.election_tree, "Attribution")
3578
- for attribution in attributions:
3579
- data_source = _get_datasource_id(attribution)
3580
- if not data_source:
3581
- continue
3582
- graph.add_node(data_source)
3583
- for child in attribution.findall("Attribution"):
3584
- child_data_source = _get_datasource_id(child)
3585
- if child_data_source:
3586
- graph.add_edge(data_source, child_data_source)
3587
-
3588
- # Find all nodes in the graph that are part of a cycle based on directed
3589
- # paths.
3590
- nodes_in_a_cycle = set()
3591
- for component in networkx.strongly_connected_components(graph):
3592
- # If the component has multiple nodes, it must be a cycle.
3593
- if len(component) > 1:
3594
- nodes_in_a_cycle.update(component)
3595
- continue
3596
- # Only include single-node components if they have a self-loop.
3597
- (node,) = component
3598
- if graph.has_edge(node, node):
3599
- nodes_in_a_cycle.add(node)
3600
-
3601
- if not nodes_in_a_cycle:
3602
- return
3603
-
3604
- error_log = []
3605
- # Optimize performance for large graphs by excluding non-cyclic nodes.
3606
- all_cycles_subgraph = graph.subgraph(sorted(nodes_in_a_cycle))
3607
- for cycle in networkx.simple_cycles(all_cycles_subgraph):
3608
- canonical = _canonicalize_cycle(cycle)
3609
- # Append the starting node to the end to represent a closed loop.
3610
- error_log.append(
3611
- loggers.LogEntry(
3612
- f"Cycle detected in Attribution: {' -> '.join(canonical)} ->"
3613
- f" {canonical[0]}"
3614
- )
3615
- )
3616
- raise loggers.ElectionError(error_log)
3617
-
3618
-
3619
659
  class RuleSet(enum.Enum):
3620
660
  """Names for sets of rules used to validate a particular feed type."""
3621
661
 
@@ -3628,221 +668,12 @@ class RuleSet(enum.Enum):
3628
668
  VOTER_INFORMATION = 7
3629
669
 
3630
670
 
3631
- class ValidateSpecialBallotSelectionCountedInTotal(base.BaseRule):
3632
- """Enforces constraints on CountedInTotal for SpecialBallotSelections.
3633
-
3634
- More specifically, BlankBallotSelection, NullBallotSelection, and
3635
- NoneOfTheAboveSelection must have an explicit value for CountedInTotal, and
3636
- AggregateBallotSelection must not have this set.
3637
- """
3638
-
3639
- def elements(self):
3640
- return [
3641
- "BlankBallotSelection",
3642
- "NullBallotSelection",
3643
- "NoneOfTheAboveBallotSelection",
3644
- "AggregateBallotSelection",
3645
- ]
3646
-
3647
- def check(self, element):
3648
- counted_in_total = element.find("CountedInTotal")
3649
- tag = element.tag
3650
-
3651
- if tag in (
3652
- "BlankBallotSelection",
3653
- "NullBallotSelection",
3654
- "NoneOfTheAboveBallotSelection",
3655
- ) and not rule_util.element_has_text(counted_in_total):
3656
- raise loggers.ElectionError.from_message(
3657
- f"{tag} must have an explicit value for CountedInTotal.",
3658
- [element],
3659
- )
3660
- elif tag == "AggregateBallotSelection" and counted_in_total is not None:
3661
- raise loggers.ElectionError.from_message(
3662
- "AggregateBallotSelection must not have CountedInTotal set.",
3663
- [element],
3664
- )
3665
-
3666
-
3667
- class ValidateIncludeInAggregationBallotSelections(base.BaseRule):
3668
- """Validates BallotSelections with IncludedInAggregation.
3669
-
3670
- Checks that the sum of all vote counts for a BallotSelection with
3671
- IncludedInAggregation must not be > the total vote counts for the
3672
- AggregateBallotSelection on that same Contest for the same vote count type.
3673
- Also requires that if IncludedInAggregation is set on any BallotSelection then
3674
- the AggregateBallotSelection must also be present on that Contest.
3675
- """
3676
-
3677
- def elements(self):
3678
- return ["CandidateContest", "PartyContest"]
3679
-
3680
- def _gather_vote_counts(self, element):
3681
- """Gathers vote counts from a selection element grouped by type."""
3682
- count_by_type_and_gp_unit = collections.defaultdict(float)
3683
- vote_counts_collection = element.find("VoteCountsCollection")
3684
- if vote_counts_collection is None:
3685
- return count_by_type_and_gp_unit
3686
-
3687
- for vote_counts in vote_counts_collection.findall("VoteCounts"):
3688
- count_element = vote_counts.find("Count")
3689
- if not rule_util.element_has_text(count_element):
3690
- continue
3691
- count = float(count_element.text)
3692
-
3693
- vote_count_type = _get_type_or_other_type(vote_counts)
3694
- gp_unit_id_element = vote_counts.find("GpUnitId")
3695
- gp_unit_id = (
3696
- gp_unit_id_element.text.strip()
3697
- if rule_util.element_has_text(gp_unit_id_element)
3698
- else ""
3699
- )
3700
-
3701
- type_and_gp_unit = (vote_count_type, gp_unit_id)
3702
- count_by_type_and_gp_unit[type_and_gp_unit] += count
3703
-
3704
- return count_by_type_and_gp_unit
3705
-
3706
- def check(self, element):
3707
- contest_id = element.get("objectId")
3708
-
3709
- candidate_selections = self.get_elements_by_class(
3710
- element, "CandidateSelection"
3711
- )
3712
- party_selections = self.get_elements_by_class(element, "PartySelection")
3713
- all_selections = candidate_selections + party_selections
3714
-
3715
- included_selections = []
3716
- for selection in all_selections:
3717
- if rule_util.is_xml_true(selection.find("IncludedInAggregation")):
3718
- included_selections.append(selection)
3719
- if not included_selections:
3720
- return
3721
-
3722
- aggregate_selection = element.find("AggregateBallotSelection")
3723
- if aggregate_selection is None:
3724
- raise loggers.ElectionError.from_message(
3725
- f"Contest {contest_id} has selections marked as IncludedInAggregation"
3726
- " but is missing AggregateBallotSelection.",
3727
- [element],
3728
- )
3729
-
3730
- aggregate_count_by_type_and_gp_unit = self._gather_vote_counts(
3731
- aggregate_selection
3732
- )
3733
-
3734
- selections_count_sum_by_type_and_gp_unit = collections.defaultdict(float)
3735
- for selection in included_selections:
3736
- for (
3737
- type_and_gp_unit,
3738
- count,
3739
- ) in self._gather_vote_counts(selection).items():
3740
- selections_count_sum_by_type_and_gp_unit[type_and_gp_unit] += count
3741
-
3742
- error_log = []
3743
- for (
3744
- type_and_gp_unit,
3745
- total_count,
3746
- ) in selections_count_sum_by_type_and_gp_unit.items():
3747
- aggregate_count = aggregate_count_by_type_and_gp_unit[type_and_gp_unit]
3748
- if total_count > aggregate_count:
3749
- resolved_type, gp_unit_id = type_and_gp_unit
3750
- error_log.append(
3751
- loggers.LogEntry(
3752
- f"In Contest {contest_id}, the sum of vote counts"
3753
- f" ({total_count}) for selections marked as"
3754
- " IncludedInAggregation exceeds the vote count"
3755
- f" ({aggregate_count}) for the AggregateBallotSelection for"
3756
- f" vote count type='{resolved_type}' (GpUnit: '{gp_unit_id}').",
3757
- [element],
3758
- )
3759
- )
3760
-
3761
- if error_log:
3762
- raise loggers.ElectionError(error_log)
3763
-
3764
-
3765
671
  # To add new rules, create a new class, inherit the base rule,
3766
672
  # and add it to the correct rule list.
3767
673
  COMMON_RULES = common_rules.COMMON_RULES
674
+ OFFICEHOLDER_RULES = officeholder_rules.OFFICEHOLDER_RULES
675
+ ELECTION_RULES = election_rules.ELECTION_RULES
3768
676
 
3769
- ELECTION_RULES = COMMON_RULES + (
3770
- # go/keep-sorted start
3771
- AttributionContainsNoCycles,
3772
- AttributionDepthLimit,
3773
- BallotTitle,
3774
- CandidateContestTypesAreCompatible,
3775
- CandidatesReferencedInRelatedContests,
3776
- CoalitionParties,
3777
- ComposingContestIdsAreValidRelatedContests,
3778
- ContestContainsValidEndDate,
3779
- ContestContainsValidStartDate,
3780
- ContestEndDateOccursAfterStartDate,
3781
- ContestEndDateOccursBeforeSubsequentContestStartDate,
3782
- ContestHasMultipleOffices,
3783
- ContestHasValidContestStage,
3784
- ContestStartDateContainsCorrespondingEndDate,
3785
- CorrectCandidateSelectionCount,
3786
- DateStatusMatches,
3787
- DuplicateBallotTitleSeatPair,
3788
- DuplicateContestNames,
3789
- DuplicatedPartyAbbreviation,
3790
- DuplicatedPartyName,
3791
- ElectionContainsStartAndEndDates,
3792
- ElectionDatesSpanContestDates,
3793
- ElectionEndDatesInThePast,
3794
- ElectionEndDatesOccurAfterStartDates,
3795
- ElectionStartDates,
3796
- ElectionTypesAndCandidateContestTypesAreCompatible,
3797
- ElectionTypesAreCompatible,
3798
- FullTextMaxLength,
3799
- FullTextOrBallotText,
3800
- GpUnitsHaveSingleRoot,
3801
- ImproperCandidateContest,
3802
- MissingPartyAbbreviationTranslation,
3803
- MissingPartyNameTranslation,
3804
- MultipleCandidatesPointToTheSamePersonInTheSameContest,
3805
- MultipleInternationalizedTextWithSameLanguageCode,
3806
- NotEmptyUniqueDataSourceUris,
3807
- OfficeHasjurisdictionSameAsElectoralDistrict,
3808
- PartisanPrimary,
3809
- PartisanPrimaryHeuristic,
3810
- PercentSum,
3811
- ProperBallotSelection,
3812
- ResultsReportingStagesMustHaveUniqueType,
3813
- SelfDeclaredCandidateMethod,
3814
- SingularPartySelection,
3815
- SubsequentContestIdIsValidRelatedContest,
3816
- UniqueDataSourceDisplayNames,
3817
- UniqueDataSourceLanguages,
3818
- ValidateDuplicateColors,
3819
- ValidateIncludeInAggregationBallotSelections,
3820
- ValidateInfoUriAnnotation,
3821
- ValidatePollsCloseDatetimes,
3822
- ValidateResultReportingStages,
3823
- ValidateResultsEmbargoEnd,
3824
- ValidateResultsExpected,
3825
- ValidateSpecialBallotSelectionCountedInTotal,
3826
- VoteCountTypesCoherency,
3827
- VoteCountValidSeatsDeltaTypes,
3828
- WinnerCountLimit,
3829
- # go/keep-sorted end
3830
- )
3831
-
3832
-
3833
- OFFICEHOLDER_RULES = COMMON_RULES + (
3834
- # go/keep-sorted start
3835
- DateOfBirthIsInPast,
3836
- OfficeHolderTenureTermDates,
3837
- OfficeSelectionMethodMatch,
3838
- OfficeTermDates,
3839
- PersonHasOffice,
3840
- RemovePersonAndOfficeHolderId60DaysAfterEndDate,
3841
- UniqueStartDatesForOfficeRoleAndJurisdiction,
3842
- UnreferencedEntitiesOfficeholders,
3843
- common_rules.ProhibitElectionData,
3844
- # go/keep-sorted end
3845
- )
3846
677
 
3847
678
  COMMITTEE_RULES = COMMON_RULES + (
3848
679
  # go/keep-sorted start