civics-cdf-validator 1.68.dev14__tar.gz → 1.68.dev15__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.dev14/civics_cdf_validator.egg-info → civics_cdf_validator-1.68.dev15}/PKG-INFO +1 -1
  2. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/base.py +89 -71
  3. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15/civics_cdf_validator.egg-info}/PKG-INFO +1 -1
  4. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/setup.py +1 -1
  5. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/validator.py +68 -36
  6. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/version.py +1 -1
  7. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/CONTRIBUTING.md +0 -0
  8. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/LICENSE-2.0.txt +0 -0
  9. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/MANIFEST.in +0 -0
  10. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/README.md +0 -0
  11. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/__init__.py +0 -0
  12. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/civics_cdf_validator.egg-info/SOURCES.txt +0 -0
  13. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/civics_cdf_validator.egg-info/dependency_links.txt +0 -0
  14. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/civics_cdf_validator.egg-info/entry_points.txt +0 -0
  15. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/civics_cdf_validator.egg-info/requires.txt +0 -0
  16. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/civics_cdf_validator.egg-info/top_level.txt +0 -0
  17. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/gpunit_rules.py +0 -0
  18. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/loggers.py +0 -0
  19. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/office_utils.py +0 -0
  20. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rules.py +0 -0
  21. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/__init__.py +0 -0
  22. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/committee_rules.py +0 -0
  23. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/common_rules.py +0 -0
  24. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/election_dates_rules.py +0 -0
  25. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/election_results_rules.py +0 -0
  26. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/election_rules.py +0 -0
  27. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/metadata_rules.py +0 -0
  28. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/officeholder_rules.py +0 -0
  29. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/rule_util.py +0 -0
  30. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/rulesets/voter_information_rules.py +0 -0
  31. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/setup.cfg +0 -0
  32. {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev15}/stats.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: civics_cdf_validator
3
- Version: 1.68.dev14
3
+ Version: 1.68.dev15
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
@@ -17,11 +17,13 @@ limitations under the License.
17
17
  from __future__ import print_function
18
18
 
19
19
  import collections
20
- from collections.abc import Set
20
+ from collections.abc import Iterable, Mapping, Set
21
21
  import datetime
22
22
  import functools
23
23
  import re
24
+ from typing import Any, BinaryIO, TextIO
24
25
 
26
+ from civics_cdf_validator import gpunit_rules
25
27
  from civics_cdf_validator import loggers
26
28
  from civics_cdf_validator import stats
27
29
  from lxml import etree
@@ -31,9 +33,9 @@ class SchemaHandler(object):
31
33
  """Base class for anything that parses an XML schema document."""
32
34
  _XSCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema"
33
35
  _XSCHEMA_INSTANCE_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"
34
- _TYPE_ATTRIB = "{%s}type" % (_XSCHEMA_INSTANCE_NAMESPACE)
36
+ _TYPE_ATTRIB = f"{{{_XSCHEMA_INSTANCE_NAMESPACE}}}type"
35
37
 
36
- def get_element_class(self, element):
38
+ def get_element_class(self, element: etree._Element | None) -> str | None:
37
39
  """Return the class of the element."""
38
40
  if element is None:
39
41
  return None
@@ -41,23 +43,25 @@ class SchemaHandler(object):
41
43
  return element.tag
42
44
  return element.attrib[self._TYPE_ATTRIB]
43
45
 
44
- def strip_schema_ns(self, element):
46
+ def strip_schema_ns(self, element: etree._Element) -> str | None:
45
47
  """Remove namespace from lxml element tag."""
46
48
  tag = element.tag
47
49
  if not hasattr(tag, "startswith"):
48
50
  # Comment tags return a function
49
51
  return None
50
- if tag.startswith("{%s}" % self._XSCHEMA_NAMESPACE):
51
- return tag[len("{%s}" % self._XSCHEMA_NAMESPACE):]
52
+ if tag.startswith(f"{{{self._XSCHEMA_NAMESPACE}}}"):
53
+ return tag[len(f"{{{self._XSCHEMA_NAMESPACE}}}"):]
52
54
  return tag
53
55
 
54
- def get_elements_by_class(self, element, element_name):
56
+ def get_elements_by_class(
57
+ self, element: etree._Element | etree._ElementTree, element_name: str
58
+ ) -> list[etree._Element]:
55
59
  """Searches for all tags under element of type element_name."""
56
60
  # find all the tags that match element_name
57
61
  elements = element.findall(".//" + element_name)
58
62
  # next find all elements where the type is element_name
59
63
  elements += element.xpath(
60
- ".//*[@xsi:type ='%s']" % (element_name),
64
+ f".//*[@xsi:type ='{element_name}']",
61
65
  namespaces={"xsi": self._XSCHEMA_INSTANCE_NAMESPACE})
62
66
  return elements
63
67
 
@@ -66,22 +70,25 @@ class BaseRule(SchemaHandler):
66
70
  """Base class for rules."""
67
71
 
68
72
  def __init__(
69
- self, election_tree=None, schema_tree=None, ocd_id_validator=None
70
- ):
73
+ self,
74
+ election_tree: etree._ElementTree | None = None,
75
+ schema_tree: etree._ElementTree | None = None,
76
+ ocd_id_validator: gpunit_rules.GpUnitOcdIdValidator | None = None,
77
+ ) -> None:
71
78
  super(BaseRule, self).__init__()
72
79
  self.election_tree = election_tree
73
80
  self.schema_tree = schema_tree
74
81
  self.ocd_id_validator = ocd_id_validator
75
82
 
76
- def elements(self):
83
+ def elements(self) -> list[str]:
77
84
  """Return a list of all the elements this rule checks."""
78
85
  raise NotImplementedError
79
86
 
80
- def check(self, element):
87
+ def check(self, element: etree._Element) -> None:
81
88
  """Given an element, check whether it implements best practices."""
82
89
  raise NotImplementedError
83
90
 
84
- def set_option(self, option):
91
+ def set_option(self, option: "RuleOption") -> None:
85
92
  """Used to set commandline options for the rule.
86
93
 
87
94
  Args:
@@ -94,14 +101,14 @@ class BaseRule(SchemaHandler):
94
101
  raise loggers.ElectionException("Invalid attribute set")
95
102
  setattr(self, option.option_name, option.option_value)
96
103
 
97
- def setup(self):
104
+ def setup(self) -> None:
98
105
  """Perform any rule specific setup before checking."""
99
106
 
100
107
 
101
108
  class SchemaRule(BaseRule):
102
109
  """Rule that needs the schema tree to be present."""
103
110
 
104
- def __init__(self, *args, **kwargs):
111
+ def __init__(self, *args, **kwargs) -> None:
105
112
  super(SchemaRule, self).__init__(*args, **kwargs)
106
113
  if self.schema_tree is None:
107
114
  raise ValueError(f"{type(self).__name__} requires a schema_tree.")
@@ -150,21 +157,21 @@ class SchemaRule(BaseRule):
150
157
  class TreeRule(BaseRule):
151
158
  """Rule that checks entire tree."""
152
159
 
153
- def elements(self):
160
+ def elements(self) -> list[str]:
154
161
  return ["tree"]
155
162
 
156
- def check(self):
163
+ def check(self) -> None:
157
164
  """Checks entire tree."""
158
165
 
159
166
 
160
167
  class ValidReferenceRule(TreeRule):
161
168
  """Rule that makes sure reference values are properly defined."""
162
169
 
163
- def __init__(self, *args, missing_element="data", **kwargs):
170
+ def __init__(self, *args, missing_element: str = "data", **kwargs) -> None:
164
171
  super(ValidReferenceRule, self).__init__(*args, **kwargs)
165
172
  self.missing_element = missing_element
166
173
 
167
- def _gather_reference_values(self):
174
+ def _gather_reference_values(self) -> set[str]:
168
175
  """Collect a set of all values that are referencing a pre-defined value.
169
176
 
170
177
  Ex: A party leader ID should reference an ID from a PersonCollection.
@@ -172,7 +179,7 @@ class ValidReferenceRule(TreeRule):
172
179
  """
173
180
  raise NotImplementedError
174
181
 
175
- def _gather_defined_values(self):
182
+ def _gather_defined_values(self) -> set[str]:
176
183
  """Collect a set of the pre-defined values that are being referenced.
177
184
 
178
185
  Ex: A party leader ID should reference an ID from a PersonCollection.
@@ -180,15 +187,15 @@ class ValidReferenceRule(TreeRule):
180
187
  """
181
188
  raise NotImplementedError
182
189
 
183
- def check(self):
190
+ def check(self) -> None:
184
191
  reference_ids = self._gather_reference_values()
185
192
  defined_ids = self._gather_defined_values()
186
193
  invalid_references = reference_ids - defined_ids
187
194
 
188
195
  if invalid_references:
189
196
  raise loggers.ElectionError.from_message(
190
- ("No defined {} for {} found in the feed.".format(
191
- self.missing_element, ", ".join(invalid_references))))
197
+ (f"No defined {self.missing_element} for "
198
+ f"{', '.join(invalid_references)} found in the feed."))
192
199
 
193
200
 
194
201
  class DateRule(BaseRule):
@@ -198,7 +205,7 @@ class DateRule(BaseRule):
198
205
  end date values.
199
206
  """
200
207
 
201
- def __init__(self, *args, **kwargs):
208
+ def __init__(self, *args, **kwargs) -> None:
202
209
  super(DateRule, self).__init__(*args, **kwargs)
203
210
  self.start_elem = None
204
211
  self.start_date = None
@@ -206,7 +213,7 @@ class DateRule(BaseRule):
206
213
  self.end_date = None
207
214
  self.error_log = []
208
215
 
209
- def reset_instance_vars(self):
216
+ def reset_instance_vars(self) -> None:
210
217
  """Reset instance variables to initial state.
211
218
 
212
219
  Due to ordered procedure of validator, instance vars created in init
@@ -218,7 +225,7 @@ class DateRule(BaseRule):
218
225
  self.end_date = None
219
226
  self.error_log = []
220
227
 
221
- def gather_dates(self, element):
228
+ def gather_dates(self, element: etree._Element) -> None:
222
229
  """Gather StartDate and EndDate values for the provided element.
223
230
 
224
231
  An election element should have a start and end date in the desired format.
@@ -252,33 +259,38 @@ class DateRule(BaseRule):
252
259
  if error_log:
253
260
  raise loggers.ElectionError(error_log)
254
261
 
255
- def is_date_in_past(self, date):
262
+ def is_date_in_past(self, date: "PartialDate") -> bool:
256
263
  """Check if a date is in the past."""
257
264
  today = datetime.datetime.now(datetime.timezone.utc)
258
265
  today_partial_date = PartialDate(today.year, today.month, today.day)
259
266
  delta = date.is_older_than(today_partial_date)
260
267
  return delta > 0
261
268
 
262
- def check_for_date_not_in_past(self, date, date_elem):
269
+ def check_for_date_not_in_past(
270
+ self, date: "PartialDate | None", date_elem: etree._Element | None
271
+ ) -> None:
263
272
  """Check if given date is not in past and add an error message to the error log if the date is in past."""
264
273
  if date is not None and self.is_date_in_past(date):
265
- error_message = """The date {} is in the past.""".format(date)
274
+ error_message = f"The date {date} is in the past."
266
275
  self.error_log.append(loggers.LogEntry(error_message, [date_elem]))
267
276
 
268
- def check_for_date_in_past(self, date, date_elem):
277
+ def check_for_date_in_past(
278
+ self, date: "PartialDate | None", date_elem: etree._Element | None
279
+ ) -> None:
269
280
  """Check if given date is in past and add an error message to the error log if the date is not in past."""
270
281
  if date is not None and not self.is_date_in_past(date):
271
- error_message = """The date {} is not in the past.""".format(date)
282
+ error_message = f"The date {date} is not in the past."
272
283
  self.error_log.append(loggers.LogEntry(error_message, [date_elem]))
273
284
 
274
- def check_end_after_start(self):
285
+ def check_end_after_start(self) -> None:
275
286
  """Checks if EndDate is after StartDate and add an error message to the error log if the EndDate is before StartDate."""
276
287
  if self.start_date is not None and self.end_date is not None:
277
288
  start_end_delta = self.start_date.is_older_than(self.end_date)
278
289
  if start_end_delta < 0:
279
- error_message = """The dates (start: {}, end: {}) are invalid.
280
- The end date must be the same or after the start date.""".format(
281
- self.start_date, self.end_date)
290
+ error_message = (
291
+ f"The dates (start: {self.start_date}, end: {self.end_date}) are "
292
+ "invalid.\n The end date must be the same or after the start "
293
+ "date.")
282
294
  self.error_log.append(loggers.LogEntry(error_message, [self.end_elem]))
283
295
 
284
296
 
@@ -289,30 +301,35 @@ class PartialDate():
289
301
  REGEX_PATTERN = re.compile(
290
302
  r"^(?P<year>[0-9]{4})(?:-(?P<month>[0-9]{2}))?(?:-(?P<day>[0-9]{2}))?$")
291
303
 
292
- def __init__(self, year=None, month=None, day=None):
304
+ def __init__(
305
+ self,
306
+ year: int | None = None,
307
+ month: int | None = None,
308
+ day: int | None = None,
309
+ ) -> None:
293
310
  self.year = year
294
311
  self.month = month
295
312
  self.day = day
296
313
 
297
- def __str__(self):
314
+ def __str__(self) -> str:
298
315
  if self.is_only_year_date():
299
- return "%s" % self.year
316
+ return f"{self.year}"
300
317
  elif self.is_month_date():
301
- return "%s-%s" %(self.year, str(self.month).zfill(2))
318
+ return f"{self.year}-{str(self.month).zfill(2)}"
302
319
  elif self.is_complete_date():
303
- return "%s-%s-%s" % (self.year, str(self.month).zfill(2), str(
304
- self.day).zfill(2))
320
+ return (f"{self.year}-{str(self.month).zfill(2)}-"
321
+ f"{str(self.day).zfill(2)}")
305
322
  else:
306
323
  return "Not defined"
307
324
 
308
- def __lt__(self, other):
325
+ def __lt__(self, other: "PartialDate") -> bool:
309
326
  return self.is_older_than(other) > 0
310
327
 
311
- def __eq__(self, other):
328
+ def __eq__(self, other: "PartialDate") -> bool:
312
329
  return self.is_older_than(other) == 0
313
330
 
314
331
  @classmethod
315
- def init_partial_date(cls, date_string):
332
+ def init_partial_date(cls, date_string: str) -> "PartialDate | None":
316
333
  """Initializing partial date."""
317
334
  match_object = re.match(cls.REGEX_PATTERN, date_string)
318
335
  if match_object is None:
@@ -337,7 +354,7 @@ class PartialDate():
337
354
  return None
338
355
  return partial_date
339
356
 
340
- def is_older_than(self, other_date):
357
+ def is_older_than(self, other_date: "PartialDate") -> int:
341
358
  """Compares 2 dates/partial dates.
342
359
 
343
360
  Args:
@@ -366,13 +383,13 @@ class PartialDate():
366
383
  return other_date.month - self.month
367
384
  return other_date.day - self.day
368
385
 
369
- def is_only_year_date(self):
386
+ def is_only_year_date(self) -> bool:
370
387
  return self.year is not None and self.month is None and self.day is None
371
388
 
372
- def is_month_date(self):
389
+ def is_month_date(self) -> bool:
373
390
  return self.year is not None and self.month is not None and self.day is None
374
391
 
375
- def is_complete_date(self):
392
+ def is_complete_date(self) -> bool:
376
393
  return (
377
394
  self.year is not None
378
395
  and self.month is not None
@@ -383,15 +400,15 @@ class PartialDate():
383
400
  class MissingFieldRule(BaseRule):
384
401
  """Check for required fields for given entity types and field names."""
385
402
 
386
- def get_severity(self):
403
+ def get_severity(self) -> int:
387
404
  """Return 0 for Info, 1 for Warning, or 2 for Error."""
388
405
  raise NotImplementedError
389
406
 
390
- def element_field_mapping(self):
407
+ def element_field_mapping(self) -> dict[str, list[str]]:
391
408
  """Return a map of element tag to list of required fields."""
392
409
  raise NotImplementedError
393
410
 
394
- def setup(self):
411
+ def setup(self) -> None:
395
412
  severity = self.get_severity()
396
413
  handled_severities = loggers.handled_severities()
397
414
  if (severity > len(handled_severities)
@@ -400,10 +417,10 @@ class MissingFieldRule(BaseRule):
400
417
  "1 (Warning), or 2 (Error)"))
401
418
  self.exception = handled_severities[severity]
402
419
 
403
- def elements(self):
420
+ def elements(self) -> list[str]:
404
421
  return list(self.element_field_mapping().keys())
405
422
 
406
- def check(self, element):
423
+ def check(self, element: etree._Element) -> None:
407
424
  error_log = []
408
425
 
409
426
  required_field_tags = self.element_field_mapping()[element.tag]
@@ -412,8 +429,8 @@ class MissingFieldRule(BaseRule):
412
429
  if (required_field is None or required_field.text is None
413
430
  or not required_field.text.strip()):
414
431
  error_log.append(loggers.LogEntry(
415
- "The element {} is missing field {}.".format(element.tag,
416
- field_tag), [element]))
432
+ f"The element {element.tag} is missing field {field_tag}.",
433
+ [element]))
417
434
 
418
435
  if error_log:
419
436
  raise self.exception(error_log)
@@ -424,7 +441,7 @@ class RuleOption(object):
424
441
  option_name = None
425
442
  option_value = None
426
443
 
427
- def __init__(self, option_name, option_value):
444
+ def __init__(self, option_name: str, option_value: Any) -> None:
428
445
  self.option_name = option_name
429
446
  self.option_value = option_value
430
447
 
@@ -437,12 +454,12 @@ class RulesRegistry(SchemaHandler):
437
454
 
438
455
  def __init__(
439
456
  self,
440
- election_file,
441
- schema_file,
442
- rule_classes_to_check,
443
- rule_options,
444
- ocd_id_validator,
445
- ):
457
+ election_file: str | BinaryIO,
458
+ schema_file: str | TextIO,
459
+ rule_classes_to_check: Iterable[type[BaseRule]],
460
+ rule_options: Mapping[str, Iterable[RuleOption]],
461
+ ocd_id_validator: gpunit_rules.GpUnitOcdIdValidator | None,
462
+ ) -> None:
446
463
  self.election_file = election_file
447
464
  self.schema_file = schema_file
448
465
  self.rule_classes_to_check = rule_classes_to_check
@@ -452,7 +469,7 @@ class RulesRegistry(SchemaHandler):
452
469
  self.exceptions_wrapper = loggers.ExceptionListWrapper()
453
470
  self.election_tree = None
454
471
 
455
- def register_rules(self):
472
+ def register_rules(self) -> None:
456
473
  """Register all the rules to be checked.
457
474
 
458
475
  Returns:
@@ -474,21 +491,22 @@ class RulesRegistry(SchemaHandler):
474
491
  else:
475
492
  self.registry[element] = [rule_instance]
476
493
 
477
- def print_exceptions(self, severity, verbose):
494
+ def print_exceptions(self, severity: int | None, verbose: bool) -> None:
478
495
  self.exceptions_wrapper.print_exceptions(severity, verbose)
479
496
 
480
- def get_all_exceptions(self):
497
+ def get_all_exceptions(
498
+ self,
499
+ ) -> dict[type[Exception], dict[str, list[loggers.LogEntry]]]:
481
500
  return self.exceptions_wrapper.get_all_exceptions()
482
501
 
483
- def count_stats(self):
502
+ def count_stats(self) -> None:
484
503
  """Aggregates the counts for each top level entity."""
485
504
  if self.election_tree:
486
505
  # Find the top-level entities.
487
- entity_path_str = ".//{0}Collection//{1}"
488
506
  print("\n" + " " * 5 + "Entity and Attribute Counts:")
489
507
  for entity_name in stats.ENTITY_STATS:
490
508
  entity_instances = self.election_tree.findall(
491
- entity_path_str.format(entity_name, entity_name))
509
+ f".//{entity_name}Collection//{entity_name}")
492
510
  if entity_instances:
493
511
  # If top-level entity exists, instantiate a stat counter with total.
494
512
  entity_stats = stats.ENTITY_STATS[entity_name](len(entity_instances))
@@ -496,17 +514,17 @@ class RulesRegistry(SchemaHandler):
496
514
  for attr in entity_stats.attribute_counts:
497
515
  for instance in entity_instances:
498
516
  entity_stats.increment_attribute(
499
- attr, len(instance.findall(".//{}".format(attr))))
517
+ attr, len(instance.findall(f".//{attr}")))
500
518
  print(entity_stats)
501
519
 
502
- def check_rules(self):
520
+ def check_rules(self) -> None:
503
521
  """Checks all rules."""
504
522
  try:
505
523
  self.schema_tree = etree.parse(self.schema_file)
506
524
  self.election_tree = etree.parse(self.election_file)
507
525
  except etree.LxmlError as e:
508
526
  exp = loggers.ElectionFatal.from_message(
509
- "Fatal Error. XML file could not be parsed. {}".format(e))
527
+ f"Fatal Error. XML file could not be parsed. {e}")
510
528
  self.exceptions_wrapper.exception_handler(exp)
511
529
  return
512
530
  self.register_rules()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: civics_cdf_validator
3
- Version: 1.68.dev14
3
+ Version: 1.68.dev15
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
@@ -54,7 +54,7 @@ setup(
54
54
  install_requires=[
55
55
  'lxml>=3.3.4',
56
56
  'language-tags>=0.4.2',
57
- '%s>=2.10' % requests_version,
57
+ f'{requests_version}>=2.10',
58
58
  'networkx>=2.6.3',
59
59
  'pycountry==22.1.10',
60
60
  'frozendict>=2.4.4',
@@ -22,11 +22,13 @@ See https://developers.google.com/elections-data/reference/
22
22
  from __future__ import print_function
23
23
 
24
24
  import argparse
25
+ from collections.abc import Callable, Collection, Iterable, Mapping
25
26
  import cProfile
26
27
  import hashlib
27
28
  import io
28
29
  import os
29
30
  import pstats
31
+ from typing import Any, BinaryIO, TypeVar
30
32
 
31
33
  from civics_cdf_validator import base
32
34
  from civics_cdf_validator import gpunit_rules
@@ -39,16 +41,18 @@ _REGISTRY_KEY = "registry"
39
41
  _METADATA_KEY = "metadata"
40
42
  _FILE_NAME_KEY = "file_name"
41
43
 
44
+ _T = TypeVar("_T")
42
45
 
43
- def _validate_path(parser, arg):
46
+
47
+ def _validate_path(parser: argparse.ArgumentParser, arg: str) -> str:
44
48
  """Check that the files provided exist."""
45
49
  if not os.path.exists(arg):
46
- parser.error("The file path for %s doesn't exist" % arg)
50
+ parser.error(f"The file path for {arg} doesn't exist")
47
51
  else:
48
52
  return arg
49
53
 
50
54
 
51
- def _validate_rules(parser, arg):
55
+ def _validate_rules(parser: argparse.ArgumentParser, arg: str) -> list[str]:
52
56
  """Check that the listed rules exist."""
53
57
  invalid_rules = []
54
58
  rule_names = [x.__name__ for x in rules.ALL_RULES]
@@ -57,25 +61,26 @@ def _validate_rules(parser, arg):
57
61
  if rule and rule not in rule_names:
58
62
  invalid_rules.append(rule)
59
63
  if invalid_rules:
60
- parser.error("The rule(s) %s do not exist" % ", ".join(invalid_rules))
64
+ parser.error(f"The rule(s) {', '.join(invalid_rules)} do not exist")
61
65
  else:
62
66
  return input_rules
63
67
 
64
68
 
65
- def _validate_severity(parser, arg):
69
+ def _validate_severity(parser: argparse.ArgumentParser, arg: str) -> int:
66
70
  """Check that the severity level provided is correct."""
67
71
  valid_severities = loggers.supported_severities_mapping()
68
72
 
69
73
  if arg.strip().lower() not in valid_severities:
70
- parser.error("Invalid severity. Options are {0}".format(
71
- valid_severities.keys()))
74
+ parser.error(f"Invalid severity. Options are {valid_severities.keys()}")
72
75
  else:
73
76
  return valid_severities[arg.strip().lower()]
74
77
 
75
78
 
76
79
  # pylint: disable=g-doc-args
77
80
  # pylint: disable=g-doc-return-or-yield
78
- def _validate_country_codes(parser, arg):
81
+ def _validate_country_codes(
82
+ parser: argparse.ArgumentParser, arg: str
83
+ ) -> str | None:
79
84
  """Check that the supplied 2 country code is correct.
80
85
 
81
86
  Check if the provided country code is listed in ISO 3166-1 alpha-2 codes
@@ -93,7 +98,7 @@ def _validate_country_codes(parser, arg):
93
98
  )
94
99
 
95
100
 
96
- def arg_parser():
101
+ def arg_parser() -> argparse.ArgumentParser:
97
102
  """Parser for command line arguments."""
98
103
 
99
104
  description = ("Script to validate that "
@@ -108,7 +113,9 @@ def arg_parser():
108
113
  return parser
109
114
 
110
115
 
111
- def add_validate_parser_args(parser, parser_validate):
116
+ def add_validate_parser_args(
117
+ parser: argparse.ArgumentParser, parser_validate: argparse.ArgumentParser
118
+ ) -> None:
112
119
  add_validate_parser_input_file_args(parser, parser_validate)
113
120
  add_validate_parser_output_args(parser, parser_validate)
114
121
  add_validate_parser_ocd_id_args(parser, parser_validate)
@@ -123,7 +130,9 @@ def add_validate_parser_args(parser, parser_validate):
123
130
  required=False)
124
131
 
125
132
 
126
- def add_validate_parser_input_file_args(parser, parser_validate):
133
+ def add_validate_parser_input_file_args(
134
+ parser: argparse.ArgumentParser, parser_validate: argparse.ArgumentParser
135
+ ) -> None:
127
136
  parser_validate.add_argument(
128
137
  "-x",
129
138
  "--xsd",
@@ -139,7 +148,9 @@ def add_validate_parser_input_file_args(parser, parser_validate):
139
148
  type=lambda x: _validate_path(parser, x))
140
149
 
141
150
 
142
- def add_validate_parser_output_args(parser, parser_validate):
151
+ def add_validate_parser_output_args(
152
+ parser: argparse.ArgumentParser, parser_validate: argparse.ArgumentParser
153
+ ) -> None:
143
154
  """Enriches cmd "validate" parser with output display config."""
144
155
  parser_validate.add_argument(
145
156
  "--verbose",
@@ -151,12 +162,13 @@ def add_validate_parser_output_args(parser, parser_validate):
151
162
  "--severity",
152
163
  "-s",
153
164
  type=lambda x: _validate_severity(parser, x),
154
- help="Minimum issue severity level - {0}".format(
155
- loggers.severities_names()),
165
+ help=f"Minimum issue severity level - {loggers.severities_names()}",
156
166
  required=False)
157
167
 
158
168
 
159
- def add_validate_parser_ocd_id_args(parser, parser_validate):
169
+ def add_validate_parser_ocd_id_args(
170
+ parser: argparse.ArgumentParser, parser_validate: argparse.ArgumentParser
171
+ ) -> None:
160
172
  """Enriches cmd "validate" parser with ocdId related arguments."""
161
173
  parser_validate.add_argument(
162
174
  "--ocdid_file",
@@ -192,7 +204,9 @@ def add_validate_parser_ocd_id_args(parser, parser_validate):
192
204
  )
193
205
 
194
206
 
195
- def add_parser_rules_filter_args(parser, cmd_parser):
207
+ def add_parser_rules_filter_args(
208
+ parser: argparse.ArgumentParser, cmd_parser: argparse.ArgumentParser
209
+ ) -> None:
196
210
  """Enriches cmd parser with rules related arguments."""
197
211
  cmd_parser.add_argument(
198
212
  "-e",
@@ -211,46 +225,51 @@ def add_parser_rules_filter_args(parser, cmd_parser):
211
225
  group.add_argument(
212
226
  "--rule_set",
213
227
  "-r",
214
- help="Pre-defined rule set: [{}].".format(", ".join(
215
- s.name.lower() for s in rules.RuleSet)),
228
+ help=("Pre-defined rule set: ["
229
+ f"{', '.join(s.name.lower() for s in rules.RuleSet)}]."),
216
230
  required=False,
217
231
  default="election",
218
232
  type=ruleset_type)
219
233
 
220
234
 
221
- def ruleset_type(enum_string):
235
+ def ruleset_type(enum_string: str) -> rules.RuleSet:
222
236
  try:
223
237
  return rules.RuleSet[enum_string.upper()]
224
238
  except KeyError:
225
- msg = "Rule set must be one of [{}]".format(", ".join(
226
- s.name.lower() for s in rules.RuleSet))
239
+ msg = ("Rule set must be one of ["
240
+ f"{', '.join(s.name.lower() for s in rules.RuleSet)}]")
227
241
  raise argparse.ArgumentTypeError(msg)
228
242
 
229
243
 
230
- def get_metadata(file):
244
+ def get_metadata(file: BinaryIO) -> list[str]:
231
245
  """Gets metadata associated with this run of the validator."""
232
- metadata = ["Validator version: {}".format(version.__version__)]
246
+ metadata = [f"Validator version: {version.__version__}"]
233
247
 
234
248
  blocksize = 65536
235
249
  digest = hashlib.new("sha3_256")
236
250
  for block in iter(lambda: file.read(blocksize), b""):
237
251
  digest.update(block)
238
- metadata.append("SHA3-256 checksum: 0x{}".format(digest.hexdigest()))
252
+ metadata.append(f"SHA3-256 checksum: 0x{digest.hexdigest()}")
239
253
  file.seek(0)
240
254
  return metadata
241
255
 
242
256
 
243
- def display_rules_details(options):
257
+ def display_rules_details(options: Any) -> None:
244
258
  """Display rules set details based on user input."""
245
259
  print("Selected rules details:")
246
260
  rules_to_display = filter_all_rules_using_user_arg(options.include,
247
261
  options.rule_set,
248
262
  options.exclude)
249
263
  for rule in sorted(rules_to_display, key=lambda x: x.__name__):
250
- print("\t{} - {}".format(rule.__name__, rule.__doc__.split("\n")[0]))
264
+ summary = rule.__doc__.split("\n")[0]
265
+ print(f"\t{rule.__name__} - {summary}")
251
266
 
252
267
 
253
- def filter_all_rules_using_user_arg(rules_allowlist, rule_set, rules_blocklist):
268
+ def filter_all_rules_using_user_arg(
269
+ rules_allowlist: Collection[str] | None,
270
+ rule_set: rules.RuleSet,
271
+ rules_blocklist: Collection[str] | None,
272
+ ) -> list[type[base.BaseRule]]:
254
273
  """Extract a sublist from ALL_RULES list using the user input."""
255
274
  if rules_allowlist:
256
275
  rule_names = rules_allowlist
@@ -280,7 +299,18 @@ def filter_all_rules_using_user_arg(rules_allowlist, rule_set, rules_blocklist):
280
299
  return rule_classes_to_check
281
300
 
282
301
 
283
- def compute_max_found_severity(exceptions_wrapper):
302
+ def compute_max_found_severity(
303
+ exceptions_wrapper: loggers.ExceptionListWrapper,
304
+ ) -> int:
305
+ """Returns a severity code for the most severe exception type found.
306
+
307
+ Args:
308
+ exceptions_wrapper: The exceptions collected during validation.
309
+
310
+ Returns:
311
+ 4 for fatal errors, 3 for errors, 2 for warnings, 1 for info and 0 if no
312
+ exceptions were found.
313
+ """
284
314
  if exceptions_wrapper.count_logs_with_exception_type(loggers.ElectionFatal):
285
315
  return 4
286
316
  elif exceptions_wrapper.count_logs_with_exception_type(loggers.ElectionError):
@@ -294,9 +324,9 @@ def compute_max_found_severity(exceptions_wrapper):
294
324
  return 0
295
325
 
296
326
 
297
- def exec_profiling(func):
327
+ def exec_profiling(func: Callable[..., _T]) -> Callable[..., _T]:
298
328
  """This is a decorator to add profiling to the feed validation."""
299
- def add_profiling_if_needed(options, *args, **kwargs):
329
+ def add_profiling_if_needed(options: Any, *args, **kwargs) -> _T:
300
330
  if options is None or not options.profile_report:
301
331
  return func(options, *args, **kwargs)
302
332
  pr = cProfile.Profile(builtins=False)
@@ -313,7 +343,9 @@ def exec_profiling(func):
313
343
 
314
344
 
315
345
  @exec_profiling
316
- def feed_validation(options, ocd_id_list=None):
346
+ def feed_validation(
347
+ options: Any, ocd_id_list: Iterable[str] | None = None
348
+ ) -> list[dict[str, Any]]:
317
349
  """Validate the input feed depending on the user parameters."""
318
350
  ocd_id_validator = gpunit_rules.GpUnitOcdIdValidator(
319
351
  options.c, options.ocdid_file, ocd_id_list
@@ -345,7 +377,9 @@ def feed_validation(options, ocd_id_list=None):
345
377
  return validation_results
346
378
 
347
379
 
348
- def print_exceptions_from_validations(options, results_validations):
380
+ def print_exceptions_from_validations(
381
+ options: Any, results_validations: Iterable[Mapping[str, Any]]
382
+ ) -> int:
349
383
  """Print errors to stdout."""
350
384
  max_error_severity = 0
351
385
  for result_validation in results_validations:
@@ -353,9 +387,7 @@ def print_exceptions_from_validations(options, results_validations):
353
387
  metadata = result_validation[_METADATA_KEY]
354
388
  rule_registry = result_validation[_REGISTRY_KEY]
355
389
  print(
356
- "\n--------- Results after validating file: {} ".format(
357
- election_filename
358
- )
390
+ f"\n--------- Results after validating file: {election_filename} "
359
391
  )
360
392
  for metadatum in metadata:
361
393
  print(metadatum)
@@ -369,7 +401,7 @@ def print_exceptions_from_validations(options, results_validations):
369
401
  return max_error_severity
370
402
 
371
403
 
372
- def main():
404
+ def main() -> int | None:
373
405
  p = arg_parser()
374
406
  options = p.parse_args()
375
407
  if options.cmd == "list":
@@ -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.dev14'
8
+ __version__ = '1.68.dev15'