civics-cdf-validator 1.68.dev14__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.
- {civics_cdf_validator-1.68.dev14/civics_cdf_validator.egg-info → civics_cdf_validator-1.68.dev16}/PKG-INFO +1 -1
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/base.py +89 -71
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16/civics_cdf_validator.egg-info}/PKG-INFO +1 -1
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/gpunit_rules.py +19 -9
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/loggers.py +47 -22
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/metadata_rules.py +43 -46
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/rule_util.py +19 -9
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/setup.py +1 -1
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/stats.py +16 -15
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/validator.py +68 -36
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/version.py +1 -1
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/CONTRIBUTING.md +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/LICENSE-2.0.txt +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/MANIFEST.in +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/README.md +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/__init__.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/SOURCES.txt +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/dependency_links.txt +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/entry_points.txt +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/requires.txt +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/civics_cdf_validator.egg-info/top_level.txt +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/office_utils.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rules.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/__init__.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/committee_rules.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/common_rules.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/election_dates_rules.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/election_results_rules.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/election_rules.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/officeholder_rules.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/rulesets/voter_information_rules.py +0 -0
- {civics_cdf_validator-1.68.dev14 → civics_cdf_validator-1.68.dev16}/setup.cfg +0 -0
|
@@ -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 = "{
|
|
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("{
|
|
51
|
-
return tag[len("{
|
|
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(
|
|
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 ='
|
|
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,
|
|
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
|
|
191
|
-
|
|
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(
|
|
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 = "
|
|
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(
|
|
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 = "
|
|
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 =
|
|
280
|
-
|
|
281
|
-
|
|
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__(
|
|
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 "
|
|
316
|
+
return f"{self.year}"
|
|
300
317
|
elif self.is_month_date():
|
|
301
|
-
return "
|
|
318
|
+
return f"{self.year}-{str(self.month).zfill(2)}"
|
|
302
319
|
elif self.is_complete_date():
|
|
303
|
-
return "
|
|
304
|
-
|
|
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 {}."
|
|
416
|
-
|
|
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(
|
|
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
|
-
|
|
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(".//{}"
|
|
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. {}"
|
|
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()
|
|
@@ -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(
|
|
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__(
|
|
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__(
|
|
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
|
|