Skip to content

Commit

Permalink
fixes tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pcrespov committed Nov 16, 2024
1 parent 78f1421 commit b735f46
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 27 deletions.
4 changes: 2 additions & 2 deletions packages/models-library/src/models_library/rest_ordering.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from .basic_types import IDStr
from .rest_base import RequestParameters
from .utils.common_validators import load_if_json_encoded_pre_validator
from .utils.common_validators import parse_json_pre_validator


class OrderDirection(str, Enum):
Expand Down Expand Up @@ -77,7 +77,7 @@ class _OrderQueryParams(_BaseOrderQueryParams):
)

_pre_parse_string = validator("order_by", allow_reuse=True, pre=True)(
load_if_json_encoded_pre_validator
parse_json_pre_validator
)

return _OrderQueryParams
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class MyModel(BaseModel):
import operator
from typing import Any

from orjson import JSONDecodeError

from .json_serialization import json_loads


Expand All @@ -41,10 +43,13 @@ def none_to_empty_list_pre_validator(value: Any):
return value


def load_if_json_encoded_pre_validator(value: Any):
def parse_json_pre_validator(value: Any):
if isinstance(value, str):
# raises JsonEncoderError which is a TypeError
return json_loads(value)
try:
return json_loads(value)
except JSONDecodeError as err:
msg = f"Invalid JSON {value=}: {err}"
raise TypeError(msg) from err
return value


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,13 @@ def _do_assert_error(

assert is_error(expected_status_code)

assert len(error["errors"]) == 1

err = error["errors"][0]
assert len(error["errors"]) >= 1
if expected_msg:
assert expected_msg in err["message"]
messages = [detail["message"] for detail in error["errors"]]
assert expected_msg in messages

if expected_error_code:
assert expected_error_code == err["code"]
codes = [detail["code"] for detail in error["errors"]]
assert expected_error_code in codes

return data, error
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ async def test_parse_request_with_invalid_headers_params(

def test_parse_request_query_parameters_as_with_order_by_query_models():

OrderByModel = create_ordering_query_model_classes(
OrderQueryModel = create_ordering_query_model_classes(
ordering_fields={"modified", "name"}, default=OrderBy(field="name")
)

Expand All @@ -373,12 +373,5 @@ def test_parse_request_query_parameters_as_with_order_by_query_models():

request = make_mocked_request("GET", path=f"{url}")

query_params = parse_request_query_parameters_as(OrderByModel, request)
query_params = parse_request_query_parameters_as(OrderQueryModel, request)
assert query_params.order_by == expected

expected_schema = {"type": "string", "format": "json-string"}
assert {
k: v
for k, v in OrderByModel.schema()["properties"]["order_by"]
if k in expected
} == expected_schema
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
import subprocess
import sys
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Callable, Iterator, NamedTuple
from typing import NamedTuple

import pytest
import requests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@

_SERVICE_RUN_GET = ServiceRunPage(
items=[
ServiceRunGet(
**{
ServiceRunGet.parse_obj(
{
"service_run_id": "comp_1_5c2110be-441b-11ee-a0e8-02420a000040_1",
"wallet_id": 1,
"wallet_name": "the super wallet!",
Expand Down Expand Up @@ -55,12 +55,11 @@

@pytest.fixture
def mock_list_usage_services(mocker: MockerFixture) -> tuple:
mock_list_usage = mocker.patch(
return mocker.patch(
"simcore_service_webserver.resource_usage._service_runs_api.service_runs.get_service_run_page",
spec=True,
return_value=_SERVICE_RUN_GET,
)
return mock_list_usage


@pytest.fixture()
Expand All @@ -79,7 +78,10 @@ def setup_wallets_db(
.returning(sa.literal_column("*"))
)
row = result.fetchone()
assert row

yield cast(int, row[0])

con.execute(wallets.delete())


Expand Down Expand Up @@ -160,6 +162,8 @@ async def test_list_service_usage_with_order_by_query_param(
setup_wallets_db,
mock_list_usage_services,
):
assert client.app

# without any additional query parameter
url = client.app.router["list_resource_usage_services"].url_for()
resp = await client.get(f"{url}")
Expand Down Expand Up @@ -237,9 +241,13 @@ async def test_list_service_usage_with_order_by_query_param(
_, error = await assert_status(resp, status.HTTP_422_UNPROCESSABLE_ENTITY)
assert mock_list_usage_services.called
assert error["status"] == status.HTTP_422_UNPROCESSABLE_ENTITY
assert error["errors"][0]["message"].startswith(
"value is not a valid enumeration member"
)

errors = {(e["code"], e["field"]) for e in error["errors"]}
assert {
("value_error", "order_by.field"),
("type_error.enum", "order_by.direction"),
} == errors
assert len(errors) == 2

# without field
_filter = {"direction": "asc"}
Expand All @@ -253,6 +261,8 @@ async def test_list_service_usage_with_order_by_query_param(
assert mock_list_usage_services.called
assert error["status"] == status.HTTP_422_UNPROCESSABLE_ENTITY
assert error["errors"][0]["message"].startswith("field required")
assert error["errors"][0]["code"] == "value_error.missing"
assert error["errors"][0]["field"] == "order_by.field"


@pytest.mark.parametrize("user_role", [(UserRole.USER)])
Expand All @@ -262,6 +272,8 @@ async def test_list_service_usage_with_filters_query_param(
setup_wallets_db,
mock_list_usage_services,
):
assert client.app

# with unable to decode filter query parameter
url = (
client.app.router["list_resource_usage_services"]
Expand Down

0 comments on commit b735f46

Please sign in to comment.