civics-cdf-validator 1.67.dev7__py3-none-any.whl → 1.67.dev9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,446 +15,15 @@
15
15
 
16
16
  from __future__ import print_function
17
17
 
18
- import datetime
19
18
  import enum
20
19
 
21
- from botocore import utils as botocore_utils
22
- from civics_cdf_validator import base
23
- from civics_cdf_validator import loggers
24
20
  from civics_cdf_validator.rulesets import committee_rules
25
21
  from civics_cdf_validator.rulesets import common_rules
26
22
  from civics_cdf_validator.rulesets import election_dates_rules
27
23
  from civics_cdf_validator.rulesets import election_rules
24
+ from civics_cdf_validator.rulesets import metadata_rules
28
25
  from civics_cdf_validator.rulesets import officeholder_rules
29
- from civics_cdf_validator.rulesets import rule_util
30
26
  from civics_cdf_validator.rulesets import voter_information_rules
31
- import dateutil
32
- from frozendict import frozendict
33
-
34
-
35
- _VALID_FEED_LONGEVITY_BY_FEED_TYPE = frozendict({
36
- "committee": ["evergreen"],
37
- "election-dates": ["evergreen"],
38
- "election-results": ["limited"],
39
- "officeholder": ["evergreen"],
40
- "pre-election": ["limited", "yearly"],
41
- })
42
-
43
-
44
- class FeedTypeHasValidFeedLongevity(base.BaseRule):
45
- """Feeds types should have valid corresponding FeedLongevity."""
46
-
47
- def elements(self):
48
- return ["Feed"]
49
-
50
- def check(self, element):
51
- feed_type_element = element.find("FeedType")
52
- feed_longevity_element = element.find("FeedLongevity")
53
- if rule_util.element_has_text(
54
- feed_type_element
55
- ) and rule_util.element_has_text(feed_longevity_element):
56
- feed_type = feed_type_element.text.lower().replace("_", "-")
57
- feed_longevity = feed_longevity_element.text.lower().replace("_", "-")
58
- if (
59
- feed_type in _VALID_FEED_LONGEVITY_BY_FEED_TYPE
60
- and feed_longevity
61
- not in _VALID_FEED_LONGEVITY_BY_FEED_TYPE[feed_type]
62
- ):
63
- raise loggers.ElectionError.from_message(
64
- "Feed type {} has invalid feed longevity {}. Valid feed"
65
- " longevities for this type are {}".format(
66
- feed_type,
67
- feed_longevity,
68
- _VALID_FEED_LONGEVITY_BY_FEED_TYPE[feed_type],
69
- ),
70
- [element],
71
- )
72
-
73
-
74
- class FeedIdsAreUnique(base.BaseRule):
75
- """FeedId should be unique."""
76
-
77
- def elements(self):
78
- return ["FeedCollection"]
79
-
80
- def check(self, element):
81
- feed_ids = set()
82
- error_log = []
83
- for feed_element in element.findall("Feed"):
84
- if rule_util.element_has_text(feed_element.find("FeedId")):
85
- feed_id = feed_element.find("FeedId").text
86
- if feed_id in feed_ids:
87
- msg = (
88
- "FeedId {} appears multiple times in the metadata feed. Feed ids"
89
- " must be unique.".format(feed_id)
90
- )
91
- error_log.append(
92
- loggers.LogEntry(
93
- msg,
94
- [feed_element],
95
- )
96
- )
97
- feed_ids.add(feed_id)
98
-
99
- if error_log:
100
- raise loggers.ElectionError(error_log)
101
-
102
-
103
- class SourceDirPathsAreUnique(base.BaseRule):
104
- """All SourceDirPaths should be unique."""
105
-
106
- def elements(self):
107
- return ["FeedCollection"]
108
-
109
- def check(self, element):
110
- source_dir_paths = set()
111
- error_log = []
112
- for feed_element in element.findall("Feed"):
113
- if rule_util.element_has_text(feed_element.find("SourceDirPath")):
114
- source_dir_path = feed_element.find("SourceDirPath").text
115
- if source_dir_path in source_dir_paths:
116
- msg = (
117
- "SourceDirPath {} appears multiple times in the metadata feed."
118
- " SourceDirPaths must be unique.".format(source_dir_path)
119
- )
120
- error_log.append(
121
- loggers.LogEntry(
122
- msg,
123
- [feed_element],
124
- )
125
- )
126
- source_dir_paths.add(source_dir_path)
127
-
128
- if error_log:
129
- raise loggers.ElectionError(error_log)
130
-
131
-
132
- _ARN_PARSER = botocore_utils.ArnParser()
133
-
134
-
135
- class SqsQueueNameIsFullyQualifiedArn(base.BaseRule):
136
- """SqsQueueName must be a valid fully qualified ARN.
137
-
138
- Only AWS region ARNs are supported.
139
- """
140
-
141
- def elements(self):
142
- return ["Feed"]
143
-
144
- def check(self, element):
145
- sqs_queue_name = element.find("SqsQueueName")
146
- if not rule_util.element_has_text(sqs_queue_name):
147
- return
148
- queue_name = sqs_queue_name.text.strip()
149
- feed_id_element = element.find("FeedId")
150
- feed_id = (
151
- feed_id_element.text.strip()
152
- if rule_util.element_has_text(feed_id_element)
153
- else ""
154
- )
155
-
156
- is_valid = False
157
- if queue_name.startswith("arn:"):
158
- try:
159
- arn_dict = _ARN_PARSER.parse_arn(queue_name)
160
- is_valid = bool(
161
- arn_dict.get("partition") == "aws"
162
- and arn_dict.get("service", "").lower() == "sqs"
163
- and arn_dict.get("region")
164
- and arn_dict.get("account")
165
- and arn_dict.get("resource")
166
- )
167
- except botocore_utils.InvalidArnException:
168
- is_valid = False
169
-
170
- if not is_valid:
171
- if feed_id:
172
- error_message = (
173
- f"SqsQueueName '{queue_name}' is not a valid fully qualified ARN"
174
- f" for feed {feed_id}."
175
- )
176
- else:
177
- error_message = (
178
- f"SqsQueueName '{queue_name}' is not a valid fully qualified ARN."
179
- )
180
- raise loggers.ElectionError.from_message(
181
- error_message,
182
- [element],
183
- [sqs_queue_name.sourceline],
184
- )
185
-
186
-
187
- class SqsQueueNameRequiresS3SourceDirPath(base.BaseRule):
188
- """If SqsQueueName is set, SourceDirPath must also be set and must be an s3 path."""
189
-
190
- def elements(self):
191
- return ["Feed"]
192
-
193
- def check(self, element):
194
- sqs_queue_name = element.find("SqsQueueName")
195
- if not rule_util.element_has_text(sqs_queue_name):
196
- return
197
- source_dir_path = element.find("SourceDirPath")
198
- if not rule_util.element_has_text(
199
- source_dir_path
200
- ) or not source_dir_path.text.strip().lower().startswith("s3://"):
201
- raise loggers.ElectionError.from_message(
202
- "If SqsQueueName is set, SourceDirPath must also be set and must be"
203
- " an s3 path for feed {}.".format(element.find("FeedId").text),
204
- [element],
205
- )
206
-
207
-
208
- class ElectionEventDatesAreSequential(base.DateRule):
209
- """Dates in an ElectionEvent element should be sequential."""
210
-
211
- def elements(self):
212
- return ["ElectionEvent"]
213
-
214
- def check(self, element):
215
- self.reset_instance_vars()
216
- self.gather_dates(element)
217
- self.check_end_after_start()
218
- if (
219
- rule_util.element_has_text(element.find("FullDeliveryDate"))
220
- and self.start_date
221
- ):
222
- full_delivery_date = base.PartialDate.init_partial_date(
223
- element.find("FullDeliveryDate").text
224
- )
225
- if self.start_date < full_delivery_date:
226
- self.error_log.append(
227
- loggers.LogEntry(
228
- "StartDate is older than FullDeliveryDate",
229
- [element],
230
- )
231
- )
232
- if rule_util.element_has_text(
233
- element.find("InitialDeliveryDate")
234
- ) and rule_util.element_has_text(element.find("FullDeliveryDate")):
235
- initial_delivery_date = base.PartialDate.init_partial_date(
236
- element.find("InitialDeliveryDate").text
237
- )
238
- full_delivery_date = base.PartialDate.init_partial_date(
239
- element.find("FullDeliveryDate").text
240
- )
241
- if full_delivery_date < initial_delivery_date:
242
- self.error_log.append(
243
- loggers.LogEntry(
244
- "FullDeliveryDate is older than InitialDeliveryDate",
245
- [element],
246
- )
247
- )
248
-
249
- if self.error_log:
250
- raise loggers.ElectionError(self.error_log)
251
-
252
-
253
- class SourceDirPathMustBeSetAfterInitialDeliveryDate(base.BaseRule):
254
- """SourceDirPath must be set if any InitialDeliveryDate is in the past."""
255
-
256
- def elements(self):
257
- return ["Feed"]
258
-
259
- def check(self, element):
260
- if rule_util.element_has_text(element.find("SourceDirPath")):
261
- return
262
- today = datetime.date.today()
263
- today_partial_date = base.PartialDate(
264
- year=today.year, month=today.month, day=today.day
265
- )
266
- initial_deliveries = element.findall(".//InitialDeliveryDate") or []
267
- for initial_delivery in initial_deliveries:
268
- initial_delivery_date = (
269
- base.PartialDate.init_partial_date(initial_delivery.text)
270
- if rule_util.element_has_text(initial_delivery)
271
- else None
272
- )
273
- if initial_delivery_date and initial_delivery_date < today_partial_date:
274
- raise loggers.ElectionError.from_message(
275
- "SourceDirPath is not set but an InitialDeliveryDate is in the "
276
- f"past for feed {element.find('FeedId').text}.",
277
- [element],
278
- )
279
-
280
-
281
- class OfficeholderSubFeedDatesAreSequential(base.DateRule):
282
- """Dates in an OfficeholderSubFeed element should be sequential."""
283
-
284
- def elements(self):
285
- return ["OfficeholderSubFeed"]
286
-
287
- def check(self, element):
288
- if rule_util.element_has_text(
289
- element.find("InitialDeliveryDate")
290
- ) and rule_util.element_has_text(element.find("FullDeliveryDate")):
291
- initial_delivery_date = base.PartialDate.init_partial_date(
292
- element.find("InitialDeliveryDate").text
293
- )
294
- full_delivery_date = base.PartialDate.init_partial_date(
295
- element.find("FullDeliveryDate").text
296
- )
297
- if full_delivery_date < initial_delivery_date:
298
- raise loggers.ElectionError.from_message(
299
- "FullDeliveryDate is older than InitialDeliveryDate",
300
- [element],
301
- )
302
-
303
-
304
- class FeedInactiveDateIsLatestDate(base.BaseRule):
305
- """Partner feeds should have a FeedInactiveDate that occurs after the FullDeliveryDate and EndDate."""
306
-
307
- ignorable_election_date_statuses = frozenset(["canceled"])
308
-
309
- def elements(self):
310
- return ["Feed"]
311
-
312
- def check(self, element):
313
- # Skip this rule for test feeds.
314
- if rule_util.is_xml_true(element.find("IsTest")):
315
- return
316
-
317
- if rule_util.element_has_text(element.find("FeedInactiveDate")):
318
- feed_inactive_date = base.PartialDate.init_partial_date(
319
- element.find("FeedInactiveDate").text
320
- )
321
- for full_delivery_date_element in element.iter("FullDeliveryDate"):
322
- full_delivery_date = base.PartialDate.init_partial_date(
323
- full_delivery_date_element.text
324
- )
325
- if feed_inactive_date < full_delivery_date:
326
- raise loggers.ElectionError.from_message(
327
- "FeedInactiveDate is older than FullDeliveryDate",
328
- [element],
329
- )
330
- for election_event_element in element.iter("ElectionEvent"):
331
- if rule_util.element_has_text(
332
- election_event_element.find("ElectionDateStatus")
333
- ) and (
334
- election_event_element.find("ElectionDateStatus").text
335
- in self.ignorable_election_date_statuses
336
- ):
337
- continue
338
- if rule_util.element_has_text(election_event_element.find("EndDate")):
339
- end_date_element = election_event_element.find("EndDate")
340
- end_date = base.PartialDate.init_partial_date(end_date_element.text)
341
- if feed_inactive_date < end_date:
342
- raise loggers.ElectionError.from_message(
343
- "FeedInactiveDate is older than EndDate",
344
- [element],
345
- )
346
-
347
-
348
- class FeedHasValidCountryCode(base.BaseRule):
349
- """Feeds should have valid country code."""
350
-
351
- def elements(self):
352
- return ["Feed"]
353
-
354
- def check(self, element):
355
- country_code_element = element.find("CountryCode")
356
- if rule_util.element_has_text(country_code_element):
357
- country_code = country_code_element.text.upper()
358
- if not rule_util.country_code_is_valid(country_code):
359
- raise loggers.ElectionError.from_message(
360
- "Invalid country code {}.".format(country_code),
361
- [element],
362
- )
363
- else:
364
- feed_type = element.find("FeedType")
365
- if rule_util.element_has_text(feed_type) and (
366
- feed_type.text.lower().replace("_", "-") == "election-dates"
367
- or feed_type.text.lower().replace("_", "-") == "voter-information"
368
- ):
369
- return
370
- raise loggers.ElectionError.from_message(
371
- "Feed {} is missing CountryCode.".format(element.find("FeedId").text),
372
- [element],
373
- )
374
-
375
-
376
- class FeedInactiveDateNotOlderThanOneYear(base.BaseRule):
377
- """Feeds should not have a FeedInactiveDate older than 1 year."""
378
-
379
- def elements(self):
380
- return ["Feed"]
381
-
382
- def check(self, element):
383
- feed_inactive_date_element = element.find("FeedInactiveDate")
384
- if not rule_util.element_has_text(feed_inactive_date_element):
385
- return
386
- feed_inactive_date = datetime.date.fromisoformat(
387
- feed_inactive_date_element.text
388
- )
389
- one_year_ago = datetime.date.today() - dateutil.relativedelta.relativedelta(
390
- years=1
391
- )
392
- if feed_inactive_date < one_year_ago:
393
- feed_id_element = element.find("FeedId")
394
- raise loggers.ElectionError.from_message(
395
- f"FeedInactiveDate '{feed_inactive_date_element.text}' is older than"
396
- f" 1 year for feed '{feed_id_element.text}'.",
397
- [element],
398
- )
399
-
400
-
401
- class FeedInactiveDateSetForNonEvergreenFeed(base.BaseRule):
402
- """All non-evergreen feeds should have a FeedInactiveDate set."""
403
-
404
- def elements(self):
405
- return ["Feed"]
406
-
407
- def check(self, element):
408
- feed_longevity = element.find("FeedLongevity")
409
- if (
410
- rule_util.element_has_text(feed_longevity)
411
- and feed_longevity.text.lower() != "evergreen"
412
- and not rule_util.element_has_text(element.find("FeedInactiveDate"))
413
- ):
414
- raise loggers.ElectionError.from_message(
415
- "FeedInactiveDate is not set for non-evergreen feed with FeedId {}."
416
- .format(element.find("FeedId").text),
417
- [element],
418
- )
419
-
420
-
421
- class FeedElementsShouldHaveSubElementsBasedOnType(base.BaseRule):
422
- """Feeds should have certain elements based on feed type.
423
-
424
- For example, Feeds of type officeholder should have an OfficeholderSubFeed,
425
- similarly pre-election and election-results feeds should have an
426
- ElectionEventCollection. In the case of an ElectionEventCollection, at least
427
- one ElectionEvent element should be present.
428
- """
429
-
430
- def elements(self):
431
- return ["Feed"]
432
-
433
- def check(self, element):
434
- feed_type = element.find("FeedType")
435
- feed_id = element.find("FeedId").text
436
-
437
- if not rule_util.element_has_text(feed_type):
438
- return
439
-
440
- feed_type = feed_type.text
441
- if feed_type == "officeholder":
442
- if element.find("OfficeholderSubFeed") is None:
443
- raise loggers.ElectionError.from_message(
444
- "OfficeholderSubFeed should exist for %s feed %s."
445
- % (feed_type, feed_id)
446
- )
447
- elif feed_type == "pre-election" or feed_type == "election-results":
448
- if element.find("ElectionEventCollection") is None:
449
- raise loggers.ElectionError.from_message(
450
- "ElectionEventCollection should exist for %s feed %s."
451
- % (feed_type, feed_id)
452
- )
453
- if not element.find("ElectionEventCollection").findall("ElectionEvent"):
454
- raise loggers.ElectionError.from_message(
455
- "ElectionEventCollection should have at least one ElectionEvent"
456
- " for %s feed %s." % (feed_type, feed_id)
457
- )
458
27
 
459
28
 
460
29
  class RuleSet(enum.Enum):
@@ -469,42 +38,16 @@ class RuleSet(enum.Enum):
469
38
  VOTER_INFORMATION = 7
470
39
 
471
40
 
472
- # To add new rules, create a new class, inherit the base rule,
473
- # and add it to the correct rule list.
41
+ # To add new rules, create a new class in the matching file under rulesets/,
42
+ # inherit the base rule, and add it to that file's rule list.
474
43
  COMMON_RULES = common_rules.COMMON_RULES
475
- OFFICEHOLDER_RULES = officeholder_rules.OFFICEHOLDER_RULES
476
44
  ELECTION_RULES = election_rules.ELECTION_RULES
477
- ELECTION_DATES_RULES = election_dates_rules.ELECTION_DATES_RULES
45
+ OFFICEHOLDER_RULES = officeholder_rules.OFFICEHOLDER_RULES
478
46
  COMMITTEE_RULES = committee_rules.COMMITTEE_RULES
47
+ ELECTION_DATES_RULES = election_dates_rules.ELECTION_DATES_RULES
48
+ METADATA_RULES = metadata_rules.METADATA_RULES
479
49
  VOTER_INFORMATION_RULES = voter_information_rules.VOTER_INFORMATION_RULES
480
50
 
481
-
482
- METADATA_RULES = (
483
- # go/keep-sorted start
484
- ElectionEventDatesAreSequential,
485
- FeedElementsShouldHaveSubElementsBasedOnType,
486
- FeedHasValidCountryCode,
487
- FeedIdsAreUnique,
488
- FeedInactiveDateIsLatestDate,
489
- FeedInactiveDateNotOlderThanOneYear,
490
- FeedInactiveDateSetForNonEvergreenFeed,
491
- FeedTypeHasValidFeedLongevity,
492
- OfficeholderSubFeedDatesAreSequential,
493
- SourceDirPathMustBeSetAfterInitialDeliveryDate,
494
- SourceDirPathsAreUnique,
495
- # TODO(b/555757644): Reenable this rule once we are ready to enforce it.
496
- # SqsQueueNameIsFullyQualifiedArn,
497
- SqsQueueNameRequiresS3SourceDirPath,
498
- common_rules.EmptyString,
499
- common_rules.EmptyText,
500
- common_rules.Encoding,
501
- common_rules.OptionalAndEmpty,
502
- common_rules.Schema,
503
- common_rules.UniqueLabel,
504
- # go/keep-sorted end
505
- )
506
-
507
-
508
51
  ALL_RULES = frozenset(
509
52
  COMMON_RULES
510
53
  + ELECTION_RULES
@@ -0,0 +1,477 @@
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Validation rules for metadata feeds of the CDF XML validator."""
15
+
16
+ from __future__ import print_function
17
+
18
+ import datetime
19
+
20
+ from botocore import utils as botocore_utils
21
+ from civics_cdf_validator import base
22
+ from civics_cdf_validator import loggers
23
+ from civics_cdf_validator.rulesets import common_rules
24
+ from civics_cdf_validator.rulesets import rule_util
25
+ import dateutil
26
+ from frozendict import frozendict
27
+
28
+
29
+ _VALID_FEED_LONGEVITY_BY_FEED_TYPE = frozendict({
30
+ "committee": ["evergreen"],
31
+ "election-dates": ["evergreen"],
32
+ "election-results": ["limited"],
33
+ "officeholder": ["evergreen"],
34
+ "pre-election": ["limited", "yearly"],
35
+ })
36
+
37
+
38
+ class FeedTypeHasValidFeedLongevity(base.BaseRule):
39
+ """Feeds types should have valid corresponding FeedLongevity."""
40
+
41
+ def elements(self):
42
+ return ["Feed"]
43
+
44
+ def check(self, element):
45
+ feed_type_element = element.find("FeedType")
46
+ feed_longevity_element = element.find("FeedLongevity")
47
+ if rule_util.element_has_text(
48
+ feed_type_element
49
+ ) and rule_util.element_has_text(feed_longevity_element):
50
+ feed_type = feed_type_element.text.lower().replace("_", "-")
51
+ feed_longevity = feed_longevity_element.text.lower().replace("_", "-")
52
+ if (
53
+ feed_type in _VALID_FEED_LONGEVITY_BY_FEED_TYPE
54
+ and feed_longevity
55
+ not in _VALID_FEED_LONGEVITY_BY_FEED_TYPE[feed_type]
56
+ ):
57
+ 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
+ ),
64
+ [element],
65
+ )
66
+
67
+
68
+ class FeedIdsAreUnique(base.BaseRule):
69
+ """FeedId should be unique."""
70
+
71
+ def elements(self):
72
+ return ["FeedCollection"]
73
+
74
+ def check(self, element):
75
+ feed_ids = set()
76
+ error_log = []
77
+ for feed_element in element.findall("Feed"):
78
+ if rule_util.element_has_text(feed_element.find("FeedId")):
79
+ feed_id = feed_element.find("FeedId").text
80
+ if feed_id in feed_ids:
81
+ msg = (
82
+ "FeedId {} appears multiple times in the metadata feed. Feed ids"
83
+ " must be unique.".format(feed_id)
84
+ )
85
+ error_log.append(
86
+ loggers.LogEntry(
87
+ msg,
88
+ [feed_element],
89
+ )
90
+ )
91
+ feed_ids.add(feed_id)
92
+
93
+ if error_log:
94
+ raise loggers.ElectionError(error_log)
95
+
96
+
97
+ class SourceDirPathsAreUnique(base.BaseRule):
98
+ """All SourceDirPaths should be unique."""
99
+
100
+ def elements(self):
101
+ return ["FeedCollection"]
102
+
103
+ def check(self, element):
104
+ source_dir_paths = set()
105
+ error_log = []
106
+ for feed_element in element.findall("Feed"):
107
+ if rule_util.element_has_text(feed_element.find("SourceDirPath")):
108
+ source_dir_path = feed_element.find("SourceDirPath").text
109
+ if source_dir_path in source_dir_paths:
110
+ msg = (
111
+ "SourceDirPath {} appears multiple times in the metadata feed."
112
+ " SourceDirPaths must be unique.".format(source_dir_path)
113
+ )
114
+ error_log.append(
115
+ loggers.LogEntry(
116
+ msg,
117
+ [feed_element],
118
+ )
119
+ )
120
+ source_dir_paths.add(source_dir_path)
121
+
122
+ if error_log:
123
+ raise loggers.ElectionError(error_log)
124
+
125
+
126
+ _ARN_PARSER = botocore_utils.ArnParser()
127
+
128
+
129
+ class SqsQueueNameIsFullyQualifiedArn(base.BaseRule):
130
+ """SqsQueueName must be a valid fully qualified ARN.
131
+
132
+ Only AWS region ARNs are supported.
133
+ """
134
+
135
+ def elements(self):
136
+ return ["Feed"]
137
+
138
+ def check(self, element):
139
+ sqs_queue_name = element.find("SqsQueueName")
140
+ if not rule_util.element_has_text(sqs_queue_name):
141
+ return
142
+ queue_name = sqs_queue_name.text.strip()
143
+ feed_id_element = element.find("FeedId")
144
+ feed_id = (
145
+ feed_id_element.text.strip()
146
+ if rule_util.element_has_text(feed_id_element)
147
+ else ""
148
+ )
149
+
150
+ is_valid = False
151
+ if queue_name.startswith("arn:"):
152
+ try:
153
+ arn_dict = _ARN_PARSER.parse_arn(queue_name)
154
+ is_valid = bool(
155
+ arn_dict.get("partition") == "aws"
156
+ and arn_dict.get("service", "").lower() == "sqs"
157
+ and arn_dict.get("region")
158
+ and arn_dict.get("account")
159
+ and arn_dict.get("resource")
160
+ )
161
+ except botocore_utils.InvalidArnException:
162
+ is_valid = False
163
+
164
+ if not is_valid:
165
+ if feed_id:
166
+ error_message = (
167
+ f"SqsQueueName '{queue_name}' is not a valid fully qualified ARN"
168
+ f" for feed {feed_id}."
169
+ )
170
+ else:
171
+ error_message = (
172
+ f"SqsQueueName '{queue_name}' is not a valid fully qualified ARN."
173
+ )
174
+ raise loggers.ElectionError.from_message(
175
+ error_message,
176
+ [element],
177
+ [sqs_queue_name.sourceline],
178
+ )
179
+
180
+
181
+ class SqsQueueNameRequiresS3SourceDirPath(base.BaseRule):
182
+ """If SqsQueueName is set, SourceDirPath must also be set and must be an s3 path."""
183
+
184
+ def elements(self):
185
+ return ["Feed"]
186
+
187
+ def check(self, element):
188
+ sqs_queue_name = element.find("SqsQueueName")
189
+ if not rule_util.element_has_text(sqs_queue_name):
190
+ return
191
+ source_dir_path = element.find("SourceDirPath")
192
+ if not rule_util.element_has_text(
193
+ source_dir_path
194
+ ) or not source_dir_path.text.strip().lower().startswith("s3://"):
195
+ raise loggers.ElectionError.from_message(
196
+ "If SqsQueueName is set, SourceDirPath must also be set and must be"
197
+ " an s3 path for feed {}.".format(element.find("FeedId").text),
198
+ [element],
199
+ )
200
+
201
+
202
+ class ElectionEventDatesAreSequential(base.DateRule):
203
+ """Dates in an ElectionEvent element should be sequential."""
204
+
205
+ def elements(self):
206
+ return ["ElectionEvent"]
207
+
208
+ def check(self, element):
209
+ self.reset_instance_vars()
210
+ self.gather_dates(element)
211
+ self.check_end_after_start()
212
+ if (
213
+ rule_util.element_has_text(element.find("FullDeliveryDate"))
214
+ and self.start_date
215
+ ):
216
+ full_delivery_date = base.PartialDate.init_partial_date(
217
+ element.find("FullDeliveryDate").text
218
+ )
219
+ if self.start_date < full_delivery_date:
220
+ self.error_log.append(
221
+ loggers.LogEntry(
222
+ "StartDate is older than FullDeliveryDate",
223
+ [element],
224
+ )
225
+ )
226
+ if rule_util.element_has_text(
227
+ element.find("InitialDeliveryDate")
228
+ ) and rule_util.element_has_text(element.find("FullDeliveryDate")):
229
+ initial_delivery_date = base.PartialDate.init_partial_date(
230
+ element.find("InitialDeliveryDate").text
231
+ )
232
+ full_delivery_date = base.PartialDate.init_partial_date(
233
+ element.find("FullDeliveryDate").text
234
+ )
235
+ if full_delivery_date < initial_delivery_date:
236
+ self.error_log.append(
237
+ loggers.LogEntry(
238
+ "FullDeliveryDate is older than InitialDeliveryDate",
239
+ [element],
240
+ )
241
+ )
242
+
243
+ if self.error_log:
244
+ raise loggers.ElectionError(self.error_log)
245
+
246
+
247
+ class SourceDirPathMustBeSetAfterInitialDeliveryDate(base.BaseRule):
248
+ """SourceDirPath must be set if any InitialDeliveryDate is in the past."""
249
+
250
+ def elements(self):
251
+ return ["Feed"]
252
+
253
+ def check(self, element):
254
+ if rule_util.element_has_text(element.find("SourceDirPath")):
255
+ return
256
+ today = datetime.date.today()
257
+ today_partial_date = base.PartialDate(
258
+ year=today.year, month=today.month, day=today.day
259
+ )
260
+ initial_deliveries = element.findall(".//InitialDeliveryDate") or []
261
+ for initial_delivery in initial_deliveries:
262
+ initial_delivery_date = (
263
+ base.PartialDate.init_partial_date(initial_delivery.text)
264
+ if rule_util.element_has_text(initial_delivery)
265
+ else None
266
+ )
267
+ if initial_delivery_date and initial_delivery_date < today_partial_date:
268
+ raise loggers.ElectionError.from_message(
269
+ "SourceDirPath is not set but an InitialDeliveryDate is in the "
270
+ f"past for feed {element.find('FeedId').text}.",
271
+ [element],
272
+ )
273
+
274
+
275
+ class OfficeholderSubFeedDatesAreSequential(base.DateRule):
276
+ """Dates in an OfficeholderSubFeed element should be sequential."""
277
+
278
+ def elements(self):
279
+ return ["OfficeholderSubFeed"]
280
+
281
+ def check(self, element):
282
+ if rule_util.element_has_text(
283
+ element.find("InitialDeliveryDate")
284
+ ) and rule_util.element_has_text(element.find("FullDeliveryDate")):
285
+ initial_delivery_date = base.PartialDate.init_partial_date(
286
+ element.find("InitialDeliveryDate").text
287
+ )
288
+ full_delivery_date = base.PartialDate.init_partial_date(
289
+ element.find("FullDeliveryDate").text
290
+ )
291
+ if full_delivery_date < initial_delivery_date:
292
+ raise loggers.ElectionError.from_message(
293
+ "FullDeliveryDate is older than InitialDeliveryDate",
294
+ [element],
295
+ )
296
+
297
+
298
+ class FeedInactiveDateIsLatestDate(base.BaseRule):
299
+ """Partner feeds should have a FeedInactiveDate that occurs after the FullDeliveryDate and EndDate."""
300
+
301
+ ignorable_election_date_statuses = frozenset(["canceled"])
302
+
303
+ def elements(self):
304
+ return ["Feed"]
305
+
306
+ def check(self, element):
307
+ # Skip this rule for test feeds.
308
+ if rule_util.is_xml_true(element.find("IsTest")):
309
+ return
310
+
311
+ if rule_util.element_has_text(element.find("FeedInactiveDate")):
312
+ feed_inactive_date = base.PartialDate.init_partial_date(
313
+ element.find("FeedInactiveDate").text
314
+ )
315
+ for full_delivery_date_element in element.iter("FullDeliveryDate"):
316
+ full_delivery_date = base.PartialDate.init_partial_date(
317
+ full_delivery_date_element.text
318
+ )
319
+ if feed_inactive_date < full_delivery_date:
320
+ raise loggers.ElectionError.from_message(
321
+ "FeedInactiveDate is older than FullDeliveryDate",
322
+ [element],
323
+ )
324
+ for election_event_element in element.iter("ElectionEvent"):
325
+ if rule_util.element_has_text(
326
+ election_event_element.find("ElectionDateStatus")
327
+ ) and (
328
+ election_event_element.find("ElectionDateStatus").text
329
+ in self.ignorable_election_date_statuses
330
+ ):
331
+ continue
332
+ if rule_util.element_has_text(election_event_element.find("EndDate")):
333
+ end_date_element = election_event_element.find("EndDate")
334
+ end_date = base.PartialDate.init_partial_date(end_date_element.text)
335
+ if feed_inactive_date < end_date:
336
+ raise loggers.ElectionError.from_message(
337
+ "FeedInactiveDate is older than EndDate",
338
+ [element],
339
+ )
340
+
341
+
342
+ class FeedHasValidCountryCode(base.BaseRule):
343
+ """Feeds should have valid country code."""
344
+
345
+ def elements(self):
346
+ return ["Feed"]
347
+
348
+ def check(self, element):
349
+ country_code_element = element.find("CountryCode")
350
+ if rule_util.element_has_text(country_code_element):
351
+ country_code = country_code_element.text.upper()
352
+ if not rule_util.country_code_is_valid(country_code):
353
+ raise loggers.ElectionError.from_message(
354
+ "Invalid country code {}.".format(country_code),
355
+ [element],
356
+ )
357
+ else:
358
+ feed_type = element.find("FeedType")
359
+ if rule_util.element_has_text(feed_type) and (
360
+ feed_type.text.lower().replace("_", "-") == "election-dates"
361
+ or feed_type.text.lower().replace("_", "-") == "voter-information"
362
+ ):
363
+ return
364
+ raise loggers.ElectionError.from_message(
365
+ "Feed {} is missing CountryCode.".format(element.find("FeedId").text),
366
+ [element],
367
+ )
368
+
369
+
370
+ class FeedInactiveDateNotOlderThanOneYear(base.BaseRule):
371
+ """Feeds should not have a FeedInactiveDate older than 1 year."""
372
+
373
+ def elements(self):
374
+ return ["Feed"]
375
+
376
+ def check(self, element):
377
+ feed_inactive_date_element = element.find("FeedInactiveDate")
378
+ if not rule_util.element_has_text(feed_inactive_date_element):
379
+ return
380
+ feed_inactive_date = datetime.date.fromisoformat(
381
+ feed_inactive_date_element.text
382
+ )
383
+ one_year_ago = datetime.date.today() - dateutil.relativedelta.relativedelta(
384
+ years=1
385
+ )
386
+ if feed_inactive_date < one_year_ago:
387
+ feed_id_element = element.find("FeedId")
388
+ raise loggers.ElectionError.from_message(
389
+ f"FeedInactiveDate '{feed_inactive_date_element.text}' is older than"
390
+ f" 1 year for feed '{feed_id_element.text}'.",
391
+ [element],
392
+ )
393
+
394
+
395
+ class FeedInactiveDateSetForNonEvergreenFeed(base.BaseRule):
396
+ """All non-evergreen feeds should have a FeedInactiveDate set."""
397
+
398
+ def elements(self):
399
+ return ["Feed"]
400
+
401
+ def check(self, element):
402
+ feed_longevity = element.find("FeedLongevity")
403
+ if (
404
+ rule_util.element_has_text(feed_longevity)
405
+ and feed_longevity.text.lower() != "evergreen"
406
+ and not rule_util.element_has_text(element.find("FeedInactiveDate"))
407
+ ):
408
+ raise loggers.ElectionError.from_message(
409
+ "FeedInactiveDate is not set for non-evergreen feed with FeedId {}."
410
+ .format(element.find("FeedId").text),
411
+ [element],
412
+ )
413
+
414
+
415
+ class FeedElementsShouldHaveSubElementsBasedOnType(base.BaseRule):
416
+ """Feeds should have certain elements based on feed type.
417
+
418
+ For example, Feeds of type officeholder should have an OfficeholderSubFeed,
419
+ similarly pre-election and election-results feeds should have an
420
+ ElectionEventCollection. In the case of an ElectionEventCollection, at least
421
+ one ElectionEvent element should be present.
422
+ """
423
+
424
+ def elements(self):
425
+ return ["Feed"]
426
+
427
+ def check(self, element):
428
+ feed_type = element.find("FeedType")
429
+ feed_id = element.find("FeedId").text
430
+
431
+ if not rule_util.element_has_text(feed_type):
432
+ return
433
+
434
+ feed_type = feed_type.text
435
+ if feed_type == "officeholder":
436
+ if element.find("OfficeholderSubFeed") is None:
437
+ raise loggers.ElectionError.from_message(
438
+ "OfficeholderSubFeed should exist for %s feed %s."
439
+ % (feed_type, feed_id)
440
+ )
441
+ elif feed_type == "pre-election" or feed_type == "election-results":
442
+ if element.find("ElectionEventCollection") is None:
443
+ raise loggers.ElectionError.from_message(
444
+ "ElectionEventCollection should exist for %s feed %s."
445
+ % (feed_type, feed_id)
446
+ )
447
+ if not element.find("ElectionEventCollection").findall("ElectionEvent"):
448
+ raise loggers.ElectionError.from_message(
449
+ "ElectionEventCollection should have at least one ElectionEvent"
450
+ " for %s feed %s." % (feed_type, feed_id)
451
+ )
452
+
453
+
454
+ METADATA_RULES = (
455
+ # go/keep-sorted start
456
+ ElectionEventDatesAreSequential,
457
+ FeedElementsShouldHaveSubElementsBasedOnType,
458
+ FeedHasValidCountryCode,
459
+ FeedIdsAreUnique,
460
+ FeedInactiveDateIsLatestDate,
461
+ FeedInactiveDateNotOlderThanOneYear,
462
+ FeedInactiveDateSetForNonEvergreenFeed,
463
+ FeedTypeHasValidFeedLongevity,
464
+ OfficeholderSubFeedDatesAreSequential,
465
+ SourceDirPathMustBeSetAfterInitialDeliveryDate,
466
+ SourceDirPathsAreUnique,
467
+ # TODO(b/555757644): Reenable this rule once we are ready to enforce it.
468
+ # SqsQueueNameIsFullyQualifiedArn,
469
+ SqsQueueNameRequiresS3SourceDirPath,
470
+ common_rules.EmptyString,
471
+ common_rules.EmptyText,
472
+ common_rules.Encoding,
473
+ common_rules.OptionalAndEmpty,
474
+ common_rules.Schema,
475
+ common_rules.UniqueLabel,
476
+ # go/keep-sorted end
477
+ )
@@ -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.67.dev7'
8
+ __version__ = '1.67.dev9'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: civics_cdf_validator
3
- Version: 1.67.dev7
3
+ Version: 1.67.dev9
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
@@ -3,21 +3,22 @@ civics_cdf_validator/base.py,sha256=o2dbEJ4haD4ddA6tGHuV_VApe_7DaslFspDb2IZ3GsY,
3
3
  civics_cdf_validator/gpunit_rules.py,sha256=Cg-qlOeVKTCQ5qUKYSxbVrrh3tdLt1X5Eg-7uyyR_SY,9487
4
4
  civics_cdf_validator/loggers.py,sha256=ZfWFd9yskcd2-qb83EPz7eqa1iGO8BRFMtDZeE1hofA,6921
5
5
  civics_cdf_validator/office_utils.py,sha256=4r0zc6-UB2YdqmUnGznEn5K5WLFRsQNQr-QMrFPo-xc,2721
6
- civics_cdf_validator/rules.py,sha256=2IOVEhAmeX8zKldt3itgcZgjzHzlSfVQVCb6JYOleEA,17263
6
+ civics_cdf_validator/rules.py,sha256=pFNjypzFO9ErXHui7vbPXypWL90-c8j2_gBN3OBRuXQ,2043
7
7
  civics_cdf_validator/stats.py,sha256=YNqv3Khkt_hJxCIunFBRSl23oXqu5gNjCmWMHFbAcSU,3819
8
8
  civics_cdf_validator/validator.py,sha256=OHXg-VngDdovYyBh0ON5M_vvA8PyKTzvfzR8SwZbEf8,12770
9
- civics_cdf_validator/version.py,sha256=S-qf3HD4Ry2zAaOiXaFqS8ANuGOM8EjHNOikmQXvKz4,188
9
+ civics_cdf_validator/version.py,sha256=3p5XJCnpltgDtDHESN9en_gWrVdwwDePz6HFQJADoIY,188
10
10
  civics_cdf_validator/rulesets/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
11
  civics_cdf_validator/rulesets/committee_rules.py,sha256=0hNnpzI-ptZDxErbH2D2r66IiIiioqVXSV3YxgXlhrE,3472
12
12
  civics_cdf_validator/rulesets/common_rules.py,sha256=vCcodXrykZBx-RHCX8J-zsUxwEFCEIl0WARkn4cm6fE,59417
13
13
  civics_cdf_validator/rulesets/election_dates_rules.py,sha256=mIOKroJ2z5QI5C_i8JR2fNUuZ_e8DJ3juEB07v8tONY,1363
14
14
  civics_cdf_validator/rulesets/election_rules.py,sha256=ldLXfYgJ3YbapIVZclQPmDemki-txOTOqrp_k8WgSS0,95874
15
+ civics_cdf_validator/rulesets/metadata_rules.py,sha256=5e4RObkNuzIRYzf_bNnqE6V2JDNMzvFWSew1u0n2na0,16099
15
16
  civics_cdf_validator/rulesets/officeholder_rules.py,sha256=N5G5Gum685ACXnb0Kwd5DseaCHOOpg3gpYK_uivAegQ,17766
16
17
  civics_cdf_validator/rulesets/rule_util.py,sha256=FWi09R7XWDfZwuHl-k2vhsFHlKuOrD5MD5YQ4QUQyVo,4431
17
18
  civics_cdf_validator/rulesets/voter_information_rules.py,sha256=9IyZRoSgaTF87K_NYJQ43C9wotwz6Wf0XOobJwv5lG8,4611
18
- civics_cdf_validator-1.67.dev7.dist-info/licenses/LICENSE-2.0.txt,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
19
- civics_cdf_validator-1.67.dev7.dist-info/METADATA,sha256=YTOeR-weNZDjWNPIiogRGKNYfJjpJqPFRm5yZcW5bF8,1280
20
- civics_cdf_validator-1.67.dev7.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
21
- civics_cdf_validator-1.67.dev7.dist-info/entry_points.txt,sha256=QibgvtMOocwDi7fQ1emgMJ2lIlI41sW0__KIQdnVn90,77
22
- civics_cdf_validator-1.67.dev7.dist-info/top_level.txt,sha256=PYT5Eclxbop5o6DJIcgs4IeU6Ds5jqyftjoFbgkkJYo,21
23
- civics_cdf_validator-1.67.dev7.dist-info/RECORD,,
19
+ civics_cdf_validator-1.67.dev9.dist-info/licenses/LICENSE-2.0.txt,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
20
+ civics_cdf_validator-1.67.dev9.dist-info/METADATA,sha256=6VffsunjGkkdRpFuqp80FlBPggI0a5kcytOTJf2O8eo,1280
21
+ civics_cdf_validator-1.67.dev9.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
22
+ civics_cdf_validator-1.67.dev9.dist-info/entry_points.txt,sha256=QibgvtMOocwDi7fQ1emgMJ2lIlI41sW0__KIQdnVn90,77
23
+ civics_cdf_validator-1.67.dev9.dist-info/top_level.txt,sha256=PYT5Eclxbop5o6DJIcgs4IeU6Ds5jqyftjoFbgkkJYo,21
24
+ civics_cdf_validator-1.67.dev9.dist-info/RECORD,,