civics-cdf-validator 1.68.dev16__tar.gz → 1.68.dev17__tar.gz

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.
Files changed (32) hide show
  1. {civics_cdf_validator-1.68.dev16/civics_cdf_validator.egg-info → civics_cdf_validator-1.68.dev17}/PKG-INFO +1 -1
  2. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17/civics_cdf_validator.egg-info}/PKG-INFO +1 -1
  3. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/committee_rules.py +11 -10
  4. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/common_rules.py +121 -119
  5. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/election_dates_rules.py +7 -1
  6. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/election_results_rules.py +2 -1
  7. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/voter_information_rules.py +11 -10
  8. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/version.py +1 -1
  9. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/CONTRIBUTING.md +0 -0
  10. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/LICENSE-2.0.txt +0 -0
  11. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/MANIFEST.in +0 -0
  12. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/README.md +0 -0
  13. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/__init__.py +0 -0
  14. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/base.py +0 -0
  15. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/civics_cdf_validator.egg-info/SOURCES.txt +0 -0
  16. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/civics_cdf_validator.egg-info/dependency_links.txt +0 -0
  17. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/civics_cdf_validator.egg-info/entry_points.txt +0 -0
  18. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/civics_cdf_validator.egg-info/requires.txt +0 -0
  19. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/civics_cdf_validator.egg-info/top_level.txt +0 -0
  20. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/gpunit_rules.py +0 -0
  21. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/loggers.py +0 -0
  22. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/office_utils.py +0 -0
  23. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rules.py +0 -0
  24. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/__init__.py +0 -0
  25. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/election_rules.py +0 -0
  26. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/metadata_rules.py +0 -0
  27. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/officeholder_rules.py +0 -0
  28. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/rulesets/rule_util.py +0 -0
  29. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/setup.cfg +0 -0
  30. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/setup.py +0 -0
  31. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/stats.py +0 -0
  32. {civics_cdf_validator-1.68.dev16 → civics_cdf_validator-1.68.dev17}/validator.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: civics_cdf_validator
3
- Version: 1.68.dev16
3
+ Version: 1.68.dev17
4
4
  Summary: Checks if an election feed follows best practices
5
5
  Home-page: https://github.com/google/civics_cdf_validator
6
6
  Author: Google Civics
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: civics_cdf_validator
3
- Version: 1.68.dev16
3
+ Version: 1.68.dev17
4
4
  Summary: Checks if an election feed follows best practices
5
5
  Home-page: https://github.com/google/civics_cdf_validator
6
6
  Author: Google Civics
@@ -21,15 +21,16 @@ from civics_cdf_validator import base
21
21
  from civics_cdf_validator import loggers
22
22
  from civics_cdf_validator.rulesets import common_rules
23
23
  from civics_cdf_validator.rulesets import rule_util
24
+ from lxml import etree
24
25
 
25
26
 
26
27
  class CommitteeClassificationEndDateOccursAfterStartDate(base.DateRule):
27
28
  """CommitteeClassification elements should have end dates that occur after the start dates."""
28
29
 
29
- def elements(self):
30
+ def elements(self) -> list[str]:
30
31
  return ["CommitteeClassification"]
31
32
 
32
- def check(self, element):
33
+ def check(self, element: etree._Element) -> None:
33
34
  self.reset_instance_vars()
34
35
  self.gather_dates(element)
35
36
 
@@ -42,10 +43,10 @@ class CommitteeClassificationEndDateOccursAfterStartDate(base.DateRule):
42
43
  class AffiliationEndDateOccursAfterStartDate(base.DateRule):
43
44
  """Affiliation elements should have end dates that occur after the start dates."""
44
45
 
45
- def elements(self):
46
+ def elements(self) -> list[str]:
46
47
  return ["Affiliation"]
47
48
 
48
- def check(self, element):
49
+ def check(self, element: etree._Element) -> None:
49
50
  self.reset_instance_vars()
50
51
  self.gather_dates(element)
51
52
 
@@ -58,15 +59,15 @@ class AffiliationEndDateOccursAfterStartDate(base.DateRule):
58
59
  class EinMatchesFormat(base.BaseRule):
59
60
  """EIN id should be in the following format: XX-XXXXXXX."""
60
61
 
61
- def __init__(self, *args, **kwargs):
62
+ def __init__(self, *args, **kwargs) -> None:
62
63
  super(EinMatchesFormat, self).__init__(*args, **kwargs)
63
64
  regex = r"\d{2}(-\d{7})?"
64
65
  self.ein_id_matcher = re.compile(regex, flags=re.U)
65
66
 
66
- def elements(self):
67
+ def elements(self) -> list[str]:
67
68
  return ["Committee"]
68
69
 
69
- def check(self, element):
70
+ def check(self, element: etree._Element) -> None:
70
71
  external_identifiers = element.find("ExternalIdentifiers")
71
72
  if external_identifiers is not None:
72
73
  ein_ids = rule_util.get_external_id_values(external_identifiers, "ein")
@@ -74,7 +75,7 @@ class EinMatchesFormat(base.BaseRule):
74
75
  e_id = ein_ids.pop()
75
76
  if not self.ein_id_matcher.match(e_id):
76
77
  raise loggers.ElectionError.from_message(
77
- "EIN id '{}' is not in the correct format.".format(e_id),
78
+ f"EIN id '{e_id}' is not in the correct format.",
78
79
  [element],
79
80
  )
80
81
 
@@ -82,10 +83,10 @@ class EinMatchesFormat(base.BaseRule):
82
83
  class AffiliationHasEitherPartyOrPerson(base.BaseRule):
83
84
  """Affiliation should contain either a Party or a Person objectId."""
84
85
 
85
- def elements(self):
86
+ def elements(self) -> list[str]:
86
87
  return ["Affiliation"]
87
88
 
88
- def check(self, element):
89
+ def check(self, element: etree._Element) -> None:
89
90
  party_id = element.find("PartyId")
90
91
  person_id = element.find("PersonId")
91
92
  if not ((party_id is None) ^ (person_id is None)):
@@ -16,6 +16,7 @@
16
16
  from __future__ import print_function
17
17
 
18
18
  import collections
19
+ from collections.abc import Collection, Iterable
19
20
  import re
20
21
 
21
22
  from civics_cdf_validator import base
@@ -109,22 +110,26 @@ _INTERNATIONALIZED_TEXT_ELEMENTS_WITH_ONLY_ONE_TEXT_PER_LANGUAGE = [
109
110
  ]
110
111
 
111
112
 
112
- def _get_office_roles(element, is_post_office_split_feed=False):
113
+ def _get_office_roles(
114
+ element: etree._Element, is_post_office_split_feed: bool = False
115
+ ) -> list[str]:
113
116
  if is_post_office_split_feed:
114
117
  return [element.text for element in element.findall("Role")]
115
118
  return rule_util.get_entity_info_for_value_type(element, "office-role")
116
119
 
117
120
 
118
- def _is_executive_office(element, is_post_office_split_feed=False):
121
+ def _is_executive_office(
122
+ element: etree._Element, is_post_office_split_feed: bool = False
123
+ ) -> bool:
119
124
  office_roles = _get_office_roles(element, is_post_office_split_feed)
120
125
  return not _EXECUTIVE_OFFICE_ROLES.isdisjoint(office_roles)
121
126
 
122
127
 
123
- def _has_government_body(element):
128
+ def _has_government_body(element: etree._Element) -> bool:
124
129
  return rule_util.element_has_text(element.find("GovernmentBodyIds"))
125
130
 
126
131
 
127
- def extract_person_fullname(person):
132
+ def extract_person_fullname(person: etree._Element) -> Collection[str]:
128
133
  """Extracts the person's fullname or builds it if needed."""
129
134
  full_name_elt = person.find("FullName")
130
135
  if full_name_elt is None:
@@ -140,12 +145,12 @@ def extract_person_fullname(person):
140
145
  class Schema(base.TreeRule):
141
146
  """Checks if election file validates against the provided schema."""
142
147
 
143
- def check(self):
148
+ def check(self) -> None:
144
149
  try:
145
150
  schema = etree.XMLSchema(etree=self.schema_tree)
146
151
  except etree.XMLSchemaParseError as e:
147
152
  raise loggers.ElectionFatal.from_message(
148
- "The schema file could not be parsed correctly %s" % str(e)
153
+ f"The schema file could not be parsed correctly {e}"
149
154
  )
150
155
  valid_xml = True
151
156
  try:
@@ -160,14 +165,14 @@ class Schema(base.TreeRule):
160
165
  lines=[error.line],
161
166
  message=(
162
167
  "The election file didn't validate "
163
- "against schema : {0}".format(error.message.encode("utf-8"))
168
+ f"against schema : {error.message.encode('utf-8')}"
164
169
  ),
165
170
  elements=self._get_error_elements(error),
166
171
  )
167
172
  )
168
173
  raise loggers.ElectionFatal(errors)
169
174
 
170
- def _get_error_elements(self, error):
175
+ def _get_error_elements(self, error: etree._LogEntry) -> list[etree._Element]:
171
176
  """Returns the elements a schema error points to, or the root element."""
172
177
  if error.path:
173
178
  try:
@@ -182,11 +187,11 @@ class Schema(base.TreeRule):
182
187
  class OptionalAndEmpty(base.BaseRule):
183
188
  """Checks for optional and empty fields."""
184
189
 
185
- def __init__(self, *args, **kwargs):
190
+ def __init__(self, *args, **kwargs) -> None:
186
191
  super(OptionalAndEmpty, self).__init__(*args, **kwargs)
187
192
  self.previous = None
188
193
 
189
- def elements(self):
194
+ def elements(self) -> list[str]:
190
195
  eligible_elements = []
191
196
  for _, element in etree.iterwalk(self.schema_tree):
192
197
  tag = self.strip_schema_ns(element)
@@ -195,7 +200,7 @@ class OptionalAndEmpty(base.BaseRule):
195
200
  return eligible_elements
196
201
 
197
202
  # pylint: disable=g-explicit-length-test
198
- def check(self, element):
203
+ def check(self, element: etree._Element) -> None:
199
204
  if element == self.previous:
200
205
  return
201
206
  self.previous = element
@@ -208,7 +213,7 @@ class OptionalAndEmpty(base.BaseRule):
208
213
  class Encoding(base.TreeRule):
209
214
  """Checks that the file provided uses UTF-8 encoding."""
210
215
 
211
- def check(self):
216
+ def check(self) -> None:
212
217
  docinfo = self.election_tree.docinfo
213
218
  if docinfo.encoding != "UTF-8":
214
219
  raise loggers.ElectionError.from_message(
@@ -219,26 +224,26 @@ class Encoding(base.TreeRule):
219
224
  class LanguageCode(base.BaseRule):
220
225
  """Check that Text and Uri elements have a valid language code."""
221
226
 
222
- def elements(self):
227
+ def elements(self) -> list[str]:
223
228
  return ["Text", "Uri"]
224
229
 
225
- def check(self, element):
230
+ def check(self, element: etree._Element) -> None:
226
231
  if "language" not in element.attrib:
227
232
  return
228
233
  elem_lang = element.get("language")
229
234
  if not elem_lang.strip() or not language_tags.tags.check(elem_lang):
230
235
  raise loggers.ElectionError.from_message(
231
- "%s is not a valid language code" % elem_lang, [element]
236
+ f"{elem_lang} is not a valid language code", [element]
232
237
  )
233
238
 
234
239
 
235
240
  class EmptyText(base.BaseRule):
236
241
  """Check that Text elements are not empty or strictly whitespace."""
237
242
 
238
- def elements(self):
243
+ def elements(self) -> list[str]:
239
244
  return ["Text"]
240
245
 
241
- def check(self, element):
246
+ def check(self, element: etree._Element) -> None:
242
247
  if element.text is None or not element.text.strip():
243
248
  raise loggers.ElectionError.from_message("Text is empty", element)
244
249
 
@@ -246,11 +251,11 @@ class EmptyText(base.BaseRule):
246
251
  class EmptyString(base.SchemaRule):
247
252
  """Check that string fields are not empty or strictly whitespace."""
248
253
 
249
- def elements(self):
254
+ def elements(self) -> list[str]:
250
255
  return list(self.get_element_names_for_type("xs:string"))
251
256
 
252
257
  # pylint: disable=g-explicit-length-test
253
- def check(self, element):
258
+ def check(self, element: etree._Element) -> None:
254
259
  if (element.text is None or not element.text.strip()) and not len(element):
255
260
  raise loggers.ElectionError.from_message(
256
261
  "String field is empty", [element]
@@ -260,7 +265,7 @@ class EmptyString(base.SchemaRule):
260
265
  class DuplicateID(base.TreeRule):
261
266
  """Check that the file does not contain duplicate object IDs."""
262
267
 
263
- def check(self):
268
+ def check(self) -> None:
264
269
  all_object_ids = set()
265
270
  error_log = []
266
271
  for _, element in etree.iterwalk(self.election_tree, events=("end",)):
@@ -286,7 +291,7 @@ class ValidIDREF(base.BaseRule):
286
291
  of the proper reference type for the given field.
287
292
  """
288
293
 
289
- def __init__(self, *args, **kwargs):
294
+ def __init__(self, *args, **kwargs) -> None:
290
295
  super(ValidIDREF, self).__init__(*args, **kwargs)
291
296
  self.object_id_mapping = {}
292
297
  self.element_reference_mapping = {}
@@ -305,14 +310,14 @@ class ValidIDREF(base.BaseRule):
305
310
  "PartyLeaderId": "Person",
306
311
  }
307
312
 
308
- def setup(self):
313
+ def setup(self) -> None:
309
314
  object_id_map = self._gather_object_ids_by_type()
310
315
  self.object_id_mapping = object_id_map
311
316
 
312
317
  element_reference_map = self._gather_reference_mapping()
313
318
  self.element_reference_mapping = element_reference_map
314
319
 
315
- def _gather_object_ids_by_type(self):
320
+ def _gather_object_ids_by_type(self) -> dict[str, set[str]]:
316
321
  """Create a mapping of element types to set of objectIds of same type."""
317
322
 
318
323
  type_obj_id_mapping = dict()
@@ -324,7 +329,7 @@ class ValidIDREF(base.BaseRule):
324
329
  type_obj_id_mapping.setdefault(obj_type, set([])).add(obj_id)
325
330
  return type_obj_id_mapping
326
331
 
327
- def _gather_reference_mapping(self):
332
+ def _gather_reference_mapping(self) -> dict[str, str | None]:
328
333
  """Create a mapping of each IDREF(S) element to their reference type."""
329
334
 
330
335
  reference_mapping = dict()
@@ -340,7 +345,7 @@ class ValidIDREF(base.BaseRule):
340
345
  reference_mapping[elem_name] = reference_type
341
346
  return reference_mapping
342
347
 
343
- def _determine_reference_type(self, name):
348
+ def _determine_reference_type(self, name: str) -> str | None:
344
349
  """Determines the XML type being referenced by an IDREF(S) element."""
345
350
 
346
351
  for elem_type in self.object_id_mapping:
@@ -351,10 +356,10 @@ class ValidIDREF(base.BaseRule):
351
356
  return self._REFERENCE_TYPE_OVERRIDES[name]
352
357
  return None
353
358
 
354
- def elements(self):
359
+ def elements(self) -> list[str]:
355
360
  return list(self.element_reference_mapping.keys())
356
361
 
357
- def check(self, element):
362
+ def check(self, element: etree._Element) -> None:
358
363
  error_log = []
359
364
 
360
365
  element_name = element.tag
@@ -368,10 +373,9 @@ class ValidIDREF(base.BaseRule):
368
373
  if id_ref not in reference_object_ids:
369
374
  error_log.append(
370
375
  loggers.LogEntry(
371
- (
372
- "{} is not a valid IDREF. {} should contain an "
373
- "objectId from a {} element."
374
- ).format(id_ref, element_name, element_reference_type),
376
+ f"{id_ref} is not a valid IDREF. {element_name} should"
377
+ f" contain an objectId from a {element_reference_type}"
378
+ " element.",
375
379
  element,
376
380
  )
377
381
  )
@@ -382,22 +386,22 @@ class ValidIDREF(base.BaseRule):
382
386
  class ValidStableID(base.BaseRule):
383
387
  """Ensure stable-ids are in the correct format."""
384
388
 
385
- def __init__(self, *args, **kwargs):
389
+ def __init__(self, *args, **kwargs) -> None:
386
390
  super(ValidStableID, self).__init__(*args, **kwargs)
387
391
  regex = r"^[a-zA-Z0-9_-]+$"
388
392
  self.stable_id_matcher = re.compile(regex, flags=re.U)
389
393
 
390
- def elements(self):
394
+ def elements(self) -> list[str]:
391
395
  return ["ExternalIdentifiers"]
392
396
 
393
- def check(self, element):
397
+ def check(self, element: etree._Element) -> None:
394
398
  stable_ids = rule_util.get_external_id_values(element, "stable")
395
399
  error_log = []
396
400
  for s_id in stable_ids:
397
401
  if not self.stable_id_matcher.match(s_id):
398
402
  error_log.append(
399
403
  loggers.LogEntry(
400
- "Stable id '{}' is not in the correct format.".format(s_id),
404
+ f"Stable id '{s_id}' is not in the correct format.",
401
405
  [element],
402
406
  )
403
407
  )
@@ -411,7 +415,7 @@ class GpUnitOcdId(base.BaseRule):
411
415
  def elements(self):
412
416
  return ["GpUnit", "ReportingUnit"]
413
417
 
414
- def check(self, element):
418
+ def check(self, element: etree._Element) -> None:
415
419
  # ReportingDevices are not expected to have OCD IDs.
416
420
  if self.get_element_class(element) == "ReportingDevice":
417
421
  return
@@ -441,10 +445,10 @@ class GpUnitOcdId(base.BaseRule):
441
445
  class DuplicatedGpUnitOcdId(base.BaseRule):
442
446
  """2 GpUnits should not have same OCD ID."""
443
447
 
444
- def elements(self):
448
+ def elements(self) -> list[str]:
445
449
  return ["GpUnitCollection"]
446
450
 
447
- def check(self, element):
451
+ def check(self, element: etree._Element) -> None:
448
452
  error_log = []
449
453
  gp_ocdid = dict()
450
454
  gpunits = element.findall("GpUnit")
@@ -454,10 +458,9 @@ class DuplicatedGpUnitOcdId(base.BaseRule):
454
458
  if ocd_id not in gp_ocdid.keys():
455
459
  gp_ocdid[ocd_id] = gpunit.get("objectId")
456
460
  else:
457
- msg = "GpUnits %s and %s have the same ocd-id %s" % (
458
- gp_ocdid[ocd_id],
459
- gpunit.get("objectId"),
460
- ocd_id,
461
+ msg = (
462
+ f"GpUnits {gp_ocdid[ocd_id]} and {gpunit.get('objectId')} have"
463
+ f" the same ocd-id {ocd_id}"
461
464
  )
462
465
  error_log.append(loggers.LogEntry(msg, [gpunit]))
463
466
  if error_log:
@@ -467,10 +470,10 @@ class DuplicatedGpUnitOcdId(base.BaseRule):
467
470
  class DuplicateGpUnits(base.BaseRule):
468
471
  """Detect GpUnits which are effectively duplicates of each other."""
469
472
 
470
- def elements(self):
473
+ def elements(self) -> list[str]:
471
474
  return ["GpUnitCollection"]
472
475
 
473
- def check(self, element):
476
+ def check(self, element: etree._Element) -> None:
474
477
  children = {}
475
478
  object_ids = set()
476
479
  error_log = []
@@ -488,11 +491,10 @@ class DuplicateGpUnits(base.BaseRule):
488
491
  composing_ids = frozenset(composing_gpunits.text.split())
489
492
  if children.get(composing_ids) is not None:
490
493
  duplicate_gpunit = children[composing_ids]
494
+ duplicate_ids = (duplicate_gpunit.get("objectId"), object_id)
491
495
  error_log.append(
492
496
  loggers.LogEntry(
493
- "GpUnits {} are duplicates".format(
494
- str((duplicate_gpunit.get("objectId"), object_id))
495
- ),
497
+ f"GpUnits {duplicate_ids} are duplicates",
496
498
  [duplicate_gpunit, gpunit],
497
499
  )
498
500
  )
@@ -505,7 +507,7 @@ class DuplicateGpUnits(base.BaseRule):
505
507
  class GpUnitsCyclesRefsValidation(base.TreeRule):
506
508
  """Ensure that GpUnits form a valid tree and no cycles are present."""
507
509
 
508
- def __init__(self, *args, **kwargs):
510
+ def __init__(self, *args, **kwargs) -> None:
509
511
  super(GpUnitsCyclesRefsValidation, self).__init__(*args, **kwargs)
510
512
  self.edges = dict() # Used to maintain the record of connected edges
511
513
  self.visited = {} # Used to store status of the nodes as visited or not.
@@ -513,13 +515,13 @@ class GpUnitsCyclesRefsValidation(base.TreeRule):
513
515
  self.bad_nodes = []
514
516
  self.gpunit_by_object_id = {}
515
517
 
516
- def build_tree(self, gpunit):
518
+ def build_tree(self, gpunit: str) -> None:
517
519
  # Check if the node is already visited
518
520
  if gpunit in self.visited:
519
521
  if gpunit not in self.bad_nodes:
520
522
  self.error_log.append(
521
523
  loggers.LogEntry(
522
- "Cycle detected at node {0}".format(gpunit),
524
+ f"Cycle detected at node {gpunit}",
523
525
  [self.gpunit_by_object_id[gpunit]],
524
526
  )
525
527
  )
@@ -533,13 +535,13 @@ class GpUnitsCyclesRefsValidation(base.TreeRule):
533
535
  else:
534
536
  self.error_log.append(
535
537
  loggers.LogEntry(
536
- "Node {0} is not present in the file as a GpUnit element."
537
- .format(child_unit),
538
+ f"Node {child_unit} is not present in the file as a GpUnit"
539
+ " element.",
538
540
  [self.gpunit_by_object_id[gpunit]],
539
541
  )
540
542
  )
541
543
 
542
- def check(self):
544
+ def check(self) -> None:
543
545
  for element in self.get_elements_by_class(self.election_tree, "GpUnit"):
544
546
  object_id = element.get("objectId")
545
547
  if object_id is None:
@@ -567,10 +569,10 @@ class OtherType(base.BaseRule):
567
569
  OtherType within the containing element.
568
570
  """
569
571
 
570
- def elements(self):
572
+ def elements(self) -> list[str]:
571
573
  eligible_elements = []
572
574
  for element in self.schema_tree.iterfind(
573
- "{%s}complexType" % self._XSCHEMA_NAMESPACE
575
+ f"{{{self._XSCHEMA_NAMESPACE}}}complexType"
574
576
  ):
575
577
  for elem in element.iter():
576
578
  tag = self.strip_schema_ns(elem)
@@ -580,7 +582,7 @@ class OtherType(base.BaseRule):
580
582
  eligible_elements.append(element.get("name"))
581
583
  return eligible_elements
582
584
 
583
- def check(self, element):
585
+ def check(self, element: etree._Element) -> None:
584
586
  type_element = element.find("Type")
585
587
  other_type_element = element.find("OtherType")
586
588
  if type_element is not None and type_element.text == "other":
@@ -602,18 +604,18 @@ class OtherType(base.BaseRule):
602
604
  class UniqueLabel(base.SchemaRule):
603
605
  """Labels should be unique within a file."""
604
606
 
605
- def __init__(self, *args, **kwargs):
607
+ def __init__(self, *args, **kwargs) -> None:
606
608
  super(UniqueLabel, self).__init__(*args, **kwargs)
607
609
  self.labels = set()
608
610
 
609
- def elements(self):
611
+ def elements(self) -> list[str]:
610
612
  return list(self.get_element_names_for_type("InternationalizedText"))
611
613
 
612
- def check(self, element):
614
+ def check(self, element: etree._Element) -> None:
613
615
  element_label = element.get("label")
614
616
  if element_label:
615
617
  if element_label in self.labels:
616
- msg = "Duplicate label '%s'. Label already defined" % element_label
618
+ msg = f"Duplicate label '{element_label}'. Label already defined"
617
619
  raise loggers.ElectionError.from_message(msg, [element])
618
620
  else:
619
621
  self.labels.add(element_label)
@@ -627,10 +629,12 @@ class PersonHasUniqueFullName(base.BaseRule):
627
629
  be raised. So, we can check if the feed is coherent.
628
630
  """
629
631
 
630
- def elements(self):
632
+ def elements(self) -> list[str]:
631
633
  return ["PersonCollection"]
632
634
 
633
- def check_specific(self, people):
635
+ def check_specific(
636
+ self, people: Iterable[etree._Element]
637
+ ) -> list[loggers.LogEntry]:
634
638
  person_def = collections.namedtuple(
635
639
  "PersonDefinition", ["fullname", "birthday"]
636
640
  )
@@ -652,15 +656,15 @@ class PersonHasUniqueFullName(base.BaseRule):
652
656
  and person_id_to_object_id[person_id] != person_object_id
653
657
  ):
654
658
  info_message = (
655
- "Person has same full name '%s' and birthday %s as Person %s."
656
- % (full_name_val, birthday_val, person_id_to_object_id[person_id])
659
+ f"Person has same full name '{full_name_val}' and birthday"
660
+ f" {birthday_val} as Person {person_id_to_object_id[person_id]}."
657
661
  )
658
662
  info_log.append(loggers.LogEntry(info_message, [person]))
659
663
  else:
660
664
  person_id_to_object_id[person_id] = person_object_id
661
665
  return info_log
662
666
 
663
- def check(self, element):
667
+ def check(self, element: etree._Element) -> None:
664
668
  info_log = []
665
669
  people = element.findall("Person")
666
670
  if len(people) < 1:
@@ -679,10 +683,10 @@ class BadCharactersInPersonFullName(base.BaseRule):
679
683
 
680
684
  regex = r"([()@$%*/]|\balias\b)"
681
685
 
682
- def elements(self):
686
+ def elements(self) -> list[str]:
683
687
  return ["Person"]
684
688
 
685
- def check(self, element):
689
+ def check(self, element: etree._Element) -> None:
686
690
  warning_message = (
687
691
  "Person has known bad characters in FullName field."
688
692
  " Aliases should be included in Nickname field."
@@ -710,7 +714,7 @@ class IndependentPartyName(base.BaseRule):
710
714
  def elements(self):
711
715
  return ["Party"]
712
716
 
713
- def check(self, party):
717
+ def check(self, party: etree._Element) -> None:
714
718
  is_independent_element = party.find("IsIndependent")
715
719
  if is_independent_element is not None:
716
720
  return
@@ -734,7 +738,7 @@ class UniqueStableID(base.TreeRule):
734
738
  Add an error message if stable id is not unique
735
739
  """
736
740
 
737
- def check(self):
741
+ def check(self) -> None:
738
742
  error_log = []
739
743
  stable_obj_dict = dict()
740
744
  stable_elements_dict = dict()
@@ -755,16 +759,14 @@ class UniqueStableID(base.TreeRule):
755
759
  stable_obj_dict[stable_id] = elem_id_list
756
760
  for k, v in stable_obj_dict.items():
757
761
  if len(v) > 1:
758
- error_message = (
759
- "Stable ID {} is not unique as it is mapped in {}".format(k, v)
760
- )
762
+ error_message = f"Stable ID {k} is not unique as it is mapped in {v}"
761
763
  error_log.append(
762
764
  loggers.LogEntry(error_message, stable_elements_dict[k])
763
765
  )
764
766
  if error_log:
765
767
  raise loggers.ElectionError(error_log)
766
768
 
767
- def _get_object_id_or_name(self, element):
769
+ def _get_object_id_or_name(self, element: etree._Element) -> str | None:
768
770
  if "objectId" in element.attrib:
769
771
  return element.get("objectId")
770
772
  names_by_language = rule_util.get_language_to_text_map(element.find("Name"))
@@ -797,10 +799,10 @@ class MissingStableIds(base.BaseRule):
797
799
  "ReportingUnit",
798
800
  ]
799
801
 
800
- def elements(self):
802
+ def elements(self) -> list[str]:
801
803
  return self._ELEMENTS_WITH_STABLE_IDS
802
804
 
803
- def check(self, element):
805
+ def check(self, element: etree._Element) -> None:
804
806
  stable_ids = []
805
807
  external_identifiers = element.find("ExternalIdentifiers")
806
808
  if external_identifiers is not None:
@@ -820,10 +822,10 @@ class PersonsMissingPartyData(base.BaseRule):
820
822
  up within this class and returned to the user as a warning.
821
823
  """
822
824
 
823
- def elements(self):
825
+ def elements(self) -> list[str]:
824
826
  return ["Person"]
825
827
 
826
- def check(self, element):
828
+ def check(self, element: etree._Element) -> None:
827
829
  party_id = element.find("PartyId")
828
830
  if party_id is None or not party_id.text or party_id.text.isspace():
829
831
  raise loggers.ElectionWarning.from_message(
@@ -834,10 +836,10 @@ class PersonsMissingPartyData(base.BaseRule):
834
836
  class CandidateImageInContactInformation(base.BaseRule):
835
837
  """Warn if candidate-image is set in ContactInformation.Uri."""
836
838
 
837
- def elements(self):
839
+ def elements(self) -> list[str]:
838
840
  return ["ContactInformation"]
839
841
 
840
- def check(self, element):
842
+ def check(self, element: etree._Element) -> None:
841
843
  candidate_image_uris = []
842
844
  for uri in element.findall("Uri"):
843
845
  annotation = uri.get("Annotation", "").strip()
@@ -855,10 +857,10 @@ class CandidateImageInContactInformation(base.BaseRule):
855
857
  class OnlyOneCandidateImagePerPerson(base.BaseRule):
856
858
  """Ensure only one candidate-image is provided per Person."""
857
859
 
858
- def elements(self):
860
+ def elements(self) -> list[str]:
859
861
  return ["Person"]
860
862
 
861
- def check(self, element):
863
+ def check(self, element: etree._Element) -> None:
862
864
  image_uris = element.findall("ImageUri")
863
865
  candidate_images = []
864
866
  for image_uri in image_uris:
@@ -868,8 +870,8 @@ class OnlyOneCandidateImagePerPerson(base.BaseRule):
868
870
 
869
871
  if len(candidate_images) > 1:
870
872
  raise loggers.ElectionError.from_message(
871
- "Person has {} ImageUri fields annotated as 'candidate-image'."
872
- " Must have at most one.".format(len(candidate_images)),
873
+ f"Person has {len(candidate_images)} ImageUri fields annotated as"
874
+ " 'candidate-image'. Must have at most one.",
873
875
  candidate_images,
874
876
  )
875
877
 
@@ -877,7 +879,7 @@ class OnlyOneCandidateImagePerPerson(base.BaseRule):
877
879
  class UniqueCandidateImageUris(base.TreeRule):
878
880
  """Check that candidate-image URIs are unique to a person."""
879
881
 
880
- def check(self):
882
+ def check(self) -> None:
881
883
  root = self.election_tree.getroot()
882
884
  if root is None:
883
885
  return
@@ -926,10 +928,10 @@ class AllCaps(base.BaseRule):
926
928
  "Person": ["FullName//Text"],
927
929
  }
928
930
 
929
- def elements(self):
931
+ def elements(self) -> list[str]:
930
932
  return list(self._element_field_mapping.keys())
931
933
 
932
- def check(self, element):
934
+ def check(self, element: etree._Element) -> None:
933
935
  element_tag = self.get_element_class(element)
934
936
  to_check_field_tags = self._element_field_mapping[element_tag]
935
937
  for field_tag in to_check_field_tags:
@@ -938,9 +940,7 @@ class AllCaps(base.BaseRule):
938
940
  text_value = to_check_field.text
939
941
  if text_value and text_value.isupper():
940
942
  raise loggers.ElectionWarning.from_message(
941
- "{0} has {1} in all upper case letters.".format(
942
- element_tag, field_tag
943
- ),
943
+ f"{element_tag} has {field_tag} in all upper case letters.",
944
944
  [element],
945
945
  )
946
946
 
@@ -954,10 +954,10 @@ class AllLanguages(base.BaseRule):
954
954
 
955
955
  required_languages = []
956
956
 
957
- def elements(self):
957
+ def elements(self) -> list[str]:
958
958
  return ["BallotName", "BallotTitle", "FullName", "Name"]
959
959
 
960
- def check(self, element):
960
+ def check(self, element: etree._Element) -> None:
961
961
  text_elements = element.findall("Text")
962
962
  if not text_elements:
963
963
  return
@@ -968,7 +968,7 @@ class AllLanguages(base.BaseRule):
968
968
  if not required_language_set.issubset(languages):
969
969
  msg = (
970
970
  "Element does not contain text in all required languages, missing"
971
- + " : %s" % str(required_language_set - languages)
971
+ f" : {required_language_set - languages}"
972
972
  )
973
973
  raise loggers.ElectionError.from_message(msg, [element])
974
974
 
@@ -983,7 +983,7 @@ class ValidEnumerations(base.BaseRule):
983
983
 
984
984
  valid_enumerations = []
985
985
 
986
- def elements(self):
986
+ def elements(self) -> list[str]:
987
987
  eligible_elements = []
988
988
  for element in self.schema_tree.iter():
989
989
  tag = self.strip_schema_ns(element)
@@ -1003,7 +1003,7 @@ class ValidEnumerations(base.BaseRule):
1003
1003
  eligible_elements.append(element.get("name"))
1004
1004
  return eligible_elements
1005
1005
 
1006
- def check(self, element):
1006
+ def check(self, element: etree._Element) -> None:
1007
1007
  type_element = element.find("Type")
1008
1008
  if type_element is not None and type_element.text == "other":
1009
1009
  other_type_element = element.find("OtherType")
@@ -1013,8 +1013,8 @@ class ValidEnumerations(base.BaseRule):
1013
1013
  ):
1014
1014
  raise loggers.ElectionError.from_message(
1015
1015
  (
1016
- "Type is set to 'other' even though '%s' is a valid enumeration"
1017
- % other_type_element.text
1016
+ "Type is set to 'other' even though"
1017
+ f" '{other_type_element.text}' is a valid enumeration"
1018
1018
  ),
1019
1019
  [element],
1020
1020
  )
@@ -1026,15 +1026,15 @@ class ValidateOcdidLowerCase(base.BaseRule):
1026
1026
  Throw a warning if the ocd-ids are not all in lowercase.
1027
1027
  """
1028
1028
 
1029
- def elements(self):
1029
+ def elements(self) -> list[str]:
1030
1030
  return ["ExternalIdentifiers"]
1031
1031
 
1032
- def check(self, element):
1032
+ def check(self, element: etree._Element) -> None:
1033
1033
  for ocd_id in rule_util.get_external_id_values(element, "ocd-id"):
1034
1034
  if not ocd_id.islower():
1035
1035
  msg = (
1036
- "OCD-ID %s is not in all lower case letters. "
1037
- "Valid OCD-IDs should be all lowercase." % (ocd_id)
1036
+ f"OCD-ID {ocd_id} is not in all lower case letters. "
1037
+ "Valid OCD-IDs should be all lowercase."
1038
1038
  )
1039
1039
  raise loggers.ElectionWarning.from_message(msg, [element])
1040
1040
 
@@ -1042,12 +1042,12 @@ class ValidateOcdidLowerCase(base.BaseRule):
1042
1042
  class PartyLeadershipMustExist(base.ValidReferenceRule):
1043
1043
  """Each party leader or party chair should refer to a person in the feed."""
1044
1044
 
1045
- def __init__(self, *args, **kwargs):
1045
+ def __init__(self, *args, **kwargs) -> None:
1046
1046
  super(PartyLeadershipMustExist, self).__init__(
1047
1047
  *args, missing_element="Person", **kwargs
1048
1048
  )
1049
1049
 
1050
- def _gather_reference_values(self):
1050
+ def _gather_reference_values(self) -> set[str]:
1051
1051
  root = self.election_tree.getroot()
1052
1052
  if root is None:
1053
1053
  return
@@ -1062,7 +1062,7 @@ class PartyLeadershipMustExist(base.ValidReferenceRule):
1062
1062
  party_leader_ids.add(external_id.find("Value").text)
1063
1063
  return party_leader_ids
1064
1064
 
1065
- def _gather_defined_values(self):
1065
+ def _gather_defined_values(self) -> set[str]:
1066
1066
  root = self.election_tree.getroot()
1067
1067
  if root is None:
1068
1068
  return
@@ -1090,16 +1090,16 @@ class PersonsHaveValidGender(base.BaseRule):
1090
1090
  "nonbinary",
1091
1091
  }
1092
1092
 
1093
- def elements(self):
1093
+ def elements(self) -> list[str]:
1094
1094
  return ["Gender"]
1095
1095
 
1096
- def check(self, element):
1096
+ def check(self, element: etree._Element) -> None:
1097
1097
  if (
1098
1098
  element.text is not None
1099
1099
  and element.text.lower() not in self._VALID_GENDERS
1100
1100
  ):
1101
1101
  raise loggers.ElectionError.from_message(
1102
- "Person object has invalid gender value: {0}".format(element.text),
1102
+ f"Person object has invalid gender value: {element.text}",
1103
1103
  [element],
1104
1104
  )
1105
1105
 
@@ -1110,10 +1110,10 @@ class URIValidator(base.BaseRule):
1110
1110
  Ensure each URL has valid protocol, domain, and query.
1111
1111
  """
1112
1112
 
1113
- def elements(self):
1113
+ def elements(self) -> list[str]:
1114
1114
  return ["Uri"]
1115
1115
 
1116
- def check(self, element):
1116
+ def check(self, element: etree._Element) -> None:
1117
1117
  url = element.text
1118
1118
  if url is None:
1119
1119
  raise loggers.ElectionError.from_message("Missing URI value.", [element])
@@ -1132,8 +1132,8 @@ class URIValidator(base.BaseRule):
1132
1132
  discrepancies.append("domain - missing")
1133
1133
  if discrepancies:
1134
1134
  msg = (
1135
- "The provided URI, {}, is invalid for the following reasons: {}."
1136
- .format(url.encode("ascii", "ignore"), ", ".join(discrepancies))
1135
+ f"The provided URI, {url.encode('ascii', 'ignore')}, is invalid for"
1136
+ f" the following reasons: {', '.join(discrepancies)}."
1137
1137
  )
1138
1138
  raise loggers.ElectionError.from_message(msg, [element])
1139
1139
 
@@ -1144,8 +1144,8 @@ class URIValidator(base.BaseRule):
1144
1144
  ):
1145
1145
  msg = (
1146
1146
  "It is recommended to use https instead of http. The provided "
1147
- "URI, '{}'."
1148
- ).format(url)
1147
+ f"URI, '{url}'."
1148
+ )
1149
1149
  raise loggers.ElectionInfo.from_message(msg, [element])
1150
1150
 
1151
1151
 
@@ -1155,7 +1155,9 @@ class UniqueURIPerAnnotationCategory(base.TreeRule):
1155
1155
  Ex: No ballotpedia URIs can be the same.
1156
1156
  """
1157
1157
 
1158
- def _extract_uris_by_category(self, uri_elements):
1158
+ def _extract_uris_by_category(
1159
+ self, uri_elements: Iterable[etree._Element]
1160
+ ) -> dict[str, dict[str | None, list[etree._Element]]]:
1159
1161
  """For given list of Uri elements return nested paths of Uri values.
1160
1162
 
1161
1163
  Args:
@@ -1184,7 +1186,7 @@ class UniqueURIPerAnnotationCategory(base.TreeRule):
1184
1186
  uri_mapping[annotation_platform][uri_value] = [uri]
1185
1187
  return uri_mapping
1186
1188
 
1187
- def check(self):
1189
+ def check(self) -> None:
1188
1190
  all_uri_elements = self.get_elements_by_class(self.election_tree, "Uri")
1189
1191
  office_uri_elements = self.get_elements_by_class(
1190
1192
  self.election_tree, "Office//ContactInformation//Uri"
@@ -1197,9 +1199,9 @@ class UniqueURIPerAnnotationCategory(base.TreeRule):
1197
1199
  for uri, uri_elements in value_counter.items():
1198
1200
  if len(uri_elements) > 1:
1199
1201
  error_message = (
1200
- "The Uris contain the annotation type '{}' with the "
1201
- "same value '{}'."
1202
- ).format(annotation, uri)
1202
+ f"The Uris contain the annotation type '{annotation}' with the "
1203
+ f"same value '{uri}'."
1204
+ )
1203
1205
  error_log.append(loggers.LogEntry(error_message, uri_elements))
1204
1206
 
1205
1207
  if error_log:
@@ -1213,10 +1215,10 @@ class ValidYoutubeURL(base.BaseRule):
1213
1215
  playlist as one of the invalid youtube URL types.
1214
1216
  """
1215
1217
 
1216
- def elements(self):
1218
+ def elements(self) -> list[str]:
1217
1219
  return ["Uri"]
1218
1220
 
1219
- def check(self, element):
1221
+ def check(self, element: etree._Element) -> None:
1220
1222
  url = element.text.strip()
1221
1223
  parsed_url = urlparse(url)
1222
1224
  if "youtube" in parsed_url.netloc and (
@@ -17,6 +17,7 @@ from __future__ import print_function
17
17
 
18
18
  from civics_cdf_validator.rulesets import common_rules
19
19
  from civics_cdf_validator.rulesets import election_rules
20
+ from lxml import etree
20
21
 
21
22
 
22
23
  class UnreferencedEntitiesElectionDates(common_rules.UnreferencedEntitiesBase):
@@ -25,7 +26,12 @@ class UnreferencedEntitiesElectionDates(common_rules.UnreferencedEntitiesBase):
25
26
  All other entity types must be referenced.
26
27
  """
27
28
 
28
- def __init__(self, election_tree, schema_tree, **kwargs):
29
+ def __init__(
30
+ self,
31
+ election_tree: etree._ElementTree,
32
+ schema_tree: etree._ElementTree,
33
+ **kwargs,
34
+ ) -> None:
29
35
  super(UnreferencedEntitiesElectionDates, self).__init__(
30
36
  election_tree,
31
37
  schema_tree,
@@ -16,6 +16,7 @@
16
16
  from civics_cdf_validator import base
17
17
  from civics_cdf_validator import loggers
18
18
  from civics_cdf_validator.rulesets import election_rules
19
+ from lxml import etree
19
20
 
20
21
  _REQUIRED_CONTEST_RESULTS_FIELDS = (
21
22
  "CurrentResultsReportingStage",
@@ -33,7 +34,7 @@ class RequiredContestResultsFieldsSet(base.SchemaRule):
33
34
  def elements(self) -> list[str]:
34
35
  return ["Contest"] + list(self.get_all_subtypes("Contest"))
35
36
 
36
- def check(self, element) -> None:
37
+ def check(self, element: etree._Element) -> None:
37
38
  missing_fields = [
38
39
  field
39
40
  for field in _REQUIRED_CONTEST_RESULTS_FIELDS
@@ -18,15 +18,16 @@ from __future__ import print_function
18
18
  from civics_cdf_validator import base
19
19
  from civics_cdf_validator import loggers
20
20
  from civics_cdf_validator.rulesets import common_rules
21
+ from lxml import etree
21
22
 
22
23
 
23
24
  class ElectoralCommissionCollectionExists(base.BaseRule):
24
25
  """ElectoralCommissionCollection should exist."""
25
26
 
26
- def elements(self):
27
+ def elements(self) -> list[str]:
27
28
  return ["ElectionReport"]
28
29
 
29
- def check(self, element):
30
+ def check(self, element: etree._Element) -> None:
30
31
  if element.find("ElectoralCommissionCollection") is None:
31
32
  raise loggers.ElectionError.from_message(
32
33
  "ElectoralCommissionCollection should exist.", [element]
@@ -36,10 +37,10 @@ class ElectoralCommissionCollectionExists(base.BaseRule):
36
37
  class VoterInformationCollectionExists(base.BaseRule):
37
38
  """Warn if there is no VoterInformationCollection."""
38
39
 
39
- def elements(self):
40
+ def elements(self) -> list[str]:
40
41
  return ["ElectionReport"]
41
42
 
42
- def check(self, element):
43
+ def check(self, element: etree._Element) -> None:
43
44
  if element.find("VoterInformationCollection") is None:
44
45
  raise loggers.ElectionWarning.from_message(
45
46
  "VoterInformationCollection should exist.", [element]
@@ -53,10 +54,10 @@ class NoExtraElectionElements(base.BaseRule):
53
54
  should all be excluded.
54
55
  """
55
56
 
56
- def elements(self):
57
+ def elements(self) -> list[str]:
57
58
  return ["Election"]
58
59
 
59
- def check(self, element):
60
+ def check(self, element: etree._Element) -> None:
60
61
  if element.find("BallotStyleCollection") is not None:
61
62
  raise loggers.ElectionError.from_message(
62
63
  "BallotStyleCollection should not exist.", [element]
@@ -80,10 +81,10 @@ class NoExtraElectionElements(base.BaseRule):
80
81
  class WarnOnElementsNotRecommendedForElection(base.BaseRule):
81
82
  """Warn on ContactInformation on an Election for voter information feeds."""
82
83
 
83
- def elements(self):
84
+ def elements(self) -> list[str]:
84
85
  return ["Election"]
85
86
 
86
- def check(self, element):
87
+ def check(self, element: etree._Element) -> None:
87
88
  if element.find("ContactInformation") is not None:
88
89
  raise loggers.ElectionWarning.from_message(
89
90
  "ContactInformation is not recommended for Election, prefer using an"
@@ -100,10 +101,10 @@ class NoExtraElectionReportCollections(base.BaseRule):
100
101
  excluded.
101
102
  """
102
103
 
103
- def elements(self):
104
+ def elements(self) -> list[str]:
104
105
  return ["ElectionReport"]
105
106
 
106
- def check(self, element):
107
+ def check(self, element: etree._Element) -> None:
107
108
  if element.find("CommitteeCollection") is not None:
108
109
  raise loggers.ElectionError.from_message(
109
110
  "CommitteeCollection should not exist.", [element]
@@ -5,4 +5,4 @@ No dependencies should be added to this module.
5
5
  See https://packaging.python.org/guides/single-sourcing-package-version/
6
6
  """
7
7
 
8
- __version__ = '1.68.dev16'
8
+ __version__ = '1.68.dev17'