Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test coverage that default_factory doesn't copy its value #1523

Merged
merged 1 commit into from May 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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