|
| 1 | +import gc |
| 2 | +import platform |
| 3 | +from typing import Any |
| 4 | +from weakref import WeakValueDictionary |
| 5 | + |
| 6 | +import pytest |
| 7 | + |
| 8 | +from pydantic_core import SchemaSerializer, SchemaValidator, core_schema |
| 9 | + |
| 10 | + |
| 11 | +@pytest.mark.xfail( |
| 12 | + condition=platform.python_implementation() == 'PyPy', reason='https://foss.heptapod.net/pypy/pypy/-/issues/3899' |
| 13 | +) |
| 14 | +def test_gc_schema_serializer() -> None: |
| 15 | + # test for https://github.com/pydantic/pydantic/issues/5136 |
| 16 | + class BaseModel: |
| 17 | + __schema__: SchemaSerializer |
| 18 | + |
| 19 | + def __init_subclass__(cls) -> None: |
| 20 | + cls.__schema__ = SchemaSerializer( |
| 21 | + core_schema.model_schema( |
| 22 | + cls, |
| 23 | + core_schema.typed_dict_schema( |
| 24 | + {'x': core_schema.typed_dict_field(core_schema.definition_reference_schema('model'))} |
| 25 | + ), |
| 26 | + ref='model', |
| 27 | + ) |
| 28 | + ) |
| 29 | + |
| 30 | + cache: 'WeakValueDictionary[int, Any]' = WeakValueDictionary() |
| 31 | + |
| 32 | + for _ in range(10_000): |
| 33 | + |
| 34 | + class MyModel(BaseModel): |
| 35 | + pass |
| 36 | + |
| 37 | + cache[id(MyModel)] = MyModel |
| 38 | + |
| 39 | + del MyModel |
| 40 | + |
| 41 | + gc.collect(0) |
| 42 | + gc.collect(1) |
| 43 | + gc.collect(2) |
| 44 | + |
| 45 | + assert len(cache) == 0 |
| 46 | + |
| 47 | + |
| 48 | +@pytest.mark.xfail( |
| 49 | + condition=platform.python_implementation() == 'PyPy', reason='https://foss.heptapod.net/pypy/pypy/-/issues/3899' |
| 50 | +) |
| 51 | +def test_gc_schema_validator() -> None: |
| 52 | + # test for https://github.com/pydantic/pydantic/issues/5136 |
| 53 | + class BaseModel: |
| 54 | + __validator__: SchemaValidator |
| 55 | + |
| 56 | + def __init_subclass__(cls) -> None: |
| 57 | + cls.__validator__ = SchemaValidator( |
| 58 | + core_schema.model_schema( |
| 59 | + cls, |
| 60 | + core_schema.typed_dict_schema( |
| 61 | + {'x': core_schema.typed_dict_field(core_schema.definition_reference_schema('model'))} |
| 62 | + ), |
| 63 | + ref='model', |
| 64 | + ) |
| 65 | + ) |
| 66 | + |
| 67 | + cache: 'WeakValueDictionary[int, Any]' = WeakValueDictionary() |
| 68 | + |
| 69 | + for _ in range(10_000): |
| 70 | + |
| 71 | + class MyModel(BaseModel): |
| 72 | + pass |
| 73 | + |
| 74 | + cache[id(MyModel)] = MyModel |
| 75 | + |
| 76 | + del MyModel |
| 77 | + |
| 78 | + gc.collect(0) |
| 79 | + gc.collect(1) |
| 80 | + gc.collect(2) |
| 81 | + |
| 82 | + assert len(cache) == 0 |
0 commit comments