Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set correct meta->schema value automatically #1323

Merged
merged 4 commits into from
Sep 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/cd_release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ jobs:
run: python -m build

- name: Publish package to PyPI
uses: pypa/gh-action-pypi-publish/@release/v1
uses: pypa/gh-action-pypi-publish@release/v1
with:
user: __token__
password: ${{ secrets.PYPI_PASSWORD }}
Expand Down
11 changes: 11 additions & 0 deletions optimade/server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,17 @@ class ServerConfig(BaseSettings):
"MongoDB-based backend."
),
)

is_index: Optional[bool] = Field(
False,
description=(
"A runtime setting to dynamically switch between index meta-database and "
"normal OPTIMADE servers. Used for switching behaviour of e.g., `meta->optimade_schema` "
"values in the response. Any provided value may be overridden when used with the reference "
"server implementation."
),
)

schema_url: Optional[Union[str, AnyHttpUrl]] = Field(
f"https://schemas.optimade.org/openapi/v{__api_version__}/optimade.json",
description=(
Expand Down
1 change: 1 addition & 0 deletions optimade/server/main_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ def add_optional_versioned_base_urls(app: FastAPI):

@app.on_event("startup")
async def startup_event():
CONFIG.is_index = True
JPBergsma marked this conversation as resolved.
Show resolved Hide resolved
# Add API endpoints for MANDATORY base URL `/vMAJOR`
add_major_version_base_url(app)
# Add API endpoints for OPTIONAL base URLs `/vMAJOR.MINOR` and `/vMAJOR.MINOR.PATCH`
Expand Down
15 changes: 11 additions & 4 deletions optimade/server/routers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import re
import urllib.parse
from datetime import datetime
from typing import Any, Dict, List, Set, Union
from typing import Any, Dict, List, Optional, Set, Union

from fastapi import Request
from fastapi.responses import JSONResponse
Expand Down Expand Up @@ -59,7 +59,7 @@ def meta_values(
data_returned: int,
data_available: int,
more_data_available: bool,
schema: str,
schema: Optional[str] = None,
**kwargs,
) -> ResponseMeta:
"""Helper to initialize the meta values"""
Expand All @@ -74,6 +74,9 @@ def meta_values(
else:
url_path = url.path

if schema is None:
schema = CONFIG.schema_url if not CONFIG.is_index else CONFIG.index_schema_url

return ResponseMeta(
query=ResponseMetaQuery(representation=f"{url_path}?{url.query}"),
api_version=__api_version__,
Expand Down Expand Up @@ -273,7 +276,9 @@ def get_entries(
data_returned=data_returned,
data_available=len(collection),
more_data_available=more_data_available,
schema=CONFIG.schema_url,
schema=CONFIG.schema_url
if not CONFIG.is_index
else CONFIG.index_schema_url,
),
included=included,
)
Expand Down Expand Up @@ -321,7 +326,9 @@ def get_single_entry(
data_returned=data_returned,
data_available=len(collection),
more_data_available=more_data_available,
schema=CONFIG.schema_url,
schema=CONFIG.schema_url
if not CONFIG.is_index
else CONFIG.index_schema_url,
),
included=included,
)
40 changes: 40 additions & 0 deletions tests/server/test_server_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,43 @@ def test_versioned_base_urls(client, index_client, server: str):
f"Mandatory 'meta' top-level field not found in request to {response.url} for "
f"server {server!r}. Response: {json.dumps(json_response, indent=2)}"
)


@pytest.mark.parametrize("server", ["regular", "index"])
def test_meta_schema_value_obeys_index(client, index_client, server: str):
"""Test that the reported `meta->schema` is correct for index/non-index
servers.
"""
try:
import simplejson as json
except ImportError:
import json

from optimade.server.routers.utils import BASE_URL_PREFIXES
from optimade.server.config import CONFIG

clients = {
"regular": client,
"index": index_client,
}

for version in BASE_URL_PREFIXES.values():

# Mimic the effect of the relevant server's startup
CONFIG.is_index = server == "index"
response = clients[server].get(url=version + "/links")
json_response = response.json()

assert response.status_code == 200, (
f"Request to {response.url} failed for server {server!r}: "
f"{json.dumps(json_response, indent=2)}"
)
assert "meta" in json_response, (
f"Mandatory 'meta' top-level field not found in request to {response.url} for "
f"server {server!r}. Response: {json.dumps(json_response, indent=2)}"
)

if server == "regular":
assert json_response["meta"].get("schema") == CONFIG.schema_url
else:
assert json_response["meta"].get("schema") == CONFIG.index_schema_url