Skip to content

Commit

Permalink
Add a test assertion that default_factory can return a singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
therefromhere committed May 17, 2020
1 parent 5067508 commit 9f030d6
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions changes/1523-therefromhere.md
@@ -0,0 +1 @@
Add a test assertion that `default_factory` can return a singleton
17 changes: 17 additions & 0 deletions tests/test_dataclasses.py
Expand Up @@ -431,6 +431,23 @@ class User:
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:
Expand Down
14 changes: 14 additions & 0 deletions tests/test_main.py
Expand Up @@ -1087,6 +1087,20 @@ class FunctionModel(BaseModel):
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():
Expand Down

0 comments on commit 9f030d6

Please sign in to comment.