Skip to content

Commit 2981058

Browse files
committed
Fix lint issues and harden dataset authors migration tests
- Refactor migrate_dataset_authors command to satisfy ruff complexity rules - Move Dataset.save before _normalize_authors_list per Django style guide - Parse JSON-string authors in get_authors_display for in-memory instances - Update migrate command tests to use raw DB authors and avoid factory bug - Shorten test docstrings to satisfy line-length checks
1 parent 5abf551 commit 2981058

5 files changed

Lines changed: 158 additions & 115 deletions

File tree

‎gateway/package.json‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,16 @@
4242
"onFail": "download"
4343
}
4444
},
45-
"browserslist": ["last 2 versions"],
45+
"browserslist": [
46+
"last 2 versions"
47+
],
4648
"babel": {
47-
"presets": ["@babel/preset-env"],
48-
"plugins": ["@babel/plugin-transform-runtime"]
49+
"presets": [
50+
"@babel/preset-env"
51+
],
52+
"plugins": [
53+
"@babel/plugin-transform-runtime"
54+
]
4955
},
5056
"parser": "babel-eslint",
5157
"parserOptions": {

‎gateway/sds_gateway/api_methods/management/commands/migrate_dataset_authors.py‎

Lines changed: 84 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,15 @@
88
"""
99

1010
import json
11+
from typing import Literal
1112

1213
from django.core.management.base import BaseCommand
1314
from loguru import logger
1415

1516
from sds_gateway.api_methods.models import Dataset
1617

18+
MigrationOutcome = Literal["updated", "skipped", "error"]
19+
1720

1821
class Command(BaseCommand):
1922
help = (
@@ -37,94 +40,98 @@ def handle(self, *args, **options):
3740
dry_run = options["dry_run"]
3841
specific_uuid = options.get("uuid")
3942

40-
# Query datasets with non-empty authors
4143
queryset = Dataset.objects.filter(authors__isnull=False).exclude(authors="")
4244
if specific_uuid:
4345
queryset = queryset.filter(uuid=specific_uuid)
4446

4547
total = queryset.count()
46-
updated = 0
47-
skipped = 0
48-
errors = 0
48+
counts = {"updated": 0, "skipped": 0, "error": 0}
4949

5050
self.stdout.write(f"Scanning {total} dataset(s) with authors...")
5151

5252
# Iterate raw DB values so Dataset.from_db() does not json.loads(authors)
5353
# before we can handle invalid JSON per row (see migration 0017).
5454
for row in queryset.values("uuid", "authors"):
55-
dataset_uuid = row["uuid"]
56-
try:
57-
authors_raw = row["authors"]
58-
if isinstance(authors_raw, str):
59-
try:
60-
authors = json.loads(authors_raw)
61-
except (json.JSONDecodeError, TypeError):
62-
logger.warning(
63-
f"Dataset {dataset_uuid}: invalid authors JSON, skipping",
64-
)
65-
skipped += 1
66-
continue
67-
else:
68-
authors = authors_raw
69-
70-
# Skip if not a list
71-
if not isinstance(authors, list):
72-
skipped += 1
73-
continue
74-
75-
# Skip empty lists
76-
if not authors:
77-
skipped += 1
78-
continue
79-
80-
# Skip if already in new format (list of dicts with 'name' key)
81-
if isinstance(authors[0], dict):
82-
skipped += 1
83-
continue
84-
85-
# Convert old format: list of strings → list of dicts
86-
if isinstance(authors[0], str):
87-
new_authors = [
88-
{"name": author, "orcid_id": ""}
89-
for author in authors
90-
if isinstance(author, str)
91-
]
92-
93-
if not new_authors:
94-
logger.warning(
95-
f"Dataset {dataset_uuid}: no valid author strings found, "
96-
"skipping",
97-
)
98-
skipped += 1
99-
continue
100-
101-
if dry_run:
102-
logger.info(
103-
f"[DRY-RUN] Would convert dataset {dataset_uuid}: "
104-
f"{len(authors)} author(s) in old format"
105-
)
106-
else:
107-
Dataset.objects.filter(uuid=dataset_uuid).update(
108-
authors=json.dumps(new_authors),
109-
)
110-
logger.info(
111-
f"Converted dataset {dataset_uuid}: "
112-
f"{len(authors)} author(s) → new format"
113-
)
114-
updated += 1
115-
else:
116-
# Unexpected format
117-
logger.warning(
118-
f"Dataset {dataset_uuid}: unexpected author type "
119-
f"{type(authors[0]).__name__}, skipping"
120-
)
121-
skipped += 1
122-
123-
except Exception as e: # noqa: BLE001 # intentional: continue processing remaining datasets
124-
logger.error(f"Error processing dataset {dataset_uuid}: {e}")
125-
errors += 1
55+
outcome = self._migrate_row(row, dry_run=dry_run)
56+
counts[outcome] += 1
12657

12758
self.stdout.write(
128-
f"Done: {updated} updated, {skipped} skipped, {errors} errors"
129-
+ (" (dry run)" if dry_run else "")
59+
f"Done: {counts['updated']} updated, {counts['skipped']} skipped, "
60+
f"{counts['error']} errors" + (" (dry run)" if dry_run else "")
13061
)
62+
63+
def _migrate_row(self, row: dict, *, dry_run: bool) -> MigrationOutcome:
64+
dataset_uuid = row["uuid"]
65+
try:
66+
authors = self._parse_authors(row["authors"], dataset_uuid)
67+
if authors is None:
68+
return "skipped"
69+
70+
new_authors = self._convert_legacy_authors(authors, dataset_uuid)
71+
if new_authors is None:
72+
return "skipped"
73+
74+
if dry_run:
75+
logger.info(
76+
f"[DRY-RUN] Would convert dataset {dataset_uuid}: "
77+
f"{len(authors)} author(s) in old format"
78+
)
79+
else:
80+
Dataset.objects.filter(uuid=dataset_uuid).update(
81+
authors=json.dumps(new_authors),
82+
)
83+
logger.info(
84+
f"Converted dataset {dataset_uuid}: "
85+
f"{len(authors)} author(s) → new format"
86+
)
87+
except Exception as e: # noqa: BLE001 # intentional: continue processing remaining datasets
88+
logger.error(f"Error processing dataset {dataset_uuid}: {e}")
89+
return "error"
90+
else:
91+
return "updated"
92+
93+
def _parse_authors(self, authors_raw, dataset_uuid: str) -> list | None:
94+
if isinstance(authors_raw, str):
95+
try:
96+
authors = json.loads(authors_raw)
97+
except (json.JSONDecodeError, TypeError):
98+
logger.warning(
99+
f"Dataset {dataset_uuid}: invalid authors JSON, skipping",
100+
)
101+
return None
102+
else:
103+
authors = authors_raw
104+
105+
if not isinstance(authors, list) or not authors:
106+
return None
107+
108+
return authors
109+
110+
def _convert_legacy_authors(
111+
self,
112+
authors: list,
113+
dataset_uuid: str,
114+
) -> list | None:
115+
if isinstance(authors[0], dict):
116+
return None
117+
118+
if not isinstance(authors[0], str):
119+
logger.warning(
120+
f"Dataset {dataset_uuid}: unexpected author type "
121+
f"{type(authors[0]).__name__}, skipping"
122+
)
123+
return None
124+
125+
new_authors = [
126+
{"name": author, "orcid_id": ""}
127+
for author in authors
128+
if isinstance(author, str)
129+
]
130+
131+
if not new_authors:
132+
logger.warning(
133+
f"Dataset {dataset_uuid}: no valid author strings found, skipping",
134+
)
135+
return None
136+
137+
return new_authors

‎gateway/sds_gateway/api_methods/models.py‎

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -984,18 +984,6 @@ class Dataset(BaseModel):
984984
def __str__(self) -> str:
985985
return self.name
986986

987-
@staticmethod
988-
def _normalize_authors_list(authors: list) -> list:
989-
"""Convert legacy list-of-strings authors to list-of-dicts on save."""
990-
if authors and any(isinstance(author, str) for author in authors):
991-
return [
992-
{"name": author, "orcid_id": ""}
993-
if isinstance(author, str)
994-
else author
995-
for author in authors
996-
]
997-
return authors
998-
999987
def save(self, *args, **kwargs) -> None:
1000988
# Serialize the list fields to a JSON string before saving
1001989
for field in self.list_fields:
@@ -1048,6 +1036,16 @@ def save(self, *args, **kwargs) -> None:
10481036

10491037
super().save(*args, **kwargs)
10501038

1039+
@staticmethod
1040+
def _normalize_authors_list(authors: list) -> list:
1041+
"""Convert legacy list-of-strings authors to list-of-dicts on save."""
1042+
if authors and any(isinstance(author, str) for author in authors):
1043+
return [
1044+
{"name": author, "orcid_id": ""} if isinstance(author, str) else author
1045+
for author in authors
1046+
]
1047+
return authors
1048+
10511049
def soft_delete(self) -> None:
10521050
"""Soft delete this record after checking for blockers."""
10531051
from sds_gateway.api_methods.utils.asset_access_control import ( # noqa: PLC0415
@@ -1119,25 +1117,35 @@ def get_authors_display(self):
11191117
if not self.authors:
11201118
return []
11211119

1120+
authors = self.authors
1121+
if isinstance(authors, str):
1122+
try:
1123+
authors = json.loads(authors)
1124+
except (json.JSONDecodeError, TypeError):
1125+
log.warning(
1126+
f"Dataset {self.uuid}: authors field is not valid JSON",
1127+
)
1128+
return []
1129+
11221130
# from_db should have already converted JSON string to list
1123-
if not isinstance(self.authors, list):
1131+
if not isinstance(authors, list):
11241132
log.warning(
11251133
f"Dataset {self.uuid}: authors field is not a list "
1126-
f"(type: {type(self.authors).__name__})",
1134+
f"(type: {type(authors).__name__})",
11271135
)
11281136
return []
11291137

11301138
# Check if authors are in old string format and need conversion
1131-
if self.authors and isinstance(self.authors[0], str):
1139+
if authors and isinstance(authors[0], str):
11321140
log.warning(
11331141
f"Dataset {self.uuid}: authors still in old string format, "
11341142
f"needs migration",
11351143
)
11361144
# Convert old format for backward compatibility
1137-
return [{"name": author, "orcid_id": ""} for author in self.authors]
1145+
return [{"name": author, "orcid_id": ""} for author in authors]
11381146

11391147
# Authors should already be in new object format
1140-
return self.authors
1148+
return authors
11411149

11421150

11431151
class TemporaryZipFile(BaseModel):

‎gateway/sds_gateway/api_methods/tests/test_dataset_authors_save.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def test_save_leaves_new_format_json_string_unchanged_semantically(self):
6969
]
7070

7171
def test_save_preserves_dict_authors_when_mixed_with_strings_first(self):
72-
"""Mixed legacy strings and dict authors keep dict entries when string is first."""
72+
"""Mixed string/dict authors keep dict entries when string is first."""
7373
co_author = {"name": "Co Author", "orcid_id": "0000-0001-2345-6789"}
7474
dataset = self._create_dataset(
7575
name="mixed-authors-string-first",
@@ -83,7 +83,7 @@ def test_save_preserves_dict_authors_when_mixed_with_strings_first(self):
8383
]
8484

8585
def test_save_preserves_dict_authors_when_mixed_with_strings_last(self):
86-
"""Mixed legacy strings and dict authors keep dict entries when string is last."""
86+
"""Mixed string/dict authors keep dict entries when string is last."""
8787
co_author = {"name": "Co Author", "orcid_id": "0000-0001-2345-6789"}
8888
dataset = self._create_dataset(
8989
name="mixed-authors-string-last",

0 commit comments

Comments
 (0)