msb-arch 3.2.2__tar.gz → 3.3.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.
- {msb_arch-3.2.2 → msb_arch-3.3.0}/CHANGELOG.md +24 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/PKG-INFO +3 -3
- {msb_arch-3.2.2 → msb_arch-3.3.0}/README.md +2 -2
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/COMPATIBILITY.md +1 -1
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/README.md +1 -1
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/ROADMAP.md +3 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/api.md +4 -2
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/guide.md +32 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/modules/base.md +4 -5
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/modules/utils.md +6 -4
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/__init__.py +3 -2
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/base/basecontainer.py +24 -16
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/base/baseentity.py +11 -6
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/base/serializable.py +120 -58
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/super/project.py +3 -13
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/utils/validation.py +10 -3
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_constraints.py +215 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/.gitignore +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/LICENSE +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/NOTICE +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/architecture.md +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/diagrams.md +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/examples.md +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/modules/mega.md +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/docs/modules/super.md +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/pyproject.toml +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/base/__init__.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/catalogue.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/errors.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/interceptors.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/mega/__init__.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/mega/manipulator.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/model.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/pipeline.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/protocols.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/py.typed +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/results.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/scaffold.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/super/__init__.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/super/builtins.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/super/super.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/utils/__init__.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/src/msb_arch/utils/logging_setup.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/README.md +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/__init__.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/integration/__init__.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/integration/test_integration.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/performance/__init__.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/performance/test_benchmarks.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/performance/test_performance.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_adapters.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_aggregate_rules_and_copies.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_all.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_apply_methods_and_batch.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_async_surface.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_basecontainer.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_baseentity.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_builtin_operations.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_catalogue.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_compiled_validators.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_concurrency.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_declared_defaults.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_declared_fields_of_collections.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_deferred_operations.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_deprecations.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_documentation.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_errors.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_interceptors.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_interpreter_versions.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_invariants.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_manipulator.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_model_graph.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_persistence.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_pipeline.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_project.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_protocols.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_provenance.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_readonly_cache.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_replay_address.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_response.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_revision.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_scaffold.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_serialization_round_trip.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_super.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_super_argument_binding.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_typevar_resolution.py +0 -0
- {msb_arch-3.2.2 → msb_arch-3.3.0}/tests/test_utils_functions.py +0 -0
|
@@ -13,6 +13,30 @@ causes it, and what to do about it. Start there when moving between versions. An
|
|
|
13
13
|
records what was true at the time of that release and is not rewritten afterwards; where a
|
|
14
14
|
statement has since been overtaken, a note says where it was resolved.
|
|
15
15
|
|
|
16
|
+
## [3.3.0] - 2026-11-17
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- `Annotated[T, NotNone()]` requires a non-null value on construction, assignment and
|
|
21
|
+
restore. A declared default satisfies the rule. Combine it with `NonEmpty()` for a
|
|
22
|
+
required, nonblank string. See the [guide](docs/guide.md#requiring-a-field-value).
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- Container clones preserve their declared fields. A mixed `set()` that replaces items
|
|
27
|
+
and fields restores the original items when a field fails validation.
|
|
28
|
+
- Containers and projects pass required field keywords to custom constructors on restore.
|
|
29
|
+
- Postponed field annotations retain their constraints when another field names a type
|
|
30
|
+
that has yet to be defined.
|
|
31
|
+
- Restoring a field uses the underlying type of an `Annotated` entity or numeric mapping key.
|
|
32
|
+
|
|
33
|
+
### Upgrade
|
|
34
|
+
|
|
35
|
+
| Model | Action |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| Existing fields | No changes required. Unmarked fields keep their existing null behaviour. |
|
|
38
|
+
| Adding `NotNone()` to saved data | Provide a default for missing keys or migrate the records. Migrate explicit `null` values before restoring. |
|
|
39
|
+
|
|
16
40
|
## [3.2.2] - 2026-10-26
|
|
17
41
|
|
|
18
42
|
`requires-python` promised four interpreters. The workflow ran one. Two of the other three had
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: msb_arch
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.3.0
|
|
4
4
|
Summary: A dependency-free domain layer for Python: entities, invariants and operations behind one entry point, driven by requests that are data
|
|
5
5
|
Project-URL: Homepage, https://github.com/Torward1024/MSB
|
|
6
6
|
Project-URL: Documentation, https://github.com/Torward1024/MSB/docs
|
|
@@ -221,7 +221,7 @@ Description-Content-Type: text/markdown
|
|
|
221
221
|
|
|
222
222
|
[](https://www.python.org/)
|
|
223
223
|
[](LICENSE)
|
|
224
|
-
[](https://github.com/Torward1024/MSB)
|
|
225
225
|
[](pyproject.toml)
|
|
226
226
|
|
|
227
227
|
**A domain layer for Python, with no dependencies.** The model, the rules it must obey and the
|
|
@@ -513,4 +513,4 @@ Available for collaboration, contract work and support — [almax1024@gmail.com]
|
|
|
513
513
|
- **Author**: Alexey Rudnitskiy
|
|
514
514
|
- **Email**: [almax1024@gmail.com](mailto:almax1024@gmail.com)
|
|
515
515
|
- **Repository**: [https://github.com/Torward1024/MSB](https://github.com/Torward1024/MSB)
|
|
516
|
-
- **Version**: 3.
|
|
516
|
+
- **Version**: 3.3.0
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.python.org/)
|
|
4
4
|
[](LICENSE)
|
|
5
|
-
[](https://github.com/Torward1024/MSB)
|
|
6
6
|
[](pyproject.toml)
|
|
7
7
|
|
|
8
8
|
**A domain layer for Python, with no dependencies.** The model, the rules it must obey and the
|
|
@@ -294,4 +294,4 @@ Available for collaboration, contract work and support — [almax1024@gmail.com]
|
|
|
294
294
|
- **Author**: Alexey Rudnitskiy
|
|
295
295
|
- **Email**: [almax1024@gmail.com](mailto:almax1024@gmail.com)
|
|
296
296
|
- **Repository**: [https://github.com/Torward1024/MSB](https://github.com/Torward1024/MSB)
|
|
297
|
-
- **Version**: 3.
|
|
297
|
+
- **Version**: 3.3.0
|
|
@@ -32,7 +32,7 @@ short:
|
|
|
32
32
|
| **Protocols** | `MethodProvider`, `Interceptor` |
|
|
33
33
|
| **Interceptors** | `RequestMetrics`, `RequestJournal` |
|
|
34
34
|
| **Derivation** | `derive`, `label_for`, `order`, `derive_model`, `dependents_of`, `holdings_of`, `path_of` |
|
|
35
|
-
| **Constraints** | `Constraint`, `Positive`, `NonNegative`, `NonZero`, `NonEmpty`, `Range`, `Predicate`, `invariant` |
|
|
35
|
+
| **Constraints** | `Constraint`, `Positive`, `NonNegative`, `NonZero`, `NonEmpty`, `NotNone`, `Range`, `Predicate`, `invariant` |
|
|
36
36
|
| **Exceptions** | `MSBError` and everything beneath it |
|
|
37
37
|
| **Utilities** | `logger`, `setup_logging`, `cache_statistics` |
|
|
38
38
|
|
|
@@ -7,6 +7,9 @@ release changed is in [`CHANGELOG.md`](../CHANGELOG.md); what will not break is
|
|
|
7
7
|
From here MSB takes bug fixes and performance work. New surface needs a reason no existing part
|
|
8
8
|
of the framework can serve, and the table below is where that argument starts.
|
|
9
9
|
|
|
10
|
+
3.3.0 added [`NotNone()`](guide.md#requiring-a-field-value) after applications had to repeat
|
|
11
|
+
the same invariant for each required field. The rule is declared on the field itself.
|
|
12
|
+
|
|
10
13
|
## Decided against
|
|
11
14
|
|
|
12
15
|
Each was considered and closed. Recorded so it is decided once rather than argued again.
|
|
@@ -108,7 +108,8 @@ Check if attribute exists.
|
|
|
108
108
|
##### `reset_attributes() -> None`
|
|
109
109
|
|
|
110
110
|
Set every public attribute to None, releasing what it referred to. `name`, `isactive` and
|
|
111
|
-
underscore-prefixed fields are kept.
|
|
111
|
+
underscore-prefixed fields are kept. A field marked with `NotNone()` makes the reset raise
|
|
112
|
+
`ConstraintError` before clearing any field.
|
|
112
113
|
|
|
113
114
|
##### `__getitem__(key: str) -> Any`
|
|
114
115
|
|
|
@@ -1151,7 +1152,8 @@ implemented, since that is Python's contract rather than MSB's.
|
|
|
1151
1152
|
An attribute's annotation is its validation rule, enforced structurally and nested to any depth:
|
|
1152
1153
|
`Union`, `Optional`, `List`, `Set`, `FrozenSet`, `Tuple` (fixed and variadic), `Dict`, `Literal`,
|
|
1153
1154
|
`Type[X]`, `Callable`, and any `Serializable` subclass. Constraints go beside the type —
|
|
1154
|
-
`price: Annotated[float, Positive()]`.
|
|
1155
|
+
`price: Annotated[float, Positive()]`. Use `sku: Annotated[str, NotNone()]` to require a
|
|
1156
|
+
non-null value after defaults have been applied.
|
|
1155
1157
|
|
|
1156
1158
|
See [Type Validation](modules/base.md#type-validation-_validate_type) for what each hint accepts
|
|
1157
1159
|
and what it refuses.
|
|
@@ -91,6 +91,38 @@ except ConstraintError as error:
|
|
|
91
91
|
`Predicate` takes any callable and the words to use when it says no, which covers the rules that
|
|
92
92
|
have no name of their own.
|
|
93
93
|
|
|
94
|
+
### Requiring a field value
|
|
95
|
+
|
|
96
|
+
Use `NotNone()` when an object needs a value as soon as it exists. A missing field uses its
|
|
97
|
+
declared default. An explicit `None` raises `ConstraintError` even when a default exists.
|
|
98
|
+
Combine `NotNone()` with `NonEmpty()` to require a nonblank string.
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from typing import Annotated
|
|
102
|
+
from msb_arch import BaseEntity, NonEmpty, NotNone
|
|
103
|
+
|
|
104
|
+
class StockItem(BaseEntity):
|
|
105
|
+
sku: Annotated[str, NotNone(), NonEmpty()]
|
|
106
|
+
quantity: Annotated[int, NotNone()] = 0
|
|
107
|
+
note: str
|
|
108
|
+
|
|
109
|
+
item = StockItem(name="part", sku="A1")
|
|
110
|
+
assert item.quantity == 0 and item.note is None
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
# raises: ConstraintError
|
|
115
|
+
StockItem(name="part") # sku has no default
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
# raises: ConstraintError
|
|
120
|
+
item.quantity = None
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`set()` and `from_dict()` enforce the same rule. When adding it to an existing model,
|
|
124
|
+
supply a default for older records missing the field, and migrate any stored `null` values.
|
|
125
|
+
|
|
94
126
|
### A rule about the whole object
|
|
95
127
|
|
|
96
128
|
A constraint guards one value. It cannot say that a discount is not larger than the price, or that
|
|
@@ -190,10 +190,9 @@ The `_validate_type` method validates that a given value matches the expected ty
|
|
|
190
190
|
**Notes:**
|
|
191
191
|
|
|
192
192
|
- Handles complex types including Union, Dict, List, and nested entities.
|
|
193
|
-
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
annotation; enforce it with an `@invariant` or in the subclass instead.
|
|
193
|
+
- A missing field starts with its declared default, or `None` if it has none.
|
|
194
|
+
Mark a field with `Annotated[T, NotNone()]` to require a non-null value.
|
|
195
|
+
Containers also require a name as the item key. See the [required field example](../guide.md#requiring-a-field-value).
|
|
197
196
|
|
|
198
197
|
**Supported type hints:**
|
|
199
198
|
|
|
@@ -813,4 +812,4 @@ All of them derive from `MSBError`, so `except MSBError` catches anything from t
|
|
|
813
812
|
and `except ValidationError` catches anything the caller got wrong. The full tree is in the
|
|
814
813
|
[API reference](../api.md#exception-hierarchy).
|
|
815
814
|
|
|
816
|
-
All operations are logged with appropriate levels (debug, info, warning, error).
|
|
815
|
+
All operations are logged with appropriate levels (debug, info, warning, error).
|
|
@@ -292,12 +292,14 @@ except ConstraintError as error:
|
|
|
292
292
|
| `NonNegative()` | zero or greater | `check_non_negative` |
|
|
293
293
|
| `NonZero()` | not zero | `check_non_zero` |
|
|
294
294
|
| `NonEmpty()` | a string with more than whitespace | `check_non_empty_string` |
|
|
295
|
+
| `NotNone()` | a value other than `None` | -- |
|
|
295
296
|
| `Range(min, max)` | between two bounds, inclusive | `check_range` |
|
|
296
297
|
| `Predicate(test, description)` | anything a function can decide | -- |
|
|
297
298
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
299
|
+
For a supplied value, MSB checks the type, then each constraint. An unset field skips value
|
|
300
|
+
constraints unless its annotation includes `NotNone()`. Use `Annotated[str, NotNone(), NonEmpty()]`
|
|
301
|
+
for a required, nonblank string. Use `list[Annotated[str, NotNone()]]` to require a value for
|
|
302
|
+
each element when assigning the list. See the [guide](../guide.md#requiring-a-field-value).
|
|
301
303
|
|
|
302
304
|
`Predicate` is the escape hatch for a one-off rule:
|
|
303
305
|
|
|
@@ -378,4 +380,4 @@ All exceptions include descriptive messages with parameter names and expected va
|
|
|
378
380
|
depending on how a rule happens to be spelled.
|
|
379
381
|
- A `bool` is not a number for these, though Python says `True == 1`.
|
|
380
382
|
- Validation failures are logged before they are raised.
|
|
381
|
-
- Type checking uses Python's built-in `isinstance()` for efficiency
|
|
383
|
+
- Type checking uses Python's built-in `isinstance()` for efficiency
|
|
@@ -36,6 +36,7 @@ from .utils.validation import (Constraint,
|
|
|
36
36
|
NonEmpty,
|
|
37
37
|
NonNegative,
|
|
38
38
|
NonZero,
|
|
39
|
+
NotNone,
|
|
39
40
|
Positive,
|
|
40
41
|
Predicate,
|
|
41
42
|
Range)
|
|
@@ -44,11 +45,11 @@ __all__ = ["Serializable", "BaseEntity", "BaseContainer", "Super", "Project", "M
|
|
|
44
45
|
"MSBError", "ValidationError", "TypeValidationError", "ConstraintError", "InvariantError", "UnknownAttributeError", "ItemNameError",
|
|
45
46
|
"DuplicateNameError", "ResolutionError", "NotFoundError", "AttributeNotFoundError", "SerializationError",
|
|
46
47
|
"OperationError", "RegistrationError", "DispatchError", "RequestError", "HandlerError",
|
|
47
|
-
"Constraint", "invariant", "Positive", "NonNegative", "NonZero", "NonEmpty", "Range", "Predicate",
|
|
48
|
+
"Constraint", "invariant", "Positive", "NonNegative", "NonZero", "NonEmpty", "NotNone", "Range", "Predicate",
|
|
48
49
|
"MethodProvider", "Interceptor", "Inspector", "Configurator", "Catalogue", "Persistence", "Loader",
|
|
49
50
|
"derive", "label_for", "order", "derive_model", "dependents_of", "holdings_of",
|
|
50
51
|
"ReadOnlyMapping", "ReadOnlyList",
|
|
51
52
|
"path_of",
|
|
52
53
|
"RequestMetrics", "RequestJournal", "cache_statistics"]
|
|
53
54
|
|
|
54
|
-
__version__ = "3.
|
|
55
|
+
__version__ = "3.3.0"
|
|
@@ -471,11 +471,23 @@ class BaseContainer(Serializable, ABC, Generic[T]):
|
|
|
471
471
|
checked once at the end, and a refusal puts every field back.
|
|
472
472
|
"""
|
|
473
473
|
items = params.get("_items", _MISSING)
|
|
474
|
-
if items is
|
|
475
|
-
params
|
|
474
|
+
if items is _MISSING:
|
|
475
|
+
if params:
|
|
476
|
+
super().set(params)
|
|
477
|
+
return
|
|
478
|
+
if len(params) == 1:
|
|
476
479
|
self.set_items(items)
|
|
477
|
-
|
|
478
|
-
|
|
480
|
+
return
|
|
481
|
+
# A mixed write also restores the items if validation of another field fails.
|
|
482
|
+
previous = self._items.copy()
|
|
483
|
+
try:
|
|
484
|
+
self.set_items(items)
|
|
485
|
+
super().set({key: value for key, value in params.items() if key != "_items"})
|
|
486
|
+
except BaseException:
|
|
487
|
+
self._items.clear()
|
|
488
|
+
self._items.update(previous)
|
|
489
|
+
self._invalidate_cache()
|
|
490
|
+
raise
|
|
479
491
|
|
|
480
492
|
def set_items(self, items: Dict[str, T]) -> None:
|
|
481
493
|
"""Set or replace all items in the container.
|
|
@@ -541,7 +553,10 @@ class BaseContainer(Serializable, ABC, Generic[T]):
|
|
|
541
553
|
new_items = {name: item.clone() for name, item in list(self._items.items())}
|
|
542
554
|
else:
|
|
543
555
|
new_items = self._items.copy()
|
|
544
|
-
|
|
556
|
+
fields = {key: getattr(self, key) for key in self._written_fields()
|
|
557
|
+
if key not in _RESTORED_SEPARATELY}
|
|
558
|
+
return self._with_fields(deepcopy(fields) if deep else fields, items=new_items,
|
|
559
|
+
name=self.name, isactive=self.isactive, use_cache=self._use_cache)
|
|
545
560
|
|
|
546
561
|
def activate_item(self, name: str) -> None:
|
|
547
562
|
"""Activate an item in the container by its name.
|
|
@@ -741,16 +756,9 @@ class BaseContainer(Serializable, ABC, Generic[T]):
|
|
|
741
756
|
# The container's own declared fields, which `to_dict` has always written and this used
|
|
742
757
|
# to drop -- restoring the class's defaults over what the file said.
|
|
743
758
|
fields = cls._declared_payload(data, _RESTORED_SEPARATELY)
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
restored = cls(items=items, name=data.get("name"), isactive=data.get("isactive", True))
|
|
748
|
-
if fields:
|
|
749
|
-
# A subclass with a constructor of its own takes the arguments it declared; its
|
|
750
|
-
# fields are written afterwards, as one group so its rules are checked once.
|
|
751
|
-
restored.set(fields)
|
|
752
|
-
return restored
|
|
753
|
-
|
|
759
|
+
return cls._with_fields(fields, items=items, name=data.get("name"),
|
|
760
|
+
isactive=data.get("isactive", True))
|
|
761
|
+
|
|
754
762
|
def __iter__(self) -> Iterator[T]:
|
|
755
763
|
"""Iterate over the items in the container.
|
|
756
764
|
|
|
@@ -861,4 +869,4 @@ class BaseContainer(Serializable, ABC, Generic[T]):
|
|
|
861
869
|
attrs.append(f"count={len(self._items)}")
|
|
862
870
|
attrs.append(f"active={active_count}")
|
|
863
871
|
attrs.append(f"inactive={len(self._items) - active_count}")
|
|
864
|
-
return f"{self.__class__.__name__}({', '.join(attr for attr in attrs if attr)})"
|
|
872
|
+
return f"{self.__class__.__name__}({', '.join(attr for attr in attrs if attr)})"
|
|
@@ -132,6 +132,9 @@ class BaseEntity(Serializable):
|
|
|
132
132
|
def reset_attributes(self) -> None:
|
|
133
133
|
"""Set every public attribute to None, releasing whatever it referred to.
|
|
134
134
|
|
|
135
|
+
Raises:
|
|
136
|
+
ConstraintError: If a field to reset is marked with `NotNone()`.
|
|
137
|
+
|
|
135
138
|
Notes:
|
|
136
139
|
- 'name' and 'isactive' are kept, and so is every underscore-prefixed field:
|
|
137
140
|
those hold framework state such as the shared type cache, and nulling them
|
|
@@ -146,10 +149,12 @@ class BaseEntity(Serializable):
|
|
|
146
149
|
>>> part.price is None
|
|
147
150
|
True
|
|
148
151
|
"""
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
152
|
+
# Refuse the reset before clearing any other field.
|
|
153
|
+
for key, rule in self._init_plan()[2].items():
|
|
154
|
+
if key not in _INTERNAL and not key.startswith('_'):
|
|
155
|
+
rule.check(None, f"Attribute '{key}'")
|
|
156
|
+
for key in self._written_fields():
|
|
157
|
+
if key not in _INTERNAL and hasattr(self, key):
|
|
153
158
|
super().__setattr__(key, None)
|
|
154
159
|
self._invalidate_cache()
|
|
155
160
|
|
|
@@ -181,7 +186,7 @@ class BaseEntity(Serializable):
|
|
|
181
186
|
"""
|
|
182
187
|
if key not in self._fields:
|
|
183
188
|
raise NotFoundError(f"Attribute '{key}' not found in {self.__class__.__name__}")
|
|
184
|
-
expected_type = self.
|
|
189
|
+
expected_type = self._resolved_fields()[key]
|
|
185
190
|
self._validate_type(key, value, expected_type)
|
|
186
191
|
setattr(self, key, value)
|
|
187
192
|
self._invalidate_cache()
|
|
@@ -239,4 +244,4 @@ class BaseEntity(Serializable):
|
|
|
239
244
|
attrs.append(f"{k}=<{value.__class__.__name__} at {id(value)}>")
|
|
240
245
|
else:
|
|
241
246
|
attrs.append(f"{k}={value!r}")
|
|
242
|
-
return f"{self.__class__.__name__}({', '.join(attr for attr in attrs if attr)})"
|
|
247
|
+
return f"{self.__class__.__name__}({', '.join(attr for attr in attrs if attr)})"
|
|
@@ -25,7 +25,7 @@ from ..errors import (AttributeNotFoundError,
|
|
|
25
25
|
TypeValidationError,
|
|
26
26
|
UnknownAttributeError)
|
|
27
27
|
from ..utils.logging_setup import logger
|
|
28
|
-
from ..utils.validation import Constraint
|
|
28
|
+
from ..utils.validation import Constraint, NotNone
|
|
29
29
|
|
|
30
30
|
CYCLIC_REFERENCE = "<cyclic reference>"
|
|
31
31
|
|
|
@@ -41,6 +41,14 @@ _MISSING = object()
|
|
|
41
41
|
#: empty" rather than "all share this one".
|
|
42
42
|
_MUTABLE_STARTS = (list, dict, set, bytearray)
|
|
43
43
|
|
|
44
|
+
|
|
45
|
+
def _not_none_rule(hint: Any) -> Optional[NotNone]:
|
|
46
|
+
"""Return the rule on this position, without inspecting nested annotations."""
|
|
47
|
+
for rule in getattr(hint, '__metadata__', ()):
|
|
48
|
+
if isinstance(rule, NotNone):
|
|
49
|
+
return rule
|
|
50
|
+
return None
|
|
51
|
+
|
|
44
52
|
# Guards the class registry. Declaring a class and reading the registry can happen on
|
|
45
53
|
# different threads, and a WeakSet cannot be added to while it is being iterated.
|
|
46
54
|
_REGISTRY_LOCK = RLock()
|
|
@@ -391,17 +399,17 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
391
399
|
self._validate_type('isactive', isactive, bool)
|
|
392
400
|
super().__setattr__('isactive', isactive)
|
|
393
401
|
|
|
394
|
-
settable, known = self.__class__._init_plan()
|
|
402
|
+
settable, known, required = self.__class__._init_plan()
|
|
395
403
|
for field, expected_type, checker, start, copied in settable:
|
|
396
404
|
if field in _INTERNAL and field not in kwargs:
|
|
397
405
|
continue
|
|
398
406
|
value = kwargs.get(field, _MISSING)
|
|
399
407
|
if value is _MISSING:
|
|
400
408
|
value = copy(start) if copied else start
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
409
|
+
if value is None:
|
|
410
|
+
if field in required:
|
|
411
|
+
required[field].check(None, f"Attribute '{field}'")
|
|
412
|
+
elif checker is None or not checker(value):
|
|
405
413
|
self._check_type(field, value, expected_type, f"Attribute '{field}'")
|
|
406
414
|
super().__setattr__(field, value)
|
|
407
415
|
if isinstance(value, Serializable):
|
|
@@ -613,23 +621,23 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
613
621
|
TypeError: If the value does not match the expected type, or if 'name' is None.
|
|
614
622
|
|
|
615
623
|
Notes:
|
|
616
|
-
-
|
|
617
|
-
|
|
618
|
-
cannot be expressed through the annotation alone; enforce it in the subclass.
|
|
619
|
-
- 'name' is the only mandatory attribute: containers index their items by it.
|
|
624
|
+
- An unset field is allowed unless its annotation carries `NotNone()`.
|
|
625
|
+
- Containers require a name to index their items.
|
|
620
626
|
- The structural check is delegated to `_check_type`, which walks nested generics.
|
|
621
627
|
"""
|
|
622
|
-
if key == 'name' and value is None:
|
|
623
|
-
raise TypeValidationError(f"Attribute '{key}' cannot be None")
|
|
624
628
|
if value is None:
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
629
|
+
if key == 'name':
|
|
630
|
+
raise TypeValidationError(f"Attribute '{key}' cannot be None")
|
|
631
|
+
if key == 'isactive':
|
|
632
|
+
# The fast path for built-in state passes bool here even on a subclass.
|
|
633
|
+
expected_type = self._resolved_fields()[key]
|
|
634
|
+
else:
|
|
635
|
+
checker = self.__class__._compiled_validator(expected_type)
|
|
636
|
+
if checker is not None and checker(value):
|
|
637
|
+
return
|
|
630
638
|
|
|
631
639
|
# Nothing compiled, or the compiled form said no and the walk names what failed.
|
|
632
|
-
self.
|
|
640
|
+
self._check_value(key, value, expected_type, f"Attribute '{key}'")
|
|
633
641
|
|
|
634
642
|
@classmethod
|
|
635
643
|
def _resolved_fields(cls) -> Dict[str, Any]:
|
|
@@ -698,10 +706,10 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
698
706
|
"""Return the fields to set when building one of these, and the names it accepts.
|
|
699
707
|
|
|
700
708
|
Returns:
|
|
701
|
-
|
|
709
|
+
tuple: For each field, its
|
|
702
710
|
name, its resolved annotation, its compiled check, what it starts as, and
|
|
703
711
|
whether that has to be copied per instance. Plus the set of names a constructor
|
|
704
|
-
may be given.
|
|
712
|
+
may be given and the fields with a `NotNone` constraint.
|
|
705
713
|
|
|
706
714
|
Notes:
|
|
707
715
|
- Resolving an annotation gives the same answer for every instance, so it is done
|
|
@@ -718,21 +726,44 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
718
726
|
list shared by every object of a class is never what was meant.
|
|
719
727
|
"""
|
|
720
728
|
plan = cls.__dict__.get('_init_plan_cache')
|
|
721
|
-
if plan is not None and plan[
|
|
722
|
-
return plan
|
|
729
|
+
if plan is not None and len(plan[1]) == len(cls._fields):
|
|
730
|
+
return plan
|
|
723
731
|
|
|
724
732
|
settable = []
|
|
733
|
+
required = {}
|
|
725
734
|
for field, hint in cls._fields.items():
|
|
726
735
|
start, copied = cls._starting_value(field)
|
|
727
736
|
try:
|
|
728
|
-
resolved = cls.
|
|
737
|
+
resolved = cls._declared_type(field, hint)
|
|
729
738
|
except Exception: # reported later, against a real value
|
|
730
739
|
settable.append((field, hint, None, start, copied))
|
|
731
740
|
continue
|
|
732
|
-
settable.append((field, resolved, cls._compiled_validator(
|
|
733
|
-
|
|
741
|
+
settable.append((field, resolved, cls._compiled_validator(resolved), start, copied))
|
|
742
|
+
rule = _not_none_rule(resolved)
|
|
743
|
+
if rule is not None:
|
|
744
|
+
required[field] = rule
|
|
745
|
+
built = (tuple(settable), frozenset(cls._fields), required)
|
|
734
746
|
type.__setattr__(cls, '_init_plan_cache', built)
|
|
735
|
-
return built
|
|
747
|
+
return built
|
|
748
|
+
|
|
749
|
+
@classmethod
|
|
750
|
+
def _declared_type(cls, field: str, hint: Any) -> Any:
|
|
751
|
+
"""Resolve a postponed expression in the scope of the class which declared it."""
|
|
752
|
+
if isinstance(hint, str) and '[' in hint:
|
|
753
|
+
from inspect import get_annotations, getmodule
|
|
754
|
+
for owner in cls.__mro__:
|
|
755
|
+
if _own_annotations(owner).get(field) != hint:
|
|
756
|
+
continue
|
|
757
|
+
# Inspect only this declaration. An unrelated forward reference can still
|
|
758
|
+
# be unresolved. Serialized type names never enter this path.
|
|
759
|
+
def declaration() -> hint:
|
|
760
|
+
pass
|
|
761
|
+
module = getmodule(owner)
|
|
762
|
+
scope = dict(vars(owner))
|
|
763
|
+
scope[owner.__name__] = owner
|
|
764
|
+
return get_annotations(declaration, globals=vars(module) if module else {},
|
|
765
|
+
locals=scope, eval_str=True)['return']
|
|
766
|
+
return cls._resolve_type(hint)
|
|
736
767
|
|
|
737
768
|
@classmethod
|
|
738
769
|
def _starting_value(cls, field: str):
|
|
@@ -835,31 +866,48 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
835
866
|
self._invalidate_cache()
|
|
836
867
|
|
|
837
868
|
@classmethod
|
|
838
|
-
def
|
|
839
|
-
"""
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
bool: True when `__init__` has a `**kwargs` of its own.
|
|
843
|
-
|
|
844
|
-
Notes:
|
|
845
|
-
- A subclass is free to write a narrower constructor -- `__init__(self, name, items)`
|
|
846
|
-
is a common and reasonable one -- and `from_dict` must not hand such a class
|
|
847
|
-
keywords it never asked for. Where it cannot, the fields are applied after
|
|
848
|
-
construction instead.
|
|
849
|
-
- Worked out once per class: reading a signature is not something to do per object.
|
|
850
|
-
"""
|
|
851
|
-
cached = cls.__dict__.get('_field_kwargs_cache')
|
|
852
|
-
if cached is not None:
|
|
869
|
+
def _constructor_keywords(cls) -> Optional[Dict[str, bool]]:
|
|
870
|
+
"""Map accepted keywords to whether they are required, or return None for **kwargs."""
|
|
871
|
+
cached = cls.__dict__.get('_field_kwargs_cache', _MISSING)
|
|
872
|
+
if cached is not _MISSING:
|
|
853
873
|
return cached
|
|
854
874
|
|
|
855
875
|
from inspect import Parameter, signature
|
|
856
876
|
try:
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
877
|
+
params = signature(cls.__init__).parameters.values()
|
|
878
|
+
except (TypeError, ValueError):
|
|
879
|
+
params = ()
|
|
880
|
+
keywords = None
|
|
881
|
+
if not any(p.kind is Parameter.VAR_KEYWORD for p in params):
|
|
882
|
+
keywords = {p.name: p.default is Parameter.empty for p in params
|
|
883
|
+
if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)}
|
|
884
|
+
type.__setattr__(cls, '_field_kwargs_cache', keywords)
|
|
885
|
+
return keywords
|
|
886
|
+
|
|
887
|
+
@classmethod
|
|
888
|
+
def _with_fields(cls, fields: Dict[str, Any], **options: Any):
|
|
889
|
+
"""Pass declared fields to the constructor it exposes and apply the rest as a group."""
|
|
890
|
+
keywords = cls._constructor_keywords()
|
|
891
|
+
if keywords is None:
|
|
892
|
+
return cls(**options, **fields)
|
|
893
|
+
required = cls._init_plan()[2]
|
|
894
|
+
# Existing optional fields of narrow constructors are restored after construction.
|
|
895
|
+
# Only pass a field early if the signature or its NotNone annotation requires it.
|
|
896
|
+
initial = {key: value for key, value in fields.items()
|
|
897
|
+
if key in keywords and (keywords[key] or key in required)}
|
|
898
|
+
pending = {key: value for key, value in fields.items() if key not in initial}
|
|
899
|
+
# Older project constructors take only name and items. Their activation flag is
|
|
900
|
+
# restored after construction when the stored value differs from its default.
|
|
901
|
+
if 'isactive' not in keywords and 'isactive' in options:
|
|
902
|
+
active = options.pop('isactive')
|
|
903
|
+
if active is not True:
|
|
904
|
+
pending['isactive'] = active
|
|
905
|
+
if 'use_cache' not in keywords:
|
|
906
|
+
options.pop('use_cache', None)
|
|
907
|
+
restored = cls(**options, **initial)
|
|
908
|
+
if pending:
|
|
909
|
+
restored.set(pending)
|
|
910
|
+
return restored
|
|
863
911
|
|
|
864
912
|
@classmethod
|
|
865
913
|
def _declared_payload(cls, data: Dict[str, Any], skip: frozenset) -> Dict[str, Any]:
|
|
@@ -1053,6 +1101,22 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
1053
1101
|
table[hint] = shape
|
|
1054
1102
|
return shape
|
|
1055
1103
|
|
|
1104
|
+
@classmethod
|
|
1105
|
+
def _check_value(cls, key: str, value: Any, hint: Any, subject: str, *,
|
|
1106
|
+
allow_unset: bool = True) -> None:
|
|
1107
|
+
"""Apply the null rule at this annotation, then check the type of a supplied value.
|
|
1108
|
+
|
|
1109
|
+
Mapping keys always undergo their type check. Other positions allow an unset value
|
|
1110
|
+
unless explicitly marked. Existing constraints only receive supplied values.
|
|
1111
|
+
"""
|
|
1112
|
+
if value is None:
|
|
1113
|
+
rule = _not_none_rule(hint)
|
|
1114
|
+
if rule is not None:
|
|
1115
|
+
rule.check(None, subject)
|
|
1116
|
+
if allow_unset:
|
|
1117
|
+
return
|
|
1118
|
+
cls._check_type(key, value, hint, subject)
|
|
1119
|
+
|
|
1056
1120
|
@classmethod
|
|
1057
1121
|
def _check_type(cls, key: str, value: Any, expected_type: Any, subject: str) -> None:
|
|
1058
1122
|
"""Recursively check a non-None value against a (possibly generic) type hint.
|
|
@@ -1072,7 +1136,7 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
1072
1136
|
TypeError: If the value does not match the expected type.
|
|
1073
1137
|
|
|
1074
1138
|
Notes:
|
|
1075
|
-
-
|
|
1139
|
+
- Collection values follow the same null rule as a field via `_check_value`.
|
|
1076
1140
|
- Type hints whose origin is an abstract collection (e.g. `Sequence[int]`) are
|
|
1077
1141
|
checked with `isinstance` against the origin only; their elements are left
|
|
1078
1142
|
unchecked so that arbitrary iterables are never consumed during validation.
|
|
@@ -1171,9 +1235,7 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
1171
1235
|
if resolved_item_type is Any:
|
|
1172
1236
|
return
|
|
1173
1237
|
for item in values:
|
|
1174
|
-
|
|
1175
|
-
continue
|
|
1176
|
-
cls._check_type(key, item, resolved_item_type, subject)
|
|
1238
|
+
cls._check_value(key, item, resolved_item_type, subject)
|
|
1177
1239
|
@classmethod
|
|
1178
1240
|
def _check_mapping(cls, key: str, value: Dict[Any, Any], key_type: Any, value_type: Any,
|
|
1179
1241
|
subject: str) -> None:
|
|
@@ -1197,9 +1259,9 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
1197
1259
|
return
|
|
1198
1260
|
for k, v in value.items():
|
|
1199
1261
|
if check_keys:
|
|
1200
|
-
cls.
|
|
1201
|
-
if check_values
|
|
1202
|
-
cls.
|
|
1262
|
+
cls._check_value(key, k, resolved_key_type, f"Key in '{key}'", allow_unset=False)
|
|
1263
|
+
if check_values:
|
|
1264
|
+
cls._check_value(key, v, resolved_value_type, f"Value in '{key}'")
|
|
1203
1265
|
@classmethod
|
|
1204
1266
|
def _check_tuple(cls, key: str, value: tuple, type_args: tuple, subject: str) -> None:
|
|
1205
1267
|
"""Check a tuple against either a variadic or a fixed-length type hint.
|
|
@@ -1224,9 +1286,7 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
1224
1286
|
if len(value) != len(type_args):
|
|
1225
1287
|
raise TypeValidationError(f"{subject} must have {len(type_args)} items, got {len(value)}")
|
|
1226
1288
|
for index, (item, item_type) in enumerate(zip(value, type_args)):
|
|
1227
|
-
|
|
1228
|
-
continue
|
|
1229
|
-
cls._check_type(key, item, item_type, f"Item {index} in tuple '{key}'")
|
|
1289
|
+
cls._check_value(key, item, item_type, f"Item {index} in tuple '{key}'")
|
|
1230
1290
|
def activate(self) -> None:
|
|
1231
1291
|
"""Activate the entity, setting its status to active.
|
|
1232
1292
|
|
|
@@ -1358,7 +1418,7 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
1358
1418
|
if value is None:
|
|
1359
1419
|
return None
|
|
1360
1420
|
|
|
1361
|
-
|
|
1421
|
+
hint, _, origin, args = cls._hint_shape(hint)
|
|
1362
1422
|
|
|
1363
1423
|
# A number or a string against an unparameterized hint is already what it will be.
|
|
1364
1424
|
if origin is None and type(value) in _PLAIN:
|
|
@@ -1409,6 +1469,8 @@ class Serializable(ABC, metaclass=EntityMeta):
|
|
|
1409
1469
|
return tuple(value)
|
|
1410
1470
|
if origin is dict and isinstance(value, dict):
|
|
1411
1471
|
key_hint = args[0] if len(args) == 2 else Any
|
|
1472
|
+
if hasattr(key_hint, '__metadata__'):
|
|
1473
|
+
key_hint = cls._hint_shape(key_hint)[0]
|
|
1412
1474
|
member = args[1] if len(args) == 2 else Any
|
|
1413
1475
|
return {cls._restore_key(key, key_hint): cls._deserialize_value(item, member,
|
|
1414
1476
|
field_path,
|
|
@@ -483,18 +483,8 @@ class Project(Serializable, ABC):
|
|
|
483
483
|
logger.error("Failed to deserialize item '%s' for project: %s", k, str(e))
|
|
484
484
|
raise SerializationError(f"Invalid data for item '{k}': {str(e)}") from e
|
|
485
485
|
fields = cls._declared_payload(data, _RESTORED_SEPARATELY)
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
return cls(name=data["name"], items=items, isactive=isactive, **fields)
|
|
489
|
-
# A subclass that wrote its own constructor takes the two arguments it declared --
|
|
490
|
-
# `__init__(self, name, items)` is the common shape -- so the rest is applied after
|
|
491
|
-
# it, as one group, with the rules checked once.
|
|
492
|
-
restored = cls(name=data["name"], items=items)
|
|
493
|
-
if isactive is not True:
|
|
494
|
-
restored.isactive = isactive
|
|
495
|
-
if fields:
|
|
496
|
-
restored.set(fields)
|
|
497
|
-
return restored
|
|
486
|
+
return cls._with_fields(fields, name=data["name"], items=items,
|
|
487
|
+
isactive=data.get("isactive", True))
|
|
498
488
|
except (KeyError, TypeError, ValueError) as e:
|
|
499
489
|
logger.error("Failed to deserialize Project from dict with name '%s': %s", data.get('name', 'unknown'), str(e))
|
|
500
490
|
raise SerializationError(f"Invalid project data: {str(e)}") from e
|
|
@@ -530,4 +520,4 @@ class Project(Serializable, ABC):
|
|
|
530
520
|
|
|
531
521
|
def __repr__(self) -> str:
|
|
532
522
|
"""Return a string representation of the Project."""
|
|
533
|
-
return f"Project(name='{self.name}', items_count={len(self._items)})"
|
|
523
|
+
return f"Project(name='{self.name}', items_count={len(self._items)})"
|
|
@@ -272,9 +272,8 @@ class Constraint(ABC):
|
|
|
272
272
|
class Product(BaseEntity):
|
|
273
273
|
price: Annotated[float, Positive()]
|
|
274
274
|
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
above, which is where the message and the logging live.
|
|
275
|
+
For supplied values, the annotation is checked before its constraints. An unset field
|
|
276
|
+
skips these checks unless its annotation includes `NotNone()`.
|
|
278
277
|
|
|
279
278
|
Subclass this to add a rule of your own; `check` is the whole interface.
|
|
280
279
|
"""
|
|
@@ -323,6 +322,14 @@ class NonEmpty(Constraint):
|
|
|
323
322
|
check_non_empty_string(value, name)
|
|
324
323
|
|
|
325
324
|
|
|
325
|
+
class NotNone(Constraint):
|
|
326
|
+
"""Require a value after applying the field's declared default."""
|
|
327
|
+
|
|
328
|
+
def check(self, value: Any, name: str) -> None:
|
|
329
|
+
if value is None:
|
|
330
|
+
raise ConstraintError(f"{name} must not be None")
|
|
331
|
+
|
|
332
|
+
|
|
326
333
|
class Range(Constraint):
|
|
327
334
|
"""The value must lie between two bounds, inclusive."""
|
|
328
335
|
|
|
@@ -10,16 +10,20 @@ arrives -- construction, `set`, and restoring from serialized data -- rather tha
|
|
|
10
10
|
author remembered to check.
|
|
11
11
|
"""
|
|
12
12
|
import json
|
|
13
|
+
from types import ModuleType
|
|
13
14
|
from typing import Annotated, Any, Dict, List, Literal, Optional
|
|
14
15
|
|
|
15
16
|
import pytest
|
|
16
17
|
|
|
17
18
|
from msb_arch import (BaseContainer,
|
|
18
19
|
BaseEntity,
|
|
20
|
+
Manipulator,
|
|
19
21
|
NonEmpty,
|
|
20
22
|
NonZero,
|
|
23
|
+
NotNone,
|
|
21
24
|
Positive,
|
|
22
25
|
Predicate,
|
|
26
|
+
Project,
|
|
23
27
|
Range,
|
|
24
28
|
errors)
|
|
25
29
|
|
|
@@ -98,6 +102,217 @@ def test_none_is_still_allowed_where_the_annotation_permits_it():
|
|
|
98
102
|
assert Optionalish(name="o").margin is None
|
|
99
103
|
|
|
100
104
|
|
|
105
|
+
class StockRecord(BaseEntity):
|
|
106
|
+
description: str
|
|
107
|
+
sku: Annotated[str, NonEmpty(), NotNone()]
|
|
108
|
+
count: Annotated[int, NotNone()] = 0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@pytest.mark.parametrize("fields", [{}, {"sku": None}, {"sku": "A1", "count": None}])
|
|
112
|
+
def test_not_none_checks_the_value_after_defaults(fields):
|
|
113
|
+
field = "count" if "count" in fields else "sku"
|
|
114
|
+
with pytest.raises(errors.ConstraintError, match=field + "'.*None"):
|
|
115
|
+
StockRecord(name="p", **fields)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_a_subclass_can_make_an_inherited_required_field_nullable():
|
|
119
|
+
class DraftStock(StockRecord):
|
|
120
|
+
sku: str
|
|
121
|
+
|
|
122
|
+
assert DraftStock(name="draft").sku is None
|
|
123
|
+
with pytest.raises(errors.ConstraintError, match="sku"):
|
|
124
|
+
StockRecord(name="final")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_not_none_preserves_falsy_values_and_the_underlying_type():
|
|
128
|
+
class Entry(BaseEntity):
|
|
129
|
+
value: Annotated[Any, NotNone()]
|
|
130
|
+
|
|
131
|
+
for value in (0, False, "", [], {}):
|
|
132
|
+
assert Entry(name="e", value=value).value is value
|
|
133
|
+
with pytest.raises(errors.TypeValidationError, match="sku"):
|
|
134
|
+
StockRecord(name="p", sku=12)
|
|
135
|
+
with pytest.raises(errors.ConstraintError, match="empty"):
|
|
136
|
+
StockRecord(name="p", sku=" ")
|
|
137
|
+
assert make(label=None).label is None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def test_not_none_rejects_assignment_and_rolls_back_group_writes_and_reset():
|
|
141
|
+
row = StockRecord(name="p", sku="A1", description="original")
|
|
142
|
+
before = row.to_dict()
|
|
143
|
+
with pytest.raises(errors.ConstraintError, match="sku"):
|
|
144
|
+
row.sku = None
|
|
145
|
+
with pytest.raises(errors.ConstraintError, match="sku"):
|
|
146
|
+
row["sku"] = None
|
|
147
|
+
with pytest.raises(errors.ConstraintError, match="sku"):
|
|
148
|
+
row.set({"description": "changed", "sku": None})
|
|
149
|
+
assert row.to_dict() == before
|
|
150
|
+
with pytest.raises(errors.ConstraintError, match="sku"):
|
|
151
|
+
row.reset_attributes()
|
|
152
|
+
assert row.to_dict() == before
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def test_not_none_restores_valid_data_and_uses_defaults_for_missing_keys():
|
|
156
|
+
row = StockRecord(name="p", sku="A1")
|
|
157
|
+
payload = json.loads(json.dumps(row.to_dict()))
|
|
158
|
+
assert StockRecord.from_dict(payload) == row
|
|
159
|
+
del payload["count"]
|
|
160
|
+
assert StockRecord.from_dict(payload).count == 0
|
|
161
|
+
payload["sku"] = None
|
|
162
|
+
with pytest.raises(errors.ConstraintError, match="sku"):
|
|
163
|
+
StockRecord.from_dict(payload)
|
|
164
|
+
del payload["sku"]
|
|
165
|
+
with pytest.raises(errors.ConstraintError, match="sku"):
|
|
166
|
+
StockRecord.from_dict(payload)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@pytest.mark.parametrize(("hint", "bad"), [
|
|
170
|
+
(list[Annotated[int, NotNone()]], [None]),
|
|
171
|
+
(tuple[Annotated[int, NotNone()], ...], (None,)),
|
|
172
|
+
(tuple[str, Annotated[int, NotNone()]], ("a", None)),
|
|
173
|
+
(dict[str, Annotated[int, NotNone()]], {"a": None}),
|
|
174
|
+
(dict[Annotated[str, NotNone()], int], {None: 1}),
|
|
175
|
+
])
|
|
176
|
+
def test_not_none_applies_at_the_annotated_collection_position(hint, bad):
|
|
177
|
+
class Entries(BaseEntity):
|
|
178
|
+
values: hint
|
|
179
|
+
|
|
180
|
+
assert Entries(name="e").values is None
|
|
181
|
+
with pytest.raises(errors.ConstraintError, match="values"):
|
|
182
|
+
Entries(name="e", values=bad)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def test_not_none_on_a_collection_leaves_unmarked_items_nullable():
|
|
186
|
+
class Entries(BaseEntity):
|
|
187
|
+
values: Annotated[list[int], NotNone()]
|
|
188
|
+
labels: dict[str, str]
|
|
189
|
+
optional: Optional[Annotated[int, NotNone()]]
|
|
190
|
+
|
|
191
|
+
assert Entries(name="e", values=[None], labels={"a": None}).optional is None
|
|
192
|
+
with pytest.raises(errors.ConstraintError, match="values"):
|
|
193
|
+
Entries(name="e")
|
|
194
|
+
with pytest.raises(errors.TypeValidationError, match="Key"):
|
|
195
|
+
Entries(name="e", values=[], labels={None: "invalid"})
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def test_required_fields_in_postponed_annotations(monkeypatch):
|
|
199
|
+
import sys
|
|
200
|
+
module = ModuleType("postponed_stock_model")
|
|
201
|
+
monkeypatch.setitem(sys.modules, module.__name__, module)
|
|
202
|
+
exec(
|
|
203
|
+
"from __future__ import annotations\n"
|
|
204
|
+
"from typing import Annotated\n"
|
|
205
|
+
"from msb_arch import BaseEntity, NotNone\n"
|
|
206
|
+
"class Stock(BaseEntity):\n"
|
|
207
|
+
" count: Annotated[int, NotNone()]\n"
|
|
208
|
+
" later: 'DefinedByTheApplicationLater'\n",
|
|
209
|
+
module.__dict__,
|
|
210
|
+
)
|
|
211
|
+
stock = module.Stock(name="a", count=0)
|
|
212
|
+
with pytest.raises(errors.ConstraintError, match="count"):
|
|
213
|
+
stock["count"] = None
|
|
214
|
+
with pytest.raises(errors.ConstraintError, match="count"):
|
|
215
|
+
module.Stock.from_dict({"name": "a"})
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def test_not_none_applies_to_an_explicitly_marked_activation_flag():
|
|
219
|
+
class Flag(BaseEntity):
|
|
220
|
+
isactive: Annotated[bool, NotNone()]
|
|
221
|
+
|
|
222
|
+
with pytest.raises(errors.ConstraintError, match="isactive"):
|
|
223
|
+
Flag(name="a", isactive=None)
|
|
224
|
+
flag = Flag(name="a", isactive=False)
|
|
225
|
+
with pytest.raises(errors.ConstraintError, match="isactive"):
|
|
226
|
+
flag.isactive = None
|
|
227
|
+
assert flag.isactive is False
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@pytest.mark.parametrize("deep", [False, True])
|
|
231
|
+
def test_cloning_a_container_keeps_required_fields_and_item_copy_policy(deep):
|
|
232
|
+
class StockBin(BaseContainer[StockRecord]):
|
|
233
|
+
label: Annotated[list[str], NotNone()]
|
|
234
|
+
|
|
235
|
+
row = StockRecord(name="p", sku="A1")
|
|
236
|
+
box = StockBin(name="bin", items={"p": row}, label=["west"])
|
|
237
|
+
cloned = box.clone(deep=deep)
|
|
238
|
+
assert cloned == box
|
|
239
|
+
assert (cloned.label is box.label) is (not deep)
|
|
240
|
+
assert (cloned.get("p") is row) is (not deep)
|
|
241
|
+
assert StockBin.from_dict(box.to_dict()) == box
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def test_annotated_key_and_entity_restore_from_plain_data():
|
|
245
|
+
class CountSheet(BaseEntity):
|
|
246
|
+
counts: dict[Annotated[int, NotNone()], int]
|
|
247
|
+
row: Annotated[StockRecord, NotNone()]
|
|
248
|
+
|
|
249
|
+
sheet = CountSheet.from_dict({"name": "s", "counts": {"1": 0},
|
|
250
|
+
"row": {"name": "p", "sku": "A1"}})
|
|
251
|
+
assert sheet.counts == {1: 0}
|
|
252
|
+
assert sheet.row.sku == "A1"
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def test_a_container_refusing_a_required_field_keeps_its_items():
|
|
256
|
+
class StockBin(BaseContainer[StockRecord]):
|
|
257
|
+
location: Annotated[str, NotNone()]
|
|
258
|
+
|
|
259
|
+
row = StockRecord(name="p", sku="A1")
|
|
260
|
+
box = StockBin(name="bin", items={"p": row}, location="west")
|
|
261
|
+
with pytest.raises(errors.ConstraintError, match="location"):
|
|
262
|
+
box.set({"_items": {}, "location": None})
|
|
263
|
+
assert box.get("p") is row
|
|
264
|
+
assert box.location == "west"
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def test_a_project_enforces_its_own_required_field_through_requests_and_restore():
|
|
268
|
+
class StockRoom(Project):
|
|
269
|
+
site: Annotated[str, NotNone()]
|
|
270
|
+
|
|
271
|
+
def create_item(self, item_code="ITEM", isactive=True):
|
|
272
|
+
self.add_item(StockRecord(name=item_code, sku=item_code, isactive=isactive))
|
|
273
|
+
|
|
274
|
+
room = StockRoom(name="room", site="west")
|
|
275
|
+
assert StockRoom.from_dict(room.to_dict()) == room
|
|
276
|
+
response = Manipulator(base_classes=[StockRoom]).configure(
|
|
277
|
+
room, set={"params": {"site": None}}, raise_on_error=False)
|
|
278
|
+
assert not response.ok and "site" in response.error
|
|
279
|
+
assert room.site == "west"
|
|
280
|
+
with pytest.raises(errors.SerializationError, match="site"):
|
|
281
|
+
StockRoom.from_dict({"name": "room", "site": None})
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def test_required_keywords_reach_narrow_collection_constructors_on_restore():
|
|
285
|
+
class NamedShelf(BaseContainer[StockRecord]):
|
|
286
|
+
site: Annotated[str, NotNone()]
|
|
287
|
+
|
|
288
|
+
def __init__(self, *, name, items, isactive=True, site):
|
|
289
|
+
super().__init__(name=name, items=items, isactive=isactive, site=site)
|
|
290
|
+
|
|
291
|
+
class Room(Project):
|
|
292
|
+
site: Annotated[str, NotNone()]
|
|
293
|
+
|
|
294
|
+
def __init__(self, *, name, items, site):
|
|
295
|
+
super().__init__(name=name, items=items, site=site)
|
|
296
|
+
|
|
297
|
+
def create_item(self, item_code="ITEM", isactive=True):
|
|
298
|
+
self.add_item(StockRecord(name=item_code, sku=item_code, isactive=isactive))
|
|
299
|
+
|
|
300
|
+
for model in (NamedShelf, Room):
|
|
301
|
+
original = model(name="store", items={}, site="west")
|
|
302
|
+
assert model.from_dict(original.to_dict()) == original
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def test_restoring_unmarked_fields_preserves_narrow_constructor_behaviour():
|
|
306
|
+
class OffsetShelf(BaseContainer[StockRecord]):
|
|
307
|
+
count: int = 0
|
|
308
|
+
|
|
309
|
+
def __init__(self, *, name, items=None, isactive=True, count=0):
|
|
310
|
+
super().__init__(name=name, items=items, isactive=isactive, count=count + 1)
|
|
311
|
+
|
|
312
|
+
shelf = OffsetShelf(name="s", count=4)
|
|
313
|
+
assert OffsetShelf.from_dict(shelf.to_dict()).count == 5
|
|
314
|
+
|
|
315
|
+
|
|
101
316
|
def test_constraints_reach_inside_a_container_item():
|
|
102
317
|
class Products(BaseContainer[Product]):
|
|
103
318
|
pass
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|