civics-cdf-validator 1.68.dev15__tar.gz → 1.68.dev16__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.dev15/civics_cdf_validator.egg-info → civics_cdf_validator-1.68.dev16}/PKG-INFO +1 -1
  2. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16/civics_cdf_validator.egg-info}/PKG-INFO +1 -1
  3. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/gpunit_rules.py +19 -9
  4. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/loggers.py +47 -22
  5. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/metadata_rules.py +43 -46
  6. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/rule_util.py +19 -9
  7. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/stats.py +16 -15
  8. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/version.py +1 -1
  9. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/CONTRIBUTING.md +0 -0
  10. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/LICENSE-2.0.txt +0 -0
  11. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/MANIFEST.in +0 -0
  12. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/README.md +0 -0
  13. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/__init__.py +0 -0
  14. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/base.py +0 -0
  15. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/SOURCES.txt +0 -0
  16. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/dependency_links.txt +0 -0
  17. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/entry_points.txt +0 -0
  18. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/requires.txt +0 -0
  19. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/top_level.txt +0 -0
  20. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/office_utils.py +0 -0
  21. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rules.py +0 -0
  22. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/__init__.py +0 -0
  23. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/committee_rules.py +0 -0
  24. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/common_rules.py +0 -0
  25. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/election_dates_rules.py +0 -0
  26. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/election_results_rules.py +0 -0
  27. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/election_rules.py +0 -0
  28. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/officeholder_rules.py +0 -0
  29. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/rulesets/voter_information_rules.py +0 -0
  30. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/setup.cfg +0 -0
  31. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/setup.py +0 -0
  32. {civics_cdf_validator-1.68.dev15 → civics_cdf_validator-1.68.dev16}/validator.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: civics_cdf_validator
3
- Version: 1.68.dev15
3
+ Version: 1.68.dev16
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.dev15
3
+ Version: 1.68.dev16
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
@@ -15,6 +15,7 @@
15
15
 
16
16
  from __future__ import print_function
17
17
 
18
+ from collections.abc import Iterable
18
19
  import csv
19
20
  import datetime
20
21
  import io
@@ -28,19 +29,21 @@ import pycountry
28
29
  import requests
29
30
 
30
31
 
31
- def generate_github_raw_url(repo_name, subdir, file_name, branch="master"):
32
+ def generate_github_raw_url(
33
+ repo_name: str, subdir: str, file_name: str, branch: str = "master"
34
+ ) -> str:
32
35
  return f"https://raw.github.com/{repo_name}/{branch}/{subdir}/{file_name}"
33
36
 
34
37
 
35
- def generate_github_archive_url(repo_name, branch="master"):
38
+ def generate_github_archive_url(repo_name: str, branch: str = "master") -> str:
36
39
  return f"https://github.com/{repo_name}/archive/refs/heads/{branch}.zip"
37
40
 
38
41
 
39
- def generate_country_filename(country_code):
42
+ def generate_country_filename(country_code: str) -> str:
40
43
  return f"country-{country_code}.csv"
41
44
 
42
45
 
43
- def generate_absolute_path(path_to_directory, country_code):
46
+ def generate_absolute_path(path_to_directory: str, country_code: str) -> str:
44
47
  return f"{path_to_directory}/{generate_country_filename(country_code)}"
45
48
 
46
49
 
@@ -56,7 +59,12 @@ class GpUnitOcdIdValidator(object):
56
59
  OCD_PATTERN_ROOT = r"^ocd-division\/(country:[a-z]{2}|region:eu)$"
57
60
  OCD_MATCHER_ROOT = re.compile(OCD_PATTERN_ROOT, flags=re.U)
58
61
 
59
- def __init__(self, country_code=None, local_file=None, ocd_id_list=None):
62
+ def __init__(
63
+ self,
64
+ country_code: str | None = None,
65
+ local_file: str | None = None,
66
+ ocd_id_list: Iterable[str] | None = None,
67
+ ) -> None:
60
68
  """Initialize the class.
61
69
 
62
70
  If a list is provided, that list will be used to initialize the set of OCD
@@ -76,7 +84,7 @@ class GpUnitOcdIdValidator(object):
76
84
  extractor = OcdIdsExtractor(country_code, local_file)
77
85
  self.ocd_ids = extractor.extract()
78
86
 
79
- def is_valid_ocd_id(self, ocd_id):
87
+ def is_valid_ocd_id(self, ocd_id: str) -> bool | None:
80
88
  """Check whether the given OCD ID is valid.
81
89
 
82
90
  An OCD ID is valid if:
@@ -98,7 +106,7 @@ class GpUnitOcdIdValidator(object):
98
106
  )
99
107
 
100
108
  @classmethod
101
- def is_valid_country_code(cls, ocd_id):
109
+ def is_valid_country_code(cls, ocd_id: str) -> bool:
102
110
  """Check whether country code in the given OCD ID is valid."""
103
111
  match_object = re.match(cls.OCD_PATTERN, ocd_id)
104
112
  if match_object is None:
@@ -113,7 +121,7 @@ class GpUnitOcdIdValidator(object):
113
121
  return False
114
122
 
115
123
  @classmethod
116
- def is_country_or_region_ocd_id(cls, ocd_id):
124
+ def is_country_or_region_ocd_id(cls, ocd_id: str) -> re.Match[str] | None:
117
125
  """Check whether the given OCD ID represents a country or region."""
118
126
  return cls.OCD_MATCHER_ROOT.match(str(ocd_id))
119
127
 
@@ -171,7 +179,9 @@ class OcdIdsExtractor(object):
171
179
  github_raw_url: str
172
180
  local_filepath: str
173
181
 
174
- def __init__(self, country_code=None, local_file=None):
182
+ def __init__(
183
+ self, country_code: str | None = None, local_file: str | None = None
184
+ ) -> None:
175
185
  self.country_code = country_code
176
186
  self.local_file = local_file
177
187
 
@@ -14,13 +14,22 @@ See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  """
16
16
 
17
+ from collections.abc import Sequence
17
18
  import copy
19
+ from typing import Self
20
+
21
+ from lxml import etree
18
22
 
19
23
 
20
24
  class LogEntry(object):
21
25
  """This class contains needed information for user output."""
22
26
 
23
- def __init__(self, message, elements=None, lines=None):
27
+ def __init__(
28
+ self,
29
+ message: str,
30
+ elements: Sequence[etree._Element | None] | None = None,
31
+ lines: Sequence[int] | None = None,
32
+ ) -> None:
24
33
  self.message = message
25
34
  self.elements = elements
26
35
  if lines is not None:
@@ -40,7 +49,7 @@ class ElectionException(Exception):
40
49
  """Base class for all the exceptions in this script."""
41
50
  description = None
42
51
 
43
- def __init__(self, log_entry):
52
+ def __init__(self, log_entry: LogEntry | list[LogEntry]) -> None:
44
53
  super(ElectionException, self).__init__()
45
54
  if isinstance(log_entry, list):
46
55
  self.log_entry = log_entry
@@ -48,7 +57,12 @@ class ElectionException(Exception):
48
57
  self.log_entry = [log_entry]
49
58
 
50
59
  @classmethod
51
- def from_message(cls, message, elements=None, lines=None):
60
+ def from_message(
61
+ cls,
62
+ message: str,
63
+ elements: Sequence[etree._Element | None] | None = None,
64
+ lines: Sequence[int] | None = None,
65
+ ) -> Self:
52
66
  return cls(LogEntry(message, elements, lines))
53
67
 
54
68
 
@@ -82,7 +96,7 @@ class ElectionInfo(ElectionException):
82
96
  description = "Info"
83
97
 
84
98
 
85
- def get_parent_hierarchy_object_id_str(elt):
99
+ def get_parent_hierarchy_object_id_str(elt: etree._Element | None) -> str:
86
100
  """Get the elt path from the 1st parent with an objectId / ElectionReport."""
87
101
  elt_hierarchy = []
88
102
  current_elt = elt
@@ -112,12 +126,14 @@ class ExceptionListWrapper:
112
126
  ElectionError,
113
127
  ElectionFatal)
114
128
 
115
- def __init__(self):
129
+ def __init__(self) -> None:
116
130
  self._rules_exc_logs = dict()
117
131
  for e_type in self.SUPPORTED_SEVERITIES:
118
132
  self._rules_exc_logs[e_type] = dict()
119
133
 
120
- def exception_handler(self, exception, rule_name="No rule"):
134
+ def exception_handler(
135
+ self, exception: ElectionException, rule_name: str = "No rule"
136
+ ) -> None:
121
137
  """Gather log entry counts by type, class, and total."""
122
138
  for e_type in self._rules_exc_logs:
123
139
  if issubclass(exception.__class__, e_type):
@@ -125,47 +141,56 @@ class ExceptionListWrapper:
125
141
  self._rules_exc_logs[e_type][rule_name] = []
126
142
  self._rules_exc_logs[e_type][rule_name].extend(exception.log_entry)
127
143
 
128
- def _select_exception_types(self, severity):
144
+ def _select_exception_types(
145
+ self, severity: int | None
146
+ ) -> tuple[type[ElectionException], ...]:
129
147
  if not severity:
130
148
  severity = 0
131
149
  elif severity > len(self.SUPPORTED_SEVERITIES):
132
150
  severity = len(self.SUPPORTED_SEVERITIES) - 1
133
151
  return self.SUPPORTED_SEVERITIES[severity:]
134
152
 
135
- def count_logs_with_exception_type(self, e_type):
153
+ def count_logs_with_exception_type(
154
+ self, e_type: type[ElectionException]
155
+ ) -> int:
136
156
  exception_count = 0
137
157
  for log_list in list(self._rules_exc_logs[e_type].values()):
138
158
  exception_count += len(log_list)
139
159
  return exception_count
140
160
 
141
- def _print_exception_type_summary(self, e_type, count_exception):
161
+ def _print_exception_type_summary(
162
+ self, e_type: type[ElectionException], count_exception: int
163
+ ) -> None:
142
164
  suffix = ""
143
165
  if count_exception > 1:
144
166
  suffix = "s"
145
- print("{0:6d} {1} message{2} found".format(count_exception,
146
- e_type.description, suffix))
167
+ print(f"{count_exception:6d} {e_type.description} message{suffix} found")
147
168
 
148
- def _print_rule_exception_summary(self, e_type, rule_name):
169
+ def _print_rule_exception_summary(
170
+ self, e_type: type[ElectionException], rule_name: str
171
+ ) -> None:
149
172
  rule_count = len(self._rules_exc_logs[e_type][rule_name])
150
173
  rule_suffix = ""
151
174
  if rule_count > 1:
152
175
  rule_suffix = "s"
153
- print("{0:10d} {1} {2} message{3}".format(rule_count, rule_name,
154
- e_type.description, rule_suffix))
176
+ print(f"{rule_count:10d} {rule_name} {e_type.description} "
177
+ f"message{rule_suffix}")
155
178
 
156
- def _print_exception_log(self, log_entry):
179
+ def _print_exception_log(self, log_entry: LogEntry) -> None:
157
180
  if log_entry.lines is not None:
158
- print(" " * 14 + "Lines %s :" % log_entry.lines)
181
+ print(" " * 14 + f"Lines {log_entry.lines} :")
159
182
  if log_entry.elements is not None:
160
183
  print(" " * 15 + "Affected elements :")
161
184
  for element in log_entry.elements:
162
185
  print(" " * 16 + get_parent_hierarchy_object_id_str(element))
163
- print(" " * 18 + "* {0}".format(log_entry.message))
186
+ print(" " * 18 + f"* {log_entry.message}")
164
187
 
165
- def get_all_exceptions(self):
188
+ def get_all_exceptions(
189
+ self,
190
+ ) -> dict[type[Exception], dict[str, list[LogEntry]]]:
166
191
  return copy.deepcopy(self._rules_exc_logs)
167
192
 
168
- def print_exceptions(self, severity, verbose):
193
+ def print_exceptions(self, severity: int | None, verbose: bool) -> None:
169
194
  """Print exceptions in decreasing order of severity."""
170
195
  exception_types = self._select_exception_types(severity)
171
196
  for e_type in reversed(exception_types):
@@ -185,11 +210,11 @@ class ExceptionListWrapper:
185
210
  self._print_exception_log(log_entry)
186
211
 
187
212
 
188
- def handled_severities():
213
+ def handled_severities() -> tuple[type[ElectionException], ...]:
189
214
  return ExceptionListWrapper.SUPPORTED_SEVERITIES
190
215
 
191
216
 
192
- def supported_severities_mapping():
217
+ def supported_severities_mapping() -> dict[str, int]:
193
218
  exp_severity_map = {}
194
219
  for n in range(len(ExceptionListWrapper.SUPPORTED_SEVERITIES)):
195
220
  exp_severity_map[
@@ -197,7 +222,7 @@ def supported_severities_mapping():
197
222
  return exp_severity_map
198
223
 
199
224
 
200
- def severities_names():
225
+ def severities_names() -> list[str]:
201
226
  names = []
202
227
  for exp in ExceptionListWrapper.SUPPORTED_SEVERITIES:
203
228
  names.append(exp.description.lower())
@@ -24,6 +24,7 @@ from civics_cdf_validator.rulesets import common_rules
24
24
  from civics_cdf_validator.rulesets import rule_util
25
25
  import dateutil
26
26
  from frozendict import frozendict
27
+ from lxml import etree
27
28
 
28
29
 
29
30
  _VALID_FEED_LONGEVITY_BY_FEED_TYPE = frozendict({
@@ -38,10 +39,10 @@ _VALID_FEED_LONGEVITY_BY_FEED_TYPE = frozendict({
38
39
  class FeedTypeHasValidFeedLongevity(base.BaseRule):
39
40
  """Feeds types should have valid corresponding FeedLongevity."""
40
41
 
41
- def elements(self):
42
+ def elements(self) -> list[str]:
42
43
  return ["Feed"]
43
44
 
44
- def check(self, element):
45
+ def check(self, element: etree._Element) -> None:
45
46
  feed_type_element = element.find("FeedType")
46
47
  feed_longevity_element = element.find("FeedLongevity")
47
48
  if rule_util.element_has_text(
@@ -55,12 +56,9 @@ class FeedTypeHasValidFeedLongevity(base.BaseRule):
55
56
  not in _VALID_FEED_LONGEVITY_BY_FEED_TYPE[feed_type]
56
57
  ):
57
58
  raise loggers.ElectionError.from_message(
58
- "Feed type {} has invalid feed longevity {}. Valid feed"
59
- " longevities for this type are {}".format(
60
- feed_type,
61
- feed_longevity,
62
- _VALID_FEED_LONGEVITY_BY_FEED_TYPE[feed_type],
63
- ),
59
+ f"Feed type {feed_type} has invalid feed longevity"
60
+ f" {feed_longevity}. Valid feed longevities for this type are"
61
+ f" {_VALID_FEED_LONGEVITY_BY_FEED_TYPE[feed_type]}",
64
62
  [element],
65
63
  )
66
64
 
@@ -68,10 +66,10 @@ class FeedTypeHasValidFeedLongevity(base.BaseRule):
68
66
  class FeedIdsAreUnique(base.BaseRule):
69
67
  """FeedId should be unique."""
70
68
 
71
- def elements(self):
69
+ def elements(self) -> list[str]:
72
70
  return ["FeedCollection"]
73
71
 
74
- def check(self, element):
72
+ def check(self, element: etree._Element) -> None:
75
73
  feed_ids = set()
76
74
  error_log = []
77
75
  for feed_element in element.findall("Feed"):
@@ -79,8 +77,8 @@ class FeedIdsAreUnique(base.BaseRule):
79
77
  feed_id = feed_element.find("FeedId").text
80
78
  if feed_id in feed_ids:
81
79
  msg = (
82
- "FeedId {} appears multiple times in the metadata feed. Feed ids"
83
- " must be unique.".format(feed_id)
80
+ f"FeedId {feed_id} appears multiple times in the metadata feed."
81
+ " Feed ids must be unique."
84
82
  )
85
83
  error_log.append(
86
84
  loggers.LogEntry(
@@ -97,10 +95,10 @@ class FeedIdsAreUnique(base.BaseRule):
97
95
  class SourceDirPathsAreUnique(base.BaseRule):
98
96
  """All SourceDirPaths should be unique."""
99
97
 
100
- def elements(self):
98
+ def elements(self) -> list[str]:
101
99
  return ["FeedCollection"]
102
100
 
103
- def check(self, element):
101
+ def check(self, element: etree._Element) -> None:
104
102
  source_dir_paths = set()
105
103
  error_log = []
106
104
  for feed_element in element.findall("Feed"):
@@ -108,8 +106,8 @@ class SourceDirPathsAreUnique(base.BaseRule):
108
106
  source_dir_path = feed_element.find("SourceDirPath").text
109
107
  if source_dir_path in source_dir_paths:
110
108
  msg = (
111
- "SourceDirPath {} appears multiple times in the metadata feed."
112
- " SourceDirPaths must be unique.".format(source_dir_path)
109
+ f"SourceDirPath {source_dir_path} appears multiple times in the"
110
+ " metadata feed. SourceDirPaths must be unique."
113
111
  )
114
112
  error_log.append(
115
113
  loggers.LogEntry(
@@ -132,10 +130,10 @@ class SqsQueueNameIsFullyQualifiedArn(base.BaseRule):
132
130
  Only AWS region ARNs are supported.
133
131
  """
134
132
 
135
- def elements(self):
133
+ def elements(self) -> list[str]:
136
134
  return ["Feed"]
137
135
 
138
- def check(self, element):
136
+ def check(self, element: etree._Element) -> None:
139
137
  sqs_queue_name = element.find("SqsQueueName")
140
138
  if not rule_util.element_has_text(sqs_queue_name):
141
139
  return
@@ -181,10 +179,10 @@ class SqsQueueNameIsFullyQualifiedArn(base.BaseRule):
181
179
  class SqsQueueNameRequiresS3SourceDirPath(base.BaseRule):
182
180
  """If SqsQueueName is set, SourceDirPath must also be set and must be an s3 path."""
183
181
 
184
- def elements(self):
182
+ def elements(self) -> list[str]:
185
183
  return ["Feed"]
186
184
 
187
- def check(self, element):
185
+ def check(self, element: etree._Element) -> None:
188
186
  sqs_queue_name = element.find("SqsQueueName")
189
187
  if not rule_util.element_has_text(sqs_queue_name):
190
188
  return
@@ -194,7 +192,7 @@ class SqsQueueNameRequiresS3SourceDirPath(base.BaseRule):
194
192
  ) or not source_dir_path.text.strip().lower().startswith("s3://"):
195
193
  raise loggers.ElectionError.from_message(
196
194
  "If SqsQueueName is set, SourceDirPath must also be set and must be"
197
- " an s3 path for feed {}.".format(element.find("FeedId").text),
195
+ f" an s3 path for feed {element.find('FeedId').text}.",
198
196
  [element],
199
197
  )
200
198
 
@@ -202,10 +200,10 @@ class SqsQueueNameRequiresS3SourceDirPath(base.BaseRule):
202
200
  class ElectionEventDatesAreSequential(base.DateRule):
203
201
  """Dates in an ElectionEvent element should be sequential."""
204
202
 
205
- def elements(self):
203
+ def elements(self) -> list[str]:
206
204
  return ["ElectionEvent"]
207
205
 
208
- def check(self, element):
206
+ def check(self, element: etree._Element) -> None:
209
207
  self.reset_instance_vars()
210
208
  self.gather_dates(element)
211
209
  self.check_end_after_start()
@@ -247,10 +245,10 @@ class ElectionEventDatesAreSequential(base.DateRule):
247
245
  class SourceDirPathMustBeSetAfterInitialDeliveryDate(base.BaseRule):
248
246
  """SourceDirPath must be set if any InitialDeliveryDate is in the past."""
249
247
 
250
- def elements(self):
248
+ def elements(self) -> list[str]:
251
249
  return ["Feed"]
252
250
 
253
- def check(self, element):
251
+ def check(self, element: etree._Element) -> None:
254
252
  if rule_util.element_has_text(element.find("SourceDirPath")):
255
253
  return
256
254
  today = datetime.date.today()
@@ -275,10 +273,10 @@ class SourceDirPathMustBeSetAfterInitialDeliveryDate(base.BaseRule):
275
273
  class OfficeholderSubFeedDatesAreSequential(base.DateRule):
276
274
  """Dates in an OfficeholderSubFeed element should be sequential."""
277
275
 
278
- def elements(self):
276
+ def elements(self) -> list[str]:
279
277
  return ["OfficeholderSubFeed"]
280
278
 
281
- def check(self, element):
279
+ def check(self, element: etree._Element) -> None:
282
280
  if rule_util.element_has_text(
283
281
  element.find("InitialDeliveryDate")
284
282
  ) and rule_util.element_has_text(element.find("FullDeliveryDate")):
@@ -300,10 +298,10 @@ class FeedInactiveDateIsLatestDate(base.BaseRule):
300
298
 
301
299
  ignorable_election_date_statuses = frozenset(["canceled"])
302
300
 
303
- def elements(self):
301
+ def elements(self) -> list[str]:
304
302
  return ["Feed"]
305
303
 
306
- def check(self, element):
304
+ def check(self, element: etree._Element) -> None:
307
305
  # Skip this rule for test feeds.
308
306
  if rule_util.is_xml_true(element.find("IsTest")):
309
307
  return
@@ -342,16 +340,16 @@ class FeedInactiveDateIsLatestDate(base.BaseRule):
342
340
  class FeedHasValidCountryCode(base.BaseRule):
343
341
  """Feeds should have valid country code."""
344
342
 
345
- def elements(self):
343
+ def elements(self) -> list[str]:
346
344
  return ["Feed"]
347
345
 
348
- def check(self, element):
346
+ def check(self, element: etree._Element) -> None:
349
347
  country_code_element = element.find("CountryCode")
350
348
  if rule_util.element_has_text(country_code_element):
351
349
  country_code = country_code_element.text.upper()
352
350
  if not rule_util.country_code_is_valid(country_code):
353
351
  raise loggers.ElectionError.from_message(
354
- "Invalid country code {}.".format(country_code),
352
+ f"Invalid country code {country_code}.",
355
353
  [element],
356
354
  )
357
355
  else:
@@ -362,7 +360,7 @@ class FeedHasValidCountryCode(base.BaseRule):
362
360
  ):
363
361
  return
364
362
  raise loggers.ElectionError.from_message(
365
- "Feed {} is missing CountryCode.".format(element.find("FeedId").text),
363
+ f"Feed {element.find('FeedId').text} is missing CountryCode.",
366
364
  [element],
367
365
  )
368
366
 
@@ -370,10 +368,10 @@ class FeedHasValidCountryCode(base.BaseRule):
370
368
  class FeedInactiveDateNotOlderThanOneYear(base.BaseRule):
371
369
  """Feeds should not have a FeedInactiveDate older than 1 year."""
372
370
 
373
- def elements(self):
371
+ def elements(self) -> list[str]:
374
372
  return ["Feed"]
375
373
 
376
- def check(self, element):
374
+ def check(self, element: etree._Element) -> None:
377
375
  feed_inactive_date_element = element.find("FeedInactiveDate")
378
376
  if not rule_util.element_has_text(feed_inactive_date_element):
379
377
  return
@@ -395,10 +393,10 @@ class FeedInactiveDateNotOlderThanOneYear(base.BaseRule):
395
393
  class FeedInactiveDateSetForNonEvergreenFeed(base.BaseRule):
396
394
  """All non-evergreen feeds should have a FeedInactiveDate set."""
397
395
 
398
- def elements(self):
396
+ def elements(self) -> list[str]:
399
397
  return ["Feed"]
400
398
 
401
- def check(self, element):
399
+ def check(self, element: etree._Element) -> None:
402
400
  feed_longevity = element.find("FeedLongevity")
403
401
  if (
404
402
  rule_util.element_has_text(feed_longevity)
@@ -406,8 +404,8 @@ class FeedInactiveDateSetForNonEvergreenFeed(base.BaseRule):
406
404
  and not rule_util.element_has_text(element.find("FeedInactiveDate"))
407
405
  ):
408
406
  raise loggers.ElectionError.from_message(
409
- "FeedInactiveDate is not set for non-evergreen feed with FeedId {}."
410
- .format(element.find("FeedId").text),
407
+ "FeedInactiveDate is not set for non-evergreen feed with FeedId"
408
+ f" {element.find('FeedId').text}.",
411
409
  [element],
412
410
  )
413
411
 
@@ -421,10 +419,10 @@ class FeedElementsShouldHaveSubElementsBasedOnType(base.BaseRule):
421
419
  one ElectionEvent element should be present.
422
420
  """
423
421
 
424
- def elements(self):
422
+ def elements(self) -> list[str]:
425
423
  return ["Feed"]
426
424
 
427
- def check(self, element):
425
+ def check(self, element: etree._Element) -> None:
428
426
  feed_type = element.find("FeedType")
429
427
  feed_id = element.find("FeedId").text
430
428
 
@@ -435,21 +433,20 @@ class FeedElementsShouldHaveSubElementsBasedOnType(base.BaseRule):
435
433
  if feed_type == "officeholder":
436
434
  if element.find("OfficeholderSubFeed") is None:
437
435
  raise loggers.ElectionError.from_message(
438
- "OfficeholderSubFeed should exist for %s feed %s."
439
- % (feed_type, feed_id),
436
+ f"OfficeholderSubFeed should exist for {feed_type} feed {feed_id}.",
440
437
  [element],
441
438
  )
442
439
  elif feed_type == "pre-election" or feed_type == "election-results":
443
440
  if element.find("ElectionEventCollection") is None:
444
441
  raise loggers.ElectionError.from_message(
445
- "ElectionEventCollection should exist for %s feed %s."
446
- % (feed_type, feed_id),
442
+ f"ElectionEventCollection should exist for {feed_type} feed"
443
+ f" {feed_id}.",
447
444
  [element],
448
445
  )
449
446
  if not element.find("ElectionEventCollection").findall("ElectionEvent"):
450
447
  raise loggers.ElectionError.from_message(
451
448
  "ElectionEventCollection should have at least one ElectionEvent"
452
- " for %s feed %s." % (feed_type, feed_id),
449
+ f" for {feed_type} feed {feed_id}.",
453
450
  [element],
454
451
  )
455
452
 
@@ -15,6 +15,7 @@
15
15
 
16
16
  from __future__ import print_function
17
17
 
18
+ from lxml import etree
18
19
  import pycountry
19
20
 
20
21
 
@@ -27,7 +28,7 @@ _IDENTIFIER_TYPES = frozenset(
27
28
  )
28
29
 
29
30
 
30
- def is_xml_true(element):
31
+ def is_xml_true(element: etree._Element | None) -> bool:
31
32
  return (
32
33
  element_has_text(element)
33
34
  and element.text.strip().lower() in _XML_TRUE_VALUES
@@ -35,8 +36,11 @@ def is_xml_true(element):
35
36
 
36
37
 
37
38
  def get_external_id_values(
38
- element, value_type, return_elements=False, search_subelements=True
39
- ):
39
+ element: etree._Element | etree._ElementTree,
40
+ value_type: str,
41
+ return_elements: bool = False,
42
+ search_subelements: bool = True,
43
+ ) -> list[str] | list[etree._Element]:
40
44
  """Helper to gather all Values of external ids for a given type.
41
45
 
42
46
  If search_subelements is True, will search all subelements, if False, will
@@ -87,9 +91,11 @@ def get_external_id_values(
87
91
  return values
88
92
 
89
93
 
90
- def get_additional_type_values(element, value_type, return_elements=False):
94
+ def get_additional_type_values(
95
+ element: etree._Element, value_type: str, return_elements: bool = False
96
+ ) -> list[str] | list[etree._Element]:
91
97
  """Helper to gather all nested additional type values for a given type."""
92
- elements = element.findall(".//AdditionalData[@type='{}']".format(value_type))
98
+ elements = element.findall(f".//AdditionalData[@type='{value_type}']")
93
99
  if not return_elements:
94
100
  return [
95
101
  val.text
@@ -99,7 +105,9 @@ def get_additional_type_values(element, value_type, return_elements=False):
99
105
  return elements
100
106
 
101
107
 
102
- def get_entity_info_for_value_type(element, info_type, return_elements=False):
108
+ def get_entity_info_for_value_type(
109
+ element: etree._Element, info_type: str, return_elements: bool = False
110
+ ) -> list[str] | list[etree._Element]:
103
111
  info_collection = get_additional_type_values(
104
112
  element, info_type, return_elements
105
113
  )
@@ -109,7 +117,9 @@ def get_entity_info_for_value_type(element, info_type, return_elements=False):
109
117
  return info_collection
110
118
 
111
119
 
112
- def get_language_to_text_map(element):
120
+ def get_language_to_text_map(
121
+ element: etree._Element | None,
122
+ ) -> dict[str, list[str]]:
113
123
  """Return a map of languages to text in an InternationalizedText element."""
114
124
  language_map = {}
115
125
  if element is None:
@@ -130,7 +140,7 @@ def get_language_to_text_map(element):
130
140
  return language_map
131
141
 
132
142
 
133
- def element_has_text(element):
143
+ def element_has_text(element: etree._Element | None) -> bool:
134
144
  return (
135
145
  element is not None
136
146
  and element.text is not None
@@ -138,7 +148,7 @@ def element_has_text(element):
138
148
  )
139
149
 
140
150
 
141
- def country_code_is_valid(country_code):
151
+ def country_code_is_valid(country_code: str) -> bool:
142
152
  # EU is part of ISO 3166/MA
143
153
  return (
144
154
  country_code.lower() == "eu"
@@ -14,31 +14,32 @@ See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  """
16
16
 
17
+ from collections.abc import Iterable
18
+
17
19
 
18
20
  class BaseEntity(object):
19
21
  """Base for keeping meta-statistics on attributes in a NIST XML feed."""
20
22
 
21
- def __init__(self, name, attributes, count):
23
+ def __init__(self, name: str, attributes: Iterable[str], count: int) -> None:
22
24
  self.name = name
23
25
  self.count = count
24
26
  self.attribute_counts = {attr: 0 for attr in attributes}
25
27
 
26
- def __str__(self):
28
+ def __str__(self) -> str:
27
29
  """Returns counts of each top level entities and nested attributes."""
28
30
  output = []
29
- row_format = "{:<30s}{:^8s}{:>15s}"
30
31
  output.append("\n" + " " * 8 + "-" * 65)
31
- output.append(" " * 8 + "{:<30s}{:^20s}{:>12s}".format(
32
- "{0} (Total: {1})".format(self.name, self.count), "| # with attribute",
33
- "| # missing attribute"))
32
+ header = f"{self.name} (Total: {self.count})"
33
+ output.append(" " * 8 + f"{header:<30s}{'| # with attribute':^20s}"
34
+ f"{'| # missing attribute':>12s}")
34
35
  output.append(" " * 8 + "-" * 65)
35
36
  for attr, attr_count in sorted(
36
37
  self.attribute_counts.items(), key=lambda x: x[1], reverse=True):
37
- output.append(" " * 8 + row_format.format(attr, str(attr_count),
38
- str(self.count - attr_count)))
38
+ output.append(" " * 8 + f"{attr:<30s}{attr_count!s:^8s}"
39
+ f"{self.count - attr_count!s:>15s}")
39
40
  return "\n".join(output)
40
41
 
41
- def increment_attribute(self, attr, count):
42
+ def increment_attribute(self, attr: str, count: int) -> None:
42
43
  """Counts the number of entities containing attr."""
43
44
  if attr in self.attribute_counts and count:
44
45
  self.attribute_counts[attr] += 1
@@ -51,7 +52,7 @@ class Party(BaseEntity):
51
52
  "InternationalizedAbbreviation"
52
53
  ]
53
54
 
54
- def __init__(self, count):
55
+ def __init__(self, count: int) -> None:
55
56
  super(Party, self).__init__("Party", self.children, count)
56
57
 
57
58
 
@@ -62,7 +63,7 @@ class Office(BaseEntity):
62
63
  "FilingDeadline", "Name", "OfficeHolderPersonIds", "Term"
63
64
  ]
64
65
 
65
- def __init__(self, count):
66
+ def __init__(self, count: int) -> None:
66
67
  super(Office, self).__init__("Office", self.children, count)
67
68
 
68
69
 
@@ -72,7 +73,7 @@ class GpUnit(BaseEntity):
72
73
  "ComposingGpUnitIds", "ExternalIdentifiers", "Name", "SummaryCounts"
73
74
  ]
74
75
 
75
- def __init__(self, count):
76
+ def __init__(self, count: int) -> None:
76
77
  super(GpUnit, self).__init__("GpUnit", self.children, count)
77
78
 
78
79
 
@@ -84,7 +85,7 @@ class Person(BaseEntity):
84
85
  "Suffix", "Title"
85
86
  ]
86
87
 
87
- def __init__(self, count):
88
+ def __init__(self, count: int) -> None:
88
89
  super(Person, self).__init__("Person", self.children, count)
89
90
 
90
91
 
@@ -95,7 +96,7 @@ class Candidate(BaseEntity):
95
96
  "PersonId"
96
97
  ]
97
98
 
98
- def __init__(self, count):
99
+ def __init__(self, count: int) -> None:
99
100
  super(Candidate, self).__init__("Candidate", self.children, count)
100
101
 
101
102
 
@@ -106,7 +107,7 @@ class Contest(BaseEntity):
106
107
  "TotalSubUnits"
107
108
  ]
108
109
 
109
- def __init__(self, count):
110
+ def __init__(self, count: int) -> None:
110
111
  super(Contest, self).__init__("Contest", self.children, count)
111
112
 
112
113
 
@@ -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.dev15'
8
+ __version__ = '1.68.dev16'