Python pydantic.Field() Examples

The following are 30 code examples of pydantic.Field(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pydantic , or try the search function .
Example #1
Source File: test_main.py    From pydantic with MIT License 6 votes vote down vote up
def test_default_factory_called_once():
    """It should call only once the given factory by default"""

    class Seq:
        def __init__(self):
            self.v = 0

        def __call__(self):
            self.v += 1
            return self.v

    class MyModel(BaseModel):
        id: int = Field(default_factory=Seq())

    m1 = MyModel()
    assert m1.id == 1
    m2 = MyModel()
    assert m2.id == 2
    assert m1.id == 1 
Example #2
Source File: test_model_parser.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_del(self):
        class Foo(CCIDictModel):
            bar: str = None
            fields_ = Field([], alias="fields")

        x = Foo.parse_obj({"bar": "q"})
        assert x["bar"] == x.bar == "q"
        assert "bar" in x
        del x["bar"]
        assert "bar" not in x
        assert x.get("bar") is None

        assert x["fields"] == x.fields == []
        assert "fields" in x
        del x["fields"]
        assert "fields" not in x
        assert x.get("fields") is None 
Example #3
Source File: test_forward_ref.py    From pydantic with MIT License 6 votes vote down vote up
def test_forward_ref_with_field(create_module):
    create_module(
        """
from typing import List
from pydantic import BaseModel, Field
from pydantic.typing import ForwardRef

Foo = ForwardRef('Foo')

try:
    class Foo(BaseModel):
        c: List[Foo] = Field(..., gt=0)
except ValueError:
    pass
else:
    raise AssertionError('error not raised')
    """
    ) 
Example #4
Source File: test_main.py    From pydantic with MIT License 6 votes vote down vote up
def test_default_factory_called_once_2():
    """It should call only once the given factory by default"""

    v = 0

    def factory():
        nonlocal v
        v += 1
        return v

    class MyModel(BaseModel):
        id: int = Field(default_factory=factory)

    m1 = MyModel()
    assert m1.id == 1
    m2 = MyModel()
    assert m2.id == 2 
Example #5
Source File: test_model_signature.py    From pydantic with MIT License 6 votes vote down vote up
def test_custom_init_signature():
    class MyModel(BaseModel):
        id: int
        name: str = 'John Doe'
        f__: str = Field(..., alias='foo')

        class Config:
            extra = Extra.allow

        def __init__(self, id: int = 1, bar=2, *, baz: Any, **data):
            super().__init__(id=id, **data)
            self.bar = bar
            self.baz = baz

    sig = signature(MyModel)
    assert _equals(
        map(str, sig.parameters.values()),
        ('id: int = 1', 'bar=2', 'baz: Any', "name: str = 'John Doe'", 'foo: str', '**data'),
    )

    assert _equals(str(sig), "(id: int = 1, bar=2, *, baz: Any, name: str = 'John Doe', foo: str, **data) -> None") 
Example #6
Source File: test_schema.py    From pydantic with MIT License 6 votes vote down vote up
def test_schema_class():
    class Model(BaseModel):
        foo: int = Field(4, title='Foo is Great')
        bar: str = Field(..., description='this description of bar')

    with pytest.raises(ValidationError):
        Model()

    m = Model(bar=123)
    assert m.dict() == {'foo': 4, 'bar': '123'}

    assert Model.schema() == {
        'type': 'object',
        'title': 'Model',
        'properties': {
            'foo': {'type': 'integer', 'title': 'Foo is Great', 'default': 4},
            'bar': {'type': 'string', 'title': 'Bar', 'description': 'this description of bar'},
        },
        'required': ['bar'],
    } 
Example #7
Source File: test_settings.py    From pydantic with MIT License 6 votes vote down vote up
def test_env_inheritance_field(env):
    class SettingsParent(BaseSettings):
        foobar: str = Field('parent default', env='foobar_env')

    class SettingsChild(SettingsParent):
        foobar: str = 'child default'

    assert SettingsParent().foobar == 'parent default'
    assert SettingsParent(foobar='abc').foobar == 'abc'

    assert SettingsChild().foobar == 'child default'
    assert SettingsChild(foobar='abc').foobar == 'abc'
    env.set('foobar_env', 'env value')
    assert SettingsParent().foobar == 'env value'
    assert SettingsParent(foobar='abc').foobar == 'abc'
    assert SettingsChild().foobar == 'child default'
    assert SettingsChild(foobar='abc').foobar == 'abc' 
Example #8
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_const_str():
    class Model(BaseModel):
        a: str = Field('some string', const=True)

    assert Model.schema() == {
        'title': 'Model',
        'type': 'object',
        'properties': {'a': {'title': 'A', 'type': 'string', 'const': 'some string'}},
    } 
Example #9
Source File: test_main.py    From pydantic with MIT License 5 votes vote down vote up
def test_dict_with_extra_keys():
    class MyModel(BaseModel):
        a: str = Field(None, alias='alias_a')

        class Config:
            extra = Extra.allow

    m = MyModel(extra_key='extra')
    assert m.dict() == {'a': None, 'extra_key': 'extra'}
    assert m.dict(by_alias=True) == {'alias_a': None, 'extra_key': 'extra'} 
Example #10
Source File: test_main.py    From pydantic with MIT License 5 votes vote down vote up
def test_two_defaults():
    with pytest.raises(ValueError, match='^cannot specify both default and default_factory$'):

        class Model(BaseModel):
            a: int = Field(default=3, default_factory=lambda: 3) 
Example #11
Source File: test_main.py    From pydantic with MIT License 5 votes vote down vote up
def test_none_min_max_items():
    # None default
    class Foo(BaseModel):
        foo: List = Field(None)
        bar: List = Field(None, min_items=0)
        baz: List = Field(None, max_items=10)

    f1 = Foo()
    f2 = Foo(bar=None)
    f3 = Foo(baz=None)
    f4 = Foo(bar=None, baz=None)
    for f in (f1, f2, f3, f4):
        assert f.foo is None
        assert f.bar is None
        assert f.baz is None 
Example #12
Source File: test_main.py    From pydantic with MIT License 5 votes vote down vote up
def test_reuse_same_field():
    required_field = Field(...)

    class Model1(BaseModel):
        required: str = required_field

    class Model2(BaseModel):
        required: str = required_field

    with pytest.raises(ValidationError):
        Model1.parse_obj({})
    with pytest.raises(ValidationError):
        Model2.parse_obj({}) 
Example #13
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_schema_class_by_alias():
    class Model(BaseModel):
        foo: int = Field(4, alias='foofoo')

    assert list(Model.schema()['properties'].keys()) == ['foofoo']
    assert list(Model.schema(by_alias=False)['properties'].keys()) == ['foo'] 
Example #14
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_choices():
    FooEnum = Enum('FooEnum', {'foo': 'f', 'bar': 'b'})
    BarEnum = IntEnum('BarEnum', {'foo': 1, 'bar': 2})

    class SpamEnum(str, Enum):
        foo = 'f'
        bar = 'b'

    class Model(BaseModel):
        foo: FooEnum
        bar: BarEnum
        spam: SpamEnum = Field(None)

    assert Model.schema() == {
        'title': 'Model',
        'type': 'object',
        'properties': {
            'foo': {'$ref': '#/definitions/FooEnum'},
            'bar': {'$ref': '#/definitions/BarEnum'},
            'spam': {'$ref': '#/definitions/SpamEnum'},
        },
        'required': ['foo', 'bar'],
        'definitions': {
            'FooEnum': {'title': 'FooEnum', 'description': 'An enumeration.', 'enum': ['f', 'b']},
            'BarEnum': {'title': 'BarEnum', 'description': 'An enumeration.', 'type': 'integer', 'enum': [1, 2]},
            'SpamEnum': {'title': 'SpamEnum', 'description': 'An enumeration.', 'type': 'string', 'enum': ['f', 'b']},
        },
    } 
Example #15
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_enum_modify_schema():
    class SpamEnum(str, Enum):
        foo = 'f'
        bar = 'b'

        @classmethod
        def __modify_schema__(cls, field_schema):
            field_schema['tsEnumNames'] = [e.name for e in cls]

    class Model(BaseModel):
        spam: SpamEnum = Field(None)

    assert Model.schema() == {
        'definitions': {
            'SpamEnum': {
                'description': 'An enumeration.',
                'enum': ['f', 'b'],
                'title': 'SpamEnum',
                'tsEnumNames': ['foo', 'bar'],
                'type': 'string',
            }
        },
        'properties': {'spam': {'$ref': '#/definitions/SpamEnum'}},
        'title': 'Model',
        'type': 'object',
    } 
Example #16
Source File: test_main.py    From pydantic with MIT License 5 votes vote down vote up
def test_const_validation_json_serializable():
    class SubForm(BaseModel):
        field: int

    class Form(BaseModel):
        field1: SubForm = Field({'field': 2}, const=True)
        field2: List[SubForm] = Field([{'field': 2}], const=True)

    with pytest.raises(ValidationError) as exc_info:
        # Fails
        Form(field1={'field': 1}, field2=[{'field': 1}])

    # This should not raise an Json error
    exc_info.value.json() 
Example #17
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_const_false():
    class Model(BaseModel):
        a: str = Field('some string', const=False)

    assert Model.schema() == {
        'title': 'Model',
        'type': 'object',
        'properties': {'a': {'title': 'A', 'type': 'string', 'default': 'some string'}},
    } 
Example #18
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_constraints_schema(kwargs, type_, expected_extra):
    class Foo(BaseModel):
        a: type_ = Field('foo', title='A title', description='A description', **kwargs)

    expected_schema = {
        'title': 'Foo',
        'type': 'object',
        'properties': {'a': {'title': 'A title', 'description': 'A description', 'default': 'foo'}},
    }

    expected_schema['properties']['a'].update(expected_extra)
    assert Foo.schema() == expected_schema 
Example #19
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_unenforced_constraints_schema(kwargs, type_):
    with pytest.raises(ValueError, match='On field "a" the following field constraints are set but not enforced'):

        class Foo(BaseModel):
            a: type_ = Field('foo', title='A title', description='A description', **kwargs) 
Example #20
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_constraints_schema_validation(kwargs, type_, value):
    class Foo(BaseModel):
        a: type_ = Field('foo', title='A title', description='A description', **kwargs)

    assert Foo(a=value) 
Example #21
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_constraints_schema_validation_raises(kwargs, type_, value):
    class Foo(BaseModel):
        a: type_ = Field('foo', title='A title', description='A description', **kwargs)

    with pytest.raises(ValidationError):
        Foo(a=value) 
Example #22
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_schema_kwargs():
    class Foo(BaseModel):
        a: str = Field('foo', examples=['bar'])

    assert Foo.schema() == {
        'title': 'Foo',
        'type': 'object',
        'properties': {'a': {'type': 'string', 'title': 'A', 'default': 'foo', 'examples': ['bar']}},
    } 
Example #23
Source File: test_schema.py    From pydantic with MIT License 5 votes vote down vote up
def test_real_vs_phony_constraints():
    class Model1(BaseModel):
        foo: int = Field(..., gt=123)

        class Config:
            title = 'Test Model'

    class Model2(BaseModel):
        foo: int = Field(..., exclusiveMinimum=123)

        class Config:
            title = 'Test Model'

    with pytest.raises(ValidationError, match='ensure this value is greater than 123'):
        Model1(foo=122)

    assert Model2(foo=122).dict() == {'foo': 122}

    assert (
        Model1.schema()
        == Model2.schema()
        == {
            'title': 'Test Model',
            'type': 'object',
            'properties': {'foo': {'title': 'Foo', 'exclusiveMinimum': 123, 'type': 'integer'}},
            'required': ['foo'],
        }
    ) 
Example #24
Source File: test_settings.py    From pydantic with MIT License 5 votes vote down vote up
def test_env_field(env):
    with pytest.raises(TypeError, match=r'invalid field env: 123 \(int\); should be string, list or set'):

        class Settings(BaseSettings):
            foobar: str = Field(..., env=123) 
Example #25
Source File: test_model_parser.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fields_items(self):
        class Foo(CCIDictModel):
            bar: str = None
            fields_ = Field([], alias="fields")

        class Document(CCIDictModel):
            __root__: Foo

        # JSON is YAML. Strange but true.
        foo = Document.parse_from_yaml(StringIO("{bar: 'blah'}"))
        assert type(foo) == Foo
        assert foo["fields"] == []

        foo = Document.parse_from_yaml(StringIO("{bar: 'blah', fields: [1,2]}"))
        assert foo["fields"] == [1, 2]

        foo["fields"] = ["a", "b"]
        assert foo["fields"] == ["a", "b"] 
Example #26
Source File: test_model_parser.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_getitem_missing(self):
        class Foo(CCIDictModel):
            bar: str = None
            fields_ = Field([], alias="fields")

        x = Foo.parse_obj({})
        assert x
        with pytest.raises(IndexError):
            x["foo"]

        assert "bar" in x
        assert "fields" in x
        assert x["fields"] == [] 
Example #27
Source File: test_model_parser.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get(self):
        class Foo(CCIDictModel):
            bar: str = None
            fields_ = Field([], alias="fields")

        x = Foo.parse_obj({"bar": "q"})
        assert x.get("bar") == x.bar == x["bar"] == "q"
        assert x.get("xyzzy", 0) == 0
        assert x.get("xyzzy") is None
        assert x.get("fields") == [] 
Example #28
Source File: test_generics.py    From pydantic with MIT License 5 votes vote down vote up
def test_custom_schema():
    T = TypeVar('T')

    class MyModel(GenericModel, Generic[T]):
        a: int = Field(1, description='Custom')

    schema = MyModel[int].schema()
    assert schema['properties']['a'].get('description') == 'Custom' 
Example #29
Source File: test_model_signature.py    From pydantic with MIT License 5 votes vote down vote up
def test_model_signature():
    class Model(BaseModel):
        a: float = Field(..., title='A')
        b = Field(10)

    sig = signature(Model)
    assert sig != signature(BaseModel)
    assert _equals(map(str, sig.parameters.values()), ('a: float', 'b: int = 10'))
    assert _equals(str(sig), '(*, a: float, b: int = 10) -> None') 
Example #30
Source File: test_model_signature.py    From pydantic with MIT License 5 votes vote down vote up
def test_invalid_identifiers_signature():
    model = create_model(
        'Model', **{'123 invalid identifier!': Field(123, alias='valid_identifier'), '!': Field(0, alias='yeah')}
    )
    assert _equals(str(signature(model)), '(*, valid_identifier: int = 123, yeah: int = 0) -> None')
    model = create_model('Model', **{'123 invalid identifier!': 123, '!': Field(0, alias='yeah')})
    assert _equals(str(signature(model)), '(*, yeah: int = 0, **extra_data: Any) -> None')