From f1ebee3fef469347b5f73088881fdbf305604cb3 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 10 Nov 2026 15:26:48 +0100 Subject: [PATCH 01/15] chore: update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f92e88e..9df87b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -# 6.X.X (2026-XX-XX) +# 6.8.0 (2026-10-11) ## New features -- 2.54.1 From 27724bad0ca2544eb1fbbaaf72ee4c00039b0bfd Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 10 Nov 2026 16:59:55 +0100 Subject: [PATCH 02/15] fix: automatically fix ruff-linting errors --- dump_things_service/audit/gitaudit.py | 4 ++-- .../audit/tests/test_gitaudit.py | 2 +- dump_things_service/backends/record_dir.py | 6 +++--- .../backends/schema_type_layer.py | 2 +- dump_things_service/backends/sqlite.py | 6 +++--- dump_things_service/collection.py | 4 +--- dump_things_service/commands/check_pids.py | 4 ++-- .../commands/create_merged_schema.py | 2 +- .../commands/download_config.py | 6 +++--- .../commands/gitaudit_report.py | 4 ++-- dump_things_service/commands/hash_token.py | 4 ++-- dump_things_service/commands/upload_config.py | 12 +++++------ .../endpoints/v0/base_endpoints.py | 14 ++++++------- .../endpoints/v0/collection_endpoints.py | 2 +- dump_things_service/endpoints/v0/curated.py | 2 +- dump_things_service/endpoints/v0/incoming.py | 2 +- .../endpoints/v0/token_endpoints.py | 2 +- dump_things_service/instance_state.py | 2 +- dump_things_service/main.py | 6 +++--- dump_things_service/model.py | 4 ++-- dump_things_service/periodic.py | 3 +-- dump_things_service/store/model_store.py | 2 +- dump_things_service/tests/fixtures.py | 6 +++--- dump_things_service/tests/test_basic.py | 2 +- dump_things_service/tests/test_config.py | 2 +- dump_things_service/tests/test_incoming.py | 2 +- dump_things_service/tests/test_roundtrip.py | 2 +- .../tests/test_roundtrip_flatsocial.py | 2 +- .../tests/test_web_interface.py | 6 +++--- dump_things_service/utils.py | 20 +++++++++---------- 30 files changed, 67 insertions(+), 70 deletions(-) diff --git a/dump_things_service/audit/gitaudit.py b/dump_things_service/audit/gitaudit.py index 382b05d..c2a04da 100644 --- a/dump_things_service/audit/gitaudit.py +++ b/dump_things_service/audit/gitaudit.py @@ -223,7 +223,7 @@ class GitAuditBackend(AuditBackend): author_id: str, record: dict, ) -> bool: - from dump_things_service.utils import json2yaml # noqa PLC0415 -- global import leads to circular imports + from dump_things_service.utils import json2yaml existing_record = self._read_record_from_repo_path(location[1]) if existing_record != record: @@ -305,7 +305,7 @@ class GitAuditBackend(AuditBackend): self, record_id: str, ) -> tuple[str, Path, Path]: - base = hashlib.sha1(record_id.encode()).hexdigest() # noqa S324 -- hash is not used for security + base = hashlib.sha1(record_id.encode()).hexdigest() dir_1, dir_2, _name = base[0:3], base[3:6], base[6:] location_dir = Path(dir_1) / Path(dir_2) return ( diff --git a/dump_things_service/audit/tests/test_gitaudit.py b/dump_things_service/audit/tests/test_gitaudit.py index ac1e51a..38c7d4c 100644 --- a/dump_things_service/audit/tests/test_gitaudit.py +++ b/dump_things_service/audit/tests/test_gitaudit.py @@ -6,7 +6,7 @@ from dump_things_service.audit.gitaudit import GitAuditBackend def _get_git_log(path: Path) -> list[str]: result = subprocess.run( - ['git', '-C', str(path), 'log', '--oneline'], # noqa S607 -- test run in a controlled environment + ['git', '-C', str(path), 'log', '--oneline'], capture_output=True, check=True, ) diff --git a/dump_things_service/backends/record_dir.py b/dump_things_service/backends/record_dir.py index 4183bf4..f5c16c3 100644 --- a/dump_things_service/backends/record_dir.py +++ b/dump_things_service/backends/record_dir.py @@ -61,7 +61,7 @@ class RecordDirResultList(BackendResultList): :param path: The path where the record is stored :return: A RecordInfo object. """ - from dump_things_service.utils import order_dict # noqa PLC0415 -- global import leads to circular imports + from dump_things_service.utils import order_dict with path.open('r') as f: json_object = yaml.load(f, Loader=yaml.SafeLoader) @@ -113,7 +113,7 @@ class _RecordDirStore(StorageBackend): class_name: str, json_object: dict, ): - from dump_things_service.utils import json2yaml # noqa PLC0415 -- global import leads to circular imports + from dump_things_service.utils import json2yaml pid = json_object['pid'] @@ -230,7 +230,7 @@ class _RecordDirStore(StorageBackend): _existing_stores: dict[Path, _RecordDirStore] = {} -def RecordDirStore( # noqa: N802 +def RecordDirStore( root: Path, pid_mapping_function: Callable, suffix: str, diff --git a/dump_things_service/backends/schema_type_layer.py b/dump_things_service/backends/schema_type_layer.py index c487f74..5ee48d1 100644 --- a/dump_things_service/backends/schema_type_layer.py +++ b/dump_things_service/backends/schema_type_layer.py @@ -190,7 +190,7 @@ def _get_schema_type( _existing_layers = {} -def SchemaTypeLayer( # noqa: N802 +def SchemaTypeLayer( backend: StorageBackend, schema: str, ) -> _SchemaTypeLayer: diff --git a/dump_things_service/backends/sqlite.py b/dump_things_service/backends/sqlite.py index 38a3d26..6f01adc 100644 --- a/dump_things_service/backends/sqlite.py +++ b/dump_things_service/backends/sqlite.py @@ -268,7 +268,7 @@ class _SQLiteBackend(StorageBackend): if pattern is None: statement = text( - 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' # noqa S608 -- all variables are controlled + 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' 'from thing ' f'where ({policy_clause}) ' f'and thing.class_name in ({class_list}) ' @@ -276,7 +276,7 @@ class _SQLiteBackend(StorageBackend): ) else: statement = text( - 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' # noqa S608 -- all variables are controlled + 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' 'from thing, json_tree(thing.object) ' f'where ({policy_clause}) ' 'and lower(json_tree.value) like lower(:pattern) ' @@ -381,7 +381,7 @@ class _SQLiteBackend(StorageBackend): _existing_sqlite_backends: dict[Path, _SQLiteBackend] = {} -def SQLiteBackend( # noqa: N802 +def SQLiteBackend( db_path: Path, *, order_by: Iterable[str] | None = None, echo: bool = False ) -> _SQLiteBackend: existing_backend = _existing_sqlite_backends.get(db_path) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 4e2ea51..b821537 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -2,10 +2,9 @@ import json import logging import os import shutil - -import fsspec from pathlib import Path +import fsspec from datalad_core.runners import ( CommandError, call_git_oneline, @@ -40,7 +39,6 @@ from dump_things_service.instance_state import ( ) from dump_things_service.utils import create_store - logger = logging.getLogger('dump_things_service') diff --git a/dump_things_service/commands/check_pids.py b/dump_things_service/commands/check_pids.py index 9c7835b..c5f2467 100644 --- a/dump_things_service/commands/check_pids.py +++ b/dump_things_service/commands/check_pids.py @@ -38,7 +38,7 @@ parser.add_argument( def check_pids_in_stores(stores: Iterable[_ModelStore]) -> int: result = 0 for store in stores: - print('checking', store.get_uri(), file=sys.stderr) # noqa T201 -- cli result output + print('checking', store.get_uri(), file=sys.stderr) for record_info in store.get_all_objects(): pid = record_info.json_object['pid'] try: @@ -95,7 +95,7 @@ def main(): arguments = parser.parse_args() result = check_pids(Path(arguments.store).absolute()) if result > 0: - print(f'found {result} unresolvable pids', file=sys.stderr) # noqa T201 -- cli result output + print(f'found {result} unresolvable pids', file=sys.stderr) return 1 return 0 diff --git a/dump_things_service/commands/create_merged_schema.py b/dump_things_service/commands/create_merged_schema.py index 738dd4d..9ace375 100644 --- a/dump_things_service/commands/create_merged_schema.py +++ b/dump_things_service/commands/create_merged_schema.py @@ -64,7 +64,7 @@ def main(): allow_unicode=True, sort_keys=False, ) - print(text) # noqa T201 -- cli result output + print(text) return 0 diff --git a/dump_things_service/commands/download_config.py b/dump_things_service/commands/download_config.py index 65226c1..1e88c78 100644 --- a/dump_things_service/commands/download_config.py +++ b/dump_things_service/commands/download_config.py @@ -61,7 +61,7 @@ def main(): admin_token = os.environ.get('DTS_ADMIN_TOKEN') if not admin_token: - print( # noqa T201 -- cli result output + print( 'An admin token must be provided in the environment variable `DTS_ADMIN_TOKEN`', file=sys.stderr, flush=True, @@ -75,9 +75,9 @@ def main(): ) if arguments.format == 'json': - print(json.dumps(configuration, indent=2, sort_keys=False)) # noqa T201 -- cli result output + print(json.dumps(configuration, indent=2, sort_keys=False)) elif arguments.format == 'yaml': - print(json2yaml(configuration)) # noqa T201 -- cli result output + print(json2yaml(configuration)) return 0 diff --git a/dump_things_service/commands/gitaudit_report.py b/dump_things_service/commands/gitaudit_report.py index 8cc552d..a117e36 100644 --- a/dump_things_service/commands/gitaudit_report.py +++ b/dump_things_service/commands/gitaudit_report.py @@ -32,7 +32,7 @@ def main(): try: re.compile(arguments.pid) except re.error as e: - print('Error in PID pattern:', e, file=sys.stderr, flush=True) # noqa T201 -- cli result output + print('Error in PID pattern:', e, file=sys.stderr, flush=True) return 1 audit_backend = GitAuditBackend(Path(arguments.audit_store)) @@ -47,7 +47,7 @@ def main(): 'diff': change[2], 'resulting-record': change[3], } - print(json.dumps(report, ensure_ascii=False), flush=True) # noqa T201 -- cli result output + print(json.dumps(report, ensure_ascii=False), flush=True) return 0 diff --git a/dump_things_service/commands/hash_token.py b/dump_things_service/commands/hash_token.py index 1881384..9ced0cb 100644 --- a/dump_things_service/commands/hash_token.py +++ b/dump_things_service/commands/hash_token.py @@ -23,10 +23,10 @@ def main(): token = arguments.token.strip() if any(s.isspace() for s in token): - print('Whitespace are not allowed in token', file=sys.stderr, flush=True) # noqa T201 -- cli result output + print('Whitespace are not allowed in token', file=sys.stderr, flush=True) return 1 - print(hash_token_representation(token)) # noqa T201 -- cli result output + print(hash_token_representation(token)) return 0 diff --git a/dump_things_service/commands/upload_config.py b/dump_things_service/commands/upload_config.py index cdd4abb..6dd16e0 100644 --- a/dump_things_service/commands/upload_config.py +++ b/dump_things_service/commands/upload_config.py @@ -80,7 +80,7 @@ def main(): elif file_type == 'yaml': configuration = yaml.safe_load(config_file) else: - print( # noqa T201 -- cli result output + print( f'Unknown file type {config_file_path} (use `.json` or `.yaml` suffix, or specify the format with --format )', file=sys.stderr, flush=True, @@ -90,7 +90,7 @@ def main(): if arguments.old_format: configuration = convert_config_1_to_config_2(configuration, arguments.store) elif arguments.store: - print( # noqa T201 -- cli result output + print( 'Warning: ignoring `--store` option because `--old-format` ' 'is not provided.', file=sys.stderr, @@ -108,7 +108,7 @@ def main(): if arguments.send_to: admin_token = os.environ.get('DTS_ADMIN_TOKEN') if not admin_token: - print( # noqa T201 -- cli result output + print( 'An admin token must be provided in the environment variable `DTS_ADMIN_TOKEN`', file=sys.stderr, flush=True, @@ -122,15 +122,15 @@ def main(): admin_token, ) except RuntimeError as rte: - print(f'{rte.args[0]}', file=sys.stderr, flush=True) # noqa T201 -- cli result output + print(f'{rte.args[0]}', file=sys.stderr, flush=True) return 2 else: return 0 if file_type == 'json': - print(json.dumps(configuration, indent=2, sort_keys=False)) # noqa T201 -- cli result output + print(json.dumps(configuration, indent=2, sort_keys=False)) elif file_type == 'yaml': - print(json2yaml(configuration)) # noqa T201 -- cli result output + print(json2yaml(configuration)) return 0 diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index 36d4131..bfbf93d 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -343,7 +343,7 @@ async def read_record_with_pid( collection: str, pid: str, api_key: Annotated[str, Depends(api_key_header_scheme)], - format: Format = Format.json, # noqa: A002 + format: Format = Format.json, ): configuration = get_config() instance_state = get_instance_state() @@ -431,7 +431,7 @@ async def read_all_records( collection: str, api_key: Annotated[str, Depends(api_key_header_scheme)], matching: str | None = None, - format: Format = Format.json, # noqa: A002 + format: Format = Format.json, ): return await _read_all_records( collection=collection, @@ -454,7 +454,7 @@ async def read_all_records_paginated( collection: str, api_key: Annotated[str, Depends(api_key_header_scheme)], matching: str | None = None, - format: Format = Format.json, # noqa: A002 + format: Format = Format.json, ) -> Page[dict | str]: result_list = await _read_all_records( collection=collection, @@ -476,7 +476,7 @@ async def read_records_of_type( class_name: str, api_key: Annotated[str, Depends(api_key_header_scheme)], matching: str | None = None, - format: Format = Format.json, # noqa: A002 + format: Format = Format.json, ): return await _read_records_of_type( collection=collection, @@ -501,7 +501,7 @@ async def read_records_of_type_paginated( class_name: str, api_key: Annotated[str, Depends(api_key_header_scheme)], matching: str | None = None, - format: Format = Format.json, # noqa: A002 + format: Format = Format.json, ) -> Page[dict | str]: result_list = await _read_records_of_type( collection=collection, @@ -517,7 +517,7 @@ async def read_records_of_type_paginated( async def _read_all_records( collection: str, matching: str | None = None, - format: Format = Format.json, # noqa: A002 + format: Format = Format.json, api_key: str = Depends(api_key_header_scheme), bound: int | None = None, ) -> LazyList: @@ -585,7 +585,7 @@ async def _read_records_of_type( collection: str, class_name: str, matching: str | None = None, - format: Format = Format.json, # noqa: A002 + format: Format = Format.json, api_key: str = Depends(api_key_header_scheme), bound: int | None = None, ) -> LazyList: diff --git a/dump_things_service/endpoints/v0/collection_endpoints.py b/dump_things_service/endpoints/v0/collection_endpoints.py index 6175995..d5445cc 100644 --- a/dump_things_service/endpoints/v0/collection_endpoints.py +++ b/dump_things_service/endpoints/v0/collection_endpoints.py @@ -30,7 +30,7 @@ from dump_things_service.abstract_config import ( ) from dump_things_service.admin import authenticate_admin from dump_things_service.api_key import api_key_header_scheme -from dump_things_service.exceptions import DumpThingsError, ConfigError +from dump_things_service.exceptions import ConfigError, DumpThingsError from dump_things_service.instance_state import InstanceState, get_instance_state from dump_things_service.manifest import manifest_configuration from dump_things_service.utils import wrap_http_exception diff --git a/dump_things_service/endpoints/v0/curated.py b/dump_things_service/endpoints/v0/curated.py index cc973d3..e343750 100644 --- a/dump_things_service/endpoints/v0/curated.py +++ b/dump_things_service/endpoints/v0/curated.py @@ -36,9 +36,9 @@ from dump_things_service.utils import ( authenticate_token, check_bounds, cleaned_json, + dict_to_base_model, order_dict, wrap_http_exception, - dict_to_base_model, ) if TYPE_CHECKING: diff --git a/dump_things_service/endpoints/v0/incoming.py b/dump_things_service/endpoints/v0/incoming.py index c4ec591..7762450 100644 --- a/dump_things_service/endpoints/v0/incoming.py +++ b/dump_things_service/endpoints/v0/incoming.py @@ -40,10 +40,10 @@ from dump_things_service.utils import ( check_bounds, cleaned_json, create_token_store, + dict_to_base_model, get_on_disk_labels, order_dict, wrap_http_exception, - dict_to_base_model, ) if TYPE_CHECKING: diff --git a/dump_things_service/endpoints/v0/token_endpoints.py b/dump_things_service/endpoints/v0/token_endpoints.py index 0f8852d..f867396 100644 --- a/dump_things_service/endpoints/v0/token_endpoints.py +++ b/dump_things_service/endpoints/v0/token_endpoints.py @@ -57,7 +57,7 @@ class AdminTokenRequest(AdminTokenConfig): def get_token_parts(token: str) -> list[str]: parts = token.split('-', 1) - if len(parts) != 2: # noqa PLR2004 -- explicit check for two parts + if len(parts) != 2: msg = 'Invalid token format' raise ValueError(msg) return parts diff --git a/dump_things_service/instance_state.py b/dump_things_service/instance_state.py index 5140e8c..f18e3b6 100644 --- a/dump_things_service/instance_state.py +++ b/dump_things_service/instance_state.py @@ -115,7 +115,7 @@ def create_instance_state( bootstrap_token: str, fastapi_app: FastAPI, ) -> InstanceState: - global g_instance_state # noqa PLW0603 -- this is cached on the first call + global g_instance_state if g_instance_state: logger.warning('create_instance_state() already called') diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 79ebc24..1b1412b 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -56,7 +56,7 @@ logger = logging.getLogger('dump_things_service') parser = argparse.ArgumentParser() -parser.add_argument('--host', default='0.0.0.0') # noqa: S104 +parser.add_argument('--host', default='0.0.0.0') parser.add_argument('--port', default=8000, type=int) parser.add_argument('--origins', action='append', default=[]) parser.add_argument( @@ -143,7 +143,7 @@ if not arguments.admin_token_hash: ) # Validate the hash token format elif not hash_matcher.match(arguments.admin_token_hash): - print( # noqa T201 -- cli result output + print( 'Hashed admin token is not a 64-digits hex-number', file=sys.stderr, flush=True, @@ -313,7 +313,7 @@ if ( ) and not g_instance_state.bootstrap_token ): - print( # noqa T201 -- cli result output + print( 'The server has an empty configuration and requires a bootstrap ' 'token (use `--admin-token-hash` or the environment variable ' '`DTS_ADMIN_TOKEN` to provide one).', diff --git a/dump_things_service/model.py b/dump_things_service/model.py index b94d3f0..a7f9284 100644 --- a/dump_things_service/model.py +++ b/dump_things_service/model.py @@ -75,7 +75,7 @@ def get_subclasses_2( collection_name: str, class_name: str, ) -> list[str]: - from dump_things_service.instance_state import get_instance_state # noqa PLC0415 -- global import leads to circular imports + from dump_things_service.instance_state import get_instance_state instance_state = get_instance_state() schema_view = instance_state.schema_info[collection_name].schema_view @@ -86,7 +86,7 @@ def compile_module_with_increasing_recursion_limit( pydantic_generator: PydanticGenerator, schema_location: str, ) -> ModuleType: - global current_recursion_limit # noqa PLW0603 -- global state is updated from within the call-tree + global current_recursion_limit module = None module_name = ( diff --git a/dump_things_service/periodic.py b/dump_things_service/periodic.py index b761e6c..2192b7b 100644 --- a/dump_things_service/periodic.py +++ b/dump_things_service/periodic.py @@ -1,6 +1,5 @@ import asyncio -from typing import Callable - +from collections.abc import Callable g_task_list = [] diff --git a/dump_things_service/store/model_store.py b/dump_things_service/store/model_store.py index f3299f7..4419c4c 100644 --- a/dump_things_service/store/model_store.py +++ b/dump_things_service/store/model_store.py @@ -266,7 +266,7 @@ class _ModelStore: _existing_model_stores = {} -def ModelStore( # noqa: N802 +def ModelStore( schema: str, backend: StorageBackend, tags: dict[str, str], diff --git a/dump_things_service/tests/fixtures.py b/dump_things_service/tests/fixtures.py index d0b2998..300cb61 100644 --- a/dump_things_service/tests/fixtures.py +++ b/dump_things_service/tests/fixtures.py @@ -164,11 +164,11 @@ g_default_tokens = [ ) for i in range(1, 3) }, - **{ + 'collection/with/slash/0': TokenCollectionConfig( mode=TokenModes.READ_CURATED, ) - }, + , }, ), TokenRequest( @@ -434,7 +434,7 @@ def fastapi_app_simple(dump_stores_simple): '--ignore-default-config-file', str(tmp_path), ] - from dump_things_service.main import app # noqa PLC0415 -- main contains one-time-code that is not guarded + from dump_things_service.main import app sys.argv = old_sys_argv return app, tmp_path, audit_tmp_path, admin_token diff --git a/dump_things_service/tests/test_basic.py b/dump_things_service/tests/test_basic.py index 99fcda1..9a0aa41 100644 --- a/dump_things_service/tests/test_basic.py +++ b/dump_things_service/tests/test_basic.py @@ -1,4 +1,3 @@ -from .common import get_std_collection_names from .. import ( HTTP_200_OK, HTTP_400_BAD_REQUEST, @@ -9,6 +8,7 @@ from .. import ( __version__, ) from . import schema_file +from .common import get_std_collection_names from .create_store import ( given_name, pid, diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index b1a43f0..9bd9fdc 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -21,11 +21,11 @@ from dump_things_service.abstract_config import ( TokenModes, dump_things_config_iri, dump_things_private_collection_name, + g_recoverable_error, get_config_backends, get_conflicting_paths, read_config, ) -from dump_things_service.abstract_config import g_recoverable_error from dump_things_service.collection import check_recoverable_errors from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest from dump_things_service.endpoints.v0.token_endpoints import TokenRequest diff --git a/dump_things_service/tests/test_incoming.py b/dump_things_service/tests/test_incoming.py index d9601ff..8063439 100644 --- a/dump_things_service/tests/test_incoming.py +++ b/dump_things_service/tests/test_incoming.py @@ -32,7 +32,7 @@ zones_filled = False def fill_zones(test_client): - global zones_filled # noqa PLW0603 -- records global state from within test harness calls + global zones_filled if zones_filled: return diff --git a/dump_things_service/tests/test_roundtrip.py b/dump_things_service/tests/test_roundtrip.py index 791b137..6b6c774 100644 --- a/dump_things_service/tests/test_roundtrip.py +++ b/dump_things_service/tests/test_roundtrip.py @@ -1,5 +1,5 @@ import freezegun -import pytest # noqa: F401 +import pytest from .. import HTTP_200_OK from ..utils import cleaned_json diff --git a/dump_things_service/tests/test_roundtrip_flatsocial.py b/dump_things_service/tests/test_roundtrip_flatsocial.py index ca6f996..8686ef1 100644 --- a/dump_things_service/tests/test_roundtrip_flatsocial.py +++ b/dump_things_service/tests/test_roundtrip_flatsocial.py @@ -1,5 +1,5 @@ import freezegun -import pytest # noqa: F401 +import pytest from .. import HTTP_200_OK from ..utils import cleaned_json diff --git a/dump_things_service/tests/test_web_interface.py b/dump_things_service/tests/test_web_interface.py index 74464e2..885f73f 100644 --- a/dump_things_service/tests/test_web_interface.py +++ b/dump_things_service/tests/test_web_interface.py @@ -14,7 +14,7 @@ pids = ('', '--------', '&&&&&', 'abc', 'abc&', 'abc&format=ttl') @pytest.mark.parametrize( - 'collection_name,class_name,query,format_name', # noqa: PT006 + 'collection_name,class_name,query,format_name', tuple(product(*(collection_names, class_names, queries, format_names))), ) def test_web_interface_post_errors( @@ -35,7 +35,7 @@ def test_web_interface_post_errors( @pytest.mark.parametrize( - 'collection_name,class_name,query,format_name', # noqa: PT006 + 'collection_name,class_name,query,format_name', tuple(product(*(collection_names, class_names, queries, format_names))), ) def test_web_interface_get_class_errors( @@ -60,7 +60,7 @@ def test_web_interface_get_class_errors( @pytest.mark.parametrize( - 'collection_name,pid,query,format_name', # noqa: PT006 + 'collection_name,pid,query,format_name', tuple(product(*(collection_names, pids, queries, format_names))), ) def test_web_interface_get_pid_errors( diff --git a/dump_things_service/utils.py b/dump_things_service/utils.py index 02c9f80..3cecb9e 100644 --- a/dump_things_service/utils.py +++ b/dump_things_service/utils.py @@ -33,13 +33,13 @@ from pydantic import ( from rdflib import Graph from dump_things_service import ( - Format, HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN, HTTP_413_CONTENT_TOO_LARGE, HTTP_422_UNPROCESSABLE_CONTENT, HTTP_503_SERVICE_UNAVAILABLE, + Format, ) from dump_things_service.abstract_config import ( Configuration, @@ -366,10 +366,10 @@ def create_token_store( collection_name: str, store_dir: Path, ) -> _ModelStore: - from dump_things_service.abstract_config import get_backend_and_extension # noqa PLC0415 -- global import leads to circular imports - from dump_things_service.backends.schema_type_layer import SchemaTypeLayer # noqa PLC0415 -- global import leads to circular imports - from dump_things_service.exceptions import ConfigError # noqa PLC0415 -- global import leads to circular imports - from dump_things_service.store.model_store import ModelStore # noqa PLC0415 -- global import leads to circular imports + from dump_things_service.abstract_config import get_backend_and_extension + from dump_things_service.backends.schema_type_layer import SchemaTypeLayer + from dump_things_service.exceptions import ConfigError + from dump_things_service.store.model_store import ModelStore # One early requirement for the service was to be able to specify # arbitrary directories for curated stores and incoming stores. This @@ -440,8 +440,8 @@ def create_record_dir_token_store_backend( mapping_function: str, suffix: str, ) -> _RecordDirStore: - from dump_things_service.backends.record_dir import RecordDirStore # noqa PLC0415 -- global import leads to circular imports - from dump_things_service.instance_state import record_dir_config_file_name # noqa PLC0415 -- global import leads to circular imports + from dump_things_service.backends.record_dir import RecordDirStore + from dump_things_service.instance_state import record_dir_config_file_name # Write the configuration to the store, if it does not yet exist. if not (store_dir / record_dir_config_file_name).exists(): @@ -466,7 +466,7 @@ def write_record_dir_config( mapping_function: str, schema: str, ): - from dump_things_service.instance_state import record_dir_config_file_name # noqa PLC0415 -- global import leads to circular imports + from dump_things_service.instance_state import record_dir_config_file_name record_dir_config_file_path = path / record_dir_config_file_name if not record_dir_config_file_path.exists(): @@ -485,8 +485,8 @@ def create_sqlite_token_store_backend( store_dir: Path, order_by: list[str], ) -> _SQLiteBackend: - from dump_things_service.backends.sqlite import SQLiteBackend # noqa PLC0415 -- global import leads to circular imports - from dump_things_service.backends.sqlite import ( # noqa PLC0415 -- global import leads to circular imports + from dump_things_service.backends.sqlite import SQLiteBackend + from dump_things_service.backends.sqlite import ( record_file_name as sqlite_record_file_name, ) -- 2.54.1 From c8907bb529f76c41fa3349e35245b24cbb744b89 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 10 Nov 2026 17:09:22 +0100 Subject: [PATCH 03/15] rf: remove unused code --- dump_things_service/collection.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index b821537..acb20d1 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -395,15 +395,6 @@ def reload_policy( ].policy_annotation_tag = policy_annotation_tag -def refresh_collection_state( - a: int, -) -> tuple[tuple, dict] | None: - print('refresh_collection_state called with argument:', a) - if a % 100 >= 10: - return None - return (), dict(a=a + 1) - - def check_recoverable_errors( abstract_configuration: Configuration, instance_state: InstanceState, -- 2.54.1 From 6fb2c915f53f4daf4244f61930c857f581d7c8fb Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 10 Nov 2026 17:10:11 +0100 Subject: [PATCH 04/15] rf: re-order import statements --- dump_things_service/collection.py | 2 +- dump_things_service/patches/compile.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index acb20d1..4cb2c42 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -408,6 +408,6 @@ def check_recoverable_errors( instance_state=instance_state, configuration=abstract_configuration, ) - except Exception as e: + except Exception as e: # noqa: BLE001 -- we don't know which errors might occur during recovery, so we catch all exceptions logger.info(f'Error recovery failed: {e}') return (abstract_configuration, instance_state), {} diff --git a/dump_things_service/patches/compile.py b/dump_things_service/patches/compile.py index 4cbf36b..8fc8d40 100644 --- a/dump_things_service/patches/compile.py +++ b/dump_things_service/patches/compile.py @@ -4,8 +4,8 @@ import logging import os import sys from importlib import import_module -from types import ModuleType from logging import warning +from types import ModuleType from linkml_runtime.utils.compile_python import file_text -- 2.54.1 From 960c4288249d00491140eb8ff82170784c8d2a7f Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 10 Nov 2026 17:11:58 +0100 Subject: [PATCH 05/15] rf: remove excess empty lines --- dump_things_service/patches/enumerations.py | 1 - dump_things_service/patches/ifabsent_processing.py | 1 - dump_things_service/patches/pythongen_gen_references.py | 1 - 3 files changed, 3 deletions(-) diff --git a/dump_things_service/patches/enumerations.py b/dump_things_service/patches/enumerations.py index b802460..64da399 100644 --- a/dump_things_service/patches/enumerations.py +++ b/dump_things_service/patches/enumerations.py @@ -8,7 +8,6 @@ from importlib import import_module from jsonasobj2 import JsonObj - logger = logging.getLogger('dump_things_service') diff --git a/dump_things_service/patches/ifabsent_processing.py b/dump_things_service/patches/ifabsent_processing.py index d87c175..aeb3f55 100644 --- a/dump_things_service/patches/ifabsent_processing.py +++ b/dump_things_service/patches/ifabsent_processing.py @@ -6,7 +6,6 @@ generated in the pydantic code generator. import logging from importlib import import_module - logger = logging.getLogger('dump_things_service') diff --git a/dump_things_service/patches/pythongen_gen_references.py b/dump_things_service/patches/pythongen_gen_references.py index a47b3ab..b840f66 100644 --- a/dump_things_service/patches/pythongen_gen_references.py +++ b/dump_things_service/patches/pythongen_gen_references.py @@ -5,7 +5,6 @@ from importlib import import_module from linkml_runtime.utils.formatutils import camelcase - logger = logging.getLogger('dump_things_service') -- 2.54.1 From 755fd6dc5fdc061dc43b46cbf326d875b42fcc19 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 10 Nov 2026 17:16:50 +0100 Subject: [PATCH 06/15] rf: use modern type annotations This commit replaces `Union[X, Y]` with `X | Y`. --- dump_things_service/patches/rdflib_loader.py | 6 +++--- dump_things_service/patches/yamlutils.py | 5 ++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/dump_things_service/patches/rdflib_loader.py b/dump_things_service/patches/rdflib_loader.py index f43f228..f219742 100644 --- a/dump_things_service/patches/rdflib_loader.py +++ b/dump_things_service/patches/rdflib_loader.py @@ -55,12 +55,12 @@ def from_rdf_graph( self, graph: Graph, schemaview: SchemaView, - target_class: type[Union[BaseModel, YAMLRoot]], - prefix_map: Union[dict[str, str], Converter, None] = None, + target_class: type[BaseModel | YAMLRoot], + prefix_map: dict[str, str] | Converter | None = None, cast_literals: bool = True, allow_unprocessed_triples: bool = True, ignore_unmapped_predicates: bool = False, -) -> list[Union[BaseModel, YAMLRoot]]: +) -> list[BaseModel | YAMLRoot]: """ Loads objects from graph into lists of the python target_class structure, recursively walking RDF graph from instances of target_class. diff --git a/dump_things_service/patches/yamlutils.py b/dump_things_service/patches/yamlutils.py index 2647bcf..b107dd0 100644 --- a/dump_things_service/patches/yamlutils.py +++ b/dump_things_service/patches/yamlutils.py @@ -9,7 +9,6 @@ from copy import copy from importlib import import_module from typing import ( Any, - Optional, Union, ) @@ -47,7 +46,7 @@ def _normalize_inlined(self, slot_name: str, slot_type: type, key_name: str, key @param keyed: True means each identifier must be unique @param is_list: True means inlined as list """ - raw_slot: Union[list, dict, JsonObj] = self[slot_name] + raw_slot: list | dict | JsonObj = self[slot_name] if raw_slot is None: raw_slot = [] elif not isinstance(raw_slot, (dict, list, JsonObj)): @@ -75,7 +74,7 @@ def _normalize_inlined(self, slot_name: str, slot_type: type, key_name: str, key loc_str = '' return loc_str + str(s) - def form_1(entries: dict[Any, Optional[Union[dict, JsonObj]]]) -> None: + def form_1(entries: dict[Any, dict | JsonObj | None]) -> None: """ A dictionary of key:dict entries where key is the identifier and dict is an instance of slot_type """ for key, raw_obj in items(entries): if raw_obj is None: -- 2.54.1 From 2ede45bd488a88dba0e1a87176ac3b5d6c3266e9 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 10 Nov 2026 17:22:18 +0100 Subject: [PATCH 07/15] rf: ignore unused import errors in patch loader --- dump_things_service/patches/enabled.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dump_things_service/patches/enabled.py b/dump_things_service/patches/enabled.py index e73f4a6..ca7fb3c 100644 --- a/dump_things_service/patches/enabled.py +++ b/dump_things_service/patches/enabled.py @@ -4,4 +4,4 @@ import dump_things_service.patches.enumerations import dump_things_service.patches.ifabsent_processing import dump_things_service.patches.pythongen_gen_references import dump_things_service.patches.rdflib_loader -import dump_things_service.patches.yamlutils +import dump_things_service.patches.yamlutils # noqa F401 -- apply patches -- 2.54.1 From aba91c94b6ec396fa4c137294d31a286c3bf4f9f Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 11 Nov 2026 09:52:54 +0100 Subject: [PATCH 08/15] rf: remove unused variables, allow `Exception`-catching This commit removes unused variables and allows the clause `except Exception` when trying to recover a configuration from a recoverable error. The latter is necessary because recovery includes remote communication which can generate a multitude of errors. --- dump_things_service/endpoints/v0/base_endpoints.py | 2 +- dump_things_service/manifest.py | 2 +- dump_things_service/tests/test_policies.py | 2 +- dump_things_service/utils.py | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index bfbf93d..15a081c 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -684,7 +684,7 @@ async def delete_record( instance_state = get_instance_state() check_collection(configuration, collection) - final_permissions, token_store, user_info = await process_token( + final_permissions, token_store, _ = await process_token( configuration, instance_state, api_key, collection ) diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index 169052a..267e185 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -139,7 +139,7 @@ def manifest_configuration( ) g_recoverable_error.add(collection_name) - except Exception as e: + except Exception as e: # noqa: BLE001 -- we don't know which errors might occur during collection creation, so we catch all exceptions # We catch all remaining errors here and log them. The collection will # be excluded from the list. logger.error( diff --git a/dump_things_service/tests/test_policies.py b/dump_things_service/tests/test_policies.py index 49bdce1..95596a2 100644 --- a/dump_things_service/tests/test_policies.py +++ b/dump_things_service/tests/test_policies.py @@ -83,7 +83,7 @@ def test_policy_functionality(fastapi_client_simple): # non-existing auth sources in the policy mapping. @pytest.mark.xfail def test_policy_mapping_errors(fastapi_client_simple): - test_client, store_path, admin_token = fastapi_client_simple + test_client, _, admin_token = fastapi_client_simple collection_request = { 'name': 'collection_8', diff --git a/dump_things_service/utils.py b/dump_things_service/utils.py index 3cecb9e..4e62fda 100644 --- a/dump_things_service/utils.py +++ b/dump_things_service/utils.py @@ -568,7 +568,7 @@ async def simple_process_token( ) -> TokenPermission: if api_key is None: collection_config = get_collection_config_by_name(abstract_config, collection) - token_store, token_permissions, user_info = get_token_store( + _, token_permissions, _ = get_token_store( abstract_config, instance_state, collection, @@ -576,7 +576,7 @@ async def simple_process_token( is_token_name=True, ) else: - token_store, token_permissions, user_info = get_token_store( + _, token_permissions, _ = get_token_store( abstract_config, instance_state, collection, -- 2.54.1 From 3f32e0165978cbfeb488f7dce1f65d2e3633263d Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 11 Nov 2026 10:09:38 +0100 Subject: [PATCH 09/15] rf: ensure trailing commas --- dump_things_service/abstract_config.py | 12 ++++----- dump_things_service/audit/gitaudit.py | 10 +++---- dump_things_service/backends/__init__.py | 2 +- dump_things_service/backends/record_dir.py | 4 +-- .../backends/record_dir_index.py | 4 +-- .../backends/schema_type_layer.py | 6 ++--- dump_things_service/backends/sqlite.py | 14 +++++----- .../backends/tests/test_record_dir.py | 2 +- dump_things_service/collection.py | 2 +- .../commands/create_merged_schema.py | 2 +- .../commands/gitaudit_rebuild_index.py | 2 +- dump_things_service/commands/rebuild_index.py | 4 +-- dump_things_service/commands/upload_config.py | 2 +- dump_things_service/converter.py | 2 +- .../endpoints/v0/base_endpoints.py | 26 +++++++++---------- .../endpoints/v0/collection_endpoints.py | 2 +- dump_things_service/endpoints/v0/curated.py | 2 +- dump_things_service/endpoints/v0/incoming.py | 4 +-- .../endpoints/v0/token_endpoints.py | 2 +- dump_things_service/endpoints/v0/validate.py | 4 +-- dump_things_service/instance_state.py | 4 +-- dump_things_service/manifest.py | 2 +- dump_things_service/model.py | 2 +- dump_things_service/store/model_store.py | 4 +-- dump_things_service/tests/create_store.py | 4 +-- dump_things_service/tests/fixtures.py | 20 +++++++------- dump_things_service/tests/test_auth.py | 8 +++--- dump_things_service/tests/test_basic.py | 4 +-- .../tests/test_collection_administration.py | 6 ++--- dump_things_service/tests/test_config.py | 6 ++--- .../tests/test_extract_inline.py | 4 +-- .../tests/test_ifabsent_patch.py | 4 +-- dump_things_service/tests/test_paths.py | 4 +-- dump_things_service/tests/test_policies.py | 4 +-- .../tests/test_roundtrip_flatsocial.py | 4 +-- .../tests/test_token_endpoints.py | 2 +- dump_things_service/tests/test_utils.py | 4 +-- dump_things_service/utils.py | 14 +++++----- 38 files changed, 104 insertions(+), 104 deletions(-) diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 6a3bb3d..5e9700a 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -122,7 +122,7 @@ class CollectionConfig(BaseModel): schema_location: str = Field(alias='schema') incoming: PurePosixPath | None = None backend: RecordDirBackendConfig | SQLiteBackendConfig = RecordDirBackendConfig( - type='record_dir+stl' + type='record_dir+stl', ) auth_sources: list[ForgejoAuthSpec | ConfigAuthSpec] = [ConfigAuthSpec()] audit_backends: list[GitAuditBackendConfig] = [] @@ -237,7 +237,7 @@ def get_config_backends( if config_backend is None: config_backend = RecordDirStore( - config_path, mapping_functions[MappingMethod.digest_md5], 'yaml' + config_path, mapping_functions[MappingMethod.digest_md5], 'yaml', ) audit_path = store_path / config_audit_path @@ -368,7 +368,7 @@ def check_label( """Check that a label exists in a collection configuration or on disk""" if label not in get_config_labels( - abstract_config, collection + abstract_config, collection, ) and label not in get_on_disk_labels(store_path, abstract_config, collection): if create_if_missing: logger.debug( @@ -557,7 +557,7 @@ def get_conflicting_paths( # is added. if collection_config.incoming: containing_path, _ = _get_containing_path( - collection_config.incoming, collection_config.curated + collection_config.incoming, collection_config.curated, ) else: containing_path = None @@ -587,7 +587,7 @@ def get_conflicting_paths( other_path, other_collection, usage_info[other_path], - ) + ), ) else: result.append( @@ -598,7 +598,7 @@ def get_conflicting_paths( current_path, current_collection, usage_info[current_path], - ) + ), ) return result diff --git a/dump_things_service/audit/gitaudit.py b/dump_things_service/audit/gitaudit.py index c2a04da..9124415 100644 --- a/dump_things_service/audit/gitaudit.py +++ b/dump_things_service/audit/gitaudit.py @@ -154,7 +154,7 @@ class GitAuditBackend(AuditBackend): filter( lambda line: not line.startswith('+++') and line.startswith('+'), log_diff_lines, - ) + ), )[1:] log_entry = json.loads(log_line) @@ -185,7 +185,7 @@ class GitAuditBackend(AuditBackend): log_entry['author_id'], yaml_diff, yaml_content, - ) + ), ) changes.sort() @@ -208,7 +208,7 @@ class GitAuditBackend(AuditBackend): filter( lambda record_id: matcher.fullmatch(record_id) is not None, self.index, - ) + ), ) return { record_id: self._locked_get_audit_log(record_id) @@ -327,7 +327,7 @@ class GitAuditBackend(AuditBackend): self.repo = Repo(self.path) call_git(['config', 'user.name', 'dump-things-service'], cwd=self.path) call_git( - ['config', 'user.email', 'dump-things-service@localhost'], cwd=self.path + ['config', 'user.email', 'dump-things-service@localhost'], cwd=self.path, ) apply_changeset( self.repo, @@ -372,6 +372,6 @@ class GitAuditBackend(AuditBackend): ['show', object_hash], cwd=self.path, capture_output=True, - ).decode() + ).decode(), ) f.write(record['pid'] + '\n') diff --git a/dump_things_service/backends/__init__.py b/dump_things_service/backends/__init__.py index bbb1ecb..dc4a23a 100644 --- a/dump_things_service/backends/__init__.py +++ b/dump_things_service/backends/__init__.py @@ -70,7 +70,7 @@ class BackendResultList(LazyList): :return: A JSON object. """ return self.generate_result( - index, info.iri, info.class_name, info.sort_key, info.private + index, info.iri, info.class_name, info.sort_key, info.private, ) def unique_identifier(self, info: ResultListInfo) -> Any: diff --git a/dump_things_service/backends/record_dir.py b/dump_things_service/backends/record_dir.py index f5c16c3..5bdd2bd 100644 --- a/dump_things_service/backends/record_dir.py +++ b/dump_things_service/backends/record_dir.py @@ -184,7 +184,7 @@ class _RecordDirStore(StorageBackend): for index_entry in self.index.get_info_for_class(class_name) ), key=lambda result_list_info: result_list_info.sort_key, - ) + ), ) def get_all_records( @@ -206,7 +206,7 @@ class _RecordDirStore(StorageBackend): for index_entry in self.index.get_info_for_all_classes() ), key=lambda result_list_info: result_list_info.sort_key, - ) + ), ) def remove_record( diff --git a/dump_things_service/backends/record_dir_index.py b/dump_things_service/backends/record_dir_index.py index 723ee72..4f9ed6a 100644 --- a/dump_things_service/backends/record_dir_index.py +++ b/dump_things_service/backends/record_dir_index.py @@ -128,7 +128,7 @@ class RecordDirIndex: class_name=class_name, path=path, sort_key=sort_key, - ) + ), ) def get_info_for_iri( @@ -216,7 +216,7 @@ class RecordDirIndex: path=str(path), class_name=class_name, sort_key=sort_key, - ) + ), ) except ValueError as e: lgr.error('Error during index creation: %s', e) diff --git a/dump_things_service/backends/schema_type_layer.py b/dump_things_service/backends/schema_type_layer.py index 5ee48d1..b0b745b 100644 --- a/dump_things_service/backends/schema_type_layer.py +++ b/dump_things_service/backends/schema_type_layer.py @@ -60,7 +60,7 @@ class SchemaTypeLayerResultList(BackendResultList): private: Any, ) -> RecordInfo: origin_element = self.origin_list.generate_result( - index, iri, class_name, sort_key, private + index, iri, class_name, sort_key, private, ) if 'schema_type' not in origin_element.json_object: origin_element.json_object = order_dict( @@ -70,7 +70,7 @@ class SchemaTypeLayerResultList(BackendResultList): origin_element.class_name, self.schema_model, ), - } + }, ) return origin_element @@ -134,7 +134,7 @@ class _SchemaTypeLayer(StorageBackend): origin_result.class_name, self.schema_model, ), - } + }, ) return origin_result diff --git a/dump_things_service/backends/sqlite.py b/dump_things_service/backends/sqlite.py index 6f01adc..7ce4a76 100644 --- a/dump_things_service/backends/sqlite.py +++ b/dump_things_service/backends/sqlite.py @@ -221,7 +221,7 @@ class _SQLiteBackend(StorageBackend): class_name=class_name, object=json_object, sort_key=sort_key, - ) + ), ) def get_record_by_iri( @@ -236,7 +236,7 @@ class _SQLiteBackend(StorageBackend): thing = session.scalar(statement) if thing: thing_policy = thing.object.get('annotations', {}).get( - policy_annotation_tag, default_policy + policy_annotation_tag, default_policy, ) if ( thing_policy and thing_policy in active_policies @@ -272,7 +272,7 @@ class _SQLiteBackend(StorageBackend): 'from thing ' f'where ({policy_clause}) ' f'and thing.class_name in ({class_list}) ' - 'ORDER BY thing.sort_key' + 'ORDER BY thing.sort_key', ) else: statement = text( @@ -281,7 +281,7 @@ class _SQLiteBackend(StorageBackend): f'where ({policy_clause}) ' 'and lower(json_tree.value) like lower(:pattern) ' f'and thing.class_name in ({class_list}) ' - "and json_tree.type = 'text' ORDER BY thing.sort_key" + "and json_tree.type = 'text' ORDER BY thing.sort_key", ) with self.engine.connect() as connection: @@ -315,7 +315,7 @@ class _SQLiteBackend(StorageBackend): 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' 'from thing ' f'where {policy_clause} ' - 'ORDER BY thing.sort_key' + 'ORDER BY thing.sort_key', ) else: statement = text( @@ -324,7 +324,7 @@ class _SQLiteBackend(StorageBackend): 'where lower(json_tree.value) like lower(:pattern) ' "and json_tree.type = 'text' " f'and ({policy_clause}) ' - 'ORDER BY thing.sort_key' + 'ORDER BY thing.sort_key', ) with self.engine.connect() as connection: @@ -382,7 +382,7 @@ _existing_sqlite_backends: dict[Path, _SQLiteBackend] = {} def SQLiteBackend( - db_path: Path, *, order_by: Iterable[str] | None = None, echo: bool = False + db_path: Path, *, order_by: Iterable[str] | None = None, echo: bool = False, ) -> _SQLiteBackend: existing_backend = _existing_sqlite_backends.get(db_path) if not existing_backend: diff --git a/dump_things_service/backends/tests/test_record_dir.py b/dump_things_service/backends/tests/test_record_dir.py index 7d4d692..c4cdfba 100644 --- a/dump_things_service/backends/tests/test_record_dir.py +++ b/dump_things_service/backends/tests/test_record_dir.py @@ -20,7 +20,7 @@ def test_add_and_delete_record(tmp_path): record_dir_store.build_index(str(schema_path)) record_dir_store.add_record( - iri=iri, class_name='Object', json_object={'pid': 'some-pid'} + iri=iri, class_name='Object', json_object={'pid': 'some-pid'}, ) record = record_dir_store.get_record_by_iri(iri=iri) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 4cb2c42..84322e3 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -196,7 +196,7 @@ def create_collection( GitAuditBackend( path=Path(instance_state.store_path / audit_backend_config.path), auto_flush_timeout=audit_backend_config.auto_flush_timeout, - ) + ), ) diff --git a/dump_things_service/commands/create_merged_schema.py b/dump_things_service/commands/create_merged_schema.py index 9ace375..eab7543 100644 --- a/dump_things_service/commands/create_merged_schema.py +++ b/dump_things_service/commands/create_merged_schema.py @@ -14,7 +14,7 @@ parser.add_argument('schema', help='File containing a schema definition') def update_uris_for_elements( - all_elements: dict, attribute_name: str, prefix_index: dict + all_elements: dict, attribute_name: str, prefix_index: dict, ): for name, info in all_elements.items(): uri = getattr(info, attribute_name) diff --git a/dump_things_service/commands/gitaudit_rebuild_index.py b/dump_things_service/commands/gitaudit_rebuild_index.py index e33cdad..e69b290 100644 --- a/dump_things_service/commands/gitaudit_rebuild_index.py +++ b/dump_things_service/commands/gitaudit_rebuild_index.py @@ -11,7 +11,7 @@ parser = ArgumentParser( description='This command rebuilds the index of a `gitaudit`-database.', ) parser.add_argument( - 'audit_store', help='The directory in which the `gitaudit`-database is located.' + 'audit_store', help='The directory in which the `gitaudit`-database is located.', ) diff --git a/dump_things_service/commands/rebuild_index.py b/dump_things_service/commands/rebuild_index.py index 09846e2..261a061 100644 --- a/dump_things_service/commands/rebuild_index.py +++ b/dump_things_service/commands/rebuild_index.py @@ -60,7 +60,7 @@ def process_config(arguments) -> tuple[Path, str, str]: Path(arguments.config) if arguments.config else store / config_file_name ) config_object = RecordDirConfigFileContent( - **yaml.load(config_path.read_text(), Loader=yaml.SafeLoader) + **yaml.load(config_path.read_text(), Loader=yaml.SafeLoader), ) return ( store, @@ -70,7 +70,7 @@ def process_config(arguments) -> tuple[Path, str, str]: def rebuild_index( - store: Path, schema: str, suffix: str, order_by: list[str] | None = None + store: Path, schema: str, suffix: str, order_by: list[str] | None = None, ): index = RecordDirIndex( store_dir=store.absolute(), diff --git a/dump_things_service/commands/upload_config.py b/dump_things_service/commands/upload_config.py index 6dd16e0..de255ba 100644 --- a/dump_things_service/commands/upload_config.py +++ b/dump_things_service/commands/upload_config.py @@ -176,7 +176,7 @@ def convert_config_1_to_config_2( msg = '--store has to be provided to convert collection with record_dir-backends' raise ValueError(msg) record_dir_config = get_record_dir_config( - store_path / collection_config['curated'] + store_path / collection_config['curated'], ) collection_config['schema'] = record_dir_config.schema_location backend = { diff --git a/dump_things_service/converter.py b/dump_things_service/converter.py index c39686a..91ee0a5 100644 --- a/dump_things_service/converter.py +++ b/dump_things_service/converter.py @@ -276,5 +276,5 @@ def _do_convert_format( dumper = get_dumper(output_format.value) return dumper.dumps( - data_obj, **({'schemaview': schema_view} if output_format == Format.ttl else {}) + data_obj, **({'schemaview': schema_view} if output_format == Format.ttl else {}), ) diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index 15a081c..f21d928 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -151,7 +151,7 @@ async def reload_configured_policy( check_collection(configuration, collection) final_permissions = await simple_process_token( - configuration, instance_state, api_key, collection + configuration, instance_state, api_key, collection, ) if not final_permissions.curated_write: @@ -231,7 +231,7 @@ async def maintenance( 'application/json': {'schema': {'type': 'object'}}, 'text/turtle': {'schema': {'type': 'string'}}, }, - } + }, }, ) async def store_record( @@ -327,7 +327,7 @@ async def store_record( class_name, ) for class_name, record in stored_records - ] + ], ), media_type='text/turtle', ) @@ -351,11 +351,11 @@ async def read_record_with_pid( check_collection(configuration, collection) final_permissions, token_store, user_info = await process_token( - configuration, instance_state, api_key, collection + configuration, instance_state, api_key, collection, ) policy_annotation_tag, default_policy, policies = _get_policy_information( - instance_state, collection, user_info + instance_state, collection, user_info, ) class_name, json_object = None, None @@ -412,8 +412,8 @@ def _get_policy_information( policy_mapping.authorized_by for policy_mapping in policy_mapping if (policy_mapping.auth_source, policy_mapping.user_id) == user_info - ] - ) + ], + ), ) return ( collection_state.policy_annotation_tag, @@ -532,11 +532,11 @@ async def _read_all_records( check_collection(configuration, collection) final_permissions, token_store, user_info = await process_token( - configuration, instance_state, api_key, collection + configuration, instance_state, api_key, collection, ) policy_annotation_tag, default_policy, policies = _get_policy_information( - instance_state, collection, user_info + instance_state, collection, user_info, ) result_list = PriorityList() @@ -608,11 +608,11 @@ async def _read_records_of_type( ) final_permissions, token_store, user_info = await process_token( - configuration, instance_state, api_key, collection + configuration, instance_state, api_key, collection, ) policy_annotation_tag, default_policy, policies = _get_policy_information( - instance_state, collection, user_info + instance_state, collection, user_info, ) result_list = PriorityList() @@ -627,7 +627,7 @@ async def _read_records_of_type( ) if bound: check_bounds( - len(token_store_list), bound, collection, f'/records/p/{class_name}' + len(token_store_list), bound, collection, f'/records/p/{class_name}', ) result_list.add_list(token_store_list) @@ -685,7 +685,7 @@ async def delete_record( check_collection(configuration, collection) final_permissions, token_store, _ = await process_token( - configuration, instance_state, api_key, collection + configuration, instance_state, api_key, collection, ) if not final_permissions.incoming_write: diff --git a/dump_things_service/endpoints/v0/collection_endpoints.py b/dump_things_service/endpoints/v0/collection_endpoints.py index d5445cc..61debe8 100644 --- a/dump_things_service/endpoints/v0/collection_endpoints.py +++ b/dump_things_service/endpoints/v0/collection_endpoints.py @@ -182,7 +182,7 @@ async def get_collections( **{ 'name': collection_name, **collection_info.model_dump(mode='json', by_alias=True), - } + }, ) for collection_name, collection_info in abstract_config.collections.items() ] diff --git a/dump_things_service/endpoints/v0/curated.py b/dump_things_service/endpoints/v0/curated.py index e343750..596e2f7 100644 --- a/dump_things_service/endpoints/v0/curated.py +++ b/dump_things_service/endpoints/v0/curated.py @@ -312,7 +312,7 @@ def _get_store_and_backend( 'application/json': {'schema': {'type': 'object'}}, 'text/turtle': {'schema': {'type': 'string'}}, }, - } + }, }, ) def store_curated_record( diff --git a/dump_things_service/endpoints/v0/incoming.py b/dump_things_service/endpoints/v0/incoming.py index 7762450..20d8e38 100644 --- a/dump_things_service/endpoints/v0/incoming.py +++ b/dump_things_service/endpoints/v0/incoming.py @@ -73,7 +73,7 @@ async def incoming_read_labels( instance_state = get_instance_state() configured_labels = get_config_labels(get_config(), collection) on_disk_labels = get_on_disk_labels( - instance_state.store_path, get_config(), collection + instance_state.store_path, get_config(), collection, ) return sorted(configured_labels.union(on_disk_labels)) @@ -370,7 +370,7 @@ async def authorize_zones( 'application/json': {'schema': {'type': 'object'}}, 'text/turtle': {'schema': {'type': 'string'}}, }, - } + }, }, ) async def store_incoming_record( diff --git a/dump_things_service/endpoints/v0/token_endpoints.py b/dump_things_service/endpoints/v0/token_endpoints.py index f867396..0373e55 100644 --- a/dump_things_service/endpoints/v0/token_endpoints.py +++ b/dump_things_service/endpoints/v0/token_endpoints.py @@ -388,7 +388,7 @@ async def get_admin_token( { 'name': '__bootstrap__', 'representation': instance_state.bootstrap_token, - } + }, ] ) diff --git a/dump_things_service/endpoints/v0/validate.py b/dump_things_service/endpoints/v0/validate.py index 0740204..71a77e3 100644 --- a/dump_things_service/endpoints/v0/validate.py +++ b/dump_things_service/endpoints/v0/validate.py @@ -50,7 +50,7 @@ router = APIRouter() 'application/json': {'schema': {'type': 'object'}}, 'text/turtle': {'schema': {'type': 'string'}}, }, - } + }, }, ) def validate_record( @@ -104,7 +104,7 @@ def validate_record( ).convert(body, class_name) model = get_model_for_schema( - abstract_config.collections[collection].schema_location + abstract_config.collections[collection].schema_location, )[0] with wrap_http_exception( diff --git a/dump_things_service/instance_state.py b/dump_things_service/instance_state.py index f18e3b6..264e323 100644 --- a/dump_things_service/instance_state.py +++ b/dump_things_service/instance_state.py @@ -95,7 +95,7 @@ class InstanceState: # Created based on abstract configuration collections: dict[str, InstanceStateCollectionInfo] = dataclasses.field( - default_factory=dict + default_factory=dict, ) tokens: dict = dataclasses.field(default_factory=dict) auth_sources: dict[str, list] = dataclasses.field(default_factory=dict) @@ -145,7 +145,7 @@ def get_record_dir_config( raise ConfigError(msg) try: return RecordDirConfigFileContent( - **yaml.load(config_path.read_text(), Loader=yaml.SafeLoader) + **yaml.load(config_path.read_text(), Loader=yaml.SafeLoader), ) except ScannerError as e: msg = f'YAML-error while reading config file {config_path}: {e}' diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index 267e185..d1321ba 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -176,7 +176,7 @@ def manifest_configuration( if faulty_collections: for collection in faulty_collections: logger.info( - 'removing fault-inducing configuration for collection "%s"', collection + 'removing fault-inducing configuration for collection "%s"', collection, ) configuration.collections.pop(collection, None) msg = 'Collection creation errors occurred:\n' + '\n'.join( diff --git a/dump_things_service/model.py b/dump_things_service/model.py index a7f9284..b8ba4ae 100644 --- a/dump_things_service/model.py +++ b/dump_things_service/model.py @@ -102,7 +102,7 @@ def compile_module_with_increasing_recursion_limit( if current_recursion_limit >= max_recursion_limit: lgr.error( f'Maximum recursion limit ({max_recursion_limit}) reached when ' - 'building Pydantic model, cannot increase further.' + 'building Pydantic model, cannot increase further.', ) raise current_recursion_limit += 1000 diff --git a/dump_things_service/store/model_store.py b/dump_things_service/store/model_store.py index 4419c4c..197e260 100644 --- a/dump_things_service/store/model_store.py +++ b/dump_things_service/store/model_store.py @@ -154,8 +154,8 @@ class _ModelStore: 'dlthings:placeholder': sub_record.pid, }, ) - ] - ) + ], + ), ) # Simplify the relations in this record. We use "empty" Thing objects # with a special annotation as placeholders for extracted records. diff --git a/dump_things_service/tests/create_store.py b/dump_things_service/tests/create_store.py index f5e0660..a1d287f 100644 --- a/dump_things_service/tests/create_store.py +++ b/dump_things_service/tests/create_store.py @@ -100,8 +100,8 @@ def create_collection( collection_config_file = curated_dir / config_file_name collection_config_file.write_text( collection_config_template.format( - schema=schema_url, mapping_function=mapping_function - ) + schema=schema_url, mapping_function=mapping_function, + ), ) # Add default entries diff --git a/dump_things_service/tests/fixtures.py b/dump_things_service/tests/fixtures.py index 300cb61..18800d3 100644 --- a/dump_things_service/tests/fixtures.py +++ b/dump_things_service/tests/fixtures.py @@ -51,7 +51,7 @@ flat_social_schema_location = ( 'https://concepts.datalad.org/s/flat-social/unreleased.yaml' ) policy_info_file_location = str( - (Path(__file__).parent / 'assets' / 'policy_info.json').absolute() + (Path(__file__).parent / 'assets' / 'policy_info.json').absolute(), ) @@ -101,7 +101,7 @@ g_default_collections.append( ], ), ], - ) + ), ) g_default_collections.append( @@ -142,7 +142,7 @@ g_default_collections.extend( 'Project', ], ), - ] + ], ) g_default_tokens = [ @@ -164,7 +164,7 @@ g_default_tokens = [ ) for i in range(1, 3) }, - + 'collection/with/slash/0': TokenCollectionConfig( mode=TokenModes.READ_CURATED, ) @@ -197,7 +197,7 @@ g_default_tokens = [ 'collection_2': TokenCollectionConfig( mode=TokenModes.WRITE_COLLECTION, incoming_label='in_token-2', - ) + ), }, ), TokenRequest( @@ -209,7 +209,7 @@ g_default_tokens = [ 'collection_8': TokenCollectionConfig( mode=TokenModes.WRITE_COLLECTION, incoming_label='test_user_8', - ) + ), }, ), TokenRequest( @@ -221,7 +221,7 @@ g_default_tokens = [ 'collection_8': TokenCollectionConfig( mode=TokenModes.WRITE_COLLECTION, incoming_label='test_user_8_default_policy', - ) + ), }, ), TokenRequest( @@ -233,7 +233,7 @@ g_default_tokens = [ 'collection_8': TokenCollectionConfig( mode=TokenModes.WRITE_COLLECTION, incoming_label='test_user_8_policy_1', - ) + ), }, ), TokenRequest( @@ -407,7 +407,7 @@ annotations: https://example.org/dumpthings/policy_set: policy_1 """, ), - ] + ], ) g_default_entries['collection_dlflatsocial-1'] = [('Person', pid_trr, test_record_trr)] @@ -454,7 +454,7 @@ def fastapi_client_simple(fastapi_app_simple): type='gitaudit', path=Path(audit_path), auto_flush_timeout=2, - ) + ), ] # Add collections via the Web-API diff --git a/dump_things_service/tests/test_auth.py b/dump_things_service/tests/test_auth.py index f26de74..51e7f4f 100644 --- a/dump_things_service/tests/test_auth.py +++ b/dump_things_service/tests/test_auth.py @@ -43,16 +43,16 @@ def setup_http_server(http_server) -> None: for instance in ('1', '2'): http_server.expect_request(f'/api/v{instance}/user').respond_with_json(user_1) http_server.expect_request(f'/api/v{instance}/user/teams').respond_with_json( - [team_1, team_3] + [team_1, team_3], ) http_server.expect_request(f'/api/v{instance}/orgs/org_1').respond_with_json( - org_1 + org_1, ) http_server.expect_request( - f'/api/v{instance}/orgs/org_1/teams' + f'/api/v{instance}/orgs/org_1/teams', ).respond_with_json([team_1, team_2, team_3]) http_server.expect_request( - f'/api/v{instance}/repos/org_1/repo_1/teams' + f'/api/v{instance}/repos/org_1/repo_1/teams', ).respond_with_json([team_1, team_2, team_3]) diff --git a/dump_things_service/tests/test_basic.py b/dump_things_service/tests/test_basic.py index 9a0aa41..87ca10b 100644 --- a/dump_things_service/tests/test_basic.py +++ b/dump_things_service/tests/test_basic.py @@ -126,7 +126,7 @@ def test_hashed_token(fastapi_client_simple): response = test_client.get( f'/collection_1/record?pid={pid}', headers={ - 'x-dumpthings-token': '1d6a827ef04170562ec35925c7057352dfcf69d24eff1171d5d1eaad0c10e66b' + 'x-dumpthings-token': '1d6a827ef04170562ec35925c7057352dfcf69d24eff1171d5d1eaad0c10e66b', }, ) assert response.status_code == HTTP_401_UNAUTHORIZED @@ -153,7 +153,7 @@ def test_search_by_class(fastapi_client_simple): 'pid': 'abc:mode_test', 'schema_type': 'abc:Person', 'annotations': { - 'https://example.org/dumpthings/policy_set': 'policy_1' + 'https://example.org/dumpthings/policy_set': 'policy_1', }, }, { diff --git a/dump_things_service/tests/test_collection_administration.py b/dump_things_service/tests/test_collection_administration.py index 302b68d..9e2733e 100644 --- a/dump_things_service/tests/test_collection_administration.py +++ b/dump_things_service/tests/test_collection_administration.py @@ -52,7 +52,7 @@ new_token_request = TokenRequest( new_collection_name: TokenCollectionConfig( mode=TokenModes.WRITE_COLLECTION, incoming_label=f'{new_collection_name}_label', - ) + ), }, ) @@ -89,7 +89,7 @@ def test_collection_adding(fastapi_client_simple): ) assert response.status_code == HTTP_200_OK new_collection_config = new_collection_request.model_dump( - mode='json', by_alias=True + mode='json', by_alias=True, ) del new_collection_config['name'] assert response.json() == new_collection_config @@ -190,7 +190,7 @@ def test_collection_putting(fastapi_client_simple, tmp_path): type='gitaudit', path=Path(tmp_path), auto_flush_timeout=2, - ) + ), ], ) diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index 9bd9fdc..2e100d0 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -66,7 +66,7 @@ def test_illegal_collection_name_detection(fastapi_client_simple): @pytest.mark.skip( - reason='Reuse detection is disabled to support existing old configurations' + reason='Reuse detection is disabled to support existing old configurations', ) def test_collection_dir_reuse_detection(fastapi_client_simple): test_client, _, admin_token = fastapi_client_simple @@ -153,7 +153,7 @@ def test_missing_incoming_detection(fastapi_client_simple): 'missing_incoming_detection_test': TokenCollectionConfig( mode=TokenModes.CURATOR, incoming_label='', - ) + ), }, ) @@ -175,7 +175,7 @@ def test_missing_incoming_detection(fastapi_client_simple): # Add a collection with incoming path collection_request.incoming = PurePosixPath( - 'missing_incoming_detection_test_incoming' + 'missing_incoming_detection_test_incoming', ) response = test_client.post( '/collections', diff --git a/dump_things_service/tests/test_extract_inline.py b/dump_things_service/tests/test_extract_inline.py index 5501174..e339645 100644 --- a/dump_things_service/tests/test_extract_inline.py +++ b/dump_things_service/tests/test_extract_inline.py @@ -394,9 +394,9 @@ def test_store_complex_things(fastapi_client_simple): 'relations': { 'http://test.complex.thing/1.1.1': { 'pid': 'http://test.complex.thing/1.1.1', - } + }, }, - } + }, }, } diff --git a/dump_things_service/tests/test_ifabsent_patch.py b/dump_things_service/tests/test_ifabsent_patch.py index e1f4312..5213b22 100644 --- a/dump_things_service/tests/test_ifabsent_patch.py +++ b/dump_things_service/tests/test_ifabsent_patch.py @@ -19,7 +19,7 @@ def test_ifabsent_patch(): # Patch in the faulty, original code and check for its result if_abs_proc.IfAbsentProcessor._uri_for = _original_uri_for gen1 = linkml.generators.PydanticGenerator( - str(schema_dir / 'schema-ifabsent-error.yaml') + str(schema_dir / 'schema-ifabsent-error.yaml'), ) x = gen1.serialize() assert 'default=XSD["04fa4r544"]' in x @@ -29,7 +29,7 @@ def test_ifabsent_patch(): # Check for proper code generation gen2 = linkml.generators.PydanticGenerator( - str(schema_dir / 'schema-ifabsent-error.yaml') + str(schema_dir / 'schema-ifabsent-error.yaml'), ) y = gen2.serialize() assert 'XSD' not in y diff --git a/dump_things_service/tests/test_paths.py b/dump_things_service/tests/test_paths.py index 24dbe56..61f9f13 100644 --- a/dump_things_service/tests/test_paths.py +++ b/dump_things_service/tests/test_paths.py @@ -35,7 +35,7 @@ def test_curated_path(fastapi_client_simple): '/collections', headers={'x-dumpthings-token': admin_token}, json=test_curated_path_collection_request.model_dump( - mode='json', by_alias=True + mode='json', by_alias=True, ), ) assert response.status_code == HTTP_406_NOT_ACCEPTABLE @@ -49,7 +49,7 @@ def test_incoming_path(fastapi_client_simple): '/collections', headers={'x-dumpthings-token': admin_token}, json=test_incoming_path_collection_request.model_dump( - mode='json', by_alias=True + mode='json', by_alias=True, ), ) assert response.status_code == HTTP_406_NOT_ACCEPTABLE diff --git a/dump_things_service/tests/test_policies.py b/dump_things_service/tests/test_policies.py index 95596a2..d7dc804 100644 --- a/dump_things_service/tests/test_policies.py +++ b/dump_things_service/tests/test_policies.py @@ -24,7 +24,7 @@ def test_policy_clause(): None, {'p1'}, [ - "json_extract(object, '$.annotations.\"tag\"') is NULL or json_extract(object, '$.annotations.\"tag\"') in ('p1')" + "json_extract(object, '$.annotations.\"tag\"') is NULL or json_extract(object, '$.annotations.\"tag\"') in ('p1')", ], ), (None, {}, ['json_extract(object, \'$.annotations."tag"\') is NULL']), @@ -101,7 +101,7 @@ def test_policy_mapping_errors(fastapi_client_simple): 'auth_source': 'xyz-something-not-existing', 'user_id': 'user_x', 'authorized_by': ['p1', 'p2'], - } + }, ], } diff --git a/dump_things_service/tests/test_roundtrip_flatsocial.py b/dump_things_service/tests/test_roundtrip_flatsocial.py index 8686ef1..3f802f4 100644 --- a/dump_things_service/tests/test_roundtrip_flatsocial.py +++ b/dump_things_service/tests/test_roundtrip_flatsocial.py @@ -184,11 +184,11 @@ def test_ttl_json_ttl_dlflatsocial(fastapi_client_simple): assert ( response.text.strip() == ttl_output_record_a.replace( - 'dlflatsocial:test_john_ttl', new_json_pid + 'dlflatsocial:test_john_ttl', new_json_pid, ).strip() ) or ( response.text.strip() == ttl_output_record_b.replace( - 'dlflatsocial:test_john_ttl', new_json_pid + 'dlflatsocial:test_john_ttl', new_json_pid, ).strip() ) diff --git a/dump_things_service/tests/test_token_endpoints.py b/dump_things_service/tests/test_token_endpoints.py index f9113c8..b0d4f00 100644 --- a/dump_things_service/tests/test_token_endpoints.py +++ b/dump_things_service/tests/test_token_endpoints.py @@ -15,7 +15,7 @@ def test_token_creation(fastapi_client_simple): 'user_id': 'u_a', 'representation': '8bb6805ff10bcb1c2ca49dcd4bfef94d', 'collections': { - 'collection_1': {'mode': 'WRITE_COLLECTION', 'incoming_label': 'i_a'} + 'collection_1': {'mode': 'WRITE_COLLECTION', 'incoming_label': 'i_a'}, }, } diff --git a/dump_things_service/tests/test_utils.py b/dump_things_service/tests/test_utils.py index 294a7d4..51c655f 100644 --- a/dump_things_service/tests/test_utils.py +++ b/dump_things_service/tests/test_utils.py @@ -14,7 +14,7 @@ def test_cleaned_json(): 'creator': 'https://orcid.org', 'schema_type': 'dlidentifiers:Identifier', 'empty': None, - } + }, ], 'empty': None, 'family_name': 'Hanke', @@ -32,7 +32,7 @@ def test_cleaned_json(): 'notation': '0000-0001-6398-6370', 'creator': 'https://orcid.org', 'schema_type': 'dlidentifiers:Identifier', - } + }, ], 'family_name': 'Hanke', 'given_name': 'Michael', diff --git a/dump_things_service/utils.py b/dump_things_service/utils.py index 4e62fda..685e452 100644 --- a/dump_things_service/utils.py +++ b/dump_things_service/utils.py @@ -175,7 +175,7 @@ def get_on_disk_labels( return set() incoming_path = store_path / cast( - 'Path', abstract_config.collections[collection].incoming + 'Path', abstract_config.collections[collection].incoming, ) if not incoming_path or not incoming_path.exists(): return set() @@ -402,7 +402,7 @@ def create_token_store( order_by=instance_state.order_by, schema_uri=schema_uri, mapping_function=cast( - 'RecordDirBackendConfig', backend_config + 'RecordDirBackendConfig', backend_config, ).mapping_method, suffix='yaml', ) @@ -497,7 +497,7 @@ def create_sqlite_token_store_backend( def check_bounds( - length: int | None, max_length: int, collection: str, alternative_url: str + length: int | None, max_length: int, collection: str, alternative_url: str, ): if length is not None and length > max_length: raise HTTPException( @@ -538,7 +538,7 @@ async def process_token( ) final_permissions = join_default_token_permissions( - abstract_config, token_permissions, collection + abstract_config, token_permissions, collection, ) # Check for maintenance mode @@ -655,7 +655,7 @@ def dict_to_base_model( configuration = get_config() model = get_model_for_schema( - configuration.collections[collection_name].schema_location + configuration.collections[collection_name].schema_location, )[0] with wrap_http_exception( ValidationError, @@ -697,10 +697,10 @@ def check_content_type( with wrap_http_exception(Exception): return Format.json, json.loads(body) raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.' + status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.', ) elif not isinstance(body, str): raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.' + status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.', ) return specified_format, body -- 2.54.1 From d66467da1f9051c14dd9f859b04d1e0dcf40804d Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 11 Nov 2026 10:10:40 +0100 Subject: [PATCH 10/15] rf: fix raise statements Remove unnecessary parenthesis from raise statements --- dump_things_service/auth/forgejo.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/dump_things_service/auth/forgejo.py b/dump_things_service/auth/forgejo.py index abaec61..18d58f1 100644 --- a/dump_things_service/auth/forgejo.py +++ b/dump_things_service/auth/forgejo.py @@ -136,14 +136,14 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): ) except Timeout: logger.info('timeout in request to %s', api_url) - raise RemoteAuthenticationError() + raise RemoteAuthenticationError except requests.exceptions.RequestException as e: logger.info('could not read from %s: %s', api_url, e) - raise RemoteAuthenticationError() + raise RemoteAuthenticationError if r.status_code >= HTTP_300_MULTIPLE_CHOICES: logger.info('invalid token: %d', r.status_code) - raise RemoteAuthenticationError() + raise RemoteAuthenticationError return r.json() @MethodCache.cache_temporary(duration=120) @@ -216,7 +216,7 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): self.team, self.organization, ) - raise RemoteAuthenticationError() + raise RemoteAuthenticationError return permissions @MethodCache.cache_temporary(duration=60) @@ -241,7 +241,7 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): 'token user is not member of team %s', self.team, ) - raise RemoteAuthenticationError() + raise RemoteAuthenticationError organization = self._get_organization(token) user_info = self._get_user(token) @@ -279,7 +279,7 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): self.organization, self.team, ) - raise RemoteAuthenticationError() + raise RemoteAuthenticationError # Get the repo.code permissions from the team definition code_permissions = self._get_unit_content(team, 'repo.code') -- 2.54.1 From b41bf253ed05edc0132778eed6e4954c23612b93 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 11 Nov 2026 10:23:11 +0100 Subject: [PATCH 11/15] fix: fix malformed logging format string --- dump_things_service/abstract_config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 5e9700a..72e75ec 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -372,7 +372,7 @@ def check_label( ) and label not in get_on_disk_labels(store_path, abstract_config, collection): if create_if_missing: logger.debug( - "Creating incoming label '%' in collection '%'", + "Creating incoming label '%s' in collection '%s'", label, collection, ) -- 2.54.1 From eeaa335404dd0719a2954e5aeec18e45f2c718ac Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 11 Nov 2026 11:00:43 +0100 Subject: [PATCH 12/15] fix: fix an unintended assignment --- dump_things_service/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 1b1412b..576681e 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -197,7 +197,7 @@ openapi_tags = [ @asynccontextmanager async def lifespan(_app: FastAPI): - task = asyncio.create_action = asyncio.create_task(periodic_worker()) + task = asyncio.create_task(periodic_worker()) yield task.cancel() try: -- 2.54.1 From 46a4cde9b4ea10aaad56731b799a689498499210 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 11 Nov 2026 14:54:37 +0100 Subject: [PATCH 13/15] rf: use parameter for class set in SQL --- dump_things_service/backends/sqlite.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/dump_things_service/backends/sqlite.py b/dump_things_service/backends/sqlite.py index 7ce4a76..56b1008 100644 --- a/dump_things_service/backends/sqlite.py +++ b/dump_things_service/backends/sqlite.py @@ -36,6 +36,7 @@ from typing import ( from sqlalchemy import ( JSON, String, + bindparam, create_engine, delete, select, @@ -271,8 +272,11 @@ class _SQLiteBackend(StorageBackend): 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' 'from thing ' f'where ({policy_clause}) ' - f'and thing.class_name in ({class_list}) ' + f'and thing.class_name in :class_set ' 'ORDER BY thing.sort_key', + ).bindparams( + bindparam('class_set', expanding=True), + class_set=class_names, ) else: statement = text( @@ -280,12 +284,16 @@ class _SQLiteBackend(StorageBackend): 'from thing, json_tree(thing.object) ' f'where ({policy_clause}) ' 'and lower(json_tree.value) like lower(:pattern) ' - f'and thing.class_name in ({class_list}) ' + f'and thing.class_name in :class_set ' "and json_tree.type = 'text' ORDER BY thing.sort_key", + ).bindparams( + bindparam('class_set', expanding=True), + pattern=pattern, + class_set=class_names, ) with self.engine.connect() as connection: - rs = connection.execute(statement, parameters={'pattern': pattern}) + rs = connection.execute(statement) return SQLResultList(self.engine).add_info( ResultListInfo( iri=thing.iri, -- 2.54.1 From 90cfdcb7411de3b47c43095658ac3f627b6cb502 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 11 Nov 2026 15:28:52 +0100 Subject: [PATCH 14/15] rf: remove linter errors --- dump_things_service/abstract_config.py | 2 ++ dump_things_service/audit/gitaudit.py | 6 +++--- .../audit/tests/test_gitaudit.py | 2 +- dump_things_service/auth/forgejo.py | 8 ++++---- dump_things_service/backends/record_dir.py | 4 +--- dump_things_service/backends/sqlite.py | 1 - .../endpoints/v0/collection_endpoints.py | 10 +++++----- dump_things_service/endpoints/v0/curated.py | 10 +++------- dump_things_service/endpoints/v0/incoming.py | 10 +++------- dump_things_service/main.py | 7 +++---- dump_things_service/manifest.py | 13 ++++++++---- dump_things_service/model.py | 6 +++--- .../tests/test_backward_compatibility.py | 2 +- dump_things_service/tests/test_config.py | 2 +- dump_things_service/tests/test_incoming.py | 2 +- pyproject.toml | 20 +++++++++++++++++++ 16 files changed, 60 insertions(+), 45 deletions(-) diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 72e75ec..14d80ad 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -618,4 +618,6 @@ def _get_containing_path( return container, position except ValueError: pass + else: + return container, position return None, None diff --git a/dump_things_service/audit/gitaudit.py b/dump_things_service/audit/gitaudit.py index 9124415..bd220bb 100644 --- a/dump_things_service/audit/gitaudit.py +++ b/dump_things_service/audit/gitaudit.py @@ -305,7 +305,7 @@ class GitAuditBackend(AuditBackend): self, record_id: str, ) -> tuple[str, Path, Path]: - base = hashlib.sha1(record_id.encode()).hexdigest() + base = hashlib.sha1(record_id.encode()).hexdigest() # noqa: S324 -- not used for crypto dir_1, dir_2, _name = base[0:3], base[3:6], base[6:] location_dir = Path(dir_1) / Path(dir_2) return ( @@ -341,7 +341,7 @@ class GitAuditBackend(AuditBackend): if not self.index_path.exists(): self.rebuild_index() - with open(self.index_path) as f: + with self.index_path.open() as f: self.index = {line.strip() for line in f} def _add_to_index( @@ -362,7 +362,7 @@ class GitAuditBackend(AuditBackend): .decode() .splitlines() ) - with open(self.index_path, 'w') as f: + with self.index_path.open('w') as f: for line in tree_entries: if not line.endswith('.yaml'): continue diff --git a/dump_things_service/audit/tests/test_gitaudit.py b/dump_things_service/audit/tests/test_gitaudit.py index 38c7d4c..844383f 100644 --- a/dump_things_service/audit/tests/test_gitaudit.py +++ b/dump_things_service/audit/tests/test_gitaudit.py @@ -9,7 +9,7 @@ def _get_git_log(path: Path) -> list[str]: ['git', '-C', str(path), 'log', '--oneline'], capture_output=True, check=True, - ) + ) # noqa S603, S607 -- environment and input are controlled return result.stdout.decode().splitlines() diff --git a/dump_things_service/auth/forgejo.py b/dump_things_service/auth/forgejo.py index 18d58f1..498a3c0 100644 --- a/dump_things_service/auth/forgejo.py +++ b/dump_things_service/auth/forgejo.py @@ -116,7 +116,7 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): self.organization = organization self.team = team self.label_type = label_type - self.instance_id = instance_id or hashlib.md5(self.api_url.encode()).hexdigest() + self.instance_id = instance_id or hashlib.md5(self.api_url.encode()).hexdigest() # noqa S324 -- not used for crypto self.repository = repository def _get_json_from_endpoint( @@ -134,12 +134,12 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): }, timeout=_timeout, ) - except Timeout: + except Timeout as e: logger.info('timeout in request to %s', api_url) - raise RemoteAuthenticationError + raise RemoteAuthenticationError from e except requests.exceptions.RequestException as e: logger.info('could not read from %s: %s', api_url, e) - raise RemoteAuthenticationError + raise RemoteAuthenticationError from e if r.status_code >= HTTP_300_MULTIPLE_CHOICES: logger.info('invalid token: %d', r.status_code) diff --git a/dump_things_service/backends/record_dir.py b/dump_things_service/backends/record_dir.py index 5bdd2bd..7b865d1 100644 --- a/dump_things_service/backends/record_dir.py +++ b/dump_things_service/backends/record_dir.py @@ -8,9 +8,7 @@ from __future__ import annotations import logging from pathlib import Path -from typing import ( - TYPE_CHECKING, -) +from typing import TYPE_CHECKING import yaml diff --git a/dump_things_service/backends/sqlite.py b/dump_things_service/backends/sqlite.py index 56b1008..5f4aa2a 100644 --- a/dump_things_service/backends/sqlite.py +++ b/dump_things_service/backends/sqlite.py @@ -258,7 +258,6 @@ class _SQLiteBackend(StorageBackend): default_policy: str | None = None, active_policies: set[str] | None = None, ) -> SQLResultList: - class_list = ', '.join(f"'{cn}'" for cn in class_names) active_policies = active_policies or set() policy_clause = self._get_policy_clause( diff --git a/dump_things_service/endpoints/v0/collection_endpoints.py b/dump_things_service/endpoints/v0/collection_endpoints.py index 61debe8..bf1cff0 100644 --- a/dump_things_service/endpoints/v0/collection_endpoints.py +++ b/dump_things_service/endpoints/v0/collection_endpoints.py @@ -121,11 +121,11 @@ async def create_or_replace_collection( ) # Check for distinct directories. - # TODO: we skip this currently because a number of version 5 installations - # deliberately put inboxes into the same path. Those configurations cannot - # be established if this check is performed. Instead of the `if False:`- - # clause, we should introduce a configuration for the server to specify - # whether unique directories are required. + # We skip this currently because a number of version 5 installations + # deliberately put inboxes into the same path. Those configurations cannot + # be established if this check is performed. Instead of the `if False:`- + # clause, we should introduce a configuration for the server to specify + # whether unique directories are required. if False: for directory in (body.incoming, body.curated): if directory: diff --git a/dump_things_service/endpoints/v0/curated.py b/dump_things_service/endpoints/v0/curated.py index 596e2f7..dc27dc7 100644 --- a/dump_things_service/endpoints/v0/curated.py +++ b/dump_things_service/endpoints/v0/curated.py @@ -223,14 +223,10 @@ async def _read_curated_records( record_info = backend.get_record_by_iri(model_store.pid_to_iri(pid)) if record_info: return record_info.json_object - return None - # TODO: check whether HTTP_404_NOT_FOUND should be raised instead of - # returning an empty HTTP_200_OK result. This will influence on how the + # TODO(cmo): check whether HTTP_404_NOT_FOUND should be raised instead of + # returning an empty HTTP_200_OK result. This will influence how the # endpoint is used by the clients. - # raise HTTPException( - # status_code=HTTP_404_NOT_FOUND, - # detail=f"no record with pid '{pid}' in curated area of collection '{collection}'", - # ) + return None if class_name: result_list = backend.get_records_of_classes([class_name], pattern=matching) else: diff --git a/dump_things_service/endpoints/v0/incoming.py b/dump_things_service/endpoints/v0/incoming.py index 20d8e38..38a3f87 100644 --- a/dump_things_service/endpoints/v0/incoming.py +++ b/dump_things_service/endpoints/v0/incoming.py @@ -243,14 +243,10 @@ async def _incoming_read_records( record_info = backend.get_record_by_iri(model_store.pid_to_iri(pid)) if record_info: return record_info.json_object - return None - # TODO: check whether HTTP_404_NOT_FOUND should be raised instead of - # returning an empty HTTP_200_OK result. This will influence on how the + # TODO(cmo): check whether HTTP_404_NOT_FOUND should be raised instead of + # returning an empty HTTP_200_OK result. This will influence how the # endpoint is used by the clients. - # raise HTTPException( - # status_code=HTTP_404_NOT_FOUND, - # detail=f'no record with pid: {pid}', - # ) + return None if class_name: result_list = backend.get_records_of_classes([class_name], pattern=matching) else: diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 576681e..4bde22c 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -313,13 +313,12 @@ if ( ) and not g_instance_state.bootstrap_token ): - print( + sys.stderr.write( 'The server has an empty configuration and requires a bootstrap ' 'token (use `--admin-token-hash` or the environment variable ' - '`DTS_ADMIN_TOKEN` to provide one).', - file=sys.stderr, - flush=True, + '`DTS_ADMIN_TOKEN` to provide one).\n', ) + sys.stderr.flush() sys.exit(2) diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index d1321ba..d961bb0 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -135,7 +135,9 @@ def manifest_configuration( # regularly. except RecoverableConfigError as e: logger.info( - f'Recoverable error creating collection "{collection_name}" from configuration: {e.__cause__}', + 'Recoverable error creating collection "%s" from configuration: %s', + collection_name, + str(e.__cause__), ) g_recoverable_error.add(collection_name) @@ -143,7 +145,9 @@ def manifest_configuration( # We catch all remaining errors here and log them. The collection will # be excluded from the list. logger.error( - f'Error creating collection "{collection_name}" from configuration: {e}', + 'Error creating collection "%s" from configuration: %s', + collection_name, + str(e), ) faulty_collections.add(collection_name) collection_errors[collection_name] = e @@ -176,7 +180,8 @@ def manifest_configuration( if faulty_collections: for collection in faulty_collections: logger.info( - 'removing fault-inducing configuration for collection "%s"', collection, + 'removing fault-inducing configuration for collection "%s"', + collection, ) configuration.collections.pop(collection, None) msg = 'Collection creation errors occurred:\n' + '\n'.join( @@ -205,7 +210,7 @@ def delete_collection_from_instance_state( instance_state: InstanceState, collection_name: str, ): - # TODO: Maybe all collection-specific information + # TODO(cmo): Maybe all collection-specific information # should go into the instance_state.collection[x]-object!? # That would allow to remove it easily. diff --git a/dump_things_service/model.py b/dump_things_service/model.py index b8ba4ae..f58aa47 100644 --- a/dump_things_service/model.py +++ b/dump_things_service/model.py @@ -57,8 +57,8 @@ def get_subclasses( ) -> list[str]: """get names of all subclasses (includes class_name itself)""" - # TODO: this could also be implemented via SchemaView: - # return schema_view.class_children(class_name, mixins=False) + # TODO(cmo): this could also be implemented via `SchemaView` with + # something like: return schema_view.class_children(class_name, mixins=False) super_class = getattr(model, class_name) return [ name @@ -67,7 +67,7 @@ def get_subclasses( ] -# TODO: shall we use the following code? +# TODO(cmo): shall we use the following code? # The code below would use schema-definitions to determine classes and not # go through the pydantic module generation. @cache diff --git a/dump_things_service/tests/test_backward_compatibility.py b/dump_things_service/tests/test_backward_compatibility.py index 77984c7..ca89efe 100644 --- a/dump_things_service/tests/test_backward_compatibility.py +++ b/dump_things_service/tests/test_backward_compatibility.py @@ -11,7 +11,7 @@ collections: incoming: penguins/incoming-v1 backend: type: sqlite - schema: https://concepts.datalad.org/s/flat-study/unreleased.yaml + schema: https://concepts.datalad.org/s/flat-study/unreleased.yaml tokens: no_access: diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index 2e100d0..42b2fe0 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -249,7 +249,7 @@ def test_submission_tags_handling(fastapi_client_simple): def test_config_structure(): - with open(reference_config_file) as f: + with reference_config_file.open() as f: config_dict = yaml.safe_load(f) _ = Configuration(**config_dict) diff --git a/dump_things_service/tests/test_incoming.py b/dump_things_service/tests/test_incoming.py index 8063439..06e7dde 100644 --- a/dump_things_service/tests/test_incoming.py +++ b/dump_things_service/tests/test_incoming.py @@ -106,7 +106,7 @@ def test_read_incoming_records( ) assert response.status_code == HTTP_200_OK json_object = response.json() - result = json_object['items'] if 'items' in json_object else json_object + result = json_object['items'] if 'items' in json_object else json_object # noqa: SIM401 -- json_object is a list, not a dict matching = [ json_object for json_object in result if json_object['pid'] == pattern ] diff --git a/pyproject.toml b/pyproject.toml index 9e4e7cb..4ea2d1f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -171,9 +171,25 @@ extend-exclude = [ line-length = 88 indent-width = 4 target-version = "py311" + [tool.ruff.format] # Prefer single quotes over double quotes. quote-style = "single" + +[tool.ruff.lint] +select = ["ALL"] +ignore = [ + "D", # Ignore all docstring requirements (pydocstyle) + "ANN", # Ignore missing type annotations (flake8-annotations) + "E501", # line too long +] + +[tool.ruff.lint.flake8-quotes] +inline-quotes = "single" +multiline-quotes = "double" +docstring-quotes = "double" +avoid-escape = true + [tool.ruff.lint.per-file-ignores] "**/test_*" = [ # permit assert statements in tests @@ -193,6 +209,10 @@ quote-style = "single" # permit access to private members in tests "SLF001", ] +"dump_things_service/commands/*" = [ + # permit print in commands + "T201", +] # permit hard-coded passwords, assert, insecure hash and magic values in fixtures "dump_things_service/tests/fixtures.py" = ["S101", "S105", "S106", "S324", "PLR2004"] # permit relative import in subpackage root -- 2.54.1 From 26960a3e11870462b9ffa95e5c753beccbb3c10b Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 11 Nov 2026 15:34:28 +0100 Subject: [PATCH 15/15] rf: allow insecure subprocess execution in tests --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 4ea2d1f..a13bb00 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -200,6 +200,8 @@ avoid-escape = true "S324", # permit standard random number generators in tests "S311", + # permit subprocess execution in tests + "S603", # permit magic values in tests "PLR2004", # permit relative import in tests -- 2.54.1