From 465bb97d14a0bdcbe11ce1c870e9452d5d0b0c77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Karao=C4=9Flu?= Date: Fri, 4 Dec 2026 10:49:56 +0300 Subject: [PATCH] Add hypothesis property-based roundtrip tests for all 95 Pydantic models --- tests/test_hypothesis_roundtrip.py | 236 +++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 tests/test_hypothesis_roundtrip.py diff --git a/tests/test_hypothesis_roundtrip.py b/tests/test_hypothesis_roundtrip.py new file mode 100644 index 0000000..a8db62a --- /dev/null +++ b/tests/test_hypothesis_roundtrip.py @@ -0,0 +1,236 @@ +"""Property-based roundtrip tests for all Pydantic models. + +Every _ApiModel subclass must survive a serialize/deserialize cycle: + model_validate(instance.model_dump(by_alias=True)) == instance + +Hypothesis generates arbitrary valid instances; failures shrink to +minimal reproducing examples. +""" + +from __future__ import annotations + +import types as builtin_types +import typing +from datetime import datetime, timezone +from typing import Any, Union, get_args, get_origin + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st +from pydantic import BaseModel +from pydantic.fields import FieldInfo +from pydantic.types import AwareDatetime + +from triggerdev._models import _ApiModel + +# --------------------------------------------------------------------------- +# Strategy infrastructure +# --------------------------------------------------------------------------- + +_aware_datetimes = st.datetimes( + min_value=datetime(2000, 1, 1), + max_value=datetime(2100, 1, 1), + timezones=st.just(timezone.utc), +) + +_json_primitives = ( + st.none() + | st.booleans() + | st.integers(-(2**31), 2**31) + | st.floats(allow_nan=False, allow_infinity=False) + | st.text(max_size=20) +) + +_json_values = st.recursive( + _json_primitives, + lambda children: st.lists(children, max_size=3) | st.dictionaries(st.text(max_size=10), children, max_size=3), + max_leaves=5, +) + +_strategy_cache: dict[type, st.SearchStrategy[Any]] = {} + + +def _extract_constraints(metadata: list[Any]) -> dict[str, Any]: + """Pull Ge, Le, MaxLen from Pydantic field metadata.""" + constraints: dict[str, Any] = {} + for m in metadata: + cls_name = type(m).__name__ + if cls_name == "Ge": + constraints["ge"] = m.ge + elif cls_name == "Le": + constraints["le"] = m.le + elif cls_name == "Gt": + constraints["gt"] = m.gt + elif cls_name == "Lt": + constraints["lt"] = m.lt + elif cls_name == "MaxLen": + constraints["max_length"] = m.max_length + elif cls_name == "MinLen": + constraints["min_length"] = m.min_length + return constraints + + +def _strategy_for_type(tp: Any, metadata: list[Any] | None = None) -> st.SearchStrategy[Any]: + """Build a hypothesis strategy for a type annotation.""" + origin = get_origin(tp) + args = get_args(tp) + constraints = _extract_constraints(metadata or []) + + if tp is type(None): + return st.none() + + if tp is Any: + return _json_values + + if tp is AwareDatetime: + return _aware_datetimes + + if origin is typing.Literal: + return st.sampled_from(args) + + if origin is Union or origin is builtin_types.UnionType: + return st.one_of([_strategy_for_type(a, metadata=metadata) for a in args]) + + if origin is list: + min_size = constraints.get("min_length", 0) + max_size = constraints.get("max_length", 5) + inner = _strategy_for_type(args[0]) if args else _json_values + return st.lists(inner, min_size=min_size, max_size=max_size) + + if origin is dict: + key_st = _strategy_for_type(args[0]) if args else st.text(max_size=10) + val_st = _strategy_for_type(args[1]) if len(args) > 1 else _json_values + return st.dictionaries(key_st, val_st, max_size=5) + + if origin is typing.Annotated: + base_type = args[0] + inner_metadata = list(args[1:]) + # FieldInfo wraps further metadata + for item in inner_metadata: + if isinstance(item, FieldInfo) and item.metadata: + inner_metadata.extend(item.metadata) + return _strategy_for_type(base_type, metadata=inner_metadata) + + if isinstance(tp, type) and issubclass(tp, BaseModel): + return _model_strategy(tp) + + if tp is str: + min_len = constraints.get("min_length", 0) + max_len = constraints.get("max_length", 50) + return st.text(min_size=min_len, max_size=max_len) + + if tp is int: + lo = constraints.get("ge", constraints.get("gt", -(2**31))) + hi = constraints.get("le", constraints.get("lt", 2**31)) + if "gt" in constraints: + lo = constraints["gt"] + 1 + if "lt" in constraints: + hi = constraints["lt"] - 1 + return st.integers(min_value=lo, max_value=hi) + + if tp is float: + return st.floats(allow_nan=False, allow_infinity=False) + + if tp is bool: + return st.booleans() + + return _json_values + + +def _model_strategy( + model_cls: type[BaseModel], +) -> st.SearchStrategy[Any]: + """Build a strategy for a Pydantic model, with caching.""" + if model_cls in _strategy_cache: + return _strategy_cache[model_cls] + deferred: st.SearchStrategy[Any] = st.deferred(lambda mc=model_cls: _build_model(mc)) + _strategy_cache[model_cls] = deferred + return deferred + + +def _build_model(model_cls: type[BaseModel]) -> st.SearchStrategy[Any]: + kwargs: dict[str, st.SearchStrategy[Any]] = {} + for name, field_info in model_cls.model_fields.items(): + field_metadata = list(field_info.metadata) if field_info.metadata else [] + kwargs[name] = _strategy_for_type(field_info.annotation, metadata=field_metadata) + return st.fixed_dictionaries(kwargs).map(lambda kw: model_cls(**kw)) + + +# --------------------------------------------------------------------------- +# Collect all _ApiModel subclasses +# --------------------------------------------------------------------------- + + +def _collect_models() -> list[type[_ApiModel]]: + """Import all type modules and collect _ApiModel subclasses.""" + import triggerdev.types.batches + import triggerdev.types.bulk_actions + import triggerdev.types.errors + import triggerdev.types.runs + import triggerdev.types.schedules + import triggerdev.types.sessions + import triggerdev.types.shared + import triggerdev.types.tasks + import triggerdev.types.waitpoints + import triggerdev.types.webhooks + + modules = [ + triggerdev.types.batches, + triggerdev.types.bulk_actions, + triggerdev.types.errors, + triggerdev.types.runs, + triggerdev.types.schedules, + triggerdev.types.sessions, + triggerdev.types.shared, + triggerdev.types.tasks, + triggerdev.types.waitpoints, + triggerdev.types.webhooks, + ] + + models: set[type[_ApiModel]] = set() + for mod in modules: + for attr_name in dir(mod): + obj = getattr(mod, attr_name) + if isinstance(obj, type) and issubclass(obj, _ApiModel) and obj is not _ApiModel: + models.add(obj) + + return sorted(models, key=lambda c: c.__name__) + + +ALL_MODELS = _collect_models() + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "model_cls", + ALL_MODELS, + ids=[m.__name__ for m in ALL_MODELS], +) +@given(data=st.data()) +@settings(max_examples=50, deadline=None) +def test_roundtrip_serialize_deserialize(model_cls: type[_ApiModel], data: st.DataObject) -> None: + """model_validate(instance.model_dump(by_alias=True)) == instance.""" + instance = data.draw(_model_strategy(model_cls)) + serialized = instance.model_dump(by_alias=True) + deserialized = model_cls.model_validate(serialized) + assert deserialized == instance + + +@pytest.mark.parametrize( + "model_cls", + ALL_MODELS, + ids=[m.__name__ for m in ALL_MODELS], +) +@given(data=st.data()) +@settings(max_examples=50, deadline=None) +def test_roundtrip_json_serialize_deserialize(model_cls: type[_ApiModel], data: st.DataObject) -> None: + """JSON is stable: serialize -> deserialize -> reserialize == original JSON.""" + instance = data.draw(_model_strategy(model_cls)) + json_bytes = instance.model_dump_json(by_alias=True) + deserialized = model_cls.model_validate_json(json_bytes) + reserialized = deserialized.model_dump_json(by_alias=True) + assert reserialized == json_bytes