civics-cdf-validator 1.67.dev3__py3-none-any.whl → 1.67.dev5__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,2314 +15,29 @@
15
15
 
16
16
  from __future__ import print_function
17
17
 
18
- import collections
19
18
  import datetime
20
19
  import enum
21
20
  import re
22
21
 
23
22
  from botocore import utils as botocore_utils
24
23
  from civics_cdf_validator import base
25
- from civics_cdf_validator import gpunit_rules
26
24
  from civics_cdf_validator import loggers
27
25
  from civics_cdf_validator.rulesets import common_rules
26
+ from civics_cdf_validator.rulesets import election_dates_rules
27
+ from civics_cdf_validator.rulesets import election_rules
28
28
  from civics_cdf_validator.rulesets import officeholder_rules
29
29
  from civics_cdf_validator.rulesets import rule_util
30
30
  import dateutil
31
31
  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 VoteCountTypesCoherency(base.BaseRule):
966
- """Ensure VoteCount types describe the appropriate votable."""
967
-
968
- PARTY_VC_TYPES = {
969
- "seats-won",
970
- "seats-leading",
971
- "party-votes",
972
- "seats-no-election",
973
- "seats-total",
974
- "seats-delta",
975
- "seats-delta-mandate",
976
- "seats-delta-institutional",
977
- }
978
- # Ibid.
979
- CAND_VC_TYPES = {"candidate-votes"}
980
-
981
- def elements(self):
982
- return ["Contest"]
983
-
984
- def check(self, element):
985
- invalid_vc_types = None
986
- contest_type = ""
987
- if element.get("type", "") == "CandidateContest":
988
- invalid_vc_types = self.PARTY_VC_TYPES
989
- contest_type = "Candidate"
990
- elif element.get("type", "") == "PartyContest":
991
- invalid_vc_types = self.CAND_VC_TYPES
992
- contest_type = "Party"
993
- if invalid_vc_types:
994
- errors = []
995
- for ballot_selection in element.findall("BallotSelection"):
996
- for vote_counts in ballot_selection.find(
997
- "VoteCountsCollection"
998
- ).findall("VoteCounts"):
999
- vc_type = vote_counts.find("OtherType").text
1000
- if vc_type in invalid_vc_types:
1001
- errors.append(vc_type)
1002
- if errors:
1003
- msg = "VoteCount types {0} should not be nested in {1} Contest".format(
1004
- ", ".join(errors), contest_type
1005
- )
1006
- raise loggers.ElectionError.from_message(msg, [element])
1007
-
1008
-
1009
- class VoteCountValidSeatsDeltaTypes(base.BaseRule):
1010
- """Ensure VoteCount seats delta types are valid."""
1011
-
1012
- def elements(self):
1013
- return ["BallotSelection"] + list(
1014
- self.get_element_names_for_type("SpecialBallotSelection")
1015
- )
1016
-
1017
- def check(self, element):
1018
- vote_count_types = set()
1019
- vote_counts_collection = element.find("VoteCountsCollection")
1020
- if vote_counts_collection is None:
1021
- return
1022
- for vote_counts in vote_counts_collection.findall("VoteCounts"):
1023
- vote_count_types.add(_get_type_or_other_type(vote_counts))
1024
- if "seats-delta" in vote_count_types:
1025
- raise loggers.ElectionError.from_message(
1026
- "Legacy VoteCounts type seats-delta is no longer supported as of"
1027
- " July 1, 2026. Please update your implementation to use"
1028
- " seats-delta-mandate and/or seats-delta-institutional.",
1029
- [element],
1030
- )
1031
-
1032
-
1033
- class OfficeHasjurisdictionSameAsElectoralDistrict(base.BaseRule):
1034
- """In election feeds, office has the electoral district same as jurisdiction."""
1035
-
1036
- def elements(self):
1037
- return ["Office"]
1038
-
1039
- def check(self, element):
1040
- jurisdiction_values = rule_util.get_entity_info_for_value_type(
1041
- element, "jurisdiction-id"
1042
- )
1043
- jurisdiction_values = [
1044
- j_id.strip() for j_id in jurisdiction_values if j_id.strip()
1045
- ]
1046
- if not jurisdiction_values or len(jurisdiction_values) > 1:
1047
- return
1048
-
1049
- electoral_district = element.find(".//ElectoralDistrictId")
1050
- if electoral_district is None:
1051
- return
1052
- if electoral_district.text.strip() != jurisdiction_values[0]:
1053
- raise loggers.ElectionInfo.from_message(
1054
- "Office has electoral district different from jurisdiction.",
1055
- [element],
1056
- )
1057
-
1058
-
1059
- class ContestHasValidContestStage(base.BaseRule):
1060
- """Each Contest must have a valid contest-stage."""
1061
-
1062
- def elements(self):
1063
- return ["CandidateContest", "PartyContest", "BallotMeasureContest"]
1064
-
1065
- def check(self, element):
1066
- contest_stage_values = [
1067
- contest_stage_value.strip()
1068
- for contest_stage_value in rule_util.get_external_id_values(
1069
- element, "contest-stage"
1070
- )
1071
- ]
1072
- for contest_stage_value in contest_stage_values:
1073
- if contest_stage_value not in _CONTEST_STAGE_TYPES:
1074
- raise loggers.ElectionError.from_message(
1075
- "The contest has invalid contest-stage '{}'.".format(
1076
- contest_stage_value
1077
- ),
1078
- [element],
1079
- )
1080
-
1081
-
1082
- class ElectionContainsStartAndEndDates(base.DateRule):
1083
- """Election elements should have start and end dates populated."""
1084
-
1085
- def elements(self):
1086
- return ["Election"]
1087
-
1088
- def check(self, element):
1089
- self.reset_instance_vars()
1090
- self.gather_dates(element)
1091
-
1092
- if self.start_elem is None:
1093
- self.error_log.append(
1094
- loggers.LogEntry(
1095
- "Election {} is missing a start date.".format(
1096
- element.get("objectId")
1097
- )
1098
- )
1099
- )
1100
-
1101
- if self.end_elem is None:
1102
- self.error_log.append(
1103
- loggers.LogEntry(
1104
- "Election {} is missing an end date.".format(
1105
- element.get("objectId")
1106
- )
1107
- )
1108
- )
1109
-
1110
- if self.error_log:
1111
- raise loggers.ElectionError(self.error_log)
1112
-
1113
-
1114
- class ElectionStartDates(base.DateRule):
1115
- """Election elements should contain valid start dates.
1116
-
1117
- Start dates in the past should raise a warning. This is not an error
1118
- as validator could conceivably be run during an ongoing election.
1119
- """
1120
-
1121
- def elements(self):
1122
- return ["Election"]
1123
-
1124
- def check(self, element):
1125
- self.reset_instance_vars()
1126
- self.gather_dates(element)
1127
-
1128
- if self.start_date:
1129
- self.check_for_date_not_in_past(self.start_date, self.start_elem)
1130
-
1131
- if self.error_log:
1132
- raise loggers.ElectionWarning(self.error_log)
1133
-
1134
-
1135
- class ElectionEndDatesInThePast(base.DateRule):
1136
- """Election elements would be in the present or in the future.
1137
-
1138
- Using a past end date needs to be notified. The warning is useful to prevent
1139
- using a wrong date.
1140
-
1141
- A bounded election with a past end date is an error since the date should be
1142
- confirmed. The only exception to this is elections that are postponed or
1143
- canceled.
1144
- """
1145
-
1146
- def elements(self):
1147
- return ["Election"]
1148
-
1149
- def check(self, element):
1150
- self.reset_instance_vars()
1151
- self.gather_dates(element)
1152
- date_type = element.find("ElectionDateType")
1153
- if date_type is not None and date_type.text.lower() == "bounded":
1154
- if self.end_date:
1155
- self.check_for_date_not_in_past(self.end_date, self.end_elem)
1156
- if self.error_log:
1157
- date_status = element.find("ElectionDateStatus")
1158
- if date_status is None or date_status.text.lower() not in [
1159
- "postponed",
1160
- "canceled",
1161
- ]:
1162
- raise loggers.ElectionError.from_message(
1163
- "A bounded election should not have an end date in the past.",
1164
- [element],
1165
- )
1166
- self.reset_instance_vars()
1167
- for contest in self.get_elements_by_class(element, "Contest"):
1168
- subsequent_contest_id_element = contest.find("SubsequentContestId")
1169
- if subsequent_contest_id_element is not None:
1170
- continue
1171
- else:
1172
- if self.end_date:
1173
- self.check_for_date_not_in_past(self.end_date, self.end_elem)
1174
- if self.error_log:
1175
- raise loggers.ElectionWarning(self.error_log)
1176
-
1177
-
1178
- class ElectionEndDatesOccurAfterStartDates(base.DateRule):
1179
- """Election elements should contain a coherent start and end dates.
1180
-
1181
- End dates should not occur before the start date.
1182
- """
1183
-
1184
- def elements(self):
1185
- return ["Election"]
1186
-
1187
- def check(self, element):
1188
- self.reset_instance_vars()
1189
- self.gather_dates(element)
1190
-
1191
- if self.end_date and self.start_date:
1192
- self.check_end_after_start()
1193
- if self.error_log:
1194
- raise loggers.ElectionError(self.error_log)
1195
-
1196
-
1197
- class ElectionDatesSpanContestDates(base.DateRule):
1198
- """Election start/end dates should span the Contest start/end dates.
1199
-
1200
- The start date of the Election should be on or before the start date of every
1201
- included Contest. The end date of the Election should be on or after the end
1202
- date of every included Contest. Only Contests that have the dates populated
1203
- will be considered.
1204
- """
1205
-
1206
- def elements(self):
1207
- return ["ElectionReport"]
1208
-
1209
- def _validate_contest_dates_within_election(self, election, contest):
1210
- self.reset_instance_vars()
1211
- self.gather_dates(election)
1212
- election_start_date = self.start_date
1213
- election_end_date = self.end_date
1214
- election_id = election.get("objectId")
1215
- self.reset_instance_vars()
1216
- self.gather_dates(contest)
1217
- contest_id = contest.get("objectId")
1218
- contest_date_status = contest.find("ContestDateStatus")
1219
- if (
1220
- election_end_date is not None
1221
- and self.end_date is not None
1222
- and election_end_date < self.end_date
1223
- # Only compare election end date to contests that are not canceled
1224
- and (
1225
- contest_date_status is None
1226
- or contest_date_status.text.lower() != "canceled"
1227
- )
1228
- ):
1229
- self.error_log.append(
1230
- loggers.LogEntry(
1231
- "Contest {} with end date {} occurs after Election {} with"
1232
- " end date {}. Election end date should be on or after any"
1233
- " Contest end date.".format(
1234
- contest_id,
1235
- self.end_date,
1236
- election_id,
1237
- election_end_date,
1238
- )
1239
- )
1240
- )
1241
- if (
1242
- election_start_date is not None
1243
- and self.start_date is not None
1244
- and self.start_date < election_start_date
1245
- ):
1246
- self.error_log.append(
1247
- loggers.LogEntry(
1248
- "Contest {} with start date {} occurs before Election {} with"
1249
- " start date {}. Election start date should be on or before"
1250
- " any Contest start date.".format(
1251
- contest_id,
1252
- self.start_date,
1253
- election_id,
1254
- election_start_date,
1255
- )
1256
- )
1257
- )
1258
-
1259
- def check(self, election_report_element):
1260
- for election in self.get_elements_by_class(
1261
- election_report_element, "Election"
1262
- ):
1263
- for contest in self.get_elements_by_class(election, "Contest"):
1264
- self._validate_contest_dates_within_election(election, contest)
1265
-
1266
- if self.error_log:
1267
- raise loggers.ElectionError(self.error_log)
1268
-
1269
-
1270
- class ElectionTypesAreCompatible(base.BaseRule):
1271
- """Election element Type values cannot be both a general and primary type."""
1272
-
1273
- def elements(self):
1274
- return ["Election"]
1275
-
1276
- def check(self, element):
1277
- election_types = element.findall("Type")
1278
- if election_types:
1279
- for i in range(len(election_types)):
1280
- election_types[i] = election_types[i].text
1281
- if "general" in election_types and (
1282
- "primary" in election_types
1283
- or "partisan-primary-open" in election_types
1284
- or "partisan-primary-closed" in election_types
1285
- ):
1286
- raise loggers.ElectionError.from_message(
1287
- "Election element has incompatible election-type values.", [element]
1288
- )
1289
-
1290
-
1291
- class ElectionTypesAndCandidateContestTypesAreCompatible(base.BaseRule):
1292
- """Election elements should contain CandidateContests with compatible types.
1293
-
1294
- Elections with the general type should not have any CandidateContests with the
1295
- primary types. Elections with the primary types should not have any
1296
- CandidateContests with the general type.
1297
- """
1298
-
1299
- def _extract_text_from_elements(self, elements):
1300
- return {
1301
- element.text.strip().lower()
1302
- for element in elements
1303
- if rule_util.element_has_text(element)
1304
- }
1305
-
1306
- def elements(self):
1307
- return ["Election"]
1308
-
1309
- def check(self, element):
1310
- errors = []
1311
- contests = self.get_elements_by_class(element, "CandidateContest")
1312
- election_types = self._extract_text_from_elements(element.findall("Type"))
1313
- primary_types = {
1314
- "primary",
1315
- "partisan-primary-open",
1316
- "partisan-primary-closed",
1317
- }
1318
- for contest in contests:
1319
- contest_types = self._extract_text_from_elements(contest.findall("Type"))
1320
- if "general" in election_types and primary_types.intersection(
1321
- contest_types
1322
- ):
1323
- errors.append(
1324
- loggers.LogEntry(
1325
- "Election %s includes CandidateContest %s with incompatible"
1326
- " type(s). General elections cannot include primary contests."
1327
- % (element.get("objectId"), contest.get("objectId")),
1328
- element,
1329
- )
1330
- )
1331
- elif (
1332
- primary_types.intersection(election_types)
1333
- and "general" in contest_types
1334
- ):
1335
- errors.append(
1336
- loggers.LogEntry(
1337
- "Election %s includes CandidateContest %s with incompatible"
1338
- " type(s). Primary elections cannot include general contests."
1339
- % (element.get("objectId"), contest.get("objectId")),
1340
- element,
1341
- )
1342
- )
1343
-
1344
- if errors:
1345
- raise loggers.ElectionError(errors)
1346
-
1347
-
1348
- class DateStatusMatches(base.DateRule):
1349
- """In most cases, ContestDateStatus should match ElectionDateStatus.
1350
-
1351
- If all contests contained in an election have the same status, and this status
1352
- does not match the status on the election, it is probably incorrect - raise
1353
- warning. Differing values among ContestDateStatus in an election are possible
1354
- but uncommon - raise Info level message.
1355
- """
1356
-
1357
- def elements(self):
1358
- return ["Election"]
1359
-
1360
- def check(self, election_elem):
1361
- election_date_status = "confirmed" # default value
1362
- election_status_elem = election_elem.find("ElectionDateStatus")
1363
-
1364
- if rule_util.element_has_text(election_status_elem):
1365
- election_date_status = election_status_elem.text.strip()
1366
-
1367
- contest_statuses = set()
1368
- for contest_elem in self.get_elements_by_class(election_elem, "Contest"):
1369
- contest_status_elem = contest_elem.find("ContestDateStatus")
1370
- if rule_util.element_has_text(contest_status_elem):
1371
- contest_statuses.add(contest_status_elem.text.strip())
1372
- else:
1373
- contest_statuses.add("confirmed")
1374
-
1375
- if len(contest_statuses) == 1:
1376
- contest_status = contest_statuses.pop()
1377
- if contest_status != election_date_status:
1378
- msg = (
1379
- "All contests on election {} have a date status of {}, but the "
1380
- "election has a date status of {}.".format(
1381
- election_elem.get("objectId"),
1382
- contest_status,
1383
- election_date_status,
1384
- )
1385
- )
1386
- raise loggers.ElectionWarning.from_message(msg, [election_elem])
1387
- elif len(contest_statuses) > 1:
1388
- msg = (
1389
- "There are multiple date statuses present for the contests on "
1390
- "election {}. This may be correct, but is an unusal case. Please "
1391
- "confirm.".format(election_elem.get("objectId"))
1392
- )
1393
- raise loggers.ElectionInfo.from_message(msg, [election_elem])
1394
-
1395
-
1396
- class ValidateInfoUriAnnotation(base.BaseRule):
1397
- """InfoUri is an annotated Uri that accepts the following annotations.
1398
-
1399
- wikipedia, ballotpedia, official-website, fulltext.
1400
- Adding a check for this.
1401
- """
1402
-
1403
- info_array = [
1404
- "wikipedia",
1405
- "ballotpedia",
1406
- "official-website",
1407
- "fulltext",
1408
- "logo-uri",
1409
- ]
1410
-
1411
- def elements(self):
1412
- return ["InfoUri"]
1413
-
1414
- def check(self, element):
1415
- error_log = []
1416
- annotation = element.attrib["Annotation"]
1417
- if annotation not in self.info_array:
1418
- error_log.append(
1419
- loggers.LogEntry(annotation + " is an invalid annotation.", [element])
1420
- )
1421
- if error_log:
1422
- raise loggers.ElectionError(error_log)
1423
-
1424
-
1425
- class FullTextMaxLength(base.BaseRule):
1426
- """FullText field should not be longer than MAX_LENGTH."""
1427
-
1428
- MAX_LENGTH = 30000 # about 8-10 pages of text, 4500-5000 words
1429
-
1430
- def elements(self):
1431
- return ["FullText"]
1432
-
1433
- def check(self, element):
1434
- intl_text_list = element.findall("Text")
1435
- for intl_text in intl_text_list:
1436
- if len(intl_text.text) > self.MAX_LENGTH:
1437
- msg = (
1438
- "FullText is longer than %s characters. Please remove and "
1439
- "include a link to the full text via InfoUri with Annotation "
1440
- "'fulltext'." % (self.MAX_LENGTH)
1441
- )
1442
- raise loggers.ElectionWarning.from_message(msg, [element])
1443
-
1444
-
1445
- class FullTextOrBallotText(base.BaseRule):
1446
- """Warn if BallotText is missing and FullText is short."""
1447
-
1448
- SUGGESTION_CUTOFF_LENGTH = 2500 # about 3 paragraphs, 250-300 words
1449
-
1450
- def elements(self):
1451
- return ["BallotMeasureContest"]
1452
-
1453
- def check(self, element):
1454
- full_text_map = rule_util.get_language_to_text_map(element.find("FullText"))
1455
- if not full_text_map:
1456
- return
1457
-
1458
- ballot_text_map = rule_util.get_language_to_text_map(
1459
- element.find("BallotText")
1460
- )
1461
- for language, full_text_strings in full_text_map.items():
1462
- full_text_string = full_text_strings[0]
1463
- if (
1464
- language not in ballot_text_map.keys()
1465
- and len(full_text_string) < self.SUGGESTION_CUTOFF_LENGTH
1466
- ):
1467
- msg = (
1468
- "Language: %s. BallotText is missing but FullText is present "
1469
- "for the same language. Please confirm that FullText contains "
1470
- "only supplementary text and not text on the ballot itself."
1471
- % (language)
1472
- )
1473
- raise loggers.ElectionWarning.from_message(msg, [element])
1474
-
1475
-
1476
- class BallotTitle(base.BaseRule):
1477
- """BallotTitle must exist and should usually be shorter than BallotText."""
1478
-
1479
- def elements(self):
1480
- return ["BallotMeasureContest"]
1481
-
1482
- def check(self, element):
1483
- ballot_title_map = rule_util.get_language_to_text_map(
1484
- element.find("BallotTitle")
1485
- )
1486
- if not ballot_title_map:
1487
- raise loggers.ElectionError.from_message(
1488
- "BallotMeasureContest is missing BallotTitle.", [element]
1489
- )
1490
-
1491
- ballot_text_map = rule_util.get_language_to_text_map(
1492
- element.find("BallotText")
1493
- )
1494
- if not ballot_text_map:
1495
- msg = (
1496
- "BallotText is missing. Please confirm that the ballot "
1497
- "text/question is not in BallotTitle."
1498
- )
1499
- raise loggers.ElectionWarning.from_message(msg, [element])
1500
-
1501
- for language, ballot_title_strings in ballot_title_map.items():
1502
- ballot_title_string = ballot_title_strings[0]
1503
- if language not in ballot_text_map.keys() or len(
1504
- ballot_text_map[language][0]
1505
- ) < len(ballot_title_string):
1506
- msg = (
1507
- "Language: %s. BallotText is missing or shorter than "
1508
- " Please confirm that the ballot text/question is not "
1509
- "in BallotTitle." % (language)
1510
- )
1511
- raise loggers.ElectionWarning.from_message(msg, [element])
1512
-
1513
-
1514
- class ImproperCandidateContest(base.TreeRule):
1515
- """Detect CandidateContest elements that should be a BallotMeasureContest."""
1516
-
1517
- _BALLOT_SELECTION_OPTIONS = frozenset({"yes", "no", "for", "against"})
1518
-
1519
- def _gather_contest_candidates(self, contest):
1520
- """Return candidate ids for given contest element."""
1521
- candidate_ids = []
1522
- cand_id_elems = contest.findall("BallotSelection//CandidateIds")
1523
- for cand_id_elem in cand_id_elems:
1524
- for cand_id in cand_id_elem.text.split():
1525
- candidate_ids.append(cand_id)
1526
- return candidate_ids
1527
-
1528
- def _gather_invalid_candidates(self):
1529
- """Return candidate ids that appear to be BallotMeasureSelections."""
1530
- invalid_candidates = []
1531
- candidates = self.get_elements_by_class(
1532
- self.election_tree, "CandidateCollection//Candidate"
1533
- )
1534
- for candidate in candidates:
1535
- ballot_name = candidate.find(".//BallotName/Text[@language='en']")
1536
- if ballot_name is not None:
1537
- if ballot_name.text.lower() in self._BALLOT_SELECTION_OPTIONS:
1538
- invalid_candidates.append(candidate.get("objectId"))
1539
- return invalid_candidates
1540
-
1541
- def check(self):
1542
- candidate_contest_mapping = {}
1543
- candidate_contests = self.get_elements_by_class(
1544
- self.election_tree, "CandidateContest"
1545
- )
1546
- for cc in candidate_contests:
1547
- cand_ids = self._gather_contest_candidates(cc)
1548
- contest_id = cc.get("objectId")
1549
- candidate_contest_mapping[contest_id] = cand_ids
1550
-
1551
- invalid_candidates = self._gather_invalid_candidates()
1552
-
1553
- warning_log = []
1554
- for contest_id, cand_ids in candidate_contest_mapping.items():
1555
- flagged_candidates = []
1556
- for cand_id in cand_ids:
1557
- if cand_id in invalid_candidates:
1558
- flagged_candidates.append(cand_id)
1559
- if flagged_candidates:
1560
- warning_message = (
1561
- "Candidates {} should be BallotMeasureSelection "
1562
- "elements. Similarly, Contest {} should be changed "
1563
- "to a BallotMeasureContest instead of a "
1564
- "CandidateContest."
1565
- ).format(", ".join(flagged_candidates), contest_id)
1566
- warning_log.append(loggers.LogEntry(warning_message))
1567
- if invalid_candidates:
1568
- warning_message = (
1569
- "There are CandidateContests that appear to be "
1570
- "BallotMeasureContests based on the "
1571
- "BallotName values."
1572
- )
1573
- raise loggers.ElectionWarning(warning_log)
1574
-
1575
-
1576
- class WinnerCountLimit(base.BaseRule):
1577
- """Number of winners must be less than or equal to NumberElected."""
1578
-
1579
- def setup(self):
1580
- self.candidate_post_election_status_by_object_id = (
1581
- self._get_candidate_post_election_status_by_object_id()
1582
- )
1583
-
1584
- def _get_candidate_post_election_status_by_object_id(self):
1585
- candidate_post_election_status_by_object_id = {}
1586
- candidates = self.get_elements_by_class(
1587
- self.election_tree, "CandidateCollection//Candidate"
1588
- )
1589
- for candidate in candidates:
1590
- object_id = candidate.get("objectId")
1591
- post_election_status = candidate.find("PostElectionStatus")
1592
- if object_id and rule_util.element_has_text(post_election_status):
1593
- candidate_post_election_status_by_object_id[object_id] = (
1594
- post_election_status.text.strip()
1595
- )
1596
- return candidate_post_election_status_by_object_id
1597
-
1598
- def elements(self):
1599
- return ["CandidateContest"]
1600
-
1601
- def check(self, element):
1602
- number_elected_element = element.find("NumberElected")
1603
- number_elected = (
1604
- int(number_elected_element.text)
1605
- if rule_util.element_has_text(number_elected_element)
1606
- else 1
1607
- )
1608
-
1609
- candidate_ids_elements = element.findall("BallotSelection//CandidateIds")
1610
- candidate_ids = set()
1611
- for candidate_ids_element in candidate_ids_elements:
1612
- if rule_util.element_has_text(candidate_ids_element):
1613
- candidate_ids.update(candidate_ids_element.text.split())
1614
-
1615
- winner_count = 0
1616
- for candidate_id in candidate_ids:
1617
- status = self.candidate_post_election_status_by_object_id.get(
1618
- candidate_id
1619
- )
1620
- if status in _WINNER_POST_ELECTION_STATUSES:
1621
- winner_count += 1
1622
-
1623
- if winner_count > number_elected:
1624
- raise loggers.ElectionError.from_message(
1625
- f"Contest {element.get('objectId')} has {winner_count} candidates"
1626
- " with PostElectionStatus of 'winner' or 'projected-winner',"
1627
- f" which exceeds NumberElected: {number_elected}.",
1628
- [element],
1629
- )
1630
-
1631
-
1632
- class SubsequentContestIdIsValidRelatedContest(base.DateRule):
1633
- """Check that SubsequentContests are valid.
1634
-
1635
- Conditions for a valid SubsequentContest:
1636
- - OfficeId, if present, must match the original contest.
1637
- - PrimaryPartyIds, if present, must match the original contest.
1638
- - EndDate, if present, must not be after EndDate of the original contest.
1639
- - ComposingContestIds must not contain the original contest.
1640
- """
1641
-
1642
- def elements(self):
1643
- return ["ElectionReport"]
1644
-
1645
- def check(self, election_report_element):
1646
- error_log = []
1647
- contest_by_id = {}
1648
- contest_end_date_by_id = {}
1649
-
1650
- for election in self.get_elements_by_class(
1651
- election_report_element, "Election"
1652
- ):
1653
- self.gather_dates(election)
1654
- election_end_date = self.end_date
1655
- for contest in self.get_elements_by_class(election, "Contest"):
1656
- self.reset_instance_vars()
1657
- self.gather_dates(contest)
1658
- contest_by_id[contest.get("objectId")] = contest
1659
- contest_end_date_by_id[contest.get("objectId")] = (
1660
- self.end_date or election_end_date
1661
- )
1662
-
1663
- for contest_id, contest in contest_by_id.items():
1664
- element = contest.find("SubsequentContestId")
1665
- if not rule_util.element_has_text(element):
1666
- continue
1667
- subsequent_contest_id = element.text.strip()
1668
-
1669
- # Check that subsequent contest exists
1670
- if subsequent_contest_id not in contest_by_id:
1671
- error_log.append(
1672
- loggers.LogEntry(
1673
- "Could not find SubsequentContest"
1674
- f" {subsequent_contest_id} referenced by Contest {contest_id}."
1675
- )
1676
- )
1677
- continue
1678
-
1679
- subsequent_contest = contest_by_id[subsequent_contest_id]
1680
- # Check that the subsequent contest has a later end date
1681
- if subsequent_contest is not None and contest is not None:
1682
- contest_end_date = contest_end_date_by_id[contest_id]
1683
- subsequent_contest_end_date = contest_end_date_by_id[
1684
- subsequent_contest_id
1685
- ]
1686
- if subsequent_contest_end_date < contest_end_date:
1687
- error_log.append(
1688
- loggers.LogEntry(
1689
- f"Contest {contest_id} references a subsequent contest with"
1690
- " an earlier end date.",
1691
- [contest],
1692
- [contest.sourceline],
1693
- )
1694
- )
1695
-
1696
- # Check that office ids match
1697
- contest_office_id = None
1698
- subsequent_contest_office_id = None
1699
- element = contest.find("OfficeIds")
1700
- if rule_util.element_has_text(element):
1701
- contest_office_id = element.text
1702
- element = subsequent_contest.find("OfficeIds")
1703
- if rule_util.element_has_text(element):
1704
- subsequent_contest_office_id = element.text
1705
-
1706
- if contest_office_id != subsequent_contest_office_id:
1707
- error_log.append(
1708
- loggers.LogEntry(
1709
- f"Contest {contest_id} references a subsequent contest with a"
1710
- " different office id.",
1711
- [contest],
1712
- [contest.sourceline],
1713
- )
1714
- )
1715
-
1716
- # Check that primary party ids match or that the subsequent contest does
1717
- # not have a primary party (e.g. primary -> general election)
1718
- contest_primary_party_ids = None
1719
- subsequent_contest_primary_party_ids = None
1720
- element = contest.find("PrimaryPartyIds")
1721
- if rule_util.element_has_text(element):
1722
- contest_primary_party_ids = set(element.text.split())
1723
- element = subsequent_contest.find("PrimaryPartyIds")
1724
- if rule_util.element_has_text(element):
1725
- subsequent_contest_primary_party_ids = set(element.text.split())
1726
-
1727
- if (
1728
- subsequent_contest_primary_party_ids is not None
1729
- and contest_primary_party_ids != subsequent_contest_primary_party_ids
1730
- ):
1731
- error_log.append(
1732
- loggers.LogEntry(
1733
- "Contest %s references a subsequent contest with different "
1734
- "primary party ids." % contest_id,
1735
- [contest],
1736
- [contest.sourceline],
1737
- )
1738
- )
1739
-
1740
- # Check that there is not a subsequent contest <-> composing contest loop
1741
- element = subsequent_contest.find("ComposingContestIds")
1742
- if rule_util.element_has_text(element):
1743
- subsequent_composing_ids = element.text.split()
1744
- if contest_id in subsequent_composing_ids:
1745
- error_log.append(
1746
- loggers.LogEntry(
1747
- f"Contest {contest_id} is listed as a composing contest for"
1748
- " its subsequent contest. Two contests can be linked by"
1749
- " SubsequentContestId or ComposingContestId, but not both.",
1750
- [contest],
1751
- [contest.sourceline],
1752
- )
1753
- )
1754
-
1755
- if error_log:
1756
- raise loggers.ElectionError(error_log)
1757
-
1758
-
1759
- class ComposingContestIdsAreValidRelatedContests(base.BaseRule):
1760
- """Check that ComposingContestIds are valid.
1761
-
1762
- Conditions for a valid ComposingContest:
1763
- - OfficeId, if present, must match the parent contest.
1764
- - PrimaryPartyIds, if present, must match the parent contest.
1765
- - ComposingContests must not be referenced by more than one parent contest.
1766
- - ComposingContests must not reference each other.
1767
- """
1768
-
1769
- def elements(self):
1770
- return ["ElectionReport"]
1771
-
1772
- def check(self, election_report_element):
1773
- error_log = []
1774
-
1775
- contests = self.get_elements_by_class(election_report_element, "Contest")
1776
- contest_ids = {cc.get("objectId"): cc for cc in contests}
1777
- composing_contests = {}
1778
- for contest_id, contest in contest_ids.items():
1779
- element = contest.find("ComposingContestIds")
1780
- if not rule_util.element_has_text(element):
1781
- continue
1782
- composing_contests[contest_id] = element.text.split()
1783
-
1784
- # Check for composing contests that appear more than once
1785
- unique_contests = set()
1786
- for contest_list in composing_contests.values():
1787
- for contest_id in contest_list:
1788
- if contest_id not in unique_contests:
1789
- unique_contests.add(contest_id)
1790
- else:
1791
- error_log.append(
1792
- loggers.LogEntry(
1793
- "Contest %s is listed as a ComposingContest for more "
1794
- "than one parent contest. ComposingContests should be a "
1795
- "strict hierarchy." % contest_id
1796
- )
1797
- )
1798
-
1799
- for contest_id, composing_contest_ids in composing_contests.items():
1800
- contest = contest_ids[contest_id]
1801
- for cc_id in composing_contest_ids:
1802
- # Check that the composing contests exist
1803
- if cc_id not in contest_ids.keys():
1804
- error_log.append(
1805
- loggers.LogEntry(
1806
- "Could not find ComposingContest % referenced by Contest %s."
1807
- % (contest_id, cc_id)
1808
- )
1809
- )
1810
- continue
1811
-
1812
- composing_contest = contest_ids[cc_id]
1813
- # Check that the office ids match
1814
- c_office_id = None
1815
- cc_office_id = None
1816
- element = contest.find("OfficeIds")
1817
- if rule_util.element_has_text(element):
1818
- c_office_id = element.text
1819
- element = composing_contest.find("OfficeIds")
1820
- if rule_util.element_has_text(element):
1821
- cc_office_id = element.text
1822
-
1823
- if c_office_id != cc_office_id:
1824
- error_log.append(
1825
- loggers.LogEntry(
1826
- "Contest %s and composing contest %s have different office "
1827
- "ids." % (contest_id, cc_id)
1828
- )
1829
- )
1830
-
1831
- # Check that primary party ids match
1832
- c_primary_party_ids = None
1833
- cc_primary_party_ids = None
1834
- element = contest.find("PrimaryPartyIds")
1835
- if rule_util.element_has_text(element):
1836
- c_primary_party_ids = set(element.text.split())
1837
- element = composing_contest.find("PrimaryPartyIds")
1838
- if rule_util.element_has_text(element):
1839
- cc_primary_party_ids = set(element.text.split())
1840
-
1841
- if c_primary_party_ids != cc_primary_party_ids:
1842
- error_log.append(
1843
- loggers.LogEntry(
1844
- "Contest %s and composing contest %s have different primary "
1845
- "party ids." % (contest_id, cc_id)
1846
- )
1847
- )
1848
-
1849
- # Check that composing contests don't reference each other
1850
- if (
1851
- cc_id in composing_contests
1852
- and contest_id in composing_contests[cc_id]
1853
- ):
1854
- error_log.append(
1855
- loggers.LogEntry(
1856
- "Contest %s and contest %s reference each other as composing "
1857
- "contests." % (contest_id, cc_id)
1858
- )
1859
- )
1860
-
1861
- if error_log:
1862
- raise loggers.ElectionError(error_log)
1863
-
1864
-
1865
- class MultipleInternationalizedTextWithSameLanguageCode(base.BaseRule):
1866
- """Checks for multiple InternationalizedText with the same language code."""
1867
-
1868
- def elements(self):
1869
- return _INTERNATIONALIZED_TEXT_ELEMENTS_WITH_ONLY_ONE_TEXT_PER_LANGUAGE
1870
-
1871
- def check(self, element):
1872
- language_map = rule_util.get_language_to_text_map(element)
1873
-
1874
- for language, texts in language_map.items():
1875
- if len(texts) > 1:
1876
- raise loggers.ElectionError.from_message(
1877
- 'Multiple "%s" texts found for "%s"' % (language, texts[0].strip())
1878
- )
1879
-
1880
-
1881
- class ContestContainsValidStartDate(base.DateRule):
1882
- """Contest elements should contain valid start dates.
1883
-
1884
- A warning will be raised for start dates in the past. These dates are still
1885
- valid because the validator could be run during an ongoing election.
1886
- """
1887
-
1888
- def elements(self):
1889
- return ["Contest"]
1890
-
1891
- def check(self, element):
1892
- self.reset_instance_vars()
1893
- self.gather_dates(element)
1894
-
1895
- if self.start_date:
1896
- self.check_for_date_not_in_past(self.start_date, self.start_elem)
1897
-
1898
- if self.error_log:
1899
- raise loggers.ElectionWarning(self.error_log)
1900
-
1901
-
1902
- class ContestContainsValidEndDate(base.DateRule):
1903
- """Contest elements should contain valid end dates.
1904
-
1905
- A warning will be raised for end dates in the past. These dates are still
1906
- valid because the validator could be run during an ongoing election.
1907
- """
1908
-
1909
- def elements(self):
1910
- return ["Contest"]
1911
-
1912
- def check(self, element):
1913
- self.reset_instance_vars()
1914
- self.gather_dates(element)
1915
-
1916
- if self.end_date:
1917
- self.check_for_date_not_in_past(self.end_date, self.end_elem)
1918
-
1919
- if self.error_log:
1920
- raise loggers.ElectionWarning(self.error_log)
1921
-
1922
-
1923
- class ContestEndDateOccursAfterStartDate(base.DateRule):
1924
- """Contest elements should have end dates that occur after the start dates."""
1925
-
1926
- def elements(self):
1927
- return ["Contest"]
1928
-
1929
- def check(self, element):
1930
- self.reset_instance_vars()
1931
- self.gather_dates(element)
1932
-
1933
- if self.end_date and self.start_date:
1934
- self.check_end_after_start()
1935
- if self.error_log:
1936
- raise loggers.ElectionError(self.error_log)
1937
-
1938
-
1939
- class ContestEndDateOccursBeforeSubsequentContestStartDate(base.DateRule):
1940
- """Contest end dates should occur before subsequent contest start dates.
1941
-
1942
- This rule will trigger if a Contest has a valid Subsequent Contest and both
1943
- Contests have dates.
1944
- """
1945
-
1946
- def elements(self):
1947
- return ["ElectionReport"]
1948
-
1949
- def check(self, election_report_element):
1950
- contest_by_contest_id = {}
1951
- dates_by_contest_id = {}
1952
-
1953
- for election in self.get_elements_by_class(
1954
- election_report_element, "Election"
1955
- ):
1956
- for contest in self.get_elements_by_class(election, "Contest"):
1957
- contest_id = contest.get("objectId")
1958
- self.reset_instance_vars()
1959
- self.gather_dates(contest)
1960
- contest_by_contest_id[contest_id] = contest
1961
- dates_by_contest_id[contest_id] = (self.start_date, self.end_date)
1962
-
1963
- for contest_id, contest in contest_by_contest_id.items():
1964
- # ignore contests that don't have a subsequent contest
1965
- subsequent_element = contest.find("SubsequentContestId")
1966
- if not rule_util.element_has_text(subsequent_element):
1967
- continue
1968
- # ignore invalid subsequent contest ids
1969
- subsequent_contest_id = subsequent_element.text.strip()
1970
- if subsequent_contest_id not in contest_by_contest_id:
1971
- continue
1972
- # compare contest end date with subsequent contest start date
1973
- _, contest_end = dates_by_contest_id[contest_id]
1974
- subsequent_contest_start, _ = dates_by_contest_id[subsequent_contest_id]
1975
- if contest_end is not None and subsequent_contest_start is not None:
1976
- if subsequent_contest_start < contest_end:
1977
- self.error_log.append(
1978
- loggers.LogEntry(
1979
- "Contest {} with end date {} does not occur before"
1980
- " subsequent contest {} with start date {}".format(
1981
- contest_id,
1982
- contest_end,
1983
- subsequent_contest_id,
1984
- subsequent_contest_start,
1985
- )
1986
- )
1987
- )
1988
-
1989
- if self.error_log:
1990
- raise loggers.ElectionError(self.error_log)
1991
-
1992
-
1993
- class ContestStartDateContainsCorrespondingEndDate(base.DateRule):
1994
- """Contest start dates must always have corresponding end dates.
1995
-
1996
- A Contest can either have both StartDate and EndDate populated or neither at
1997
- all.
1998
- """
1999
-
2000
- def elements(self):
2001
- return ["Contest"]
2002
-
2003
- def check(self, element):
2004
- self.reset_instance_vars()
2005
- self.gather_dates(element)
2006
-
2007
- if self.start_elem is None and self.end_elem is not None:
2008
- raise loggers.ElectionError.from_message(
2009
- "Contest has an EndDate but is missing a StartDate. Every EndDate"
2010
- " must have a corresponding StartDate.",
2011
- [element],
2012
- )
2013
-
2014
- if self.start_elem is not None and self.end_elem is None:
2015
- raise loggers.ElectionError.from_message(
2016
- "Contest has a StartDate but is missing an EndDate. Every StartDate"
2017
- " must have a corresponding EndDate.",
2018
- [element],
2019
- )
2020
-
2021
-
2022
- class ValidatePollsCloseDatetimes(base.BaseRule):
2023
- """Checks that LatestPollsClose is not before EarliestPollsClose."""
2024
-
2025
- def elements(self):
2026
- return ["Contest"]
2027
-
2028
- def check(self, element):
2029
- earliest_polls_close_element = element.find("EarliestPollsClose")
2030
- latest_polls_close_element = element.find("LatestPollsClose")
2031
-
2032
- if not rule_util.element_has_text(
2033
- earliest_polls_close_element
2034
- ) or not rule_util.element_has_text(latest_polls_close_element):
2035
- return
2036
-
2037
- earliest_polls_close_text = earliest_polls_close_element.text.strip()
2038
- latest_polls_close_text = latest_polls_close_element.text.strip()
2039
32
 
2040
- try:
2041
- earliest_polls_close = datetime.datetime.fromisoformat(
2042
- earliest_polls_close_text
2043
- )
2044
- latest_polls_close = datetime.datetime.fromisoformat(
2045
- latest_polls_close_text
2046
- )
2047
-
2048
- if latest_polls_close < earliest_polls_close:
2049
- raise loggers.ElectionError.from_message(
2050
- f"LatestPollsClose ({latest_polls_close_text}) must not be before"
2051
- f" EarliestPollsClose ({earliest_polls_close_text}) for Contest"
2052
- f" {element.get('objectId')}.",
2053
- [element],
2054
- )
2055
- except ValueError as e:
2056
- raise loggers.ElectionError.from_message(
2057
- "Invalid PollsClose datetime format in Contest"
2058
- f" {element.get('objectId')}: {e}",
2059
- [element],
2060
- )
2061
-
2062
-
2063
- class ValidateResultsExpected(base.BaseRule):
2064
- """Checks that ResultsExpected is not before the first ResultsReportingStage.
2065
-
2066
- The ResultsExpected datetime must not be before the ExpectedStartDateTime
2067
- of the earliest ResultsReportingStage excluding the no-results stage.
2068
- """
2069
-
2070
- def elements(self):
2071
- return ["Contest"]
2072
-
2073
- def check(self, element):
2074
- results_expected_element = element.find("ResultsExpected")
2075
- if not rule_util.element_has_text(results_expected_element):
2076
- return
2077
-
2078
- results_expected_text = results_expected_element.text.strip()
2079
-
2080
- try:
2081
- results_expected = datetime.datetime.fromisoformat(results_expected_text)
2082
- except ValueError as e:
2083
- raise loggers.ElectionError.from_message(
2084
- "Invalid ResultsExpected datetime format in Contest"
2085
- f" {element.get('objectId')}: {e}",
2086
- [element],
2087
- )
2088
-
2089
- stage_collection = element.find("ResultsReportingStageCollection")
2090
- if stage_collection is None:
2091
- return
2092
-
2093
- earliest_start = None
2094
- earliest_start_text = None
2095
- for stage in stage_collection.findall("ResultsReportingStage"):
2096
- stage_type_element = stage.find("StageType")
2097
- if (
2098
- rule_util.element_has_text(stage_type_element)
2099
- and stage_type_element.text.strip() == "no-results"
2100
- ):
2101
- continue
2102
-
2103
- start_element = stage.find("ExpectedStartDateTime")
2104
- if not rule_util.element_has_text(start_element):
2105
- continue
2106
-
2107
- start_text = start_element.text.strip()
2108
- try:
2109
- start = datetime.datetime.fromisoformat(start_text)
2110
- if earliest_start is None or start < earliest_start:
2111
- earliest_start = start
2112
- earliest_start_text = start_text
2113
- except ValueError as e:
2114
- raise loggers.ElectionError.from_message(
2115
- "Invalid ExpectedStartDateTime datetime format for the"
2116
- f" '{stage_type_element.text.strip()}' ResultsReportingStage in"
2117
- f" Contest {element.get('objectId')}: {e}",
2118
- [element],
2119
- )
2120
-
2121
- if earliest_start and results_expected < earliest_start:
2122
- raise loggers.ElectionError.from_message(
2123
- f"ResultsExpected ({results_expected_text}) must not be before the"
2124
- f" ExpectedStartDateTime ({earliest_start_text}) of the earliest"
2125
- f" ResultsReportingStage for Contest {element.get('objectId')}.",
2126
- [element],
2127
- )
2128
-
2129
-
2130
- class ValidateResultsEmbargoEnd(base.BaseRule):
2131
- """Checks that ResultsEmbargoEnd is not after the official ResultsReportingStage start."""
2132
-
2133
- def elements(self):
2134
- return ["Contest"]
2135
-
2136
- def check(self, element):
2137
- results_embargo_end_element = element.find("ResultsEmbargoEnd")
2138
- if not rule_util.element_has_text(results_embargo_end_element):
2139
- return
2140
-
2141
- results_embargo_end_text = results_embargo_end_element.text.strip()
2142
-
2143
- try:
2144
- results_embargo_end = datetime.datetime.fromisoformat(
2145
- results_embargo_end_text
2146
- )
2147
- except ValueError as e:
2148
- raise loggers.ElectionError.from_message(
2149
- "Invalid ResultsEmbargoEnd datetime format in Contest"
2150
- f" {element.get('objectId')}: {e}",
2151
- [element],
2152
- )
2153
-
2154
- stage_collection = element.find("ResultsReportingStageCollection")
2155
- if stage_collection is None:
2156
- return
2157
-
2158
- official_start = None
2159
- official_start_text = None
2160
- for stage in stage_collection.findall("ResultsReportingStage"):
2161
- stage_type_element = stage.find("StageType")
2162
- if (
2163
- rule_util.element_has_text(stage_type_element)
2164
- and stage_type_element.text.strip() == "official"
2165
- ):
2166
- start_element = stage.find("ExpectedStartDateTime")
2167
- if not rule_util.element_has_text(start_element):
2168
- continue
2169
-
2170
- start_text = start_element.text.strip()
2171
- try:
2172
- official_start = datetime.datetime.fromisoformat(start_text)
2173
- official_start_text = start_text
2174
- break
2175
- except ValueError as e:
2176
- raise loggers.ElectionError.from_message(
2177
- "Invalid ExpectedStartDateTime datetime format for the"
2178
- " 'official' ResultsReportingStage in Contest"
2179
- f" {element.get('objectId')}: {e}",
2180
- [element],
2181
- )
2182
-
2183
- if official_start and official_start < results_embargo_end:
2184
- raise loggers.ElectionError.from_message(
2185
- f"ResultsEmbargoEnd ({results_embargo_end_text}) must not be after"
2186
- f" the ExpectedStartDateTime ({official_start_text}) of the official"
2187
- f" ResultsReportingStage for Contest {element.get('objectId')}.",
2188
- [element],
2189
- )
2190
-
2191
-
2192
- class ResultsReportingStagesMustHaveUniqueType(base.BaseRule):
2193
- """Checks that each ResultsReportingStage has a unique StageType per Contest."""
2194
-
2195
- def elements(self):
2196
- return ["ResultsReportingStageCollection"]
2197
-
2198
- def check(self, element):
2199
- stages_by_type = collections.defaultdict(list)
2200
- for stage in element.findall("ResultsReportingStage"):
2201
- stage_type_element = stage.find("StageType")
2202
- if rule_util.element_has_text(stage_type_element):
2203
- stage_type = stage_type_element.text.strip()
2204
- stages_by_type[stage_type].append(stage)
2205
-
2206
- errors = []
2207
- for stage_type, stages in stages_by_type.items():
2208
- if len(stages) > 1:
2209
- errors.append(
2210
- loggers.LogEntry(
2211
- f"Duplicate ResultsReportingStage StageType '{stage_type}'"
2212
- " found in the same ResultsReportingStageCollection.",
2213
- stages,
2214
- )
2215
- )
2216
- if errors:
2217
- raise loggers.ElectionError(errors)
2218
-
2219
-
2220
- class ValidateResultReportingStages(base.BaseRule):
2221
- """Validates ResultsReportingStage elements in a stage collection."""
2222
-
2223
- def setup(self):
2224
- self.composing_contest_ids = self._get_composing_contest_ids()
2225
-
2226
- def _get_composing_contest_ids(self):
2227
- composing_contest_ids = set()
2228
- for contest in self.get_elements_by_class(self.election_tree, "Contest"):
2229
- composing_contest_ids_element = contest.find("ComposingContestIds")
2230
- if rule_util.element_has_text(composing_contest_ids_element):
2231
- composing_contest_ids.update(composing_contest_ids_element.text.split())
2232
- return composing_contest_ids
2233
-
2234
- def elements(self):
2235
- return ["ResultsReportingStageCollection"]
2236
-
2237
- def check(self, element):
2238
- inherit_from_composed = rule_util.is_xml_true(
2239
- element.find("InheritFromComposedContest")
2240
- )
2241
- stages = element.findall("ResultsReportingStage")
2242
-
2243
- if inherit_from_composed:
2244
- error_log = []
2245
- if stages:
2246
- error_log.append(
2247
- loggers.LogEntry(
2248
- "ResultsReportingStageCollection must not contain any"
2249
- " ResultsReportingStage elements when"
2250
- " InheritFromComposedContest is true.",
2251
- [element],
2252
- )
2253
- )
2254
- contest = element.getparent()
2255
- contest_id = contest.get("objectId") if contest is not None else None
2256
- if contest_id not in self.composing_contest_ids:
2257
- error_log.append(
2258
- loggers.LogEntry(
2259
- f"Contest {contest_id} sets InheritFromComposedContest to"
2260
- " true but is not listed in the ComposingContestIds of any"
2261
- " other Contest.",
2262
- [contest],
2263
- )
2264
- )
2265
- if error_log:
2266
- raise loggers.ElectionError(error_log)
2267
- return
2268
-
2269
- if not stages:
2270
- raise loggers.ElectionError.from_message(
2271
- "ResultsReportingStageCollection must contain at least one"
2272
- " ResultsReportingStage element when InheritFromComposedContest is"
2273
- " not true.",
2274
- [element],
2275
- )
2276
33
 
2277
- stage_types = set()
2278
- for stage in stages:
2279
- stage_type_element = stage.find("StageType")
2280
- if rule_util.element_has_text(stage_type_element):
2281
- stage_types.add(stage_type_element.text.strip())
2282
-
2283
- if (
2284
- len(stages) < 2
2285
- or "no-results" not in stage_types
2286
- or stage_types.isdisjoint({"preliminary", "official"})
2287
- ):
2288
- raise loggers.ElectionWarning.from_message(
2289
- "ResultsReportingStageCollection should contain at least two"
2290
- " ResultsReportingStage elements, including one of StageType"
2291
- " 'no-results' and at least one of StageType 'preliminary' or"
2292
- " 'official', when InheritFromComposedContest is not true.",
2293
- [element],
2294
- )
2295
-
2296
-
2297
- class CandidateContestTypesAreCompatible(base.BaseRule):
2298
- """CandidateContest Type values cannot have both a general and primary type."""
2299
-
2300
- def elements(self):
2301
- return ["CandidateContest"]
2302
-
2303
- def check(self, element):
2304
- primary_types = {
2305
- "primary",
2306
- "partisan-primary-open",
2307
- "partisan-primary-closed",
2308
- }
2309
- contest_type_elements = element.findall("Type")
2310
- if contest_type_elements:
2311
- contest_types = {
2312
- type_element.text.strip().lower()
2313
- for type_element in contest_type_elements
2314
- if rule_util.element_has_text(type_element)
2315
- }
2316
- if "general" in contest_types and primary_types.intersection(
2317
- contest_types
2318
- ):
2319
- raise loggers.ElectionError.from_message(
2320
- "CandidateContest {} has incompatible type values. A contest cannot"
2321
- " have both a general and primary type.".format(
2322
- element.get("objectId")
2323
- ),
2324
- [element],
2325
- )
34
+ _VALID_FEED_LONGEVITY_BY_FEED_TYPE = frozendict({
35
+ "committee": ["evergreen"],
36
+ "election-dates": ["evergreen"],
37
+ "election-results": ["limited"],
38
+ "officeholder": ["evergreen"],
39
+ "pre-election": ["limited", "yearly"],
40
+ })
2326
41
 
2327
42
 
2328
43
  class CommitteeClassificationEndDateOccursAfterStartDate(base.DateRule):
@@ -2775,22 +490,6 @@ class FeedInactiveDateSetForNonEvergreenFeed(base.BaseRule):
2775
490
  )
2776
491
 
2777
492
 
2778
- class UnreferencedEntitiesElectionDates(common_rules.UnreferencedEntitiesBase):
2779
- """CDF elections and contests are top-level in election dates feeds.
2780
-
2781
- All other entity types must be referenced.
2782
- """
2783
-
2784
- def __init__(self, election_tree, schema_tree, **kwargs):
2785
- super(UnreferencedEntitiesElectionDates, self).__init__(
2786
- election_tree,
2787
- schema_tree,
2788
- frozenset(["Election", "Contest"]),
2789
- frozenset([]),
2790
- **kwargs,
2791
- )
2792
-
2793
-
2794
493
  class ElectoralCommissionCollectionExists(base.BaseRule):
2795
494
  """ElectoralCommissionCollection should exist."""
2796
495
 
@@ -2942,235 +641,6 @@ class FeedElementsShouldHaveSubElementsBasedOnType(base.BaseRule):
2942
641
  )
2943
642
 
2944
643
 
2945
- class NotEmptyUniqueDataSourceUris(base.BaseRule):
2946
- """Checks that DataSource entities have globally unique URIs and they are not empty."""
2947
-
2948
- def elements(self):
2949
- return ["DataSourceCollection"]
2950
-
2951
- def check(self, element):
2952
- data_source_ids_by_uri = collections.defaultdict(set)
2953
- error_log = []
2954
-
2955
- for data_source in element.findall("DataSource"):
2956
- datasource_id = data_source.get("objectId")
2957
- for uri_element in data_source.findall("Uri"):
2958
- if not rule_util.element_has_text(uri_element):
2959
- error_log.append(
2960
- loggers.LogEntry(
2961
- "DataSource {} has an empty Uri.".format(datasource_id),
2962
- [data_source],
2963
- )
2964
- )
2965
- continue
2966
- uri = uri_element.text.strip()
2967
- data_source_ids_by_uri[uri].add(data_source)
2968
-
2969
- for uri, data_sources in data_source_ids_by_uri.items():
2970
- if len(data_sources) <= 1:
2971
- continue
2972
- sorted_data_sources = sorted(
2973
- data_sources, key=lambda ds: ds.get("objectId")
2974
- )
2975
- data_source_ids = [
2976
- data_source.get("objectId") for data_source in sorted_data_sources
2977
- ]
2978
- error_log.append(
2979
- loggers.LogEntry(
2980
- "DataSource entities {} have duplicate Uri '{}'.".format(
2981
- ", ".join(data_source_ids), uri
2982
- ),
2983
- sorted_data_sources,
2984
- )
2985
- )
2986
-
2987
- if error_log:
2988
- raise loggers.ElectionError(error_log)
2989
-
2990
-
2991
- class UniqueDataSourceLanguages(base.BaseRule):
2992
- """Checks that Uri elements have unique languages within a DataSource."""
2993
-
2994
- def elements(self):
2995
- return ["DataSourceCollection"]
2996
-
2997
- def check(self, element):
2998
- error_log = []
2999
-
3000
- for data_source in element.findall("DataSource"):
3001
- data_source_id = data_source.get("objectId")
3002
- seen_uri_languages = set()
3003
- for uri_element in data_source.findall("Uri"):
3004
- language = uri_element.get("language")
3005
- if not language:
3006
- error_log.append(
3007
- loggers.LogEntry(
3008
- "DataSource {} has a Uri element without a language.".format(
3009
- data_source_id
3010
- ),
3011
- [uri_element],
3012
- )
3013
- )
3014
- continue
3015
- language = language.strip()
3016
- if language in seen_uri_languages:
3017
- error_log.append(
3018
- loggers.LogEntry(
3019
- "DataSource {} has multiple Uri elements with the same"
3020
- " language '{}'.".format(data_source_id, language),
3021
- [element],
3022
- )
3023
- )
3024
- else:
3025
- seen_uri_languages.add(language)
3026
-
3027
- if error_log:
3028
- raise loggers.ElectionError(error_log)
3029
-
3030
-
3031
- class UniqueDataSourceDisplayNames(base.BaseRule):
3032
- """Checks that DataSource entities have globally unique DisplayNames."""
3033
-
3034
- def elements(self):
3035
- return ["DataSourceCollection"]
3036
-
3037
- def check(self, element):
3038
- data_source_ids_by_name = collections.defaultdict(set)
3039
- error_log = []
3040
-
3041
- for data_source in element.findall("DataSource"):
3042
- data_source_id = data_source.get("objectId")
3043
- display_name_element = data_source.find("DisplayName")
3044
- for text_element in display_name_element.findall("Text"):
3045
- if not rule_util.element_has_text(text_element):
3046
- error_log.append(
3047
- loggers.LogEntry(
3048
- "DataSource {} has a DisplayName element without"
3049
- " text.".format(data_source_id),
3050
- [data_source],
3051
- )
3052
- )
3053
- continue
3054
- name_text = text_element.text.strip()
3055
- data_source_ids_by_name[name_text].add(data_source)
3056
-
3057
- for name_text, data_sources in data_source_ids_by_name.items():
3058
- if len(data_sources) <= 1:
3059
- continue
3060
- sorted_data_sources = sorted(
3061
- data_sources, key=lambda ds: ds.get("objectId")
3062
- )
3063
- datasource_ids = [ds.get("objectId") for ds in sorted_data_sources]
3064
- error_log.append(
3065
- loggers.LogEntry(
3066
- "DataSource entities {} have duplicate DisplayName '{}'.".format(
3067
- ", ".join(datasource_ids), name_text
3068
- ),
3069
- sorted_data_sources,
3070
- )
3071
- )
3072
-
3073
- if error_log:
3074
- raise loggers.ElectionError(error_log)
3075
-
3076
-
3077
- def _get_attribution_depth(element):
3078
- """Helper to recursively get the maximum depth of an Attribution tree."""
3079
- children = element.findall("Attribution")
3080
- if not children:
3081
- return 1
3082
- return 1 + max(_get_attribution_depth(child) for child in children)
3083
-
3084
-
3085
- def _get_datasource_id(element):
3086
- """Helper to safely extract and strip the text of the DataSourceId child."""
3087
- ds_element = element.find("DataSourceId")
3088
- return (
3089
- ds_element.text.strip() if rule_util.element_has_text(ds_element) else ""
3090
- )
3091
-
3092
-
3093
- class AttributionDepthLimit(base.BaseRule):
3094
- """Checks that each top-level Attribution in a ResultsReportingStage has at most three levels of depth."""
3095
-
3096
- def elements(self):
3097
- return ["ResultsReportingStage"]
3098
-
3099
- def check(self, element):
3100
- error_log = []
3101
- # This findall query is non-recursive and only returns direct children.
3102
- for attribution in element.findall("Attribution"):
3103
- depth = _get_attribution_depth(attribution)
3104
- if depth > 3:
3105
- data_source_id = _get_datasource_id(attribution)
3106
- error_log.append(
3107
- loggers.LogEntry(
3108
- f"Attribution starting with DataSourceId '{data_source_id}'"
3109
- f" has a depth of {depth}, exceeding the limit of 3.",
3110
- [attribution],
3111
- )
3112
- )
3113
- if error_log:
3114
- raise loggers.ElectionError(error_log)
3115
-
3116
-
3117
- def _canonicalize_cycle(cycle):
3118
- """Canonicalizes a cycle by rotating it to start with the min element."""
3119
- if not cycle:
3120
- return []
3121
- min_node = min(cycle)
3122
- min_idx = cycle.index(min_node)
3123
- return cycle[min_idx:] + cycle[:min_idx]
3124
-
3125
-
3126
- class AttributionContainsNoCycles(base.TreeRule):
3127
- """Checks that there are no cycles between Attribution elements."""
3128
-
3129
- def check(self):
3130
- graph = networkx.DiGraph()
3131
-
3132
- attributions = self.get_elements_by_class(self.election_tree, "Attribution")
3133
- for attribution in attributions:
3134
- data_source = _get_datasource_id(attribution)
3135
- if not data_source:
3136
- continue
3137
- graph.add_node(data_source)
3138
- for child in attribution.findall("Attribution"):
3139
- child_data_source = _get_datasource_id(child)
3140
- if child_data_source:
3141
- graph.add_edge(data_source, child_data_source)
3142
-
3143
- # Find all nodes in the graph that are part of a cycle based on directed
3144
- # paths.
3145
- nodes_in_a_cycle = set()
3146
- for component in networkx.strongly_connected_components(graph):
3147
- # If the component has multiple nodes, it must be a cycle.
3148
- if len(component) > 1:
3149
- nodes_in_a_cycle.update(component)
3150
- continue
3151
- # Only include single-node components if they have a self-loop.
3152
- (node,) = component
3153
- if graph.has_edge(node, node):
3154
- nodes_in_a_cycle.add(node)
3155
-
3156
- if not nodes_in_a_cycle:
3157
- return
3158
-
3159
- error_log = []
3160
- # Optimize performance for large graphs by excluding non-cyclic nodes.
3161
- all_cycles_subgraph = graph.subgraph(sorted(nodes_in_a_cycle))
3162
- for cycle in networkx.simple_cycles(all_cycles_subgraph):
3163
- canonical = _canonicalize_cycle(cycle)
3164
- # Append the starting node to the end to represent a closed loop.
3165
- error_log.append(
3166
- loggers.LogEntry(
3167
- f"Cycle detected in Attribution: {' -> '.join(canonical)} ->"
3168
- f" {canonical[0]}"
3169
- )
3170
- )
3171
- raise loggers.ElectionError(error_log)
3172
-
3173
-
3174
644
  class RuleSet(enum.Enum):
3175
645
  """Names for sets of rules used to validate a particular feed type."""
3176
646
 
@@ -3183,207 +653,12 @@ class RuleSet(enum.Enum):
3183
653
  VOTER_INFORMATION = 7
3184
654
 
3185
655
 
3186
- class ValidateSpecialBallotSelectionCountedInTotal(base.BaseRule):
3187
- """Enforces constraints on CountedInTotal for SpecialBallotSelections.
3188
-
3189
- More specifically, BlankBallotSelection, NullBallotSelection, and
3190
- NoneOfTheAboveSelection must have an explicit value for CountedInTotal, and
3191
- AggregateBallotSelection must not have this set.
3192
- """
3193
-
3194
- def elements(self):
3195
- return [
3196
- "BlankBallotSelection",
3197
- "NullBallotSelection",
3198
- "NoneOfTheAboveBallotSelection",
3199
- "AggregateBallotSelection",
3200
- ]
3201
-
3202
- def check(self, element):
3203
- counted_in_total = element.find("CountedInTotal")
3204
- tag = element.tag
3205
-
3206
- if tag in (
3207
- "BlankBallotSelection",
3208
- "NullBallotSelection",
3209
- "NoneOfTheAboveBallotSelection",
3210
- ) and not rule_util.element_has_text(counted_in_total):
3211
- raise loggers.ElectionError.from_message(
3212
- f"{tag} must have an explicit value for CountedInTotal.",
3213
- [element],
3214
- )
3215
- elif tag == "AggregateBallotSelection" and counted_in_total is not None:
3216
- raise loggers.ElectionError.from_message(
3217
- "AggregateBallotSelection must not have CountedInTotal set.",
3218
- [element],
3219
- )
3220
-
3221
-
3222
- class ValidateIncludeInAggregationBallotSelections(base.BaseRule):
3223
- """Validates BallotSelections with IncludedInAggregation.
3224
-
3225
- Checks that the sum of all vote counts for a BallotSelection with
3226
- IncludedInAggregation must not be > the total vote counts for the
3227
- AggregateBallotSelection on that same Contest for the same vote count type.
3228
- Also requires that if IncludedInAggregation is set on any BallotSelection then
3229
- the AggregateBallotSelection must also be present on that Contest.
3230
- """
3231
-
3232
- def elements(self):
3233
- return ["CandidateContest", "PartyContest"]
3234
-
3235
- def _gather_vote_counts(self, element):
3236
- """Gathers vote counts from a selection element grouped by type."""
3237
- count_by_type_and_gp_unit = collections.defaultdict(float)
3238
- vote_counts_collection = element.find("VoteCountsCollection")
3239
- if vote_counts_collection is None:
3240
- return count_by_type_and_gp_unit
3241
-
3242
- for vote_counts in vote_counts_collection.findall("VoteCounts"):
3243
- count_element = vote_counts.find("Count")
3244
- if not rule_util.element_has_text(count_element):
3245
- continue
3246
- count = float(count_element.text)
3247
-
3248
- vote_count_type = _get_type_or_other_type(vote_counts)
3249
- gp_unit_id_element = vote_counts.find("GpUnitId")
3250
- gp_unit_id = (
3251
- gp_unit_id_element.text.strip()
3252
- if rule_util.element_has_text(gp_unit_id_element)
3253
- else ""
3254
- )
3255
-
3256
- type_and_gp_unit = (vote_count_type, gp_unit_id)
3257
- count_by_type_and_gp_unit[type_and_gp_unit] += count
3258
-
3259
- return count_by_type_and_gp_unit
3260
-
3261
- def check(self, element):
3262
- contest_id = element.get("objectId")
3263
-
3264
- candidate_selections = self.get_elements_by_class(
3265
- element, "CandidateSelection"
3266
- )
3267
- party_selections = self.get_elements_by_class(element, "PartySelection")
3268
- all_selections = candidate_selections + party_selections
3269
-
3270
- included_selections = []
3271
- for selection in all_selections:
3272
- if rule_util.is_xml_true(selection.find("IncludedInAggregation")):
3273
- included_selections.append(selection)
3274
- if not included_selections:
3275
- return
3276
-
3277
- aggregate_selection = element.find("AggregateBallotSelection")
3278
- if aggregate_selection is None:
3279
- raise loggers.ElectionError.from_message(
3280
- f"Contest {contest_id} has selections marked as IncludedInAggregation"
3281
- " but is missing AggregateBallotSelection.",
3282
- [element],
3283
- )
3284
-
3285
- aggregate_count_by_type_and_gp_unit = self._gather_vote_counts(
3286
- aggregate_selection
3287
- )
3288
-
3289
- selections_count_sum_by_type_and_gp_unit = collections.defaultdict(float)
3290
- for selection in included_selections:
3291
- for (
3292
- type_and_gp_unit,
3293
- count,
3294
- ) in self._gather_vote_counts(selection).items():
3295
- selections_count_sum_by_type_and_gp_unit[type_and_gp_unit] += count
3296
-
3297
- error_log = []
3298
- for (
3299
- type_and_gp_unit,
3300
- total_count,
3301
- ) in selections_count_sum_by_type_and_gp_unit.items():
3302
- aggregate_count = aggregate_count_by_type_and_gp_unit[type_and_gp_unit]
3303
- if total_count > aggregate_count:
3304
- resolved_type, gp_unit_id = type_and_gp_unit
3305
- error_log.append(
3306
- loggers.LogEntry(
3307
- f"In Contest {contest_id}, the sum of vote counts"
3308
- f" ({total_count}) for selections marked as"
3309
- " IncludedInAggregation exceeds the vote count"
3310
- f" ({aggregate_count}) for the AggregateBallotSelection for"
3311
- f" vote count type='{resolved_type}' (GpUnit: '{gp_unit_id}').",
3312
- [element],
3313
- )
3314
- )
3315
-
3316
- if error_log:
3317
- raise loggers.ElectionError(error_log)
3318
-
3319
-
3320
656
  # To add new rules, create a new class, inherit the base rule,
3321
657
  # and add it to the correct rule list.
3322
658
  COMMON_RULES = common_rules.COMMON_RULES
3323
659
  OFFICEHOLDER_RULES = officeholder_rules.OFFICEHOLDER_RULES
3324
-
3325
- ELECTION_RULES = COMMON_RULES + (
3326
- # go/keep-sorted start
3327
- AttributionContainsNoCycles,
3328
- AttributionDepthLimit,
3329
- BallotTitle,
3330
- CandidateContestTypesAreCompatible,
3331
- CandidatesReferencedInRelatedContests,
3332
- CoalitionParties,
3333
- ComposingContestIdsAreValidRelatedContests,
3334
- ContestContainsValidEndDate,
3335
- ContestContainsValidStartDate,
3336
- ContestEndDateOccursAfterStartDate,
3337
- ContestEndDateOccursBeforeSubsequentContestStartDate,
3338
- ContestHasMultipleOffices,
3339
- ContestHasValidContestStage,
3340
- ContestStartDateContainsCorrespondingEndDate,
3341
- CorrectCandidateSelectionCount,
3342
- DateStatusMatches,
3343
- DuplicateBallotTitleSeatPair,
3344
- DuplicateContestNames,
3345
- DuplicatedPartyAbbreviation,
3346
- DuplicatedPartyName,
3347
- ElectionContainsStartAndEndDates,
3348
- ElectionDatesSpanContestDates,
3349
- ElectionEndDatesInThePast,
3350
- ElectionEndDatesOccurAfterStartDates,
3351
- ElectionStartDates,
3352
- ElectionTypesAndCandidateContestTypesAreCompatible,
3353
- ElectionTypesAreCompatible,
3354
- FullTextMaxLength,
3355
- FullTextOrBallotText,
3356
- GpUnitsHaveSingleRoot,
3357
- ImproperCandidateContest,
3358
- MissingPartyAbbreviationTranslation,
3359
- MissingPartyNameTranslation,
3360
- MultipleCandidatesPointToTheSamePersonInTheSameContest,
3361
- MultipleInternationalizedTextWithSameLanguageCode,
3362
- NotEmptyUniqueDataSourceUris,
3363
- OfficeHasjurisdictionSameAsElectoralDistrict,
3364
- PartisanPrimary,
3365
- PartisanPrimaryHeuristic,
3366
- PercentSum,
3367
- ProperBallotSelection,
3368
- ResultsReportingStagesMustHaveUniqueType,
3369
- SelfDeclaredCandidateMethod,
3370
- SingularPartySelection,
3371
- SubsequentContestIdIsValidRelatedContest,
3372
- UniqueDataSourceDisplayNames,
3373
- UniqueDataSourceLanguages,
3374
- ValidateDuplicateColors,
3375
- ValidateIncludeInAggregationBallotSelections,
3376
- ValidateInfoUriAnnotation,
3377
- ValidatePollsCloseDatetimes,
3378
- ValidateResultReportingStages,
3379
- ValidateResultsEmbargoEnd,
3380
- ValidateResultsExpected,
3381
- ValidateSpecialBallotSelectionCountedInTotal,
3382
- VoteCountTypesCoherency,
3383
- VoteCountValidSeatsDeltaTypes,
3384
- WinnerCountLimit,
3385
- # go/keep-sorted end
3386
- )
660
+ ELECTION_RULES = election_rules.ELECTION_RULES
661
+ ELECTION_DATES_RULES = election_dates_rules.ELECTION_DATES_RULES
3387
662
 
3388
663
 
3389
664
  COMMITTEE_RULES = COMMON_RULES + (
@@ -3396,7 +671,6 @@ COMMITTEE_RULES = COMMON_RULES + (
3396
671
  # go/keep-sorted end
3397
672
  )
3398
673
 
3399
- ELECTION_DATES_RULES = ELECTION_RULES + (UnreferencedEntitiesElectionDates,)
3400
674
 
3401
675
  METADATA_RULES = (
3402
676
  # go/keep-sorted start