|
| 1 | +"""Test methods in abstract.py. Uses hypothesis""" |
| 2 | +import json |
| 3 | +from datetime import date |
| 4 | +from datetime import datetime |
| 5 | +from ipaddress import IPv4Address |
| 6 | +from ipaddress import IPv6Address |
| 7 | +from typing import Dict |
| 8 | +from typing import List |
| 9 | +from typing import Tuple |
| 10 | +from typing import Union |
| 11 | + |
| 12 | +import pytest |
| 13 | +from hypothesis import given |
| 14 | +from hypothesis import strategies as st |
| 15 | +from pydantic_aioredis.model import Model |
| 16 | + |
| 17 | + |
| 18 | +class SimpleModel(Model): |
| 19 | + _primary_key_field: str = "test_str" |
| 20 | + test_str: str |
| 21 | + test_int: int |
| 22 | + test_float: float |
| 23 | + test_date: date |
| 24 | + test_datetime: datetime |
| 25 | + test_ip_v4: IPv4Address |
| 26 | + test_ip_v6: IPv6Address |
| 27 | + test_list: List |
| 28 | + test_dict: Dict[str, Union[int, float]] |
| 29 | + test_tuple: Tuple[str] |
| 30 | + |
| 31 | + |
| 32 | +parameters = [ |
| 33 | + (st.text, [], {}, "test_str", None), |
| 34 | + (st.integers, [], {}, "test_int", None), |
| 35 | + (st.floats, [], {"allow_nan": False}, "test_float", None), |
| 36 | + (st.dates, [], {}, "test_date", lambda x: json.dumps(x.isoformat())), |
| 37 | + (st.datetimes, [], {}, "test_datetime", lambda x: json.dumps(x.isoformat())), |
| 38 | + (st.ip_addresses, [], {"v": 4}, "test_ip_v4", lambda x: json.dumps(str(x))), |
| 39 | + (st.ip_addresses, [], {"v": 6}, "test_ip_v4", lambda x: json.dumps(str(x))), |
| 40 | + ( |
| 41 | + st.lists, |
| 42 | + [st.tuples(st.integers(), st.floats())], |
| 43 | + {}, |
| 44 | + "test_list", |
| 45 | + lambda x: json.dumps(x), |
| 46 | + ), |
| 47 | + ( |
| 48 | + st.dictionaries, |
| 49 | + [st.text(), st.tuples(st.integers(), st.floats())], |
| 50 | + {}, |
| 51 | + "test_dict", |
| 52 | + lambda x: json.dumps(x), |
| 53 | + ), |
| 54 | + (st.tuples, [st.text()], {}, "test_tuple", lambda x: json.dumps(x)), |
| 55 | +] |
| 56 | + |
| 57 | + |
| 58 | +@pytest.mark.parametrize( |
| 59 | + "strategy, strategy_args, strategy_kwargs, model_field, serialize_callable", |
| 60 | + parameters, |
| 61 | +) |
| 62 | +@given(st.data()) |
| 63 | +def test_serialize_partially( |
| 64 | + strategy, strategy_args, strategy_kwargs, model_field, serialize_callable, data |
| 65 | +): |
| 66 | + value = data.draw(strategy(*strategy_args, **strategy_kwargs)) |
| 67 | + serialized = SimpleModel.serialize_partially({model_field: value}) |
| 68 | + if serialize_callable is None: |
| 69 | + assert serialized[model_field] == value |
| 70 | + else: |
| 71 | + assert serialized[model_field] == serialize_callable(value) |
| 72 | + |
| 73 | + |
| 74 | +def test_serialize_partially_skip_missing_filed(): |
| 75 | + serialized = SimpleModel.serialize_partially({"unknown": "test"}) |
| 76 | + assert serialized["unknown"] == "test" |
0 commit comments