2023-05-08 16:42:21 +01:00
|
|
|
from dataclasses import dataclass
|
2023-05-09 15:30:46 +01:00
|
|
|
from typing import Any, Optional, Tuple
|
2022-11-05 13:45:16 +04:00
|
|
|
|
|
|
|
|
import pytest
|
2023-05-08 16:42:21 +01:00
|
|
|
from pydantic import BaseModel, ValidationError
|
2022-11-05 13:45:16 +04:00
|
|
|
|
2023-05-08 16:42:21 +01:00
|
|
|
from fastapi_cache.coder import JsonCoder, PickleCoder
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class DCItem:
|
|
|
|
|
name: str
|
|
|
|
|
price: float
|
|
|
|
|
description: Optional[str] = None
|
|
|
|
|
tax: Optional[float] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class PDItem(BaseModel):
|
|
|
|
|
name: str
|
|
|
|
|
price: float
|
|
|
|
|
description: Optional[str] = None
|
|
|
|
|
tax: Optional[float] = None
|
2022-11-05 13:45:16 +04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
|
"value",
|
|
|
|
|
[
|
|
|
|
|
1,
|
|
|
|
|
"some_string",
|
|
|
|
|
(1, 2),
|
|
|
|
|
[1, 2, 3],
|
|
|
|
|
{"some_key": 1, "other_key": 2},
|
2023-05-08 16:42:21 +01:00
|
|
|
DCItem(name="foo", price=42.0, description="some dataclass item", tax=0.2),
|
|
|
|
|
PDItem(name="foo", price=42.0, description="some pydantic item", tax=0.2),
|
2022-11-05 13:45:16 +04:00
|
|
|
],
|
|
|
|
|
)
|
|
|
|
|
def test_pickle_coder(value: Any) -> None:
|
|
|
|
|
encoded_value = PickleCoder.encode(value)
|
2023-05-09 18:17:28 +01:00
|
|
|
assert isinstance(encoded_value, bytes)
|
2022-11-05 13:45:16 +04:00
|
|
|
decoded_value = PickleCoder.decode(encoded_value)
|
|
|
|
|
assert decoded_value == value
|
2023-05-08 16:42:21 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
|
("value", "return_type"),
|
|
|
|
|
[
|
|
|
|
|
(1, None),
|
|
|
|
|
("some_string", None),
|
2023-05-09 15:30:46 +01:00
|
|
|
((1, 2), Tuple[int, int]),
|
2023-05-08 16:42:21 +01:00
|
|
|
([1, 2, 3], None),
|
|
|
|
|
({"some_key": 1, "other_key": 2}, None),
|
|
|
|
|
(DCItem(name="foo", price=42.0, description="some dataclass item", tax=0.2), DCItem),
|
|
|
|
|
(PDItem(name="foo", price=42.0, description="some pydantic item", tax=0.2), PDItem),
|
|
|
|
|
],
|
|
|
|
|
)
|
|
|
|
|
def test_json_coder(value: Any, return_type) -> None:
|
|
|
|
|
encoded_value = JsonCoder.encode(value)
|
2023-05-09 18:17:28 +01:00
|
|
|
assert isinstance(encoded_value, bytes)
|
2023-05-08 16:42:21 +01:00
|
|
|
decoded_value = JsonCoder.decode_as_type(encoded_value, type_=return_type)
|
|
|
|
|
assert decoded_value == value
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_json_coder_validation_error() -> None:
|
2023-05-09 18:17:28 +01:00
|
|
|
invalid = b'{"name": "incomplete"}'
|
2023-05-08 16:42:21 +01:00
|
|
|
with pytest.raises(ValidationError):
|
|
|
|
|
JsonCoder.decode_as_type(invalid, type_=PDItem)
|