mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
Add a test assertion that default_factory can return a singleton (#1523)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
Add a test assertion that `default_factory` can return a singleton
|
||||
@@ -431,6 +431,23 @@ def test_default_factory_field():
|
||||
assert fields['aliases'].default == {'John': 'Joey'}
|
||||
|
||||
|
||||
def test_default_factory_singleton_field():
|
||||
class MySingleton:
|
||||
pass
|
||||
|
||||
class MyConfig:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
MY_SINGLETON = MySingleton()
|
||||
|
||||
@pydantic.dataclasses.dataclass(config=MyConfig)
|
||||
class Foo:
|
||||
singleton: MySingleton = dataclasses.field(default_factory=lambda: MY_SINGLETON)
|
||||
|
||||
# Returning a singleton from a default_factory is supported
|
||||
assert Foo().singleton is Foo().singleton
|
||||
|
||||
|
||||
def test_schema():
|
||||
@pydantic.dataclasses.dataclass
|
||||
class User:
|
||||
|
||||
@@ -1087,6 +1087,20 @@ def test_default_factory():
|
||||
m = FunctionModel()
|
||||
assert m.uid is uuid4
|
||||
|
||||
# Returning a singleton from a default_factory is supported
|
||||
class MySingleton:
|
||||
pass
|
||||
|
||||
MY_SINGLETON = MySingleton()
|
||||
|
||||
class SingletonFieldModel(BaseModel):
|
||||
singleton: MySingleton = Field(default_factory=lambda: MY_SINGLETON)
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
assert SingletonFieldModel().singleton is SingletonFieldModel().singleton
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.version_info < (3, 7), reason='field constraints are set but not enforced with python 3.6')
|
||||
def test_none_min_max_items():
|
||||
|
||||
Reference in New Issue
Block a user