valira 0.1.0__tar.gz
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.
- valira-0.1.0/LICENSE +21 -0
- valira-0.1.0/PKG-INFO +44 -0
- valira-0.1.0/README.md +34 -0
- valira-0.1.0/pyproject.toml +19 -0
- valira-0.1.0/setup.cfg +4 -0
- valira-0.1.0/src/valira/__init__.py +11 -0
- valira-0.1.0/src/valira/py.typed +0 -0
- valira-0.1.0/src/valira/schema.py +244 -0
- valira-0.1.0/src/valira.egg-info/PKG-INFO +44 -0
- valira-0.1.0/src/valira.egg-info/SOURCES.txt +11 -0
- valira-0.1.0/src/valira.egg-info/dependency_links.txt +1 -0
- valira-0.1.0/src/valira.egg-info/top_level.txt +1 -0
- valira-0.1.0/tests/test_validation.py +42 -0
valira-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 valira contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
valira-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: valira
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed validation for Python application data, requests, and forms
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# valira for Python
|
|
12
|
+
|
|
13
|
+
Compose input rules for requests, forms, and application data. The package supports Python 3.10 or later and has zero runtime dependencies.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
python -m pip install valira
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from valira import Success, email, number, object_schema, optional, validate
|
|
21
|
+
|
|
22
|
+
signup = object_schema({
|
|
23
|
+
"email": email(),
|
|
24
|
+
"seats": optional(number(integer=True, coerce=True, min_value=1, max_value=20)),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
result = validate(signup, {"email": "user@example.com", "seats": "2"})
|
|
28
|
+
if isinstance(result, Success):
|
|
29
|
+
print(result.data)
|
|
30
|
+
else:
|
|
31
|
+
print(result.issues)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Primitive rules cover strings, numbers, and booleans. Format rules cover common ASCII email addresses, absolute HTTP or HTTPS URLs without credentials, and international phone strings with a leading plus. These rules check format. Applications handle ownership and network access policy.
|
|
35
|
+
|
|
36
|
+
Object and array schemas validate nested dictionaries and lists. Objects drop unknown fields by default or can reject them. `optional()` permits a missing object field. Present values, including `None`, are still checked. Coercion is opt-in. `refine()` adds synchronous field or object predicates. Each issue has a path, code, and message, and built-in messages omit raw input values. Pass values after extracting them from requests or forms.
|
|
37
|
+
|
|
38
|
+
## Development
|
|
39
|
+
|
|
40
|
+
Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package.
|
|
41
|
+
|
|
42
|
+
## License
|
|
43
|
+
|
|
44
|
+
MIT
|
valira-0.1.0/README.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# valira for Python
|
|
2
|
+
|
|
3
|
+
Compose input rules for requests, forms, and application data. The package supports Python 3.10 or later and has zero runtime dependencies.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
python -m pip install valira
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from valira import Success, email, number, object_schema, optional, validate
|
|
11
|
+
|
|
12
|
+
signup = object_schema({
|
|
13
|
+
"email": email(),
|
|
14
|
+
"seats": optional(number(integer=True, coerce=True, min_value=1, max_value=20)),
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
result = validate(signup, {"email": "user@example.com", "seats": "2"})
|
|
18
|
+
if isinstance(result, Success):
|
|
19
|
+
print(result.data)
|
|
20
|
+
else:
|
|
21
|
+
print(result.issues)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Primitive rules cover strings, numbers, and booleans. Format rules cover common ASCII email addresses, absolute HTTP or HTTPS URLs without credentials, and international phone strings with a leading plus. These rules check format. Applications handle ownership and network access policy.
|
|
25
|
+
|
|
26
|
+
Object and array schemas validate nested dictionaries and lists. Objects drop unknown fields by default or can reject them. `optional()` permits a missing object field. Present values, including `None`, are still checked. Coercion is opt-in. `refine()` adds synchronous field or object predicates. Each issue has a path, code, and message, and built-in messages omit raw input values. Pass values after extracting them from requests or forms.
|
|
27
|
+
|
|
28
|
+
## Development
|
|
29
|
+
|
|
30
|
+
Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package.
|
|
31
|
+
|
|
32
|
+
## License
|
|
33
|
+
|
|
34
|
+
MIT
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "valira"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Typed validation for Python application data, requests, and forms"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = []
|
|
14
|
+
|
|
15
|
+
[tool.setuptools.packages.find]
|
|
16
|
+
where = ["src"]
|
|
17
|
+
|
|
18
|
+
[tool.setuptools.package-data]
|
|
19
|
+
valira = ["py.typed"]
|
valira-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Composable validation for data from requests and forms."""
|
|
2
|
+
|
|
3
|
+
from .schema import (
|
|
4
|
+
Failure, Issue, Schema, Success, array, boolean, email, number, object_schema,
|
|
5
|
+
optional, phone, refine, string, url, validate,
|
|
6
|
+
)
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Failure", "Issue", "Schema", "Success", "array", "boolean", "email", "number",
|
|
10
|
+
"object_schema", "optional", "phone", "refine", "string", "url", "validate",
|
|
11
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Schema rules and structured validation results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from ipaddress import IPv6Address
|
|
8
|
+
from math import isfinite
|
|
9
|
+
import re
|
|
10
|
+
from typing import Generic, TypeVar, cast
|
|
11
|
+
from urllib.parse import urlsplit
|
|
12
|
+
|
|
13
|
+
T = TypeVar("T")
|
|
14
|
+
T_co = TypeVar("T_co", covariant=True)
|
|
15
|
+
Path = tuple[str | int, ...]
|
|
16
|
+
_MISSING = object()
|
|
17
|
+
_LOCAL = re.compile(r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*",
|
|
18
|
+
re.IGNORECASE | re.ASCII)
|
|
19
|
+
_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", re.IGNORECASE | re.ASCII)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class _Invalid:
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
_INVALID = _Invalid()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Issue:
|
|
31
|
+
path: Path
|
|
32
|
+
code: str
|
|
33
|
+
message: str
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Success(Generic[T]):
|
|
38
|
+
data: T
|
|
39
|
+
ok = True
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Failure:
|
|
44
|
+
issues: tuple[Issue, ...]
|
|
45
|
+
ok = False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Schema(Generic[T_co]):
|
|
50
|
+
_read: Callable[[object, Path, list[Issue]], T_co | _Invalid]
|
|
51
|
+
_optional: bool = False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _issue(issues: list[Issue], path: Path, code: str, message: str) -> _Invalid:
|
|
55
|
+
issues.append(Issue(path, code, message))
|
|
56
|
+
return _INVALID
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _required(parser: Callable[[object, Path, list[Issue]], T | _Invalid]) -> Schema[T]:
|
|
60
|
+
def read(value: object, path: Path, issues: list[Issue]) -> T | _Invalid:
|
|
61
|
+
if value is _MISSING:
|
|
62
|
+
return _issue(issues, path, "required", "A value is required.")
|
|
63
|
+
return parser(value, path, issues)
|
|
64
|
+
return Schema(read)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def validate(schema: Schema[T], value: object) -> Success[T] | Failure:
|
|
68
|
+
issues: list[Issue] = []
|
|
69
|
+
data = schema._read(value, (), issues)
|
|
70
|
+
return Failure(tuple(issues)) if isinstance(data, _Invalid) else Success(data)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def optional(schema: Schema[T]) -> Schema[T]:
|
|
74
|
+
"""Allow a missing object field."""
|
|
75
|
+
return Schema(schema._read, _optional=True)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def refine(schema: Schema[T], predicate: Callable[[T], bool],
|
|
79
|
+
message: str = "The value does not satisfy the rule.") -> Schema[T]:
|
|
80
|
+
def read(value: object, path: Path, issues: list[Issue]) -> T | _Invalid:
|
|
81
|
+
result = schema._read(value, path, issues)
|
|
82
|
+
if isinstance(result, _Invalid) or predicate(result) is True:
|
|
83
|
+
return result
|
|
84
|
+
return _issue(issues, path, "custom", message)
|
|
85
|
+
return Schema(read, _optional=schema._optional)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _bounds(minimum: int, maximum: int | None) -> None:
|
|
89
|
+
if type(minimum) is not int or minimum < 0 or (
|
|
90
|
+
maximum is not None and (type(maximum) is not int or maximum < minimum)
|
|
91
|
+
):
|
|
92
|
+
raise ValueError("Length limits must be nonnegative integers in ascending order.")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _check_length(length: int, minimum: int, maximum: int | None, unit: str,
|
|
96
|
+
path: Path, issues: list[Issue]) -> _Invalid | None:
|
|
97
|
+
if length < minimum:
|
|
98
|
+
return _issue(issues, path, "min", f"Expected at least {minimum} {unit}.")
|
|
99
|
+
if maximum is not None and length > maximum:
|
|
100
|
+
return _issue(issues, path, "max", f"Expected at most {maximum} {unit}.")
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def string(*, trim: bool = False, min_length: int = 0, max_length: int | None = None) -> Schema[str]:
|
|
105
|
+
_bounds(min_length, max_length)
|
|
106
|
+
|
|
107
|
+
def read(value: object, path: Path, issues: list[Issue]) -> str | _Invalid:
|
|
108
|
+
if not isinstance(value, str):
|
|
109
|
+
return _issue(issues, path, "type", "Expected a string.")
|
|
110
|
+
result = value.strip() if trim else value
|
|
111
|
+
return _check_length(len(result), min_length, max_length, "characters", path, issues) or result
|
|
112
|
+
return _required(read)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _finite_number(value: object) -> bool:
|
|
116
|
+
return type(value) is int or (type(value) is float and isfinite(value))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def number(*, min_value: int | float | None = None, max_value: int | float | None = None,
|
|
120
|
+
integer: bool = False, coerce: bool = False) -> Schema[int | float]:
|
|
121
|
+
if (min_value is not None and not _finite_number(min_value)) or (
|
|
122
|
+
max_value is not None and not _finite_number(max_value)
|
|
123
|
+
) or (min_value is not None and max_value is not None and min_value > max_value):
|
|
124
|
+
raise ValueError("Number limits must be finite and in ascending order.")
|
|
125
|
+
|
|
126
|
+
def read(value: object, path: Path, issues: list[Issue]) -> int | float | _Invalid:
|
|
127
|
+
if coerce and isinstance(value, str) and re.fullmatch(r"-?[0-9]+(?:\.[0-9]+)?", value):
|
|
128
|
+
try:
|
|
129
|
+
value = float(value) if "." in value else int(value)
|
|
130
|
+
except ValueError:
|
|
131
|
+
return _issue(issues, path, "format", "The decimal number is too large.")
|
|
132
|
+
if not _finite_number(value):
|
|
133
|
+
return _issue(issues, path, "type", "Expected a finite number.")
|
|
134
|
+
numeric = cast(int | float, value)
|
|
135
|
+
if integer:
|
|
136
|
+
if isinstance(numeric, float) and not numeric.is_integer():
|
|
137
|
+
return _issue(issues, path, "format", "Expected an integer.")
|
|
138
|
+
numeric = int(numeric)
|
|
139
|
+
if min_value is not None and numeric < min_value:
|
|
140
|
+
return _issue(issues, path, "min", f"Expected a number of at least {min_value}.")
|
|
141
|
+
if max_value is not None and numeric > max_value:
|
|
142
|
+
return _issue(issues, path, "max", f"Expected a number of at most {max_value}.")
|
|
143
|
+
return numeric
|
|
144
|
+
return _required(read)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def boolean(*, coerce: bool = False) -> Schema[bool]:
|
|
148
|
+
def read(value: object, path: Path, issues: list[Issue]) -> bool | _Invalid:
|
|
149
|
+
if isinstance(value, bool):
|
|
150
|
+
return value
|
|
151
|
+
if coerce and isinstance(value, str) and value in {"true", "false"}:
|
|
152
|
+
return value == "true"
|
|
153
|
+
return _issue(issues, path, "type", "Expected a boolean.")
|
|
154
|
+
return _required(read)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _format(check: Callable[[str], bool], message: str) -> Schema[str]:
|
|
158
|
+
def read(value: object, path: Path, issues: list[Issue]) -> str | _Invalid:
|
|
159
|
+
if not isinstance(value, str):
|
|
160
|
+
return _issue(issues, path, "type", "Expected a string.")
|
|
161
|
+
return value if check(value) else _issue(issues, path, "format", message)
|
|
162
|
+
return _required(read)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def email() -> Schema[str]:
|
|
166
|
+
def check(value: str) -> bool:
|
|
167
|
+
if len(value) > 254:
|
|
168
|
+
return False
|
|
169
|
+
local, _, domain = value.partition("@")
|
|
170
|
+
return bool(len(local) <= 64 and _LOCAL.fullmatch(local) and "." in domain and all(
|
|
171
|
+
_LABEL.fullmatch(label) for label in domain.split(".")
|
|
172
|
+
))
|
|
173
|
+
return _format(check, "Expected an email address.")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def url() -> Schema[str]:
|
|
177
|
+
def check(value: str) -> bool:
|
|
178
|
+
if not re.match(r"^https?://[^/]", value, re.IGNORECASE) or any(
|
|
179
|
+
ch.isspace() or ch == "\\" or ord(ch) <= 31 or ord(ch) == 127 for ch in value
|
|
180
|
+
):
|
|
181
|
+
return False
|
|
182
|
+
try:
|
|
183
|
+
parsed = urlsplit(value)
|
|
184
|
+
host = parsed.hostname
|
|
185
|
+
if not host or parsed.username is not None or parsed.password is not None or parsed.port == 0:
|
|
186
|
+
return False
|
|
187
|
+
if ":" in host:
|
|
188
|
+
IPv6Address(host)
|
|
189
|
+
return True
|
|
190
|
+
labels = host.removesuffix(".").encode("idna").decode("ascii").split(".")
|
|
191
|
+
return all(_LABEL.fullmatch(label) is not None for label in labels)
|
|
192
|
+
except (ValueError, UnicodeError):
|
|
193
|
+
return False
|
|
194
|
+
return _format(check, "Expected an absolute HTTP or HTTPS URL without credentials.")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def phone() -> Schema[str]:
|
|
198
|
+
return _format(lambda value: re.fullmatch(r"\+[1-9][0-9]{1,14}", value) is not None,
|
|
199
|
+
"Expected an international phone number starting with +.")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def object_schema(shape: Mapping[str, Schema[object]], *,
|
|
203
|
+
unknown_keys: str = "strip") -> Schema[dict[str, object]]:
|
|
204
|
+
if unknown_keys not in {"strip", "reject"}:
|
|
205
|
+
raise ValueError("Invalid unknown key policy.")
|
|
206
|
+
fields = dict(shape)
|
|
207
|
+
if any(not isinstance(key, str) or not isinstance(rule, Schema) for key, rule in fields.items()):
|
|
208
|
+
raise ValueError("Object fields require string keys and schemas.")
|
|
209
|
+
|
|
210
|
+
def read(value: object, path: Path, issues: list[Issue]) -> dict[str, object] | _Invalid:
|
|
211
|
+
if type(value) is not dict:
|
|
212
|
+
return _issue(issues, path, "type", "Expected a dictionary.")
|
|
213
|
+
start = len(issues)
|
|
214
|
+
if unknown_keys == "reject" and any(key not in fields for key in value):
|
|
215
|
+
_issue(issues, path, "unknown_key", "The object contains unrecognized fields.")
|
|
216
|
+
result: dict[str, object] = {}
|
|
217
|
+
for key, rule in fields.items():
|
|
218
|
+
item = value.get(key, _MISSING)
|
|
219
|
+
if item is _MISSING and rule._optional:
|
|
220
|
+
continue
|
|
221
|
+
parsed = rule._read(item, (*path, key), issues)
|
|
222
|
+
if not isinstance(parsed, _Invalid):
|
|
223
|
+
result[key] = parsed
|
|
224
|
+
return _INVALID if len(issues) != start else result
|
|
225
|
+
return _required(read)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def array(item: Schema[T], *, min_length: int = 0, max_length: int = 1000) -> Schema[list[T]]:
|
|
229
|
+
_bounds(min_length, max_length)
|
|
230
|
+
|
|
231
|
+
def read(value: object, path: Path, issues: list[Issue]) -> list[T] | _Invalid:
|
|
232
|
+
if type(value) is not list:
|
|
233
|
+
return _issue(issues, path, "type", "Expected a list.")
|
|
234
|
+
error = _check_length(len(value), min_length, max_length, "items", path, issues)
|
|
235
|
+
if error:
|
|
236
|
+
return error
|
|
237
|
+
start = len(issues)
|
|
238
|
+
output: list[T] = []
|
|
239
|
+
for index, entry in enumerate(value):
|
|
240
|
+
parsed = item._read(entry, (*path, index), issues)
|
|
241
|
+
if not isinstance(parsed, _Invalid):
|
|
242
|
+
output.append(parsed)
|
|
243
|
+
return _INVALID if len(issues) != start else output
|
|
244
|
+
return _required(read)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: valira
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed validation for Python application data, requests, and forms
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# valira for Python
|
|
12
|
+
|
|
13
|
+
Compose input rules for requests, forms, and application data. The package supports Python 3.10 or later and has zero runtime dependencies.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
python -m pip install valira
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from valira import Success, email, number, object_schema, optional, validate
|
|
21
|
+
|
|
22
|
+
signup = object_schema({
|
|
23
|
+
"email": email(),
|
|
24
|
+
"seats": optional(number(integer=True, coerce=True, min_value=1, max_value=20)),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
result = validate(signup, {"email": "user@example.com", "seats": "2"})
|
|
28
|
+
if isinstance(result, Success):
|
|
29
|
+
print(result.data)
|
|
30
|
+
else:
|
|
31
|
+
print(result.issues)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Primitive rules cover strings, numbers, and booleans. Format rules cover common ASCII email addresses, absolute HTTP or HTTPS URLs without credentials, and international phone strings with a leading plus. These rules check format. Applications handle ownership and network access policy.
|
|
35
|
+
|
|
36
|
+
Object and array schemas validate nested dictionaries and lists. Objects drop unknown fields by default or can reject them. `optional()` permits a missing object field. Present values, including `None`, are still checked. Coercion is opt-in. `refine()` adds synchronous field or object predicates. Each issue has a path, code, and message, and built-in messages omit raw input values. Pass values after extracting them from requests or forms.
|
|
37
|
+
|
|
38
|
+
## Development
|
|
39
|
+
|
|
40
|
+
Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package.
|
|
41
|
+
|
|
42
|
+
## License
|
|
43
|
+
|
|
44
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/valira/__init__.py
|
|
5
|
+
src/valira/py.typed
|
|
6
|
+
src/valira/schema.py
|
|
7
|
+
src/valira.egg-info/PKG-INFO
|
|
8
|
+
src/valira.egg-info/SOURCES.txt
|
|
9
|
+
src/valira.egg-info/dependency_links.txt
|
|
10
|
+
src/valira.egg-info/top_level.txt
|
|
11
|
+
tests/test_validation.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
valira
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
from valira import Failure, Success, array, boolean, email, number, object_schema, optional, phone, refine, string, url, validate
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ValidationTests(unittest.TestCase):
|
|
7
|
+
def test_typed_values_and_unknown_fields(self):
|
|
8
|
+
schema = object_schema({
|
|
9
|
+
"email": email(), "seats": number(integer=True, coerce=True),
|
|
10
|
+
"name": optional(string(trim=True)),
|
|
11
|
+
})
|
|
12
|
+
self.assertEqual(validate(schema, {"email": "user@example.com", "seats": "2", "extra": 1}),
|
|
13
|
+
Success({"email": "user@example.com", "seats": 2}))
|
|
14
|
+
self.assertEqual(validate(boolean(coerce=True), "false"), Success(False))
|
|
15
|
+
self.assertIsInstance(validate(number(), True), Failure)
|
|
16
|
+
|
|
17
|
+
def test_paths_do_not_echo_input(self):
|
|
18
|
+
schema = object_schema({"contacts": array(object_schema({"email": email(), "phone": phone()}))},
|
|
19
|
+
unknown_keys="reject")
|
|
20
|
+
result = validate(schema, {"contacts": [{"email": "private value"}], "private key": 1})
|
|
21
|
+
self.assertIsInstance(result, Failure)
|
|
22
|
+
self.assertEqual([(x.path, x.code) for x in result.issues], [
|
|
23
|
+
((), "unknown_key"), (("contacts", 0, "email"), "format"),
|
|
24
|
+
(("contacts", 0, "phone"), "required"),
|
|
25
|
+
])
|
|
26
|
+
self.assertNotIn("private", repr(result))
|
|
27
|
+
|
|
28
|
+
def test_custom_rules_and_array_limits(self):
|
|
29
|
+
schema = object_schema({"count": refine(optional(number()), lambda value: value > 0)})
|
|
30
|
+
self.assertEqual(validate(schema, {}), Success({}))
|
|
31
|
+
self.assertIsInstance(validate(schema, {"count": 0}), Failure)
|
|
32
|
+
self.assertIsInstance(validate(array(number(), max_length=1), [1, 2]), Failure)
|
|
33
|
+
self.assertIsInstance(validate(optional(string()), None), Failure)
|
|
34
|
+
|
|
35
|
+
def test_formats_and_number_coercion(self):
|
|
36
|
+
self.assertEqual(validate(phone(), "+12025550134"), Success("+12025550134"))
|
|
37
|
+
self.assertIsInstance(validate(phone(), "202-555-0134"), Failure)
|
|
38
|
+
self.assertIsInstance(validate(url(), "https://user:secret@example.com"), Failure)
|
|
39
|
+
self.assertIsInstance(validate(url(), "https://example.com:invalid"), Failure)
|
|
40
|
+
self.assertEqual(validate(url(), "https://example.com/path"), Success("https://example.com/path"))
|
|
41
|
+
self.assertIsInstance(validate(number(coerce=True), "0x10"), Failure)
|
|
42
|
+
self.assertIsInstance(validate(number(integer=True), 1.2), Failure)
|