pboot-validator 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. pboot_validator/__init__.py +461 -0
  2. pboot_validator/_internal/__init__.py +0 -0
  3. pboot_validator/_internal/_config.py +408 -0
  4. pboot_validator/_internal/_contextlib.py +84 -0
  5. pboot_validator/_internal/_core_metadata.py +97 -0
  6. pboot_validator/_internal/_core_utils.py +156 -0
  7. pboot_validator/_internal/_dataclasses.py +327 -0
  8. pboot_validator/_internal/_decorators.py +906 -0
  9. pboot_validator/_internal/_decorators_v1.py +174 -0
  10. pboot_validator/_internal/_discriminated_union.py +510 -0
  11. pboot_validator/_internal/_docs_extraction.py +128 -0
  12. pboot_validator/_internal/_fields.py +910 -0
  13. pboot_validator/_internal/_forward_ref.py +23 -0
  14. pboot_validator/_internal/_generate_schema.py +3053 -0
  15. pboot_validator/_internal/_generics.py +572 -0
  16. pboot_validator/_internal/_git.py +27 -0
  17. pboot_validator/_internal/_import_utils.py +20 -0
  18. pboot_validator/_internal/_known_annotated_metadata.py +412 -0
  19. pboot_validator/_internal/_mock_val_ser.py +241 -0
  20. pboot_validator/_internal/_model_construction.py +833 -0
  21. pboot_validator/_internal/_namespace_utils.py +300 -0
  22. pboot_validator/_internal/_repr.py +129 -0
  23. pboot_validator/_internal/_schema_gather.py +49 -0
  24. pboot_validator/_internal/_schema_generation_shared.py +126 -0
  25. pboot_validator/_internal/_serializers.py +59 -0
  26. pboot_validator/_internal/_signature.py +193 -0
  27. pboot_validator/_internal/_type_refs.py +128 -0
  28. pboot_validator/_internal/_typing_extra.py +506 -0
  29. pboot_validator/_internal/_utils.py +433 -0
  30. pboot_validator/_internal/_validate_call.py +141 -0
  31. pboot_validator/_internal/_validators.py +541 -0
  32. pboot_validator/_migration.py +317 -0
  33. pboot_validator/alias_generators.py +62 -0
  34. pboot_validator/aliases.py +136 -0
  35. pboot_validator/annotated_handlers.py +123 -0
  36. pboot_validator/class_validators.py +5 -0
  37. pboot_validator/color.py +605 -0
  38. pboot_validator/config.py +1295 -0
  39. pboot_validator/dataclasses.py +385 -0
  40. pboot_validator/datetime_parse.py +5 -0
  41. pboot_validator/decorator.py +5 -0
  42. pboot_validator/deprecated/__init__.py +0 -0
  43. pboot_validator/deprecated/class_validators.py +257 -0
  44. pboot_validator/deprecated/config.py +72 -0
  45. pboot_validator/deprecated/copy_internals.py +224 -0
  46. pboot_validator/deprecated/decorator.py +286 -0
  47. pboot_validator/deprecated/json.py +142 -0
  48. pboot_validator/deprecated/parse.py +81 -0
  49. pboot_validator/deprecated/tools.py +104 -0
  50. pboot_validator/env_settings.py +5 -0
  51. pboot_validator/error_wrappers.py +5 -0
  52. pboot_validator/errors.py +185 -0
  53. pboot_validator/experimental/__init__.py +1 -0
  54. pboot_validator/experimental/arguments_schema.py +44 -0
  55. pboot_validator/experimental/missing_sentinel.py +29 -0
  56. pboot_validator/experimental/pipeline.py +684 -0
  57. pboot_validator/fields.py +2065 -0
  58. pboot_validator/functional_serializers.py +461 -0
  59. pboot_validator/functional_validators.py +920 -0
  60. pboot_validator/generics.py +5 -0
  61. pboot_validator/json.py +5 -0
  62. pboot_validator/json_schema.py +3283 -0
  63. pboot_validator/main.py +1947 -0
  64. pboot_validator/mypy.py +1469 -0
  65. pboot_validator/networks.py +1417 -0
  66. pboot_validator/parse.py +5 -0
  67. pboot_validator/plugin/__init__.py +190 -0
  68. pboot_validator/plugin/_loader.py +56 -0
  69. pboot_validator/plugin/_schema_validator.py +152 -0
  70. pboot_validator/py.typed +0 -0
  71. pboot_validator/root_model.py +189 -0
  72. pboot_validator/schema.py +5 -0
  73. pboot_validator/tools.py +5 -0
  74. pboot_validator/type_adapter.py +780 -0
  75. pboot_validator/types.py +3405 -0
  76. pboot_validator/typing.py +5 -0
  77. pboot_validator/utils.py +5 -0
  78. pboot_validator/v1/__init__.py +131 -0
  79. pboot_validator/v1/_hypothesis_plugin.py +391 -0
  80. pboot_validator/v1/annotated_types.py +72 -0
  81. pboot_validator/v1/class_validators.py +361 -0
  82. pboot_validator/v1/color.py +494 -0
  83. pboot_validator/v1/config.py +191 -0
  84. pboot_validator/v1/dataclasses.py +503 -0
  85. pboot_validator/v1/datetime_parse.py +248 -0
  86. pboot_validator/v1/decorator.py +264 -0
  87. pboot_validator/v1/env_settings.py +350 -0
  88. pboot_validator/v1/error_wrappers.py +161 -0
  89. pboot_validator/v1/errors.py +646 -0
  90. pboot_validator/v1/fields.py +1253 -0
  91. pboot_validator/v1/generics.py +400 -0
  92. pboot_validator/v1/json.py +112 -0
  93. pboot_validator/v1/main.py +1130 -0
  94. pboot_validator/v1/mypy.py +950 -0
  95. pboot_validator/v1/networks.py +747 -0
  96. pboot_validator/v1/parse.py +66 -0
  97. pboot_validator/v1/py.typed +0 -0
  98. pboot_validator/v1/schema.py +1163 -0
  99. pboot_validator/v1/tools.py +92 -0
  100. pboot_validator/v1/types.py +1213 -0
  101. pboot_validator/v1/typing.py +627 -0
  102. pboot_validator/v1/utils.py +807 -0
  103. pboot_validator/v1/validators.py +768 -0
  104. pboot_validator/v1/version.py +38 -0
  105. pboot_validator/validate_call_decorator.py +121 -0
  106. pboot_validator/validators.py +5 -0
  107. pboot_validator/version.py +113 -0
  108. pboot_validator/warnings.py +130 -0
  109. pboot_validator-1.0.0.dist-info/METADATA +93 -0
  110. pboot_validator-1.0.0.dist-info/RECORD +112 -0
  111. pboot_validator-1.0.0.dist-info/WHEEL +4 -0
  112. pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,5 @@
1
+ """`typing` module is a backport module from V1."""
2
+
3
+ from ._migration import getattr_migration
4
+
5
+ __getattr__ = getattr_migration(__name__)
@@ -0,0 +1,5 @@
1
+ """The `utils` module is a backport module from V1."""
2
+
3
+ from ._migration import getattr_migration
4
+
5
+ __getattr__ = getattr_migration(__name__)
@@ -0,0 +1,131 @@
1
+ # flake8: noqa
2
+ from pboot_validator.v1 import dataclasses
3
+ from pboot_validator.v1.annotated_types import create_model_from_namedtuple, create_model_from_typeddict
4
+ from pboot_validator.v1.class_validators import root_validator, validator
5
+ from pboot_validator.v1.config import BaseConfig, ConfigDict, Extra
6
+ from pboot_validator.v1.decorator import validate_arguments
7
+ from pboot_validator.v1.env_settings import BaseSettings
8
+ from pboot_validator.v1.error_wrappers import ValidationError
9
+ from pboot_validator.v1.errors import *
10
+ from pboot_validator.v1.fields import Field, PrivateAttr, Required
11
+ from pboot_validator.v1.main import *
12
+ from pboot_validator.v1.networks import *
13
+ from pboot_validator.v1.parse import Protocol
14
+ from pboot_validator.v1.tools import *
15
+ from pboot_validator.v1.types import *
16
+ from pboot_validator.v1.version import VERSION, compiled
17
+
18
+ __version__ = VERSION
19
+
20
+ # WARNING __all__ from pboot_validator.errors is not included here, it will be removed as an export here in v2
21
+ # please use "from pboot_validator.v1.errors import ..." instead
22
+ __all__ = [
23
+ # annotated types utils
24
+ 'create_model_from_namedtuple',
25
+ 'create_model_from_typeddict',
26
+ # dataclasses
27
+ 'dataclasses',
28
+ # class_validators
29
+ 'root_validator',
30
+ 'validator',
31
+ # config
32
+ 'BaseConfig',
33
+ 'ConfigDict',
34
+ 'Extra',
35
+ # decorator
36
+ 'validate_arguments',
37
+ # env_settings
38
+ 'BaseSettings',
39
+ # error_wrappers
40
+ 'ValidationError',
41
+ # fields
42
+ 'Field',
43
+ 'Required',
44
+ # main
45
+ 'BaseModel',
46
+ 'create_model',
47
+ 'validate_model',
48
+ # network
49
+ 'AnyUrl',
50
+ 'AnyHttpUrl',
51
+ 'FileUrl',
52
+ 'HttpUrl',
53
+ 'stricturl',
54
+ 'EmailStr',
55
+ 'NameEmail',
56
+ 'IPvAnyAddress',
57
+ 'IPvAnyInterface',
58
+ 'IPvAnyNetwork',
59
+ 'PostgresDsn',
60
+ 'CockroachDsn',
61
+ 'AmqpDsn',
62
+ 'RedisDsn',
63
+ 'MongoDsn',
64
+ 'KafkaDsn',
65
+ 'validate_email',
66
+ # parse
67
+ 'Protocol',
68
+ # tools
69
+ 'parse_file_as',
70
+ 'parse_obj_as',
71
+ 'parse_raw_as',
72
+ 'schema_of',
73
+ 'schema_json_of',
74
+ # types
75
+ 'NoneStr',
76
+ 'NoneBytes',
77
+ 'StrBytes',
78
+ 'NoneStrBytes',
79
+ 'StrictStr',
80
+ 'ConstrainedBytes',
81
+ 'conbytes',
82
+ 'ConstrainedList',
83
+ 'conlist',
84
+ 'ConstrainedSet',
85
+ 'conset',
86
+ 'ConstrainedFrozenSet',
87
+ 'confrozenset',
88
+ 'ConstrainedStr',
89
+ 'constr',
90
+ 'PyObject',
91
+ 'ConstrainedInt',
92
+ 'conint',
93
+ 'PositiveInt',
94
+ 'NegativeInt',
95
+ 'NonNegativeInt',
96
+ 'NonPositiveInt',
97
+ 'ConstrainedFloat',
98
+ 'confloat',
99
+ 'PositiveFloat',
100
+ 'NegativeFloat',
101
+ 'NonNegativeFloat',
102
+ 'NonPositiveFloat',
103
+ 'FiniteFloat',
104
+ 'ConstrainedDecimal',
105
+ 'condecimal',
106
+ 'ConstrainedDate',
107
+ 'condate',
108
+ 'UUID1',
109
+ 'UUID3',
110
+ 'UUID4',
111
+ 'UUID5',
112
+ 'FilePath',
113
+ 'DirectoryPath',
114
+ 'Json',
115
+ 'JsonWrapper',
116
+ 'SecretField',
117
+ 'SecretStr',
118
+ 'SecretBytes',
119
+ 'StrictBool',
120
+ 'StrictBytes',
121
+ 'StrictInt',
122
+ 'StrictFloat',
123
+ 'PaymentCardNumber',
124
+ 'PrivateAttr',
125
+ 'ByteSize',
126
+ 'PastDate',
127
+ 'FutureDate',
128
+ # version
129
+ 'compiled',
130
+ 'VERSION',
131
+ ]
@@ -0,0 +1,391 @@
1
+ """
2
+ Register Hypothesis strategies for Pydantic custom types.
3
+
4
+ This enables fully-automatic generation of test data for most Pydantic classes.
5
+
6
+ Note that this module has *no* runtime impact on Pydantic itself; instead it
7
+ is registered as a setuptools entry point and Hypothesis will import it if
8
+ Pydantic is installed. See also:
9
+
10
+ https://hypothesis.readthedocs.io/en/latest/strategies.html#registering-strategies-via-setuptools-entry-points
11
+ https://hypothesis.readthedocs.io/en/latest/data.html#hypothesis.strategies.register_type_strategy
12
+ https://hypothesis.readthedocs.io/en/latest/strategies.html#interaction-with-pytest-cov
13
+ https://docs.pydantic.dev/usage/types/#pydantic-types
14
+
15
+ Note that because our motivation is to *improve user experience*, the strategies
16
+ are always sound (never generate invalid data) but sacrifice completeness for
17
+ maintainability (ie may be unable to generate some tricky but valid data).
18
+
19
+ Finally, this module makes liberal use of `# type: ignore[<code>]` pragmas.
20
+ This is because Hypothesis annotates `register_type_strategy()` with
21
+ `(T, SearchStrategy[T])`, but in most cases we register e.g. `ConstrainedInt`
22
+ to generate instances of the builtin `int` type which match the constraints.
23
+ """
24
+
25
+ import contextlib
26
+ import datetime
27
+ import ipaddress
28
+ import json
29
+ import math
30
+ from fractions import Fraction
31
+ from typing import Callable, Dict, Type, Union, cast, overload
32
+
33
+ import hypothesis.strategies as st
34
+
35
+ import pboot_validator
36
+ import pboot_validator.color
37
+ import pboot_validator.types
38
+ from pboot_validator.v1.utils import lenient_issubclass
39
+
40
+ # FilePath and DirectoryPath are explicitly unsupported, as we'd have to create
41
+ # them on-disk, and that's unsafe in general without being told *where* to do so.
42
+ #
43
+ # URLs are unsupported because it's easy for users to define their own strategy for
44
+ # "normal" URLs, and hard for us to define a general strategy which includes "weird"
45
+ # URLs but doesn't also have unpredictable performance problems.
46
+ #
47
+ # conlist() and conset() are unsupported for now, because the workarounds for
48
+ # Cython and Hypothesis to handle parametrized generic types are incompatible.
49
+ # We are rethinking Hypothesis compatibility in Pydantic v2.
50
+
51
+ # Emails
52
+ try:
53
+ import email_validator
54
+ except ImportError: # pragma: no cover
55
+ pass
56
+ else:
57
+
58
+ def is_valid_email(s: str) -> bool:
59
+ # Hypothesis' st.emails() occasionally generates emails like 0@A0--0.ac
60
+ # that are invalid according to email-validator, so we filter those out.
61
+ try:
62
+ email_validator.validate_email(s, check_deliverability=False)
63
+ return True
64
+ except email_validator.EmailNotValidError: # pragma: no cover
65
+ return False
66
+
67
+ # Note that these strategies deliberately stay away from any tricky Unicode
68
+ # or other encoding issues; we're just trying to generate *something* valid.
69
+ st.register_type_strategy(pboot_validator.EmailStr, st.emails().filter(is_valid_email)) # type: ignore[arg-type]
70
+ st.register_type_strategy(
71
+ pboot_validator.NameEmail,
72
+ st.builds(
73
+ '{} <{}>'.format, # type: ignore[arg-type]
74
+ st.from_regex('[A-Za-z0-9_]+( [A-Za-z0-9_]+){0,5}', fullmatch=True),
75
+ st.emails().filter(is_valid_email),
76
+ ),
77
+ )
78
+
79
+ # PyObject - dotted names, in this case taken from the math module.
80
+ st.register_type_strategy(
81
+ pboot_validator.PyObject, # type: ignore[arg-type]
82
+ st.sampled_from(
83
+ [cast(pboot_validator.PyObject, f'math.{name}') for name in sorted(vars(math)) if not name.startswith('_')]
84
+ ),
85
+ )
86
+
87
+ # CSS3 Colors; as name, hex, rgb(a) tuples or strings, or hsl strings
88
+ _color_regexes = (
89
+ '|'.join(
90
+ (
91
+ pboot_validator.color.r_hex_short,
92
+ pboot_validator.color.r_hex_long,
93
+ pboot_validator.color.r_rgb,
94
+ pboot_validator.color.r_rgba,
95
+ pboot_validator.color.r_hsl,
96
+ pboot_validator.color.r_hsla,
97
+ )
98
+ )
99
+ # Use more precise regex patterns to avoid value-out-of-range errors
100
+ .replace(pboot_validator.color._r_sl, r'(?:(\d\d?(?:\.\d+)?|100(?:\.0+)?)%)')
101
+ .replace(pboot_validator.color._r_alpha, r'(?:(0(?:\.\d+)?|1(?:\.0+)?|\.\d+|\d{1,2}%))')
102
+ .replace(pboot_validator.color._r_255, r'(?:((?:\d|\d\d|[01]\d\d|2[0-4]\d|25[0-4])(?:\.\d+)?|255(?:\.0+)?))')
103
+ )
104
+ st.register_type_strategy(
105
+ pboot_validator.color.Color,
106
+ st.one_of(
107
+ st.sampled_from(sorted(pboot_validator.color.COLORS_BY_NAME)),
108
+ st.tuples(
109
+ st.integers(0, 255),
110
+ st.integers(0, 255),
111
+ st.integers(0, 255),
112
+ st.none() | st.floats(0, 1) | st.floats(0, 100).map('{}%'.format),
113
+ ),
114
+ st.from_regex(_color_regexes, fullmatch=True),
115
+ ),
116
+ )
117
+
118
+
119
+ # Card numbers, valid according to the Luhn algorithm
120
+
121
+
122
+ def add_luhn_digit(card_number: str) -> str:
123
+ # See https://en.wikipedia.org/wiki/Luhn_algorithm
124
+ for digit in '0123456789':
125
+ with contextlib.suppress(Exception):
126
+ pboot_validator.PaymentCardNumber.validate_luhn_check_digit(card_number + digit)
127
+ return card_number + digit
128
+ raise AssertionError('Unreachable') # pragma: no cover
129
+
130
+
131
+ card_patterns = (
132
+ # Note that these patterns omit the Luhn check digit; that's added by the function above
133
+ '4[0-9]{14}', # Visa
134
+ '5[12345][0-9]{13}', # Mastercard
135
+ '3[47][0-9]{12}', # American Express
136
+ '[0-26-9][0-9]{10,17}', # other (incomplete to avoid overlap)
137
+ )
138
+ st.register_type_strategy(
139
+ pboot_validator.PaymentCardNumber,
140
+ st.from_regex('|'.join(card_patterns), fullmatch=True).map(add_luhn_digit), # type: ignore[arg-type]
141
+ )
142
+
143
+ # UUIDs
144
+ st.register_type_strategy(pboot_validator.UUID1, st.uuids(version=1))
145
+ st.register_type_strategy(pboot_validator.UUID3, st.uuids(version=3))
146
+ st.register_type_strategy(pboot_validator.UUID4, st.uuids(version=4))
147
+ st.register_type_strategy(pboot_validator.UUID5, st.uuids(version=5))
148
+
149
+ # Secrets
150
+ st.register_type_strategy(pboot_validator.SecretBytes, st.binary().map(pboot_validator.SecretBytes))
151
+ st.register_type_strategy(pboot_validator.SecretStr, st.text().map(pboot_validator.SecretStr))
152
+
153
+ # IP addresses, networks, and interfaces
154
+ st.register_type_strategy(pboot_validator.IPvAnyAddress, st.ip_addresses()) # type: ignore[arg-type]
155
+ st.register_type_strategy(
156
+ pboot_validator.IPvAnyInterface,
157
+ st.from_type(ipaddress.IPv4Interface) | st.from_type(ipaddress.IPv6Interface), # type: ignore[arg-type]
158
+ )
159
+ st.register_type_strategy(
160
+ pboot_validator.IPvAnyNetwork,
161
+ st.from_type(ipaddress.IPv4Network) | st.from_type(ipaddress.IPv6Network), # type: ignore[arg-type]
162
+ )
163
+
164
+ # We hook into the con***() functions and the ConstrainedNumberMeta metaclass,
165
+ # so here we only have to register subclasses for other constrained types which
166
+ # don't go via those mechanisms. Then there are the registration hooks below.
167
+ st.register_type_strategy(pboot_validator.StrictBool, st.booleans())
168
+ st.register_type_strategy(pboot_validator.StrictStr, st.text())
169
+
170
+
171
+ # FutureDate, PastDate
172
+ st.register_type_strategy(pboot_validator.FutureDate, st.dates(min_value=datetime.date.today() + datetime.timedelta(days=1)))
173
+ st.register_type_strategy(pboot_validator.PastDate, st.dates(max_value=datetime.date.today() - datetime.timedelta(days=1)))
174
+
175
+
176
+ # Constrained-type resolver functions
177
+ #
178
+ # For these ones, we actually want to inspect the type in order to work out a
179
+ # satisfying strategy. First up, the machinery for tracking resolver functions:
180
+
181
+ RESOLVERS: Dict[type, Callable[[type], st.SearchStrategy]] = {} # type: ignore[type-arg]
182
+
183
+
184
+ @overload
185
+ def _registered(typ: Type[pboot_validator.types.T]) -> Type[pboot_validator.types.T]:
186
+ pass
187
+
188
+
189
+ @overload
190
+ def _registered(typ: pboot_validator.types.ConstrainedNumberMeta) -> pboot_validator.types.ConstrainedNumberMeta:
191
+ pass
192
+
193
+
194
+ def _registered(
195
+ typ: Union[Type[pboot_validator.types.T], pboot_validator.types.ConstrainedNumberMeta]
196
+ ) -> Union[Type[pboot_validator.types.T], pboot_validator.types.ConstrainedNumberMeta]:
197
+ # This function replaces the version in `pboot_validator.types`, in order to
198
+ # effect the registration of new constrained types so that Hypothesis
199
+ # can generate valid examples.
200
+ pboot_validator.types._DEFINED_TYPES.add(typ)
201
+ for supertype, resolver in RESOLVERS.items():
202
+ if issubclass(typ, supertype):
203
+ st.register_type_strategy(typ, resolver(typ)) # type: ignore
204
+ return typ
205
+ raise NotImplementedError(f'Unknown type {typ!r} has no resolver to register') # pragma: no cover
206
+
207
+
208
+ def resolves(
209
+ typ: Union[type, pboot_validator.types.ConstrainedNumberMeta]
210
+ ) -> Callable[[Callable[..., st.SearchStrategy]], Callable[..., st.SearchStrategy]]: # type: ignore[type-arg]
211
+ def inner(f): # type: ignore
212
+ assert f not in RESOLVERS
213
+ RESOLVERS[typ] = f
214
+ return f
215
+
216
+ return inner
217
+
218
+
219
+ # Type-to-strategy resolver functions
220
+
221
+
222
+ @resolves(pboot_validator.JsonWrapper)
223
+ def resolve_json(cls): # type: ignore[no-untyped-def]
224
+ try:
225
+ inner = st.none() if cls.inner_type is None else st.from_type(cls.inner_type)
226
+ except Exception: # pragma: no cover
227
+ finite = st.floats(allow_infinity=False, allow_nan=False)
228
+ inner = st.recursive(
229
+ base=st.one_of(st.none(), st.booleans(), st.integers(), finite, st.text()),
230
+ extend=lambda x: st.lists(x) | st.dictionaries(st.text(), x), # type: ignore
231
+ )
232
+ inner_type = getattr(cls, 'inner_type', None)
233
+ return st.builds(
234
+ cls.inner_type.json if lenient_issubclass(inner_type, pboot_validator.BaseModel) else json.dumps,
235
+ inner,
236
+ ensure_ascii=st.booleans(),
237
+ indent=st.none() | st.integers(0, 16),
238
+ sort_keys=st.booleans(),
239
+ )
240
+
241
+
242
+ @resolves(pboot_validator.ConstrainedBytes)
243
+ def resolve_conbytes(cls): # type: ignore[no-untyped-def] # pragma: no cover
244
+ min_size = cls.min_length or 0
245
+ max_size = cls.max_length
246
+ if not cls.strip_whitespace:
247
+ return st.binary(min_size=min_size, max_size=max_size)
248
+ # Fun with regex to ensure we neither start nor end with whitespace
249
+ repeats = '{{{},{}}}'.format(
250
+ min_size - 2 if min_size > 2 else 0,
251
+ max_size - 2 if (max_size or 0) > 2 else '',
252
+ )
253
+ if min_size >= 2:
254
+ pattern = rf'\W.{repeats}\W'
255
+ elif min_size == 1:
256
+ pattern = rf'\W(.{repeats}\W)?'
257
+ else:
258
+ assert min_size == 0
259
+ pattern = rf'(\W(.{repeats}\W)?)?'
260
+ return st.from_regex(pattern.encode(), fullmatch=True)
261
+
262
+
263
+ @resolves(pboot_validator.ConstrainedDecimal)
264
+ def resolve_condecimal(cls): # type: ignore[no-untyped-def]
265
+ min_value = cls.ge
266
+ max_value = cls.le
267
+ if cls.gt is not None:
268
+ assert min_value is None, 'Set `gt` or `ge`, but not both'
269
+ min_value = cls.gt
270
+ if cls.lt is not None:
271
+ assert max_value is None, 'Set `lt` or `le`, but not both'
272
+ max_value = cls.lt
273
+ s = st.decimals(min_value, max_value, allow_nan=False, places=cls.decimal_places)
274
+ if cls.lt is not None:
275
+ s = s.filter(lambda d: d < cls.lt)
276
+ if cls.gt is not None:
277
+ s = s.filter(lambda d: cls.gt < d)
278
+ return s
279
+
280
+
281
+ @resolves(pboot_validator.ConstrainedFloat)
282
+ def resolve_confloat(cls): # type: ignore[no-untyped-def]
283
+ min_value = cls.ge
284
+ max_value = cls.le
285
+ exclude_min = False
286
+ exclude_max = False
287
+
288
+ if cls.gt is not None:
289
+ assert min_value is None, 'Set `gt` or `ge`, but not both'
290
+ min_value = cls.gt
291
+ exclude_min = True
292
+ if cls.lt is not None:
293
+ assert max_value is None, 'Set `lt` or `le`, but not both'
294
+ max_value = cls.lt
295
+ exclude_max = True
296
+
297
+ if cls.multiple_of is None:
298
+ return st.floats(min_value, max_value, exclude_min=exclude_min, exclude_max=exclude_max, allow_nan=False)
299
+
300
+ if min_value is not None:
301
+ min_value = math.ceil(min_value / cls.multiple_of)
302
+ if exclude_min:
303
+ min_value = min_value + 1
304
+ if max_value is not None:
305
+ assert max_value >= cls.multiple_of, 'Cannot build model with max value smaller than multiple of'
306
+ max_value = math.floor(max_value / cls.multiple_of)
307
+ if exclude_max:
308
+ max_value = max_value - 1
309
+
310
+ return st.integers(min_value, max_value).map(lambda x: x * cls.multiple_of)
311
+
312
+
313
+ @resolves(pboot_validator.ConstrainedInt)
314
+ def resolve_conint(cls): # type: ignore[no-untyped-def]
315
+ min_value = cls.ge
316
+ max_value = cls.le
317
+ if cls.gt is not None:
318
+ assert min_value is None, 'Set `gt` or `ge`, but not both'
319
+ min_value = cls.gt + 1
320
+ if cls.lt is not None:
321
+ assert max_value is None, 'Set `lt` or `le`, but not both'
322
+ max_value = cls.lt - 1
323
+
324
+ if cls.multiple_of is None or cls.multiple_of == 1:
325
+ return st.integers(min_value, max_value)
326
+
327
+ # These adjustments and the .map handle integer-valued multiples, while the
328
+ # .filter handles trickier cases as for confloat.
329
+ if min_value is not None:
330
+ min_value = math.ceil(Fraction(min_value) / Fraction(cls.multiple_of))
331
+ if max_value is not None:
332
+ max_value = math.floor(Fraction(max_value) / Fraction(cls.multiple_of))
333
+ return st.integers(min_value, max_value).map(lambda x: x * cls.multiple_of)
334
+
335
+
336
+ @resolves(pboot_validator.ConstrainedDate)
337
+ def resolve_condate(cls): # type: ignore[no-untyped-def]
338
+ if cls.ge is not None:
339
+ assert cls.gt is None, 'Set `gt` or `ge`, but not both'
340
+ min_value = cls.ge
341
+ elif cls.gt is not None:
342
+ min_value = cls.gt + datetime.timedelta(days=1)
343
+ else:
344
+ min_value = datetime.date.min
345
+ if cls.le is not None:
346
+ assert cls.lt is None, 'Set `lt` or `le`, but not both'
347
+ max_value = cls.le
348
+ elif cls.lt is not None:
349
+ max_value = cls.lt - datetime.timedelta(days=1)
350
+ else:
351
+ max_value = datetime.date.max
352
+ return st.dates(min_value, max_value)
353
+
354
+
355
+ @resolves(pboot_validator.ConstrainedStr)
356
+ def resolve_constr(cls): # type: ignore[no-untyped-def] # pragma: no cover
357
+ min_size = cls.min_length or 0
358
+ max_size = cls.max_length
359
+
360
+ if cls.regex is None and not cls.strip_whitespace:
361
+ return st.text(min_size=min_size, max_size=max_size)
362
+
363
+ if cls.regex is not None:
364
+ strategy = st.from_regex(cls.regex)
365
+ if cls.strip_whitespace:
366
+ strategy = strategy.filter(lambda s: s == s.strip())
367
+ elif cls.strip_whitespace:
368
+ repeats = '{{{},{}}}'.format(
369
+ min_size - 2 if min_size > 2 else 0,
370
+ max_size - 2 if (max_size or 0) > 2 else '',
371
+ )
372
+ if min_size >= 2:
373
+ strategy = st.from_regex(rf'\W.{repeats}\W')
374
+ elif min_size == 1:
375
+ strategy = st.from_regex(rf'\W(.{repeats}\W)?')
376
+ else:
377
+ assert min_size == 0
378
+ strategy = st.from_regex(rf'(\W(.{repeats}\W)?)?')
379
+
380
+ if min_size == 0 and max_size is None:
381
+ return strategy
382
+ elif max_size is None:
383
+ return strategy.filter(lambda s: min_size <= len(s))
384
+ return strategy.filter(lambda s: min_size <= len(s) <= max_size)
385
+
386
+
387
+ # Finally, register all previously-defined types, and patch in our new function
388
+ for typ in list(pboot_validator.types._DEFINED_TYPES):
389
+ _registered(typ)
390
+ pboot_validator.types._registered = _registered
391
+ st.register_type_strategy(pboot_validator.Json, resolve_json)
@@ -0,0 +1,72 @@
1
+ import sys
2
+ from typing import TYPE_CHECKING, Any, Dict, FrozenSet, NamedTuple, Type
3
+
4
+ from pboot_validator.v1.fields import Required
5
+ from pboot_validator.v1.main import BaseModel, create_model
6
+ from pboot_validator.v1.typing import is_typeddict, is_typeddict_special
7
+
8
+ if TYPE_CHECKING:
9
+ from typing_extensions import TypedDict
10
+
11
+ if sys.version_info < (3, 11):
12
+
13
+ def is_legacy_typeddict(typeddict_cls: Type['TypedDict']) -> bool: # type: ignore[valid-type]
14
+ return is_typeddict(typeddict_cls) and type(typeddict_cls).__module__ == 'typing'
15
+
16
+ else:
17
+
18
+ def is_legacy_typeddict(_: Any) -> Any:
19
+ return False
20
+
21
+
22
+ def create_model_from_typeddict(
23
+ # Mypy bug: `Type[TypedDict]` is resolved as `Any` https://github.com/python/mypy/issues/11030
24
+ typeddict_cls: Type['TypedDict'], # type: ignore[valid-type]
25
+ **kwargs: Any,
26
+ ) -> Type['BaseModel']:
27
+ """
28
+ Create a `BaseModel` based on the fields of a `TypedDict`.
29
+ Since `typing.TypedDict` in Python 3.8 does not store runtime information about optional keys,
30
+ we raise an error if this happens (see https://bugs.python.org/issue38834).
31
+ """
32
+ field_definitions: Dict[str, Any]
33
+
34
+ # Best case scenario: with python 3.9+ or when `TypedDict` is imported from `typing_extensions`
35
+ if not hasattr(typeddict_cls, '__required_keys__'):
36
+ raise TypeError(
37
+ 'You should use `typing_extensions.TypedDict` instead of `typing.TypedDict` with Python < 3.9.2. '
38
+ 'Without it, there is no way to differentiate required and optional fields when subclassed.'
39
+ )
40
+
41
+ if is_legacy_typeddict(typeddict_cls) and any(
42
+ is_typeddict_special(t) for t in typeddict_cls.__annotations__.values()
43
+ ):
44
+ raise TypeError(
45
+ 'You should use `typing_extensions.TypedDict` instead of `typing.TypedDict` with Python < 3.11. '
46
+ 'Without it, there is no way to reflect Required/NotRequired keys.'
47
+ )
48
+
49
+ required_keys: FrozenSet[str] = typeddict_cls.__required_keys__ # type: ignore[attr-defined]
50
+ field_definitions = {
51
+ field_name: (field_type, Required if field_name in required_keys else None)
52
+ for field_name, field_type in typeddict_cls.__annotations__.items()
53
+ }
54
+
55
+ return create_model(typeddict_cls.__name__, **kwargs, **field_definitions)
56
+
57
+
58
+ def create_model_from_namedtuple(namedtuple_cls: Type['NamedTuple'], **kwargs: Any) -> Type['BaseModel']:
59
+ """
60
+ Create a `BaseModel` based on the fields of a named tuple.
61
+ A named tuple can be created with `typing.NamedTuple` and declared annotations
62
+ but also with `collections.namedtuple`, in this case we consider all fields
63
+ to have type `Any`.
64
+ """
65
+ # With python 3.10+, `__annotations__` always exists but can be empty hence the `getattr... or...` logic
66
+ namedtuple_annotations: Dict[str, Type[Any]] = getattr(namedtuple_cls, '__annotations__', None) or {
67
+ k: Any for k in namedtuple_cls._fields
68
+ }
69
+ field_definitions: Dict[str, Any] = {
70
+ field_name: (field_type, Required) for field_name, field_type in namedtuple_annotations.items()
71
+ }
72
+ return create_model(namedtuple_cls.__name__, **kwargs, **field_definitions)