Skip to content

Commit ae4113d

Browse files
committed
refactor: apply manual ruff rules and snapshots
Updates: - Update to use lowercased function-level variables - Update to use snake-casing - Move dynamic getattr-calls to module level from function default parameters - Postfix exception-classes with 'Error' - Move tzinfo-variable to module-level to reduce excessive code duplication - Update syrupy snapshots - Update GDPR-tests - Update timezone-filtering to work with Django 5 Refs: PT-1947
1 parent 6802347 commit ae4113d

22 files changed

Lines changed: 251 additions & 224 deletions

File tree

common/tests/test_mixins.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,21 +29,21 @@ def user(self):
2929

3030
@pytest.mark.django_db
3131
def test_write_audit_access_log_of_paginated_objects(self, factory, user):
32-
BATCH_SIZE = 3
33-
p_events = PalvelutarjotinEventFactory.create_batch(BATCH_SIZE)
32+
batch_size = 3
33+
p_events = PalvelutarjotinEventFactory.create_batch(batch_size)
3434
request = factory.get("/")
3535
request.user = user
3636
list_view = self.DummyListView(request)
3737
with mock.patch("auditlog.signals.accessed.send") as mock_send:
3838
list_view._write_audit_access_log_of_paginated_objects(p_events)
39-
assert mock_send.call_count == BATCH_SIZE
39+
assert mock_send.call_count == batch_size
4040
for p_event in p_events:
4141
mock_send.assert_any_call(sender=PalvelutarjotinEvent, instance=p_event)
4242

4343
@pytest.mark.django_db
4444
def test_paginate_queryset_no_pagination(self, factory, user):
45-
BATCH_SIZE = 3
46-
p_events = PalvelutarjotinEventFactory.create_batch(BATCH_SIZE)
45+
batch_size = 3
46+
p_events = PalvelutarjotinEventFactory.create_batch(batch_size)
4747
request = factory.get("/")
4848
request.user = user
4949
list_view = self.DummyListView(request)
@@ -57,15 +57,12 @@ def test_paginate_queryset_no_pagination(self, factory, user):
5757
@parameterized.expand([(5, 5), (10, 20)])
5858
@pytest.mark.django_db
5959
def test_paginate_queryset_with_pagination(self, page_size, batch_size):
60-
PAGE_SIZE = page_size
6160
user = UserFactory()
6261
factory = APIRequestFactory()
6362

6463
class CustomPaginator(PageNumberPagination):
65-
page_size = PAGE_SIZE
66-
6764
def paginate_queryset(self, queryset, request, **kwargs):
68-
return queryset[: self.page_size]
65+
return queryset[:page_size]
6966

7067
p_events = PalvelutarjotinEventFactory.create_batch(batch_size)
7168
request = factory.get("/", {"page": 1})
@@ -79,7 +76,7 @@ def paginate_queryset(self, queryset, request, **kwargs):
7976
result = list_view.paginate_queryset(p_events)
8077
assert result is not None
8178
mock_write_log.assert_called_once()
82-
assert len(mock_write_log.call_args[0][0]) == PAGE_SIZE
79+
assert len(mock_write_log.call_args[0][0]) == page_size
8380

8481
@pytest.mark.django_db
8582
def test_paginate_queryset_with_empty_queryset(self, factory, user):
@@ -100,14 +97,14 @@ def test_access_log_written_from_every_result(self, factory, user):
10097
Test that an access log entry is written for each object in the list view
10198
result.
10299
"""
103-
BATCH_SIZE = 3
104-
p_events = PalvelutarjotinEventFactory.create_batch(BATCH_SIZE)
100+
batch_size = 3
101+
p_events = PalvelutarjotinEventFactory.create_batch(batch_size)
105102
request = factory.get("/")
106103
request.user = user
107104
list_view = self.DummyListView(request)
108105
list_view.paginate_queryset(p_events)
109-
assert PalvelutarjotinEvent.objects.count() == BATCH_SIZE
106+
assert PalvelutarjotinEvent.objects.count() == batch_size
110107
assert (
111108
LogEntry.objects.filter(actor=user, action=LogEntry.Action.ACCESS).count()
112-
== BATCH_SIZE
109+
== batch_size
113110
)

common/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,9 @@ def convert_to_localtime_tz(value):
100100
dt = datetime.combine(datetime.now().date(), value)
101101
if timezone.is_naive(value):
102102
# Auto add local timezone to naive time
103-
return timezone.make_aware(dt).timetz()
103+
return timezone.make_aware(dt)
104104
else:
105-
return timezone.localtime(dt).timetz()
105+
return timezone.localtime(dt)
106106

107107

108108
def to_local_datetime_if_naive(value) -> datetime:

gdpr/tests/test_gdpr_api.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -282,15 +282,20 @@ def test_delete_profile_data_from_gdpr_api(
282282
all_count = LogEntry.objects.count()
283283
assert all_count > 2
284284
created = LogEntry.objects.filter(action=LogEntry.Action.CREATE)
285+
updated = LogEntry.objects.filter(action=LogEntry.Action.UPDATE)
285286
deleted = LogEntry.objects.filter(action=LogEntry.Action.DELETE)
286-
assert created.count() == all_count - deleted.count()
287+
assert created.count() == all_count - updated.count() - deleted.count()
288+
assert updated.count() == 1
289+
assert updated.first().object_id == user.id
287290
assert deleted.count() == 1
288291
assert deleted.first().object_id == user.id
289292
else:
290-
assert LogEntry.objects.count() == 2
291-
(created_log, deleted_log) = LogEntry.objects.all().order_by("id")
293+
assert LogEntry.objects.count() == 3
294+
(created_log, updated_log, deleted_log) = LogEntry.objects.all().order_by("id")
292295
assert created_log.action == LogEntry.Action.CREATE
293296
assert created_log.object_id == user.id
297+
assert updated_log.action == LogEntry.Action.UPDATE
298+
assert updated_log.object_id == user.id
294299
assert deleted_log.action == LogEntry.Action.DELETE
295300
assert deleted_log.object_id == user.id
296301

graphene_linked_events/schema.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ class LocalisedObjectInput(InputObjectType):
8888

8989
class Division(ObjectType):
9090
type = String(required=True)
91-
ocdId = String(description="Open Civic Data ID")
91+
ocd_id = String(description="Open Civic Data ID")
9292
municipality = String()
9393
name = Field(LocalisedObject)
9494

graphene_linked_events/tests/__snapshots__/test_api.ambr

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -868,7 +868,7 @@
868868
'divisions': list([
869869
dict({
870870
'municipality': None,
871-
'ocdId': None,
871+
'ocdId': 'ocd-division/country:fi/kunta:espoo',
872872
}),
873873
]),
874874
'email': 'sellonkirjasto@espoo.fi',
@@ -937,7 +937,7 @@
937937
'divisions': list([
938938
dict({
939939
'municipality': None,
940-
'ocdId': None,
940+
'ocdId': 'ocd-division/country:fi/kunta:espoo',
941941
}),
942942
]),
943943
'email': 'sellonkirjasto@espoo.fi',
@@ -998,7 +998,7 @@
998998
'divisions': list([
999999
dict({
10001000
'municipality': None,
1001-
'ocdId': None,
1001+
'ocdId': 'ocd-division/country:fi/kunta:espoo',
10021002
}),
10031003
]),
10041004
'email': 'kirjasto.entresse@espoo.fi',
@@ -1710,7 +1710,7 @@
17101710
'divisions': list([
17111711
dict({
17121712
'municipality': None,
1713-
'ocdId': None,
1713+
'ocdId': 'ocd-division/country:fi/kunta:espoo',
17141714
}),
17151715
]),
17161716
'email': 'sellonkirjasto@espoo.fi',
@@ -1771,7 +1771,7 @@
17711771
'divisions': list([
17721772
dict({
17731773
'municipality': None,
1774-
'ocdId': None,
1774+
'ocdId': 'ocd-division/country:fi/kunta:espoo',
17751775
}),
17761776
]),
17771777
'email': 'kirjasto.entresse@espoo.fi',

graphene_linked_events/tests/test_api.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -669,13 +669,13 @@ def test_resolve_events_parameter_mapping(
669669
linked_event_id = EVENTS_DATA["data"][0]["id"]
670670
organisation_id = to_global_id("OrganisationNode", organisation.id)
671671
PalvelutarjotinEventFactory(linked_event_id=linked_event_id)
672-
with patch.object(LinkedEventsApiClient, "list") as linkedEventsApiClientMock:
672+
with patch.object(LinkedEventsApiClient, "list") as linked_events_api_client_mock:
673673
api_client.execute(
674674
GET_EVENTS_QUERY,
675675
variables={"organisationId": organisation_id, given: ["test"]},
676676
)
677677

678-
linkedEventsApiClientMock.assert_called_with(
678+
linked_events_api_client_mock.assert_called_with(
679679
"event",
680680
filter_list={"publisher": organisation.publisher_id, expected: ["test"]},
681681
is_event_staff=False,
@@ -980,12 +980,16 @@ def test_create_event_with_null_organisation_id(
980980
) in executed["errors"][0]["message"]
981981

982982

983-
@pytest.mark.parametrize("organisationId", ["", " ", " " * 10])
983+
@pytest.mark.parametrize("organisation_id", ["", " ", " " * 10])
984984
def test_create_event_with_empty_or_whitespace_only_organisation_id(
985-
event_staff_api_client, person, mock_create_event_data, organisation, organisationId
985+
event_staff_api_client,
986+
person,
987+
mock_create_event_data,
988+
organisation,
989+
organisation_id,
986990
):
987991
variables = deepcopy(CREATE_EVENT_VARIABLES)
988-
variables["input"]["organisationId"] = organisationId
992+
variables["input"]["organisationId"] = organisation_id
989993
variables["input"]["pEvent"]["contactPersonId"] = to_global_id(
990994
"PersonNode", person.id
991995
)
@@ -1353,12 +1357,16 @@ def test_update_event_with_null_organisation_id(
13531357
) in executed["errors"][0]["message"]
13541358

13551359

1356-
@pytest.mark.parametrize("organisationId", ["", " ", " " * 10])
1360+
@pytest.mark.parametrize("organisation_id", ["", " ", " " * 10])
13571361
def test_update_event_with_empty_or_whitespace_only_organisation_id(
1358-
event_staff_api_client, person, mock_update_event_data, organisation, organisationId
1362+
event_staff_api_client,
1363+
person,
1364+
mock_update_event_data,
1365+
organisation,
1366+
organisation_id,
13591367
):
13601368
variables = deepcopy(UPDATE_EVENT_VARIABLES)
1361-
variables["input"]["organisationId"] = organisationId
1369+
variables["input"]["organisationId"] = organisation_id
13621370
variables["input"]["pEvent"]["contactPersonId"] = to_global_id(
13631371
"PersonNode", person.id
13641372
)
@@ -1927,24 +1935,24 @@ def test_get_upcoming_events(
19271935
Event are ordered so that the event with the next upcoming occurrence is first.
19281936
"""
19291937
mocked_responses.assert_all_requests_are_fired = False
1930-
UPCOMING_MOCKED_EVENTS = []
1938+
upcoming_mocked_events = []
19311939

19321940
for i in range(1, 4):
19331941
p_event = PalvelutarjotinEventFactory(
19341942
linked_event_id=f"kultus:{i}", organisation=organisation
19351943
)
1936-
MOCK_EVENT_DATA = {**EVENT_DATA, "id": p_event.linked_event_id}
1944+
mock_event_data = {**EVENT_DATA, "id": p_event.linked_event_id}
19371945
mocked_responses.add(
19381946
responses.GET,
19391947
url=settings.LINKED_EVENTS_API_CONFIG["ROOT"]
19401948
+ f"event/{p_event.linked_event_id}/",
1941-
json=MOCK_EVENT_DATA,
1949+
json=mock_event_data,
19421950
)
19431951
mocked_responses.add(
19441952
responses.PUT,
19451953
url=settings.LINKED_EVENTS_API_CONFIG["ROOT"]
19461954
+ f"event/{p_event.linked_event_id}/",
1947-
json=MOCK_EVENT_DATA,
1955+
json=mock_event_data,
19481956
)
19491957

19501958
if cancelled:
@@ -1967,7 +1975,7 @@ def test_get_upcoming_events(
19671975
end = start + timedelta(hours=1)
19681976
OccurrenceFactory.create(p_event=p_event, start_time=start, end_time=end)
19691977

1970-
UPCOMING_MOCKED_EVENTS.append(MOCK_EVENT_DATA)
1978+
upcoming_mocked_events.append(mock_event_data)
19711979

19721980
if upcoming:
19731981
ds = settings.LINKED_EVENTS_API_CONFIG["DATA_SOURCE"]
@@ -1977,11 +1985,11 @@ def test_get_upcoming_events(
19771985
url=f"{settings.LINKED_EVENTS_API_CONFIG['ROOT']}event/?{query_string}",
19781986
json={
19791987
"meta": {
1980-
"count": len(UPCOMING_MOCKED_EVENTS),
1988+
"count": len(upcoming_mocked_events),
19811989
"next": None,
19821990
"previous": None,
19831991
},
1984-
"data": UPCOMING_MOCKED_EVENTS,
1992+
"data": upcoming_mocked_events,
19851993
},
19861994
)
19871995

notification_importers/admin.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
from .notification_importer import (
1616
AbstractNotificationImporter,
17-
NotificationImporterException,
17+
NotificationImporterExceptionError,
1818
)
1919

2020
logger = logging.getLogger(__name__)
@@ -30,7 +30,7 @@ class NotificationTemplateAdminWithImporter(NotificationTemplateAdmin):
3030
def changelist_view(self, request, *args, **kwargs):
3131
try:
3232
self.importer = self.__load_importer_class_from_settings()
33-
except NotificationImporterException as e:
33+
except NotificationImporterExceptionError as e:
3434
self._send_error_message(request, e)
3535
return super().changelist_view(request, *args, **kwargs)
3636

@@ -55,7 +55,7 @@ def update_selected(self, request, queryset):
5555

5656
try:
5757
num_of_updated = self.importer.update_notifications(queryset)
58-
except NotificationImporterException as e:
58+
except NotificationImporterExceptionError as e:
5959
self._send_error_message(request, e)
6060
return
6161

@@ -88,7 +88,7 @@ def import_missing_notifications(self, request):
8888
if self.importer:
8989
try:
9090
num_of_created = self.importer.create_missing_notifications()
91-
except NotificationImporterException as e:
91+
except NotificationImporterExceptionError as e:
9292
self._send_error_message(request, e)
9393
else:
9494
if num_of_created:

notification_importers/management/commands/import_notifications_from_google_sheets.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from notification_importers.notification_importer import (
44
NotificationGoogleSheetImporter,
5-
NotificationImporterException,
5+
NotificationImporterExceptionError,
66
)
77

88

@@ -18,7 +18,7 @@ def handle(self, *args, **options):
1818
num_of_created,
1919
num_of_updated,
2020
) = importer.create_missing_and_update_existing_notifications()
21-
except NotificationImporterException as e:
21+
except NotificationImporterExceptionError as e:
2222
self.stdout.write(self.style.ERROR(e))
2323
return
2424

notification_importers/management/commands/import_notifications_from_template_files.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from notification_importers.notification_importer import (
44
NotificationFileImporter,
5-
NotificationImporterException,
5+
NotificationImporterExceptionError,
66
)
77

88

@@ -18,7 +18,7 @@ def handle(self, *args, **options):
1818
num_of_created,
1919
num_of_updated,
2020
) = importer.create_missing_and_update_existing_notifications()
21-
except NotificationImporterException as e:
21+
except NotificationImporterExceptionError as e:
2222
self.stdout.write(self.style.ERROR(e))
2323
return
2424

notification_importers/notification_importer.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
logger = getLogger(__name__)
3434

3535

36-
class NotificationImporterException(Exception):
36+
class NotificationImporterExceptionError(Exception):
3737
pass
3838

3939

@@ -138,7 +138,7 @@ def _create_or_update_notification_using_source_data(
138138
language_code=language,
139139
)
140140
except NotificationTemplateException as e:
141-
raise NotificationImporterException(
141+
raise NotificationImporterExceptionError(
142142
f'Error rendering notification "{notification}": {e}'
143143
) from e
144144

@@ -173,7 +173,7 @@ def __init__(self, sheet_id: str = None) -> None:
173173
else None
174174
)
175175
if not self.sheet_id:
176-
raise NotificationImporterException("Sheet ID not set.")
176+
raise NotificationImporterExceptionError("Sheet ID not set.")
177177

178178
self.source_data: SourceData = self._fetch_data()
179179

@@ -196,7 +196,7 @@ def __fetch_csv_data(self) -> str:
196196
response = requests.get(self.url, timeout=self.TIMEOUT)
197197
response.raise_for_status()
198198
except RequestException as e:
199-
raise NotificationImporterException(
199+
raise NotificationImporterExceptionError(
200200
f"Error fetching data from the spreadsheet: {e}"
201201
) from e
202202
return response.content.decode("utf-8")

0 commit comments

Comments
 (0)