diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4a2b2c616..64b9b22d1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -29,13 +29,13 @@ repos: args: [--markdown-linebreak-ext=md] - repo: https://github.com/asottile/pyupgrade - rev: v3.19.0 + rev: v3.19.1 hooks: - id: pyupgrade args: [--py310-plus] - repo: https://github.com/astral-sh/ruff-pre-commit - rev: 'v0.7.2' + rev: 'v0.9.3' hooks: - id: ruff @@ -59,7 +59,7 @@ repos: description: Update the API Reference documentation whenever a Python file is touched in the code base. - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.13.0 + rev: v1.14.1 hooks: - id: mypy name: "MyPy" diff --git a/optimade/client/client.py b/optimade/client/client.py index 96513b670..558af476c 100644 --- a/optimade/client/client.py +++ b/optimade/client/client.py @@ -1113,7 +1113,7 @@ def _build_url( """ if not version: - version = f'v{__api_version__.split(".")[0]}' + version = f"v{__api_version__.split('.')[0]}" while base_url.endswith("/"): base_url = base_url[:-1] @@ -1129,7 +1129,7 @@ def _build_url( params_dict["response_fields"] = "response_fields=id" else: params_dict["response_fields"] = ( - f'response_fields={",".join(response_fields)}' + f"response_fields={','.join(response_fields)}" ) if page_limit: diff --git a/optimade/server/middleware.py b/optimade/server/middleware.py index 75b4fae60..741a1957c 100644 --- a/optimade/server/middleware.py +++ b/optimade/server/middleware.py @@ -242,7 +242,7 @@ async def dispatch(self, request: Request, call_next): base_url = get_base_url(request.url) new_request = ( - f"{base_url}{version_path}{str(request.url)[len(base_url):]}" + f"{base_url}{version_path}{str(request.url)[len(base_url) :]}" ) url = urllib.parse.urlsplit(new_request) q = "&".join( @@ -354,9 +354,9 @@ def showwarning( line: Source content of the line that issued the warning. """ - assert isinstance( - message, Warning - ), "'message' is expected to be a Warning or subclass thereof." + assert isinstance(message, Warning), ( + "'message' is expected to be a Warning or subclass thereof." + ) if not isinstance(message, OptimadeWarning): # If the Warning is not an OptimadeWarning or subclass thereof, diff --git a/optimade/utils.py b/optimade/utils.py index 3ec5b01b4..93867d8b3 100644 --- a/optimade/utils.py +++ b/optimade/utils.py @@ -64,9 +64,9 @@ def insert_from_jsonl(jsonl_path: Path, create_default_index: bool = False) -> N with open(jsonl_path) as handle: header = handle.readline() header_jsonl = json.loads(header) - assert header_jsonl.get( - "x-optimade" - ), "No x-optimade header, not sure if this is a JSONL file" + assert header_jsonl.get("x-optimade"), ( + "No x-optimade header, not sure if this is a JSONL file" + ) for line_no, json_str in enumerate(handle): try: diff --git a/optimade/validator/validator.py b/optimade/validator/validator.py index 5b79936b8..2305ee3a2 100644 --- a/optimade/validator/validator.py +++ b/optimade/validator/validator.py @@ -1039,7 +1039,7 @@ def _test_multi_entry_endpoint(self, endp: str) -> None: request_str = f"{endp}?page_limit={self.page_limit}" if response_fields: - request_str += f'&response_fields={",".join(response_fields)}' + request_str += f"&response_fields={','.join(response_fields)}" response, _ = self._get_endpoint(request_str) @@ -1529,7 +1529,7 @@ def _get_endpoint( message += "\nAdditional details from implementation:" try: for error in response.json().get("errors", []): - message += f'\n {error.get("title", "N/A")}: {error.get("detail", "N/A")} ({error.get("source", {}).get("pointer", "N/A")})' + message += f"\n {error.get('title', 'N/A')}: {error.get('detail', 'N/A')} ({error.get('source', {}).get('pointer', 'N/A')})" except json.JSONDecodeError: message += f"\n Could not parse response as JSON. Content type was {response.headers.get('content-type')!r}." diff --git a/tests/models/test_optimade_json.py b/tests/models/test_optimade_json.py index f96b88aa1..2b5657e2f 100644 --- a/tests/models/test_optimade_json.py +++ b/tests/models/test_optimade_json.py @@ -46,9 +46,9 @@ def test_convert_python_types(): python_types_as_objects, ]: for index, python_type in enumerate(list_of_python_types): - assert isinstance( - DataType.from_python_type(python_type), DataType - ), f"python_type: {python_type}" + assert isinstance(DataType.from_python_type(python_type), DataType), ( + f"python_type: {python_type}" + ) assert DataType.from_python_type(python_type) == expected_data_type[index] @@ -70,9 +70,9 @@ def test_convert_json_types(): for list_of_schema_types in [json_types, openapi_formats]: for schema_type, optimade_type in list_of_schema_types: - assert isinstance( - DataType.from_json_type(schema_type), DataType - ), f"json_type: {schema_type}" + assert isinstance(DataType.from_json_type(schema_type), DataType), ( + f"json_type: {schema_type}" + ) assert DataType.from_json_type(schema_type) == optimade_type diff --git a/tests/server/conftest.py b/tests/server/conftest.py index 09268833e..075844c5a 100644 --- a/tests/server/conftest.py +++ b/tests/server/conftest.py @@ -96,9 +96,9 @@ def inner( response_json = response.json() assert response.status_code == 200, f"Request failed: {response_json}" expected_mime_type = "application/vnd.api+json" - assert ( - response.headers["content-type"] == expected_mime_type - ), f"Response should have MIME type {expected_mime_type!r}, not {response.headers['content-type']!r}." + assert response.headers["content-type"] == expected_mime_type, ( + f"Response should have MIME type {expected_mime_type!r}, not {response.headers['content-type']!r}." + ) except json.JSONDecodeError: print( f"Request attempted:\n{used_client.base_url}{used_client.version}" @@ -220,9 +220,9 @@ def inner( f"but instead {response.status_code} was received.\nResponse:\n{response.json()}", ) expected_mime_type = "application/vnd.api+json" - assert ( - response.headers["content-type"] == expected_mime_type - ), f"Response should have MIME type {expected_mime_type!r}, not {response.headers['content-type']!r}." + assert response.headers["content-type"] == expected_mime_type, ( + f"Response should have MIME type {expected_mime_type!r}, not {response.headers['content-type']!r}." + ) response = response.json() assert len(response["errors"]) == 1, response.get( diff --git a/tests/server/middleware/test_api_hint.py b/tests/server/middleware/test_api_hint.py index 9eb0da1f5..75f340f4e 100644 --- a/tests/server/middleware/test_api_hint.py +++ b/tests/server/middleware/test_api_hint.py @@ -123,7 +123,7 @@ def test_handle_api_hint(): ) with pytest.raises(VersionNotSupported): - api_hint = f"v{int(BASE_URL_PREFIXES['major'][len('/v'):]) + 1}" + api_hint = f"v{int(BASE_URL_PREFIXES['major'][len('/v') :]) + 1}" HandleApiHint.handle_api_hint([api_hint]) api_hint = "v0" diff --git a/tests/server/middleware/test_cors.py b/tests/server/middleware/test_cors.py index a847e2980..a48afe2b7 100644 --- a/tests/server/middleware/test_cors.py +++ b/tests/server/middleware/test_cors.py @@ -3,9 +3,9 @@ def test_regular_CORS_request(both_clients): response = both_clients.get("/info", headers={"Origin": "http://example.org"}) - assert ( - ("access-control-allow-origin", "*") in tuple(response.headers.items()) - ), f"Access-Control-Allow-Origin header not found in response headers: {response.headers}" + assert ("access-control-allow-origin", "*") in tuple(response.headers.items()), ( + f"Access-Control-Allow-Origin header not found in response headers: {response.headers}" + ) def test_preflight_CORS_request(both_clients): @@ -18,6 +18,6 @@ def test_preflight_CORS_request(both_clients): "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", ): - assert response_header.lower() in list( - response.headers.keys() - ), f"{response_header} header not found in response headers: {response.headers}" + assert response_header.lower() in list(response.headers.keys()), ( + f"{response_header} header not found in response headers: {response.headers}" + ) diff --git a/tests/server/test_client.py b/tests/server/test_client.py index 687026373..4f12a5d32 100644 --- a/tests/server/test_client.py +++ b/tests/server/test_client.py @@ -471,7 +471,7 @@ def write_to_file(_: str, results: dict): with open(tmp_path / "formulae.csv", "a") as f: for structure in results["data"]: f.write( - f'\n{structure["id"]}, {structure["attributes"]["chemical_formula_reduced"]}' + f"\n{structure['id']}, {structure['attributes']['chemical_formula_reduced']}" ) return None @@ -538,9 +538,9 @@ def test_binary_search_internals(trial_counts): window, probe = cli._update_probe_and_window(window, probe, below=below) # print(trial_counts, window, probe) if window[0] == window[1] == probe: - assert ( - window[0] == trial_counts - ), "Binary search did not converge to the correct value." + assert window[0] == trial_counts, ( + "Binary search did not converge to the correct value." + ) break attempts += 1 else: diff --git a/tests/server/test_config.py b/tests/server/test_config.py index a09a8f796..2b9bdee7d 100644 --- a/tests/server/test_config.py +++ b/tests/server/test_config.py @@ -92,9 +92,9 @@ def test_debug_is_respected_when_off(both_clients: "OptimadeTestClient") -> None CONFIG.debug = False response = both_clients.get("/non/existent/path") - assert ( - response.status_code == 404 - ), f"Request should have failed, but didn't: {response.json()}" + assert response.status_code == 404, ( + f"Request should have failed, but didn't: {response.json()}" + ) response = response.json() assert "data" not in response @@ -118,9 +118,9 @@ def test_debug_is_respected_when_on(both_clients: "OptimadeTestClient") -> None: CONFIG.debug = True response = both_clients.get("/non/existent/path") - assert ( - response.status_code == 404 - ), f"Request should have failed, but didn't: {response.json()}" + assert response.status_code == 404, ( + f"Request should have failed, but didn't: {response.json()}" + ) response = response.json() assert "data" not in response @@ -174,13 +174,13 @@ def test_yaml_config_file() -> None: os.environ["OPTIMADE_CONFIG_FILE"] = str(Path(config_file.name).resolve()) CONFIG = ServerConfig() - assert CONFIG.aliases == { - "references": {"last_modified": "mtime"} - }, f"Config: {CONFIG.aliases}" + assert CONFIG.aliases == {"references": {"last_modified": "mtime"}}, ( + f"Config: {CONFIG.aliases}" + ) assert CONFIG.debug, f"Config: {CONFIG.debug}" - assert CONFIG.provider_fields == { - "references": ["great_paper"] - }, f"Config: {CONFIG.provider_fields}" + assert CONFIG.provider_fields == {"references": ["great_paper"]}, ( + f"Config: {CONFIG.provider_fields}" + ) with tempfile.NamedTemporaryFile("w+t", suffix=".yml") as config_file: config_file.write(yaml_content + extra_yaml_content) diff --git a/tests/server/utils.py b/tests/server/utils.py index ec8d72c62..8032d42c5 100644 --- a/tests/server/utils.py +++ b/tests/server/utils.py @@ -97,9 +97,9 @@ class BaseEndpointTests: @staticmethod def check_keys(keys: list, response_subset: "Iterable[str]"): for key in keys: - assert ( - key in response_subset - ), f"{key!r} missing from response {response_subset}" + assert key in response_subset, ( + f"{key!r} missing from response {response_subset}" + ) def test_response_okay(self): """Make sure the response was successful""" @@ -251,9 +251,9 @@ def get_response(self, both_clients): def test_response_okay(self): """Make sure the response was successful""" - assert ( - self.response.status_code == 200 - ), f"Request to {self.request_str} failed: {self.response.content}" + assert self.response.status_code == 200, ( + f"Request to {self.request_str} failed: {self.response.content}" + ) class HttpxTestClient(httpx.Client): diff --git a/tests/test_setup.py b/tests/test_setup.py index b1b731dc8..c8d1888ae 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -37,6 +37,6 @@ def test_distribution_package_data(package_file: str, build_dist: str) -> None: """Make sure a distribution has all the needed package data.""" import re - assert re.findall( - package_file, build_dist - ), f"{package_file} file NOT found.\nOUTPUT:\n{build_dist}" + assert re.findall(package_file, build_dist), ( + f"{package_file} file NOT found.\nOUTPUT:\n{build_dist}" + )