Skip to content

Commit

Permalink
Fix tests for live backend
Browse files Browse the repository at this point in the history
  • Loading branch information
CasperWA committed Jan 9, 2024
1 parent acc0204 commit 40beaf7
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 33 deletions.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,33 @@ docker compose --env-file .env up -d
pytest --live-backend
```

### Extra pytest markers

There are two custom pytest markers:

- `skip_if_live_backend`: skips the test if the `--live-backend` flag is set.
Add this marker to tests that should not be run against a live backend.
Either because they are not relevant for a live backend, or because they currently impossible to replicate within a live backend.

A reason can be specified as an argument to the marker, e.g.:

```python
@pytest.mark.skip_if_live_backend(reason="Cannot force an HTTP error")
def test_something():
...
```

**Availability**: This marker is available for all tests.

- `no_token`: run test without a mock authentication token set.
Add this marker to tests that should be run without an automatic mock authentication token set.
This is useful for testing the service's behaviour when no token is provided or to test letting the service set a token.

This marker is meant to be used together with the `_use_valid_token` fixture, which will automatically set a valid mock authentication token for a test.
The `_use_valid_token` fixture is used for all tests by default in the `cli.test_upload` file.

**Availability**: This marker is only available for tests in the `cli` test module (folder), and sub-modules (sub-folders) therein.

## Licensing & copyright

All files in this repository are [MIT licensed](LICENSE).
Expand Down
24 changes: 12 additions & 12 deletions dlite_entities_service/models/soft5.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,17 +112,17 @@ class SOFT5Entity(BaseModel):
list[SOFT5Property], Field(description="A list of properties.")
]

@field_validator("uri", "namespace")
@classmethod
def _validate_base_url(cls, value: AnyHttpUrl) -> AnyHttpUrl:
"""Validate `uri` starts with the current base URL for the service."""
if not str(value).startswith(str(CONFIG.base_url)):
error_message = (
"This service only works with DLite/SOFT entities at "
f"{CONFIG.base_url}.\n"
)
raise ValueError(error_message)
return value
# @field_validator("uri", "namespace", mode="after")
# @classmethod
# def _validate_base_url(cls, value: AnyHttpUrl) -> AnyHttpUrl:
# """Validate `uri` starts with the current base URL for the service."""
# if not str(value).startswith(str(CONFIG.base_url)):
# error_message = (
# "This service only works with DLite/SOFT entities at "
# f"{CONFIG.base_url}.\n"
# )
# raise ValueError(error_message)
# return value

@field_validator("uri", mode="after")
@classmethod
Expand All @@ -136,7 +136,7 @@ def _validate_uri(cls, value: AnyHttpUrl) -> AnyHttpUrl:
raise ValueError(error_message)
return value

@field_validator("meta")
@field_validator("meta", mode="after")
@classmethod
def _only_support_onto_ns(cls, value: AnyHttpUrl) -> AnyHttpUrl:
"""Validate `meta` only refers to onto-ns.com EntitySchema v0.3."""
Expand Down
24 changes: 12 additions & 12 deletions dlite_entities_service/models/soft7.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,18 +108,18 @@ class SOFT7Entity(BaseModel):
),
]

@field_validator("uri", "namespace", mode="after")
@classmethod
def _validate_base_url(cls, value: AnyHttpUrl) -> AnyHttpUrl:
"""Validate `uri` and `namespace` starts with the current base URL for the
service."""
if not str(value).startswith(str(CONFIG.base_url)):
error_message = (
"This service only works with DLite/SOFT entities at "
f"{CONFIG.base_url}.\n"
)
raise ValueError(error_message)
return value
# @field_validator("uri", "namespace", mode="after")
# @classmethod
# def _validate_base_url(cls, value: AnyHttpUrl) -> AnyHttpUrl:
# """Validate `uri` and `namespace` starts with the current base URL for the
# service."""
# if not str(value).startswith(str(CONFIG.base_url)):
# error_message = (
# "This service only works with DLite/SOFT entities at "
# f"{CONFIG.base_url}.\n"
# )
# raise ValueError(error_message)
# return value

@field_validator("uri", mode="after")
@classmethod
Expand Down
25 changes: 16 additions & 9 deletions tests/cli/test_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ def test_existing_entity_different_content(
from copy import deepcopy

from dlite_entities_service.cli.main import APP
from dlite_entities_service.models import URI_REGEX
from dlite_entities_service.service.config import CONFIG

entity_filepath = static_dir / "valid_entities" / "Person.json"
Expand All @@ -339,12 +340,16 @@ def test_existing_entity_different_content(
json=raw_entity,
)

original_uri_match = URI_REGEX.match(raw_entity["uri"])
assert original_uri_match is not None
original_uri_match_dict = original_uri_match.groupdict()

# Create a new file with a change in the content
new_entity = deepcopy(raw_entity)
new_entity["dimensions"]["n_skills"] = "Skill number."
new_entity["namespace"] = str(CONFIG.base_url)
new_entity["version"] = "0.1"
new_entity["name"] = "Person"
new_entity["namespace"] = original_uri_match_dict["namespace"]
new_entity["version"] = original_uri_match_dict["version"]
new_entity["name"] = original_uri_match_dict["name"]
assert new_entity != raw_entity
new_entity_file = tmp_path / "Person.json"
new_entity_file.write_text(json.dumps(new_entity))
Expand Down Expand Up @@ -377,9 +382,10 @@ def test_existing_entity_different_content(
# Mock response for "Upload entities"
new_entity_file_to_be_uploaded = deepcopy(new_entity)
new_entity_file_to_be_uploaded["version"] = "0.1.1"
new_entity_file_to_be_uploaded[
"uri"
] = f"{str(CONFIG.base_url).rstrip('/')}/0.1.1/Person"
new_entity_file_to_be_uploaded["uri"] = (
f"{original_uri_match_dict['namespace']}/0.1.1"
f"/{original_uri_match_dict['name']}"
)
httpx_mock.add_response(
url=f"{str(CONFIG.base_url).rstrip('/')}/_admin/create_many",
method="POST",
Expand Down Expand Up @@ -416,9 +422,10 @@ def test_existing_entity_different_content(
# Mock response for "Upload entities"
new_entity_file_to_be_uploaded = deepcopy(new_entity)
new_entity_file_to_be_uploaded["version"] = custom_version
new_entity_file_to_be_uploaded[
"uri"
] = f"{str(CONFIG.base_url).rstrip('/')}/{custom_version}/Person"
new_entity_file_to_be_uploaded["uri"] = (
f"{original_uri_match_dict['namespace']}/{custom_version}"
f"/{original_uri_match_dict['name']}"
)
httpx_mock.add_response(
url=f"{str(CONFIG.base_url).rstrip('/')}/_admin/create_many",
method="POST",
Expand Down

0 comments on commit 40beaf7

Please sign in to comment.