invariants 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.
Files changed (44) hide show
  1. invariants-0.1.0/.gitignore +217 -0
  2. invariants-0.1.0/LICENSE +21 -0
  3. invariants-0.1.0/PKG-INFO +193 -0
  4. invariants-0.1.0/README.md +168 -0
  5. invariants-0.1.0/invariants/__init__.py +0 -0
  6. invariants-0.1.0/invariants/conditions.py +20 -0
  7. invariants-0.1.0/invariants/factories/__init__.py +4 -0
  8. invariants-0.1.0/invariants/factories/sqlalchemy.py +160 -0
  9. invariants-0.1.0/invariants/factories/state.py +21 -0
  10. invariants-0.1.0/invariants/mappers/__init__.py +20 -0
  11. invariants-0.1.0/invariants/mappers/_introspect.py +34 -0
  12. invariants-0.1.0/invariants/mappers/base.py +323 -0
  13. invariants-0.1.0/invariants/mappers/decorators.py +49 -0
  14. invariants-0.1.0/invariants/py.typed +0 -0
  15. invariants-0.1.0/invariants/state.py +109 -0
  16. invariants-0.1.0/invariants/viz/__init__.py +0 -0
  17. invariants-0.1.0/invariants/viz/__main__.py +3 -0
  18. invariants-0.1.0/invariants/viz/xstate.py +852 -0
  19. invariants-0.1.0/pyproject.toml +81 -0
  20. invariants-0.1.0/tests/__init__.py +0 -0
  21. invariants-0.1.0/tests/support/__init__.py +1 -0
  22. invariants-0.1.0/tests/support/orm.py +15 -0
  23. invariants-0.1.0/tests/support/states.py +97 -0
  24. invariants-0.1.0/tests/test_conditions.py +68 -0
  25. invariants-0.1.0/tests/test_factories/__init__.py +0 -0
  26. invariants-0.1.0/tests/test_factories/conftest.py +40 -0
  27. invariants-0.1.0/tests/test_factories/test_sqlalchemy.py +244 -0
  28. invariants-0.1.0/tests/test_factories/test_state.py +23 -0
  29. invariants-0.1.0/tests/test_mappers/__init__.py +0 -0
  30. invariants-0.1.0/tests/test_mappers/conftest.py +12 -0
  31. invariants-0.1.0/tests/test_mappers/test_base.py +314 -0
  32. invariants-0.1.0/tests/test_mappers/test_decorators.py +210 -0
  33. invariants-0.1.0/tests/test_mappers/test_registries.py +140 -0
  34. invariants-0.1.0/tests/test_state.py +160 -0
  35. invariants-0.1.0/tests/test_viz/__init__.py +0 -0
  36. invariants-0.1.0/tests/test_viz/test_xstate/__init__.py +0 -0
  37. invariants-0.1.0/tests/test_viz/test_xstate/test_config.py +214 -0
  38. invariants-0.1.0/tests/test_viz/test_xstate/test_discovery.py +152 -0
  39. invariants-0.1.0/tests/test_viz/test_xstate/test_extraction.py +144 -0
  40. invariants-0.1.0/tests/test_viz/test_xstate/test_guards.py +86 -0
  41. invariants-0.1.0/tests/test_viz/test_xstate/test_introspection.py +80 -0
  42. invariants-0.1.0/tests/test_viz/test_xstate/test_nesting.py +131 -0
  43. invariants-0.1.0/tests/test_viz/test_xstate/test_rendering.py +204 -0
  44. invariants-0.1.0/tests/test_viz/test_xstate/test_sketch.py +74 -0
@@ -0,0 +1,217 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+ # Sketch visualizer (auto-cloned by `python -m invariants.viz serve`)
210
+ .sketch/
211
+
212
+ # Cosmic Ray mutation testing
213
+ mutation.sqlite
214
+ mutation-report.html
215
+
216
+ # Claude files
217
+ .claude/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Nick Khitrov
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.
@@ -0,0 +1,193 @@
1
+ Metadata-Version: 2.5
2
+ Name: invariants
3
+ Version: 0.1.0
4
+ Summary: Type-safe state modeling for Python — split entity invariants into validated, immutable state classes with Pydantic
5
+ Project-URL: Homepage, https://github.com/nkhitrov/invariants
6
+ Project-URL: Repository, https://github.com/nkhitrov/invariants
7
+ Project-URL: Issues, https://github.com/nkhitrov/invariants/issues
8
+ Author-email: Nick Khitrov <khitrov34@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: immutable,invariants,pydantic,state,state-machine,typing
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: pydantic>=2.12.4
21
+ Provides-Extra: factories
22
+ Requires-Dist: polyfactory>=3.0.0; extra == 'factories'
23
+ Requires-Dist: sqlalchemy>=2.0.44; extra == 'factories'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # invariants
27
+
28
+ [![PyPI](https://img.shields.io/pypi/v/invariants)](https://pypi.org/project/invariants/)
29
+ [![Python](https://img.shields.io/pypi/pyversions/invariants)](https://pypi.org/project/invariants/)
30
+ [![License](https://img.shields.io/github/license/nkhitrov/invariants)](https://github.com/nkhitrov/invariants/blob/main/LICENSE)
31
+
32
+ Type-safe state modeling for Python. Split entity invariants into separate, validated, immutable state classes using Pydantic.
33
+
34
+ ## Why?
35
+
36
+ When an entity has multiple states, each state often has different field requirements. Typically, this is modeled with optional fields and runtime checks. **invariants** enforces these constraints at the type level:
37
+
38
+ - Each state is a separate class with its own field types
39
+ - A metaclass ensures child states override all abstract fields and don't add new ones
40
+ - All states are immutable
41
+ - `StateMachine` defines valid transitions with type-safe signatures
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ pip install invariants
47
+ ```
48
+
49
+ ## Quick Start
50
+
51
+ Define a root state with `Statefull` fields (abstract markers), then create concrete states that override them:
52
+
53
+ ```python
54
+ from datetime import datetime
55
+ from typing import Literal
56
+
57
+ from invariants.state import State, Statefull, StateMachine
58
+
59
+
60
+ class LoanState(State):
61
+ id: int
62
+ status: Statefull
63
+ postponement_date: Statefull
64
+
65
+
66
+ class ActiveLoan(LoanState):
67
+ status: Literal["active"] = "active"
68
+ postponement_date: datetime
69
+
70
+
71
+ class ClosedLoan(LoanState):
72
+ status: Literal["closed"] = "closed"
73
+ postponement_date: None = None
74
+
75
+
76
+ class OverdueLoan(LoanState):
77
+ status: Literal["overdue"] = "overdue"
78
+ postponement_date: datetime
79
+ ```
80
+
81
+ The metaclass enforces two rules at class creation time:
82
+ 1. Child states **cannot add new fields** — only override parent fields
83
+ 2. Child states **must override all `Statefull` fields** with concrete types
84
+
85
+ Define state transitions with `StateMachine`:
86
+
87
+ ```python
88
+ class CloseLoan(StateMachine[LoanState]):
89
+ def execute(self, loan: ActiveLoan | OverdueLoan) -> ClosedLoan:
90
+ return ClosedLoan(id=loan.id)
91
+
92
+
93
+ class MakeLoanOverdue(StateMachine[LoanState]):
94
+ def execute(self, loan: ActiveLoan) -> OverdueLoan:
95
+ return OverdueLoan(id=loan.id, postponement_date=loan.postponement_date)
96
+ ```
97
+
98
+ The `execute` method signature documents which transitions are valid — from which states to which.
99
+
100
+ ## Nested States
101
+
102
+ States can contain other states. Use `ContainsOne` to validate that a collection includes at least one instance of a specific type:
103
+
104
+ ```python
105
+ from typing import Annotated, Literal
106
+ from invariants.conditions import ContainsOne
107
+
108
+
109
+ class DebtState(State):
110
+ status: Statefull
111
+ loans: Statefull
112
+
113
+
114
+ class ActiveDebt(DebtState):
115
+ status: Literal["active"] = "active"
116
+ loans: Annotated[tuple[ActiveLoan | ClosedLoan, ...], ContainsOne(ActiveLoan)]
117
+
118
+
119
+ class ClosedDebt(DebtState):
120
+ status: Literal["closed"] = "closed"
121
+ loans: tuple[ClosedLoan, ...]
122
+
123
+
124
+ class OverdueDebt(DebtState):
125
+ status: Literal["overdue"] = "overdue"
126
+ loans: Annotated[
127
+ tuple[OverdueLoan | ActiveLoan | ClosedLoan, ...], ContainsOne(OverdueLoan)
128
+ ]
129
+ ```
130
+
131
+ `ActiveDebt` guarantees at compile time that it only contains active or closed loans, and at runtime that at least one is active.
132
+
133
+ ## Factories (Testing)
134
+
135
+ Optional integration with [polyfactory](https://github.com/litestar-org/polyfactory) for generating test data. The key idea: **a factory always produces a valid state** — all business invariants are satisfied automatically.
136
+
137
+ ```bash
138
+ pip install invariants[factories]
139
+ ```
140
+
141
+ Define factories for concrete states — the model is inferred from the generic argument:
142
+
143
+ ```python
144
+ from invariants.factories import StateFactory
145
+
146
+
147
+ class ActiveLoanFactory(StateFactory[ActiveLoan]): ...
148
+ class ClosedLoanFactory(StateFactory[ClosedLoan]): ...
149
+ class ActiveDebtFactory(StateFactory[ActiveDebt]): ...
150
+ ```
151
+
152
+ When you build a nested state, child entities are generated automatically:
153
+
154
+ ```python
155
+ debt = ActiveDebtFactory.build()
156
+
157
+ # loans are auto-populated with valid ActiveLoan | ClosedLoan instances
158
+ # ContainsOne(ActiveLoan) is always satisfied — at least one loan is active
159
+ assert any(isinstance(loan, ActiveLoan) for loan in debt.loans)
160
+ ```
161
+
162
+ ### SQLAlchemy Integration
163
+
164
+ `SQLAlchemyStateFactory` maps Pydantic states to ORM models — `build()` returns ORM instances instead of Pydantic models:
165
+
166
+ ```python
167
+ from invariants.factories.sqlalchemy import SQLAlchemyStateFactory
168
+
169
+
170
+ class ActiveLoanORMFactory(SQLAlchemyStateFactory[ActiveLoan, LoanORM]): ...
171
+
172
+ loan = ActiveLoanORMFactory.build()
173
+ assert isinstance(loan, LoanORM) # ORM instance, not Pydantic model
174
+ ```
175
+
176
+ Both `StateFactory` and `SQLAlchemyStateFactory` are thin wrappers over [polyfactory](https://polyfactory.litestar.dev/) — all interfaces (sessions, persistence, batch creation) work the same as in the polyfactory docs.
177
+
178
+ ## XState Visualization
179
+
180
+ Generate [XState v5](https://stately.ai/docs/xstate) state machine code from your `StateMachine` subclasses:
181
+
182
+ ```bash
183
+ # Print generated JS — paste it into https://sketch.stately.ai
184
+ python -m invariants.viz print examples.debt
185
+
186
+ # Start a local Stately Sketch with one document per state machine
187
+ # (clones https://github.com/statelyai/sketch on first run; needs Node.js with pnpm or npx)
188
+ python -m invariants.viz serve examples.debt
189
+ ```
190
+
191
+ `serve` opens each machine in the browser
192
+
193
+ ![img.png](docs/img.png)
@@ -0,0 +1,168 @@
1
+ # invariants
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/invariants)](https://pypi.org/project/invariants/)
4
+ [![Python](https://img.shields.io/pypi/pyversions/invariants)](https://pypi.org/project/invariants/)
5
+ [![License](https://img.shields.io/github/license/nkhitrov/invariants)](https://github.com/nkhitrov/invariants/blob/main/LICENSE)
6
+
7
+ Type-safe state modeling for Python. Split entity invariants into separate, validated, immutable state classes using Pydantic.
8
+
9
+ ## Why?
10
+
11
+ When an entity has multiple states, each state often has different field requirements. Typically, this is modeled with optional fields and runtime checks. **invariants** enforces these constraints at the type level:
12
+
13
+ - Each state is a separate class with its own field types
14
+ - A metaclass ensures child states override all abstract fields and don't add new ones
15
+ - All states are immutable
16
+ - `StateMachine` defines valid transitions with type-safe signatures
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install invariants
22
+ ```
23
+
24
+ ## Quick Start
25
+
26
+ Define a root state with `Statefull` fields (abstract markers), then create concrete states that override them:
27
+
28
+ ```python
29
+ from datetime import datetime
30
+ from typing import Literal
31
+
32
+ from invariants.state import State, Statefull, StateMachine
33
+
34
+
35
+ class LoanState(State):
36
+ id: int
37
+ status: Statefull
38
+ postponement_date: Statefull
39
+
40
+
41
+ class ActiveLoan(LoanState):
42
+ status: Literal["active"] = "active"
43
+ postponement_date: datetime
44
+
45
+
46
+ class ClosedLoan(LoanState):
47
+ status: Literal["closed"] = "closed"
48
+ postponement_date: None = None
49
+
50
+
51
+ class OverdueLoan(LoanState):
52
+ status: Literal["overdue"] = "overdue"
53
+ postponement_date: datetime
54
+ ```
55
+
56
+ The metaclass enforces two rules at class creation time:
57
+ 1. Child states **cannot add new fields** — only override parent fields
58
+ 2. Child states **must override all `Statefull` fields** with concrete types
59
+
60
+ Define state transitions with `StateMachine`:
61
+
62
+ ```python
63
+ class CloseLoan(StateMachine[LoanState]):
64
+ def execute(self, loan: ActiveLoan | OverdueLoan) -> ClosedLoan:
65
+ return ClosedLoan(id=loan.id)
66
+
67
+
68
+ class MakeLoanOverdue(StateMachine[LoanState]):
69
+ def execute(self, loan: ActiveLoan) -> OverdueLoan:
70
+ return OverdueLoan(id=loan.id, postponement_date=loan.postponement_date)
71
+ ```
72
+
73
+ The `execute` method signature documents which transitions are valid — from which states to which.
74
+
75
+ ## Nested States
76
+
77
+ States can contain other states. Use `ContainsOne` to validate that a collection includes at least one instance of a specific type:
78
+
79
+ ```python
80
+ from typing import Annotated, Literal
81
+ from invariants.conditions import ContainsOne
82
+
83
+
84
+ class DebtState(State):
85
+ status: Statefull
86
+ loans: Statefull
87
+
88
+
89
+ class ActiveDebt(DebtState):
90
+ status: Literal["active"] = "active"
91
+ loans: Annotated[tuple[ActiveLoan | ClosedLoan, ...], ContainsOne(ActiveLoan)]
92
+
93
+
94
+ class ClosedDebt(DebtState):
95
+ status: Literal["closed"] = "closed"
96
+ loans: tuple[ClosedLoan, ...]
97
+
98
+
99
+ class OverdueDebt(DebtState):
100
+ status: Literal["overdue"] = "overdue"
101
+ loans: Annotated[
102
+ tuple[OverdueLoan | ActiveLoan | ClosedLoan, ...], ContainsOne(OverdueLoan)
103
+ ]
104
+ ```
105
+
106
+ `ActiveDebt` guarantees at compile time that it only contains active or closed loans, and at runtime that at least one is active.
107
+
108
+ ## Factories (Testing)
109
+
110
+ Optional integration with [polyfactory](https://github.com/litestar-org/polyfactory) for generating test data. The key idea: **a factory always produces a valid state** — all business invariants are satisfied automatically.
111
+
112
+ ```bash
113
+ pip install invariants[factories]
114
+ ```
115
+
116
+ Define factories for concrete states — the model is inferred from the generic argument:
117
+
118
+ ```python
119
+ from invariants.factories import StateFactory
120
+
121
+
122
+ class ActiveLoanFactory(StateFactory[ActiveLoan]): ...
123
+ class ClosedLoanFactory(StateFactory[ClosedLoan]): ...
124
+ class ActiveDebtFactory(StateFactory[ActiveDebt]): ...
125
+ ```
126
+
127
+ When you build a nested state, child entities are generated automatically:
128
+
129
+ ```python
130
+ debt = ActiveDebtFactory.build()
131
+
132
+ # loans are auto-populated with valid ActiveLoan | ClosedLoan instances
133
+ # ContainsOne(ActiveLoan) is always satisfied — at least one loan is active
134
+ assert any(isinstance(loan, ActiveLoan) for loan in debt.loans)
135
+ ```
136
+
137
+ ### SQLAlchemy Integration
138
+
139
+ `SQLAlchemyStateFactory` maps Pydantic states to ORM models — `build()` returns ORM instances instead of Pydantic models:
140
+
141
+ ```python
142
+ from invariants.factories.sqlalchemy import SQLAlchemyStateFactory
143
+
144
+
145
+ class ActiveLoanORMFactory(SQLAlchemyStateFactory[ActiveLoan, LoanORM]): ...
146
+
147
+ loan = ActiveLoanORMFactory.build()
148
+ assert isinstance(loan, LoanORM) # ORM instance, not Pydantic model
149
+ ```
150
+
151
+ Both `StateFactory` and `SQLAlchemyStateFactory` are thin wrappers over [polyfactory](https://polyfactory.litestar.dev/) — all interfaces (sessions, persistence, batch creation) work the same as in the polyfactory docs.
152
+
153
+ ## XState Visualization
154
+
155
+ Generate [XState v5](https://stately.ai/docs/xstate) state machine code from your `StateMachine` subclasses:
156
+
157
+ ```bash
158
+ # Print generated JS — paste it into https://sketch.stately.ai
159
+ python -m invariants.viz print examples.debt
160
+
161
+ # Start a local Stately Sketch with one document per state machine
162
+ # (clones https://github.com/statelyai/sketch on first run; needs Node.js with pnpm or npx)
163
+ python -m invariants.viz serve examples.debt
164
+ ```
165
+
166
+ `serve` opens each machine in the browser
167
+
168
+ ![img.png](docs/img.png)
File without changes
@@ -0,0 +1,20 @@
1
+ from typing import Any
2
+
3
+ from pydantic import AfterValidator
4
+
5
+
6
+ class ContainsOne(AfterValidator):
7
+ required_type: type
8
+
9
+ def __init__(self, obj: Any):
10
+ super().__init__(self.validator(obj))
11
+ object.__setattr__(self, "required_type", obj)
12
+
13
+ @staticmethod
14
+ def validator(obj: Any) -> Any:
15
+ def validate(value: Any) -> Any:
16
+ if not any(o for o in value if isinstance(o, obj)):
17
+ raise ValueError(f"must contains one or more item of type `{obj}`")
18
+ return value
19
+
20
+ return validate
@@ -0,0 +1,4 @@
1
+ from invariants.factories.state import StateFactory
2
+
3
+
4
+ __all__ = ["StateFactory"]