repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
pydantic
tests/test_types_typeddict.py
.py
""" Tests for TypedDict """ import sys import typing from typing import Annotated, Any, Generic, Optional, TypeVar import pytest import typing_extensions from annotated_types import Lt from pydantic_core import core_schema from typing_extensions import NotRequired, ReadOnly, Required, TypedDict from pydantic import ...
1,141
33,614
pydantic
tests/test_deprecated_validate_arguments.py
.py
import asyncio import inspect from pathlib import Path from typing import Annotated import pytest from dirty_equals import IsInstance from pydantic import BaseModel, Field, PydanticDeprecatedSince20, ValidationError from pydantic.deprecated.decorator import ValidatedFunction from pydantic.deprecated.decorator import ...
392
12,261
pydantic
tests/test_version.py
.py
from unittest.mock import patch import pytest from packaging.version import parse as parse_version import pydantic from pydantic.version import check_pydantic_core_version, version_info, version_short def test_version_info(): version_info_fields = [ 'pydantic version', 'pydantic-core version', ...
48
1,222
pydantic
tests/test_type_hints.py
.py
""" Test pydantic model type hints (annotations) and that they can be queried by :py:meth:`typing.get_type_hints`. """ import inspect from functools import lru_cache from typing import ( Any, Generic, TypeVar, ) import pytest import typing_extensions from pydantic import ( BaseModel, RootModel, )...
165
4,905
pydantic
tests/test_computed_fields.py
.py
import random import sys from abc import ABC, abstractmethod from collections.abc import Callable from functools import cached_property, lru_cache, singledispatchmethod from typing import Annotated, Any, ClassVar, Generic, TypeVar import pytest from pydantic_core import ValidationError, core_schema from typing_extensi...
896
26,096
pydantic
tests/test_parse.py
.py
import pytest from pydantic_core import CoreSchema from pydantic import BaseModel, GetJsonSchemaHandler, PydanticUserError, ValidationError, model_validator, parse_obj_as from pydantic.functional_serializers import model_serializer from pydantic.json_schema import JsonSchemaValue class Model(BaseModel): a: float...
257
7,459
pydantic
tests/test_networks.py
.py
import json import operator from typing import Annotated, Any import pytest from pydantic_core import MultiHostHost, PydanticCustomError, PydanticSerializationError, Url from pydantic import ( AfterValidator, AmqpDsn, AnyHttpUrl, AnyUrl, BaseModel, ClickHouseDsn, CockroachDsn, Field, ...
1,282
46,700
pydantic
tests/test_serialize.py
.py
""" New tests for v2 of serialization logic. """ import json import re import sys from collections.abc import Callable from enum import Enum from functools import partial, partialmethod from re import Pattern from typing import Annotated, Any, ClassVar, Optional import pytest from pydantic_core import PydanticSeriali...
1,440
43,502
pydantic
tests/test_type_adapter.py
.py
import json from dataclasses import dataclass from datetime import date, datetime from typing import Annotated, Any, ForwardRef, Generic, NamedTuple, TypeAlias, TypeVar, Union import pytest from pydantic_core import ValidationError from typing_extensions import TypedDict from pydantic import BaseModel, Field, TypeAda...
760
29,048
pydantic
tests/test_annotated.py
.py
import datetime as dt from collections.abc import Callable, Iterator from dataclasses import dataclass from decimal import Decimal from typing import Annotated, Any, Generic, TypeVar import pytest import pytz from annotated_types import BaseMetadata, GroupedMetadata, Gt, Lt, Not, Predicate from pydantic_core import Co...
641
21,259
pydantic
tests/test_json_schema.py
.py
import dataclasses import json import math import re import sys import typing from collections import deque from collections.abc import Callable, Iterable, Sequence from datetime import date, datetime, time, timedelta from decimal import Decimal from enum import Enum, IntEnum from ipaddress import IPv4Address, IPv4Inte...
7,330
234,488
pydantic
tests/test_pipeline.py
.py
"""Tests for the experimental transform module.""" from __future__ import annotations import datetime import re from collections.abc import Callable from decimal import Decimal from typing import Annotated, Any import pytest import pytz from annotated_types import Interval from pydantic import TypeAdapter, Validati...
551
22,245
pydantic
tests/test_aliases.py
.py
from contextlib import AbstractContextManager from contextlib import nullcontext as does_not_raise from inspect import signature from typing import Any import pytest from dirty_equals import IsStr from pydantic_core import PydanticUndefined from pydantic import ( AliasChoices, AliasGenerator, AliasPath, ...
907
30,000
pydantic
tests/test_internal.py
.py
""" Tests for internal things that are complex enough to warrant their own unit tests. """ import sys from copy import deepcopy from dataclasses import dataclass from decimal import Decimal from typing import Any import pytest from dirty_equals import Contains, IsPartialDict from pydantic_core import CoreSchema, Pyda...
291
9,759
pydantic
tests/test_typing.py
.py
from collections import namedtuple from typing import Annotated, ClassVar, ForwardRef, NamedTuple import pytest from pydantic import BaseModel, Field # noqa: F401 from pydantic._internal._typing_extra import ( NoneType, get_function_type_hints, is_classvar_annotation, is_namedtuple, parent_frame_...
105
3,111
pydantic
tests/test_networks_ipaddress.py
.py
import json from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from typing import Any import pytest from pydantic import BaseModel, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, ValidationError from pydantic.config import ConfigDict @pytest.mark.parametrize( ...
492
15,794
pydantic
tests/test_callable.py
.py
import typing from collections.abc import Callable as CollectionsCallable import pytest from pydantic import BaseModel, ValidationError collection_callable_types = [ pytest.param(typing.Callable, id='typing_Callable'), pytest.param(typing.Callable[[int], int], id='typing_Callable_parameterized'), pytest....
32
930
pydantic
tests/test_dunder_all.py
.py
def test_explicit_reexports() -> None: from pydantic import __all__ as root_all from pydantic.deprecated.tools import __all__ as tools from pydantic.main import __all__ as main from pydantic.networks import __all__ as networks from pydantic.types import __all__ as types for name, export_all in ...
18
777
pydantic
tests/test_validators.py
.py
import contextlib import re from collections import deque from collections.abc import Callable from dataclasses import dataclass from datetime import date, datetime from enum import Enum from functools import partial, partialmethod from itertools import product from os.path import normcase from typing import ( Anno...
3,180
92,250
pydantic
tests/test_dataclasses.py
.py
import dataclasses import inspect import pickle import re import sys import traceback from collections.abc import Callable, Hashable from dataclasses import InitVar from datetime import date, datetime from functools import cached_property from pathlib import Path from typing import ( Annotated, Any, ClassVa...
3,348
93,866
pydantic
tests/test_experimental_arguments_schema.py
.py
from typing import Annotated, Any, Generic, Literal, TypeVar import pytest from pydantic_core import ArgsKwargs, SchemaValidator from typing_extensions import TypedDict, Unpack from pydantic import AliasGenerator, Field, PydanticUserError, ValidationError from pydantic.experimental.arguments_schema import generate_ar...
189
5,623
pydantic
tests/test_model_validator.py
.py
from __future__ import annotations from typing import Any, cast import pytest from pydantic import ( BaseModel, PydanticDeprecatedSince212, ValidationInfo, ValidatorFunctionWrapHandler, model_validator, ) def test_model_validator_wrap() -> None: class Model(BaseModel): x: int ...
196
6,142
pydantic
tests/test_docs_extraction.py
.py
import sys import textwrap from dataclasses import dataclass, field from typing import Annotated, Generic, TypeVar import pytest from typing_extensions import TypedDict from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, create_model, with_config from pydantic.dataclasses import dataclass as pydantic_data...
434
11,095
pydantic
tests/test_json.py
.py
import json import math import re import sys from collections.abc import Generator from dataclasses import dataclass as vanilla_dataclass from datetime import date, datetime, time, timedelta, timezone from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Ad...
589
19,199
pydantic
tests/test_allow_partial.py
.py
from typing import Annotated import pytest from annotated_types import Ge from typing_extensions import TypedDict from pydantic import TypeAdapter, ValidationError from .conftest import Err @pytest.mark.parametrize( 'mode,value,expected', [ ('python', {'a': 1, 'b': 'b', 'c': (3, '4')}, {'a': 1, 'b'...
88
3,745
pydantic
tests/test_migration.py
.py
import importlib import pytest from pydantic._migration import DEPRECATED_MOVED_IN_V2, MOVED_IN_V2, REDIRECT_TO_V1, REMOVED_IN_V2, getattr_migration from pydantic.errors import PydanticImportError from pydantic.version import version_short from pydantic.warnings import PydanticDeprecatedSince20 def import_from(dott...
64
2,209
pydantic
tests/test_types_payment_card_number.py
.py
from collections import namedtuple from typing import Any import pytest from pydantic_core import PydanticCustomError from pydantic import BaseModel, ValidationError from pydantic.types import PaymentCardBrand, PaymentCardNumber pytestmark = pytest.mark.filterwarnings( 'ignore:The `PaymentCardNumber` class is de...
157
5,153
pydantic
tests/test_assert_in_validators.py
.py
""" PYTEST_DONT_REWRITE """ import difflib import pprint import pytest from dirty_equals import HasRepr from pydantic import BaseModel, ValidationError, field_validator def _pformat_lines(obj): return pprint.pformat(obj).splitlines(keepends=True) def _assert_eq(left, right): if left != right: pyt...
50
1,111
pydantic
tests/test_color.py
.py
from datetime import datetime import pytest from pydantic_core import PydanticCustomError from pydantic import BaseModel, ValidationError from pydantic.color import Color pytestmark = pytest.mark.filterwarnings( 'ignore:The `Color` class is deprecated, use `pydantic_extra_types` instead.*:DeprecationWarning' ) ...
226
7,751
pydantic
tests/test_deferred_annotations.py
.py
"""Tests related to deferred evaluation of annotations introduced in Python 3.14 by PEP 649 and 749.""" import sys from dataclasses import field from typing import Annotated import pytest from annotated_types import MaxLen from pydantic import ( BaseModel, Field, TypeAdapter, ValidationError, fie...
157
3,527
pydantic
tests/test_pickle.py
.py
import dataclasses import gc import pickle import platform import subprocess import sys from pathlib import Path from textwrap import dedent from typing import TYPE_CHECKING import pytest import pydantic from pydantic import BaseModel, PositiveFloat, ValidationError from pydantic._internal._model_construction import ...
392
11,505
pydantic
tests/test_forward_ref.py
.py
import dataclasses import platform import re import sys import typing from typing import Annotated, Any, Generic, Optional, TypeVar, Union import pytest from annotated_types import Gt from typing_extensions import get_args, get_origin # noqa: UP035 from typing_inspection import typing_objects from pydantic import Ba...
1,686
45,219
pydantic
tests/test_serialize_as_any.py
.py
import json import pytest from typing_extensions import TypedDict from pydantic import BaseModel, ConfigDict, RootModel, SecretStr, SerializeAsAny, TypeAdapter from .utils import dataclass_decorators class User(BaseModel): name: str class UserLogin(User): password: SecretStr user = User(name='pydantic'...
212
6,598
pydantic
tests/test_abc.py
.py
import abc import sys import pytest from pydantic import BaseModel def test_model_subclassing_abstract_base_classes(): class Model(BaseModel, abc.ABC): some_field: str @pytest.mark.skipif(sys.version_info < (3, 12), reason='error value different on older versions') def test_model_subclassing_abstract_...
60
1,557
pydantic
tests/test_validate_call.py
.py
import asyncio import inspect import pickle import re import sys from collections import UserDict from datetime import datetime, timezone from functools import partial from typing import Annotated, Any, Generic, Literal, TypeVar import pytest from pydantic_core import ArgsKwargs from typing_extensions import Required,...
1,332
38,327
pydantic
tests/test_decorators.py
.py
import pytest from pydantic import BaseModel, PydanticUserError, computed_field from pydantic._internal._decorators import inspect_annotated_serializer, inspect_field_serializer, inspect_validator def _two_pos_required_args(a, b): pass def _two_pos_required_args_extra_optional(a, b, c=1, d=2, *, e=3): pass...
141
4,354
pydantic
tests/test_warnings.py
.py
from pydantic import PydanticDeprecatedSince20, PydanticDeprecationWarning from pydantic.version import version_short def test_pydantic_deprecation_warning(): warning = PydanticDeprecationWarning('Warning message', 'Arbitrary argument', since=(2, 1), expected_removal=(4, 0)) assert str(warning) == 'Warning m...
42
1,692
pydantic
tests/test_plugins.py
.py
from __future__ import annotations import contextlib from collections.abc import Generator from functools import partial from typing import Any import pytest from pydantic_core import ValidationError from pydantic import BaseModel, TypeAdapter, create_model, dataclasses, field_validator, validate_call from pydantic....
541
19,098
pydantic
tests/test_docs.py
.py
from __future__ import annotations as _annotations import os import platform import re import subprocess import sys from datetime import datetime from pathlib import Path from tempfile import NamedTemporaryFile from typing import Any import pytest from pydantic_core import core_schema from pydantic.errors import Pyd...
294
10,734
pydantic
tests/test_fields.py
.py
import copy from typing import Annotated, Any, Final, Generic, TypeVar import pytest from annotated_types import Gt from pydantic_core import PydanticUndefined from typing_extensions import TypeAliasType import pydantic.dataclasses from pydantic import ( AfterValidator, BaseModel, ConfigDict, Field, ...
476
14,632
pydantic
tests/test_model_signature.py
.py
import sys from collections.abc import Iterable from inspect import Parameter, Signature, signature from typing import Annotated, Any, Generic, TypeVar import pytest from annotated_types import Gt from typing_extensions import get_origin # noqa: UP035 from typing_inspection import typing_objects from pydantic import...
194
6,035
pydantic
tests/test_validation_context.py
.py
from typing import Annotated import pytest from typing_extensions import TypedDict from pydantic import TypeAdapter, ValidationError, ValidationInfo, ValidatorFunctionWrapHandler, WrapValidator def test_context(): def f(value, handler: ValidatorFunctionWrapHandler, info: ValidationInfo): return handler(...
84
3,374
pydantic
tests/test_types.py
.py
import ipaddress import json import math import os import re import sys import warnings from collections.abc import Callable, Sequence from dataclasses import dataclass from datetime import date, datetime, timedelta from decimal import Decimal from enum import Enum from typing import ( Annotated, Any, Liter...
2,427
79,564
pydantic
tests/test_main.py
.py
import json import platform import re import sys import threading import typing import warnings from collections import defaultdict from collections.abc import Callable, Mapping from copy import deepcopy from dataclasses import dataclass from datetime import date, datetime from enum import Enum from functools import ca...
3,904
114,383
pydantic
tests/test_strict.py
.py
from typing import Annotated, Any import pytest from pydantic import BaseModel, ConfigDict, Field, ValidationError @pytest.fixture(scope='session', name='ModelWithStrictField') def model_with_strict_field(): class ModelWithStrictField(BaseModel): a: Annotated[int, Field(strict=True)] return ModelWi...
88
3,075
pydantic
tests/test_edge_cases.py
.py
import functools import importlib.util import re import sys import typing from abc import ABC, abstractmethod from collections.abc import Callable, Hashable, Sequence from decimal import Decimal from enum import Enum, auto from typing import ( Annotated, Any, ForwardRef, Generic, Literal, Option...
3,212
97,524
pydantic
tests/test_utils.py
.py
import collections.abc import os import pickle import time from collections.abc import Callable from copy import copy, deepcopy from typing import Annotated, Generic, TypeVar, Union import pytest from pydantic_core import PydanticCustomError, PydanticUndefined from pydantic import BaseModel from pydantic._internal im...
522
16,470
pydantic
tests/test_tools.py
.py
from collections.abc import Mapping import pytest from pydantic import BaseModel, PydanticDeprecatedSince20, ValidationError from pydantic.dataclasses import dataclass from pydantic.deprecated.tools import parse_obj_as, schema_json_of, schema_of pytestmark = pytest.mark.filterwarnings('ignore::DeprecationWarning') ...
96
2,656
pydantic
tests/test_root_model.py
.py
import importlib.util import inspect import pickle import typing from datetime import date, datetime from typing import Annotated, Any, Generic, Literal, TypeVar import pytest from pydantic_core import CoreSchema from pydantic_core.core_schema import SerializerFunctionWrapHandler from pydantic import ( Base64Str,...
753
21,231
pydantic
tests/test_v1.py
.py
import sys import warnings import pytest from pydantic import VERSION from pydantic import BaseModel as V2BaseModel from pydantic.v1 import VERSION as V1_VERSION from pydantic.v1 import BaseModel as V1BaseModel from pydantic.v1 import root_validator as v1_root_validator def test_version(): assert V1_VERSION.sta...
51
1,286
pydantic
tests/test_titles.py
.py
import re import typing from typing import Any import pytest import typing_extensions from _pytest.mark.structures import ParameterSet import pydantic from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, computed_field from pydantic.fields import FieldInfo from pydantic.json_schema import model_json_schema...
495
17,858
pydantic
tests/test_construction.py
.py
import pickle from typing import Any import pytest from pydantic_core import PydanticUndefined, ValidationError from pydantic import AliasChoices, AliasPath, BaseModel, ConfigDict, Field, PrivateAttr, PydanticDeprecatedSince20 class Model(BaseModel): a: float b: int = 10 def test_simple_construct(): m...
672
18,634
pydantic
tests/test_type_alias_type.py
.py
import datetime from collections.abc import Sequence from dataclasses import dataclass from typing import Annotated, Generic, Literal, TypeVar, Union import pytest from annotated_types import MaxLen from typing_extensions import TypeAliasType from pydantic import BaseModel, PlainSerializer, PydanticUserError, TypeAda...
491
16,574
pydantic
tests/conftest.py
.py
from __future__ import annotations import importlib.util import inspect import os import re import secrets import subprocess import sys import textwrap from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from types import FunctionType, ModuleType from typing import Any impo...
229
8,050
pydantic
tests/typechecking/misc.py
.py
from pydantic import BaseModel class Sub(BaseModel): a: int b: int class Model(BaseModel): subs: list[Sub] def func(model: Model) -> None: model.model_dump( include={'a': {1: True}}, ) model.model_dump( include={'a': {'__all__': True}}, ) model.model_dump( i...
31
567
pydantic
tests/typechecking/pipeline_api.py
.py
import datetime from pathlib import Path from typing import Annotated from pydantic import FilePath, NewPath from pydantic.experimental.pipeline import validate_as # TODO: since Pyright 1.1.384, support for PEP 746 was disabled. # `a1` and `a2` should have a `pyright: ignore[reportInvalidTypeArguments]` comment. a1 =...
28
1,181
pydantic
tests/typechecking/fields.py
.py
from pydantic import BaseModel, Field, PrivateAttr # private attributes should be excluded from # the synthesized `__init__` method: class ModelWithPrivateAttr(BaseModel): _private_field: str = PrivateAttr() m = ModelWithPrivateAttr() def new_list() -> list[int]: return [] class Model(BaseModel): # ...
46
2,146
pydantic
tests/typechecking/with_config_decorator.py
.py
from typing import TypedDict from typing_extensions import assert_type from pydantic import ConfigDict, with_config @with_config(ConfigDict(str_to_lower=True)) class Model1(TypedDict): a: str @with_config(str_to_lower=True) class Model2(TypedDict): pass @with_config(config=ConfigDict(str_to_lower=True))...
28
509
pydantic
tests/typechecking/secret.py
.py
from pydantic import Secret def takes_secret(scalar_secret: Secret[str | int | float | bool]) -> None: ... def secret_usage() -> None: secret: Secret[str] = Secret('my secret') takes_secret(secret)
10
210
pydantic
tests/typechecking/json_schema_examples.py
.py
from pydantic.json_schema import Examples e_good = Examples([]) e_deprecated = Examples({}) # type: ignore[deprecated] # pyright: ignore[reportDeprecated]
5
158
pydantic
tests/typechecking/validate_call.py
.py
from typing_extensions import assert_type from pydantic import validate_call @validate_call def foo(a: int, *, c: str = 'x') -> str: return c * a a = foo(1, c='a') assert_type(a, str) foo('', c=1) # type: ignore[arg-type] # pyright: ignore[reportArgumentType] # Not possible to type check currently (see htt...
28
655
pydantic
tests/typechecking/base_model.py
.py
""" This file is used to test pyright's ability to check Pydantic's `BaseModel` related code. """ from typing_extensions import assert_type from pydantic import BaseModel, Field from pydantic.fields import ComputedFieldInfo, FieldInfo class MyModel(BaseModel): x: str y: list[int] z: int = 1 m1 = MyMod...
39
1,350
pydantic
tests/typechecking/decorators.py
.py
""" This file is used to test pyright's ability to check Pydantic decorators used in `BaseModel`. """ from functools import partial, partialmethod from typing import Any from pydantic_core.core_schema import ValidatorFunctionWrapHandler from typing_extensions import Self, assert_type from pydantic import ( BaseM...
311
11,790
pydantic
tests/typechecking/type_adapter.py
.py
# to be removed with PEP 747: # mypy: disable_error_code=var-annotated from typing import Annotated from typing_extensions import assert_type from pydantic import TypeAdapter ta1 = TypeAdapter(int) assert_type(ta1, TypeAdapter[int]) assert_type(ta1.validate_python('1'), int) ta1.dump_python(1) ta1.dump_python('1') ...
28
925
pydantic
tests/typechecking/root_model.py
.py
from typing_extensions import assert_type from pydantic import RootModel IntRootModel = RootModel[int] int_root_model = IntRootModel(1) bad_root_model = IntRootModel('1') # type: ignore[arg-type] # pyright: ignore[reportArgumentType] assert_type(int_root_model.root, int) class StrRootModel(RootModel[str]): ...
20
406
pydantic
tests/typechecking/computed_field.py
.py
from functools import cached_property from pydantic import BaseModel, computed_field class Square(BaseModel): side: float # mypy limitation, see: # https://mypy.readthedocs.io/en/stable/error_code_list.html#decorator-preceding-property-not-supported-prop-decorator @computed_field # type: ignore[pro...
27
799
pydantic
tests/benchmarks/test_imports.py
.py
import pytest @pytest.mark.benchmark def test_import_basemodel(benchmark) -> None: @benchmark def run(): from pydantic import BaseModel assert BaseModel @pytest.mark.benchmark def test_import_field(benchmark) -> None: @benchmark def run(): from pydantic import Field ...
20
334
pydantic
tests/benchmarks/basemodel_eq_performance.py
.py
from __future__ import annotations import dataclasses import enum import gc import itertools import operator import sys import textwrap import timeit from collections.abc import Callable, Iterable, Sized from importlib import metadata from typing import TYPE_CHECKING, Any, Generic, TypeVar # Do not import additional ...
616
22,826
pydantic
tests/benchmarks/test_model_serialization.py
.py
import pytest from pydantic import BaseModel from .shared import ComplexModel, NestedModel, OuterModel, SimpleModel @pytest.mark.benchmark(group='model_serialization') def test_simple_model_serialization(benchmark): model = SimpleModel(field1='test', field2=42, field3=3.14) benchmark(model.model_dump) @py...
41
1,426
pydantic
tests/benchmarks/test_attribute_access.py
.py
from functools import cached_property import pytest from pydantic import BaseModel, ConfigDict, ValidationError class InnerValidateAssignment(BaseModel): model_config = ConfigDict(validate_assignment=True) inner_field1: str inner_field2: int class Model(BaseModel): field1: str field2: int ...
85
2,311
pydantic
tests/benchmarks/test_model_eq.py
.py
from pydantic import BaseModel, create_model ModelNoExtra = create_model( 'ModelNoExtra', __config__={'extra': 'forbid'}, **{f'f{i}': (int, i) for i in range(30)}, # pyright: ignore ) ModelExtra = create_model( 'ModelNoExtra', __config__={'extra': 'allow'}, **{f'f{i}': (int, i) for i in range...
39
907
pydantic
tests/benchmarks/test_model_schema_generation.py
.py
import sys from collections.abc import Mapping, Sequence from typing import ( Annotated, Any, Generic, Literal, TypeVar, Union, get_origin, ) import pytest from typing_extensions import Self, type_repr from pydantic import ( AfterValidator, BaseModel, BeforeValidator, Discr...
380
11,511
pydantic
tests/benchmarks/test_validators_build.py
.py
from pydantic import BaseModel, computed_field, field_validator def test_validators_build(benchmark) -> None: class Base1(BaseModel): a: int @field_validator('a', mode='after') @classmethod def val_a(cls, value: int) -> int: ... @computed_field def prop(self) -> i...
40
918
pydantic
tests/benchmarks/shared.py
.py
from collections import deque from collections.abc import Callable, Iterable, Sequence from datetime import date, datetime, time, timedelta from decimal import Decimal from enum import Enum, IntEnum from ipaddress import ( IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6...
233
4,901
pydantic
tests/benchmarks/test_fastapi_startup_generics.py
.py
"""https://github.com/pydantic/pydantic/issues/6768""" from __future__ import annotations from pathlib import Path from typing import Annotated, Any, Generic, TypeVar from pydantic import BaseModel, TypeAdapter, create_model from pydantic.fields import FieldInfo TYPES_DEFAULTS = {int: 0, str: '', bool: False} # so...
144
4,435
pydantic
tests/benchmarks/test_isinstance.py
.py
from pydantic import BaseModel class ModelV2(BaseModel): my_str: str mv2 = ModelV2(my_str='hello') def test_isinstance_basemodel(benchmark) -> None: @benchmark def run(): for _ in range(10000): assert isinstance(mv2, BaseModel)
16
266
pydantic
tests/benchmarks/test_model_schema_generation_recursive.py
.py
from typing import Generic, Literal, Optional, TypeVar, Union import pytest from pydantic import Field from .shared import DeferredModel, rebuild_model @pytest.mark.benchmark(group='model_schema_generation_recursive') def test_simple_recursive_model_schema_generation(benchmark): class Foo(DeferredModel): ...
87
2,381
pydantic
tests/benchmarks/test_model_validation.py
.py
import pytest from pydantic import BaseModel from .shared import ComplexModel, OuterModel, SimpleModel pytestmark = [ pytest.mark.benchmark(group='model_validation'), pytest.mark.parametrize('method', ['model_validate', '__init__']), ] def test_simple_model_validation(method: str, benchmark): data = {'...
46
1,562
pydantic
tests/benchmarks/test_discriminated_unions.py
.py
from __future__ import annotations from typing import Annotated, Literal, Union import pytest from pydantic import BaseModel, Field, TypeAdapter class NestedState(BaseModel): state_type: Literal['nested'] substate: AnyState class LoopState(BaseModel): state_type: Literal['loop'] substate: AnyStat...
53
1,300
pydantic
tests/benchmarks/generate_north_star_data.py
.py
from collections.abc import Callable from datetime import datetime from typing import Any, TypeVar, Union from faker import Faker f = Faker() Faker.seed(0) T = TypeVar('T') ## Helper functions # by default faker uses upper bound of now for datetime, which # is not helpful for reproducing benchmark data _END_DATET...
129
3,258
pydantic
tests/benchmarks/test_regex.py
.py
from typing import Annotated, Any from pydantic import Field, create_model from .shared import DeferredModel, rebuild_model def test_repeated_regex_pattern(benchmark): ConstraintType = Annotated[str, Field(pattern='^(\\p{L}|_)(\\p{L}|\\p{N}|[.\\-_])*$')] fields: dict[str, Any] = {f'f{i}': ConstraintType fo...
16
457
pydantic
tests/benchmarks/test_north_star.py
.py
""" An integration-style benchmark of a model with a class of what should (hopefully) be some of the most common field types used in pydantic validation. Used to gauge overall pydantic performance. """ import json from datetime import date, datetime, time from decimal import Decimal from pathlib import Path from typi...
125
4,015
pydantic
tests/benchmarks/test_fastapi_startup_simple.py
.py
"""https://github.com/pydantic/pydantic/issues/6768""" from __future__ import annotations from collections.abc import Callable from datetime import datetime from pathlib import Path from typing import Annotated, Any from uuid import UUID import pytest from annotated_types import Gt from pydantic import AnyUrl, Base...
118
3,226
pydantic
tests/plugin/test_plugin.py
.py
import os import pytest pytestmark = pytest.mark.skipif(not os.getenv('TEST_PLUGIN'), reason='Test only with `TEST_PLUGIN` env var set.') def test_plugin_usage(): from pydantic import BaseModel class MyModel(BaseModel): x: int y: str m = MyModel(x='10', y='hello') assert m.x == 10 ...
25
543
pydantic
tests/plugin/example_plugin.py
.py
from pydantic import BaseModel class MyModel(BaseModel): x: int m = MyModel(x='10') if m.x != 10: raise ValueError('m.x should be 10') log = [] class ValidatePythonHandler: def on_enter(self, *args, **kwargs) -> None: log.append(f'on_enter args={args} kwargs={kwargs}') def on_success(sel...
32
676
pydantic
tests/types/test_literal.py
.py
import typing from typing import Literal import pytest import typing_extensions from pydantic import TypeAdapter, ValidationError def test_literal_single(): ta = TypeAdapter(Literal['a']) assert ta.validate_python('a') == 'a' with pytest.raises(ValidationError) as exc_info: ta.validate_python('...
58
1,541
pydantic
tests/types/test_fraction.py
.py
from decimal import Decimal from fractions import Fraction from typing import Annotated import annotated_types import pytest from pydantic import Field, TypeAdapter, ValidationError class FractionSubclass(Fraction): pass @pytest.mark.parametrize( 'input_value,expected', [ (0, Fraction(0)), ...
228
6,547
pydantic
tests/types/test_ordered_dict.py
.py
import collections import typing from collections import OrderedDict import pytest from pydantic import TypeAdapter, ValidationError def test_ordered_dict(): ta = TypeAdapter(OrderedDict) assert ta.validate_python(OrderedDict([(1, 10), (2, 20)])) == OrderedDict([(1, 10), (2, 20)]) assert ta.validate_py...
81
2,359
pydantic
tests/types/test_mapping.py
.py
from collections import UserDict from collections.abc import Mapping, MutableMapping from typing import Any import pytest from pydantic import ConfigDict, PydanticSchemaGenerationError, TypeAdapter, ValidationError def test_mapping_subclass_without_core_schema() -> None: class MyDict(dict[int, int]): # ...
46
1,891
pydantic
tests/types/test_pattern.py
.py
import re from re import Pattern from typing import Annotated import pytest from pydantic import BaseModel, Field, PydanticSchemaGenerationError, StringConstraints, TypeAdapter, ValidationError @pytest.mark.parametrize( ('pattern_type', 'pattern_value', 'matching_value', 'non_matching_value'), [ pyt...
149
5,046
pydantic
tests/types/test_ellipsis.py
.py
from types import EllipsisType import pytest from pydantic_core import PydanticSerializationError, PydanticSerializationUnexpectedValue from pydantic import TypeAdapter def test_ellipsis_literal() -> None: ta = TypeAdapter(EllipsisType) assert ta.validate_python(...) is ... assert ta.dump_python(...) i...
22
583
pydantic
tests/types/test_namedtuple.py
.py
from collections import namedtuple from collections.abc import Mapping from typing import Annotated, Generic, NamedTuple, Optional, TypeVar import pytest from typing_extensions import NamedTuple as TypingExtensionsNamedTuple from pydantic import BaseModel, ConfigDict, Field, PlainSerializer, PositiveInt, TypeAdapter,...
536
15,219
pydantic
tests/types/test_iterable.py
.py
import itertools import re from collections.abc import Iterable from typing import Annotated, Any import pytest from pydantic import ( BaseModel, ConfigDict, Field, PydanticSchemaGenerationError, TypeAdapter, ValidationError, field_validator, ) def test_infinite_iterable_int(): def i...
192
5,216
pydantic
tests/types/test_date.py
.py
from datetime import date, datetime from decimal import Decimal from typing import Annotated import pytest from pydantic import Field, TypeAdapter, ValidationError @pytest.mark.parametrize( 'value,expected', [ (date(2017, 5, 5), date(2017, 5, 5)), (datetime(2017, 5, 5), date(2017, 5, 5)), ...
82
2,616
pydantic
tests/types/test_bytes.py
.py
from typing import Annotated import annotated_types import pytest from pydantic import BaseModel, Field, Strict, StrictBytes, TypeAdapter, ValidationError @pytest.mark.parametrize( 'value,expected', [ pytest.param('s', b's', id='s_str'), pytest.param(' s ', b' s ', id='s_str_untouched'),...
153
4,843
pydantic
tests/types/test_enum.py
.py
import re from enum import Enum, IntEnum from typing import Annotated, Any, NamedTuple import pytest from dirty_equals import IsStr from pydantic_core import CoreSchema, core_schema from pydantic import ( BaseModel, ConfigDict, Field, GetCoreSchemaHandler, Strict, TypeAdapter, ValidationEr...
374
9,804
pydantic
tests/types/test_bool.py
.py
from decimal import Decimal import pytest from pydantic import StrictBool, TypeAdapter, ValidationError class BoolCastable: def __bool__(self) -> bool: return True @pytest.mark.parametrize( 'value,expected', [ pytest.param(True, True, id='True_bool'), pytest.param(1, True, id='...
113
3,263
pydantic
tests/types/test_uuid.py
.py
import json import uuid from uuid import UUID import pytest from pydantic import UUID1, UUID3, UUID4, UUID5, BaseModel, ConfigDict, Field, TypeAdapter, ValidationError @pytest.mark.parametrize( 'value,expected', [ ('ebcdab58-6eb8-46fb-a190-d07a33e9eac8', UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8'))...
250
8,073
pydantic
tests/types/test_str.py
.py
import re from decimal import Decimal from enum import Enum from numbers import Number from typing import Annotated import annotated_types import pytest from pydantic import ( AfterValidator, BaseModel, ConfigDict, Field, StrictStr, StringConstraints, TypeAdapter, ValidationError, ) fr...
337
10,349
pydantic
tests/types/test_datetime.py
.py
from datetime import date, datetime, timezone from decimal import Decimal from typing import Annotated import pytest from pydantic import Field, TypeAdapter, ValidationError @pytest.mark.parametrize( 'value,expected', [ (datetime(2017, 5, 5, 10, 10, 10), datetime(2017, 5, 5, 10, 10, 10)), (d...
88
3,171