forked from litestar-org/polyfactory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_provider_map.py
More file actions
80 lines (54 loc) · 2.02 KB
/
test_provider_map.py
File metadata and controls
80 lines (54 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from dataclasses import dataclass
from typing import Any, Callable, Generic, TypeVar
import pytest
from polyfactory.exceptions import ParameterException
from polyfactory.factories.base import BaseFactory
from polyfactory.factories.dataclass_factory import DataclassFactory
def test_provider_map() -> None:
provider_map = BaseFactory.get_provider_map()
provider_map.pop(Any)
for type_, handler in provider_map.items():
value = handler()
assert isinstance(value, type_)
def test_provider_map_with_any() -> None:
@dataclass
class Foo:
foo: Any
class FooFactory(DataclassFactory[Foo]):
@classmethod
def get_provider_map(cls) -> dict[Any, Callable[[], Any]]:
provider_map = super().get_provider_map()
provider_map[Any] = lambda: "any"
return provider_map
foo = FooFactory.build()
assert foo.foo == "any"
coverage_result = list(FooFactory.coverage())
assert all(result.foo == "any" for result in coverage_result)
def test_provider_map_with_typevar() -> None:
T = TypeVar("T")
@dataclass
class Foo(Generic[T]):
foo: T
class FooFactory(DataclassFactory[Foo]):
@classmethod
def get_provider_map(cls) -> dict[Any, Callable[[], Any]]:
provider_map = super().get_provider_map()
provider_map[T] = lambda: "any"
return provider_map
foo = FooFactory.build()
assert foo.foo == "any"
coverage_result = list(FooFactory.coverage())
assert all(result.foo == "any" for result in coverage_result)
def test_add_custom_provider() -> None:
class CustomType:
def __init__(self, _: Any) -> None:
pass
@dataclass
class Foo:
foo: CustomType
FooFactory = DataclassFactory.create_factory(Foo)
with pytest.raises(ParameterException):
FooFactory.build()
BaseFactory.add_provider(CustomType, lambda: CustomType("custom"))
# after adding the provider, nothing should raise!
assert FooFactory.build()