Skip to content

Commit

Permalink
Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
symroe committed Apr 12, 2023
1 parent f99ca7a commit 992fe1e
Show file tree
Hide file tree
Showing 13 changed files with 45 additions and 57 deletions.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import sys
import os
import sys

sys.path.insert(0, os.path.abspath(".."))

Expand Down
1 change: 0 additions & 1 deletion run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import sys
import unittest


if __name__ == "__main__":
dirname = os.path.dirname(os.path.abspath(__file__))
loader = unittest.TestLoader()
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os

from setuptools import setup

# allow setup.py to be run from any path
Expand Down
9 changes: 3 additions & 6 deletions tests/data_schemas.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import json
from dataclasses import Field
from pathlib import Path
from typing import Dict, Optional, Any, Type
from typing import Dict, Optional

from pydantic import BaseModel, HttpUrl, root_validator

Expand Down Expand Up @@ -30,9 +28,8 @@ def validate(cls, values):
voting_system_slugs = values["voting_systems"].keys()

def _recurse_defaults(d: dict):
if value := d.get("default"):
if value not in voting_system_slugs:
raise ValueError(f"'{value}' is not a valid voting system")
if (value := d.get("default")) and value not in voting_system_slugs:
raise ValueError(f"'{value}' is not a valid voting system")
for k, v in d.items():
if isinstance(v, dict):
_recurse_defaults(v)
Expand Down
1 change: 1 addition & 0 deletions tests/test_id_builder.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import date
from unittest import TestCase

from uk_election_ids.election_ids import IdBuilder


Expand Down
15 changes: 7 additions & 8 deletions tests/test_id_requirements.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,13 @@ def test_defaults_valid_id_requirements(self):

def iter_defaults(data: dict, parent=None):
default = data.get("default", "")
if default == "":
if parent not in ["dates", "nations"]:
self.assertTrue(
any(
[key in ["nations", "dates"] for key in data.keys()]
),
msg=f"{data} requires either a `default`, `nations` or `dates` key",
)
if default == "" and parent not in ["dates", "nations"]:
self.assertTrue(
any(
[key in ["nations", "dates"] for key in data]
),
msg=f"{data} requires either a `default`, `nations` or `dates` key",
)
for key, value in data.items():
if isinstance(value, dict):
iter_defaults(value, parent=key)
Expand Down
1 change: 1 addition & 0 deletions tests/test_meta_data_matcher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from unittest import TestCase

from uk_election_ids.metadata_tools import IDRequirementsMatcher


Expand Down
1 change: 1 addition & 0 deletions tests/test_slugger.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-

from unittest import TestCase

from uk_election_ids.slugger import slugify


Expand Down
1 change: 1 addition & 0 deletions tests/test_validator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from unittest import TestCase

from uk_election_ids.election_ids import validate


Expand Down
15 changes: 7 additions & 8 deletions tests/test_voting_systems.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,13 @@ def test_defaults_valid_voting_systems(self):

def iter_defaults(data: dict, parent=None):
default = data.get("default", None)
if not default:
if not parent in ["dates", "nations"]:
self.assertTrue(
any(
[key in ["nations", "dates"] for key in data.keys()]
),
msg=f"{data} requires either a `default`, `nations` or `dates` key",
)
if not default and parent not in ["dates", "nations"]:
self.assertTrue(
any(
[key in ["nations", "dates"] for key in data]
),
msg=f"{data} requires either a `default`, `nations` or `dates` key",
)
for key, value in data.items():
if isinstance(value, dict):
iter_defaults(value, parent=key)
Expand Down
21 changes: 8 additions & 13 deletions uk_election_ids/election_ids.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import contextlib
from datetime import datetime

from .datapackage import ELECTION_TYPES
from .parser import DataPackageParser
from .slugger import slugify
Expand Down Expand Up @@ -70,8 +72,7 @@ def _format_date(self, date):
def _can_have_divs(self):
if isinstance(self.spec.can_have_divs, (bool,)):
return self.spec.can_have_divs
else:
return self.spec.can_have_divs[self.subtype]
return self.spec.can_have_divs[self.subtype]

def with_subtype(self, subtype):
"""Add a subtype segment
Expand Down Expand Up @@ -203,7 +204,7 @@ def _validate_division(self, division):
def _validate_contest_type(self, contest_type):
if not contest_type:
return True
if not contest_type.lower() in CONTEST_TYPES:
if contest_type.lower() not in CONTEST_TYPES:
raise ValueError(
"Allowed values for contest_type are %s"
% (str(list(CONTEST_TYPES)))
Expand Down Expand Up @@ -352,22 +353,16 @@ def ids(self):
"""
ids = []

try:
with contextlib.suppress(ValueError):
ids.append(self.election_group_id)
except ValueError:
pass

if isinstance(self.spec.subtypes, tuple):
try:
with contextlib.suppress(ValueError):
ids.append(self.subtype_group_id)
except ValueError:
pass

if self.spec.can_have_orgs:
try:
with contextlib.suppress(ValueError):
ids.append(self.organisation_group_id)
except ValueError:
pass

try:
if self.ballot_id not in ids:
Expand Down Expand Up @@ -432,7 +427,7 @@ def from_id(cls, identifier: str) -> "IdBuilder":
# use the builder object to validate the remaining parts,
# popping as we go
if id_parts[-1] == "by":
contest_type = id_parts.pop(-1)
id_parts.pop(-1)
builder = builder.with_contest_type("by")
if builder.spec.subtypes:
subtype = id_parts.pop(0)
Expand Down
15 changes: 6 additions & 9 deletions uk_election_ids/metadata_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,8 @@ def match_dates(self, data):
if not end:
end = datetime.date(year=9999, month=12, day=31)

if self.date >= start:
if self.date < end:
return value
if self.date >= start and self.date < end:
return value
raise ValueError("No date for range")


Expand All @@ -100,9 +99,8 @@ class VotingSystemMatcher(MetaDataMatcher):

def get_voting_system(self):
id_part, data = self.match_id()
if self.nation:
if self.nation in data.get("nations", {}):
data = data["nations"][self.nation]
if self.nation and self.nation in data.get("nations", {}):
data = data["nations"][self.nation]

if data.get("dates"):
data = self.match_dates(data["dates"])
Expand All @@ -121,9 +119,8 @@ class IDRequirementsMatcher(MetaDataMatcher):

def get_id_requirements(self):
id_part, data = self.match_id()
if self.nation:
if self.nation in data.get("nations", {}):
data = data["nations"][self.nation]
if self.nation and self.nation in data.get("nations", {}):
data = data["nations"][self.nation]

if data.get("dates"):
data = self.match_dates(data["dates"])
Expand Down
19 changes: 8 additions & 11 deletions uk_election_ids/parser.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from collections import namedtuple


IdSpec = namedtuple("IdSpec", ["subtypes", "can_have_orgs", "can_have_divs"])


Expand All @@ -25,20 +24,18 @@ def build_subtypes(self, record):
def build_can_have_orgs(self, record):
if "can_have_orgs" in record:
return record["can_have_orgs"]
else:
return {
subtype["election_subtype"]: subtype["can_have_orgs"]
for subtype in record["subtypes"]
}
return {
subtype["election_subtype"]: subtype["can_have_orgs"]
for subtype in record["subtypes"]
}

def build_can_have_divs(self, record):
if "can_have_divs" in record:
return record["can_have_divs"]
else:
return {
subtype["election_subtype"]: subtype["can_have_divs"]
for subtype in record["subtypes"]
}
return {
subtype["election_subtype"]: subtype["can_have_divs"]
for subtype in record["subtypes"]
}

def build_rules(self):
rules = {}
Expand Down

0 comments on commit 992fe1e

Please sign in to comment.