varco-fastapi 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 (68) hide show
  1. varco_fastapi-0.1.0/.gitignore +209 -0
  2. varco_fastapi-0.1.0/PKG-INFO +35 -0
  3. varco_fastapi-0.1.0/README.md +0 -0
  4. varco_fastapi-0.1.0/pyproject.toml +89 -0
  5. varco_fastapi-0.1.0/tests/__init__.py +0 -0
  6. varco_fastapi-0.1.0/tests/milestone_a/__init__.py +0 -0
  7. varco_fastapi-0.1.0/tests/milestone_a/test_context.py +102 -0
  8. varco_fastapi-0.1.0/tests/milestone_a/test_job_base.py +215 -0
  9. varco_fastapi-0.1.0/tests/milestone_a/test_middleware.py +222 -0
  10. varco_fastapi-0.1.0/tests/milestone_a/test_server_auth.py +264 -0
  11. varco_fastapi-0.1.0/tests/milestone_b/__init__.py +0 -0
  12. varco_fastapi-0.1.0/tests/milestone_b/test_job.py +412 -0
  13. varco_fastapi-0.1.0/tests/milestone_b/test_router.py +431 -0
  14. varco_fastapi-0.1.0/tests/milestone_c/__init__.py +0 -0
  15. varco_fastapi-0.1.0/tests/milestone_c/test_client.py +716 -0
  16. varco_fastapi-0.1.0/tests/milestone_d/__init__.py +0 -0
  17. varco_fastapi-0.1.0/tests/milestone_d/test_job_fixes.py +493 -0
  18. varco_fastapi-0.1.0/tests/milestone_e/__init__.py +0 -0
  19. varco_fastapi-0.1.0/tests/milestone_e/test_di_context.py +97 -0
  20. varco_fastapi-0.1.0/tests/milestone_e/test_router_split.py +226 -0
  21. varco_fastapi-0.1.0/tests/milestone_e/test_task_runner.py +305 -0
  22. varco_fastapi-0.1.0/tests/milestone_f/__init__.py +0 -0
  23. varco_fastapi-0.1.0/tests/milestone_f/test_app_factory.py +322 -0
  24. varco_fastapi-0.1.0/tests/milestone_f/test_mcp_adapter.py +461 -0
  25. varco_fastapi-0.1.0/tests/milestone_f/test_skill_adapter.py +536 -0
  26. varco_fastapi-0.1.0/tests/milestone_f/test_validation.py +277 -0
  27. varco_fastapi-0.1.0/varco_fastapi/__init__.py +315 -0
  28. varco_fastapi-0.1.0/varco_fastapi/app.py +632 -0
  29. varco_fastapi-0.1.0/varco_fastapi/auth/__init__.py +64 -0
  30. varco_fastapi-0.1.0/varco_fastapi/auth/client_auth.py +340 -0
  31. varco_fastapi-0.1.0/varco_fastapi/auth/server_auth.py +613 -0
  32. varco_fastapi-0.1.0/varco_fastapi/auth/trust_store.py +209 -0
  33. varco_fastapi-0.1.0/varco_fastapi/client/__init__.py +69 -0
  34. varco_fastapi-0.1.0/varco_fastapi/client/base.py +924 -0
  35. varco_fastapi-0.1.0/varco_fastapi/client/configurator.py +374 -0
  36. varco_fastapi-0.1.0/varco_fastapi/client/handle.py +313 -0
  37. varco_fastapi-0.1.0/varco_fastapi/client/middleware.py +646 -0
  38. varco_fastapi-0.1.0/varco_fastapi/client/protocol.py +150 -0
  39. varco_fastapi-0.1.0/varco_fastapi/client/sync.py +314 -0
  40. varco_fastapi-0.1.0/varco_fastapi/context.py +476 -0
  41. varco_fastapi-0.1.0/varco_fastapi/di.py +523 -0
  42. varco_fastapi-0.1.0/varco_fastapi/exceptions.py +149 -0
  43. varco_fastapi-0.1.0/varco_fastapi/job/__init__.py +36 -0
  44. varco_fastapi-0.1.0/varco_fastapi/job/poller.py +239 -0
  45. varco_fastapi-0.1.0/varco_fastapi/job/response.py +191 -0
  46. varco_fastapi-0.1.0/varco_fastapi/job/runner.py +879 -0
  47. varco_fastapi-0.1.0/varco_fastapi/job/store.py +196 -0
  48. varco_fastapi-0.1.0/varco_fastapi/lifespan.py +192 -0
  49. varco_fastapi-0.1.0/varco_fastapi/middleware/__init__.py +50 -0
  50. varco_fastapi-0.1.0/varco_fastapi/middleware/cors.py +212 -0
  51. varco_fastapi-0.1.0/varco_fastapi/middleware/error.py +180 -0
  52. varco_fastapi-0.1.0/varco_fastapi/middleware/logging.py +138 -0
  53. varco_fastapi-0.1.0/varco_fastapi/middleware/request_context.py +173 -0
  54. varco_fastapi-0.1.0/varco_fastapi/middleware/session.py +150 -0
  55. varco_fastapi-0.1.0/varco_fastapi/middleware/tracing.py +184 -0
  56. varco_fastapi-0.1.0/varco_fastapi/py.typed +0 -0
  57. varco_fastapi-0.1.0/varco_fastapi/router/__init__.py +0 -0
  58. varco_fastapi-0.1.0/varco_fastapi/router/base.py +1245 -0
  59. varco_fastapi-0.1.0/varco_fastapi/router/crud.py +483 -0
  60. varco_fastapi-0.1.0/varco_fastapi/router/endpoint.py +439 -0
  61. varco_fastapi-0.1.0/varco_fastapi/router/health.py +273 -0
  62. varco_fastapi-0.1.0/varco_fastapi/router/introspection.py +413 -0
  63. varco_fastapi-0.1.0/varco_fastapi/router/mcp.py +685 -0
  64. varco_fastapi-0.1.0/varco_fastapi/router/mixins.py +473 -0
  65. varco_fastapi-0.1.0/varco_fastapi/router/pagination.py +134 -0
  66. varco_fastapi-0.1.0/varco_fastapi/router/presets.py +234 -0
  67. varco_fastapi-0.1.0/varco_fastapi/router/skill.py +747 -0
  68. varco_fastapi-0.1.0/varco_fastapi/validation.py +326 -0
@@ -0,0 +1,209 @@
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
+ todo*.txt
205
+
206
+ # Marimo
207
+ marimo/_static/
208
+ marimo/_lsp/
209
+ __marimo__/
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: varco-fastapi
3
+ Version: 0.1.0
4
+ Summary: FastAPI adapter for varco — routing, auth middleware, job running, typed HTTP client, and DI wiring
5
+ Project-URL: Homepage, https://github.com/edoardoscarpaci/varco
6
+ Project-URL: Repository, https://github.com/edoardoscarpaci/varco/tree/main/varco_fastapi
7
+ Project-URL: Issues, https://github.com/edoardoscarpaci/varco/issues
8
+ Author-email: "edoardo.scarpaci" <edoardo.scarpaci@gmail.com>
9
+ License: Apache-2.0
10
+ Keywords: async,auth,domain-model,fastapi,jobs,middleware,rest-api,varco
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: FastAPI
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
18
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.12
21
+ Requires-Dist: fastapi>=0.115.0
22
+ Requires-Dist: httpx>=0.27.0
23
+ Requires-Dist: providify>=0.1.4a3
24
+ Requires-Dist: pydantic-settings>=2.0
25
+ Requires-Dist: python-multipart>=0.0.9
26
+ Requires-Dist: varco-core
27
+ Provides-Extra: a2a
28
+ Provides-Extra: mcp
29
+ Requires-Dist: mcp>=1.0; extra == 'mcp'
30
+ Provides-Extra: otel
31
+ Requires-Dist: opentelemetry-api>=1.20; extra == 'otel'
32
+ Requires-Dist: opentelemetry-instrumentation-fastapi>=0.42b0; extra == 'otel'
33
+ Requires-Dist: opentelemetry-sdk>=1.20; extra == 'otel'
34
+ Provides-Extra: ws
35
+ Requires-Dist: varco-ws; extra == 'ws'
File without changes
@@ -0,0 +1,89 @@
1
+ [project]
2
+ name = "varco-fastapi"
3
+ version = "0.1.0"
4
+ description = "FastAPI adapter for varco — routing, auth middleware, job running, typed HTTP client, and DI wiring"
5
+ authors = [{ name = "edoardo.scarpaci", email = "edoardo.scarpaci@gmail.com" }]
6
+ readme = "README.md"
7
+ license = { text = "Apache-2.0" }
8
+ requires-python = ">=3.12"
9
+ keywords = ["fastapi", "async", "rest-api", "domain-model", "varco", "middleware", "auth", "jobs"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: Apache Software License",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
17
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
18
+ "Framework :: FastAPI",
19
+ "Typing :: Typed",
20
+ ]
21
+ dependencies = [
22
+ # Workspace sibling — resolved from the monorepo via [tool.uv.sources] below.
23
+ "varco-core",
24
+ # FastAPI provides the HTTP framework, routing, and OpenAPI schema generation.
25
+ "fastapi>=0.115.0",
26
+ # httpx is the async HTTP client used by AsyncVarcoClient and SyncVarcoClient.
27
+ "httpx>=0.27.0",
28
+ # pydantic-settings for env-var-based configuration (CORSConfig, TrustStore, etc.)
29
+ "pydantic-settings>=2.0",
30
+ # providify for DI wiring (@Configuration, @Provider, Inject[], DIContainer)
31
+ "providify>=0.1.4a3",
32
+ # python-multipart is required for FastAPI form data parsing (file uploads, etc.)
33
+ "python-multipart>=0.0.9",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ # WebSocket and SSE support (requires varco_ws from the workspace)
38
+ ws = ["varco-ws"]
39
+ # MCP (Model Context Protocol) adapter support
40
+ # Enables MCPAdapter.to_mcp_server() and MCPAdapter.mount()
41
+ mcp = ["mcp>=1.0"]
42
+ # A2A (Agent-to-Agent / Google A2A protocol) support
43
+ # SkillAdapter works without this extra (it uses FastAPI directly);
44
+ # install for the google-a2a SDK types if you need A2A client utilities.
45
+ a2a = []
46
+ # OpenTelemetry instrumentation — optional; gracefully no-ops when absent
47
+ otel = [
48
+ "opentelemetry-api>=1.20",
49
+ "opentelemetry-sdk>=1.20",
50
+ "opentelemetry-instrumentation-fastapi>=0.42b0",
51
+ ]
52
+
53
+ [project.urls]
54
+ Homepage = "https://github.com/edoardoscarpaci/varco"
55
+ Repository = "https://github.com/edoardoscarpaci/varco/tree/main/varco_fastapi"
56
+ Issues = "https://github.com/edoardoscarpaci/varco/issues"
57
+
58
+ [tool.uv.sources]
59
+ # Resolve workspace siblings from the monorepo instead of PyPI.
60
+ varco-core = { workspace = true }
61
+ varco-ws = { workspace = true }
62
+
63
+ [dependency-groups]
64
+ dev = [
65
+ "pytest>=8.0",
66
+ "pytest-asyncio>=0.24",
67
+ # httpx is used as a test client via fastapi.testclient.TestClient + AsyncClient
68
+ "httpx>=0.27.0",
69
+ # uvicorn for integration test server
70
+ "uvicorn>=0.30",
71
+ # starlette test client
72
+ "anyio>=4.0",
73
+ # cryptography for JWT auth tests
74
+ "cryptography>=42.0",
75
+ ]
76
+
77
+ [build-system]
78
+ requires = ["hatchling"]
79
+ build-backend = "hatchling.build"
80
+
81
+ [tool.hatch.build.targets.wheel]
82
+ packages = ["varco_fastapi"]
83
+
84
+ [tool.pytest.ini_options]
85
+ asyncio_mode = "auto"
86
+ testpaths = ["tests"]
87
+ markers = [
88
+ "integration: real external services required (disabled by default — use -m integration)",
89
+ ]
File without changes
File without changes
@@ -0,0 +1,102 @@
1
+ """
2
+ Tests for varco_fastapi.context — ContextVars and context managers.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import pytest
8
+
9
+ from varco_core.auth.base import AuthContext
10
+ from varco_fastapi.context import (
11
+ auth_context,
12
+ auth_context_var,
13
+ get_auth_context,
14
+ get_auth_context_or_none,
15
+ get_request_id,
16
+ get_request_token,
17
+ request_scope,
18
+ request_id_var,
19
+ )
20
+
21
+
22
+ async def test_get_auth_context_raises_outside_context():
23
+ """get_auth_context() raises RuntimeError when no context is set."""
24
+ auth_context_var.set(None)
25
+ with pytest.raises(RuntimeError, match="No AuthContext"):
26
+ get_auth_context()
27
+
28
+
29
+ async def test_get_auth_context_or_none_returns_none_outside_context():
30
+ """get_auth_context_or_none() returns None when no context is set."""
31
+ auth_context_var.set(None)
32
+ assert get_auth_context_or_none() is None
33
+
34
+
35
+ async def test_auth_context_sets_and_restores():
36
+ """auth_context() sets auth_context_var and restores on exit."""
37
+ ctx = AuthContext(user_id="usr_1", roles=frozenset({"admin"}))
38
+ auth_context_var.set(None)
39
+
40
+ async with auth_context(ctx, token="tok_abc"):
41
+ assert get_auth_context() is ctx
42
+ assert get_request_token() == "tok_abc"
43
+
44
+ # Restored to None after exit
45
+ assert get_auth_context_or_none() is None
46
+ assert get_request_token() is None
47
+
48
+
49
+ async def test_auth_context_nested():
50
+ """Nested auth_context() restores each level correctly."""
51
+ outer = AuthContext(user_id="usr_outer")
52
+ inner = AuthContext(user_id="usr_inner")
53
+
54
+ async with auth_context(outer, token="tok_outer"):
55
+ assert get_auth_context().user_id == "usr_outer"
56
+ async with auth_context(inner, token="tok_inner"):
57
+ assert get_auth_context().user_id == "usr_inner"
58
+ assert get_request_token() == "tok_inner"
59
+ # Restored to outer
60
+ assert get_auth_context().user_id == "usr_outer"
61
+ assert get_request_token() == "tok_outer"
62
+
63
+ # Fully cleaned up
64
+ assert get_auth_context_or_none() is None
65
+
66
+
67
+ async def test_request_scope_generates_request_id():
68
+ """request_scope() generates a request_id if not provided."""
69
+ request_id_var.set(None)
70
+
71
+ async with request_scope() as rid:
72
+ assert rid is not None
73
+ assert len(rid) > 0
74
+ assert get_request_id() == rid
75
+
76
+ # Restored
77
+ assert request_id_var.get() is None
78
+
79
+
80
+ async def test_request_scope_uses_provided_id():
81
+ """request_scope() uses the provided request_id."""
82
+ async with request_scope(request_id="req_custom_123") as rid:
83
+ assert rid == "req_custom_123"
84
+ assert get_request_id() == "req_custom_123"
85
+
86
+
87
+ async def test_request_scope_sets_correlation_id():
88
+ """request_scope() enters correlation_context with the request_id."""
89
+ from varco_core.tracing import current_correlation_id
90
+
91
+ async with request_scope(request_id="req_corr_456") as _rid:
92
+ assert current_correlation_id() == "req_corr_456"
93
+
94
+ # Correlation ID is restored to None after exit
95
+ assert current_correlation_id() is None
96
+
97
+
98
+ async def test_get_request_id_raises_outside_scope():
99
+ """get_request_id() raises RuntimeError when request_scope() is not entered."""
100
+ request_id_var.set(None)
101
+ with pytest.raises(RuntimeError, match="No request_id"):
102
+ get_request_id()
@@ -0,0 +1,215 @@
1
+ """
2
+ Tests for varco_core.job.base — Job, JobStatus, auth snapshot helpers.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from datetime import datetime, timezone
8
+ from uuid import uuid4
9
+
10
+ import pytest
11
+
12
+ from varco_core.auth.base import Action, AuthContext, ResourceGrant
13
+ from varco_core.job.base import (
14
+ Job,
15
+ JobStatus,
16
+ auth_context_from_snapshot,
17
+ auth_context_to_snapshot,
18
+ )
19
+
20
+
21
+ # ── JobStatus ──────────────────────────────────────────────────────────────────
22
+
23
+
24
+ def test_job_status_terminal_states():
25
+ """COMPLETED, FAILED, CANCELLED are terminal; PENDING, RUNNING are not."""
26
+ assert JobStatus.COMPLETED.is_terminal
27
+ assert JobStatus.FAILED.is_terminal
28
+ assert JobStatus.CANCELLED.is_terminal
29
+ assert not JobStatus.PENDING.is_terminal
30
+ assert not JobStatus.RUNNING.is_terminal
31
+
32
+
33
+ # ── Job transitions ────────────────────────────────────────────────────────────
34
+
35
+
36
+ def test_job_as_running():
37
+ """as_running() transitions PENDING → RUNNING and sets started_at."""
38
+ job = Job(job_id=uuid4(), created_at=datetime.now(timezone.utc))
39
+ running = job.as_running()
40
+ assert running.status == JobStatus.RUNNING
41
+ assert running.started_at is not None
42
+ assert running.job_id == job.job_id # same job ID
43
+
44
+
45
+ def test_job_as_completed():
46
+ """as_completed() transitions RUNNING → COMPLETED and sets result."""
47
+ job = Job(job_id=uuid4(), status=JobStatus.RUNNING)
48
+ completed = job.as_completed(result=b'{"ok": true}')
49
+ assert completed.status == JobStatus.COMPLETED
50
+ assert completed.result == b'{"ok": true}'
51
+ assert completed.completed_at is not None
52
+
53
+
54
+ def test_job_as_failed():
55
+ """as_failed() transitions RUNNING → FAILED and sets error."""
56
+ job = Job(job_id=uuid4(), status=JobStatus.RUNNING)
57
+ failed = job.as_failed(error="Connection timeout")
58
+ assert failed.status == JobStatus.FAILED
59
+ assert failed.error == "Connection timeout"
60
+ assert failed.completed_at is not None
61
+
62
+
63
+ def test_job_as_cancelled_from_pending():
64
+ """as_cancelled() transitions PENDING → CANCELLED."""
65
+ job = Job(job_id=uuid4(), status=JobStatus.PENDING)
66
+ cancelled = job.as_cancelled()
67
+ assert cancelled.status == JobStatus.CANCELLED
68
+ assert cancelled.completed_at is not None
69
+
70
+
71
+ def test_job_as_cancelled_from_running():
72
+ """as_cancelled() transitions RUNNING → CANCELLED."""
73
+ job = Job(job_id=uuid4(), status=JobStatus.RUNNING)
74
+ cancelled = job.as_cancelled()
75
+ assert cancelled.status == JobStatus.CANCELLED
76
+
77
+
78
+ def test_job_transitions_are_immutable():
79
+ """Job.as_*() returns a new Job instance; original is unchanged."""
80
+ job = Job(job_id=uuid4())
81
+ running = job.as_running()
82
+ assert job.status == JobStatus.PENDING # original unchanged
83
+ assert running.status == JobStatus.RUNNING
84
+
85
+
86
+ def test_job_as_running_raises_on_non_pending():
87
+ """as_running() raises ValueError if job is not PENDING."""
88
+ job = Job(job_id=uuid4(), status=JobStatus.RUNNING)
89
+ with pytest.raises(ValueError, match="Only PENDING"):
90
+ job.as_running()
91
+
92
+
93
+ def test_job_as_completed_raises_on_non_running():
94
+ """as_completed() raises ValueError if job is not RUNNING."""
95
+ job = Job(job_id=uuid4(), status=JobStatus.PENDING)
96
+ with pytest.raises(ValueError, match="Only RUNNING"):
97
+ job.as_completed(result=b"")
98
+
99
+
100
+ def test_job_as_cancelled_raises_on_terminal():
101
+ """as_cancelled() raises ValueError if job is already in a terminal state."""
102
+ job = Job(job_id=uuid4(), status=JobStatus.COMPLETED)
103
+ with pytest.raises(ValueError, match="terminal state"):
104
+ job.as_cancelled()
105
+
106
+
107
+ # ── Auth snapshot serialization ────────────────────────────────────────────────
108
+
109
+
110
+ def test_auth_context_to_snapshot_serializes_all_fields():
111
+ """auth_context_to_snapshot() produces a JSON-safe dict."""
112
+ ctx = AuthContext(
113
+ user_id="usr_1",
114
+ roles=frozenset({"admin", "editor"}),
115
+ scopes=frozenset({"write:posts"}),
116
+ grants=(
117
+ ResourceGrant(
118
+ resource="posts",
119
+ actions=frozenset({Action.CREATE, Action.READ}),
120
+ ),
121
+ ),
122
+ metadata={"tenant_id": "t1"},
123
+ )
124
+ snapshot = auth_context_to_snapshot(ctx)
125
+
126
+ assert snapshot["user_id"] == "usr_1"
127
+ assert sorted(snapshot["roles"]) == ["admin", "editor"]
128
+ assert snapshot["scopes"] == ["write:posts"]
129
+ assert snapshot["grants"][0]["resource"] == "posts"
130
+ assert sorted(snapshot["grants"][0]["actions"]) == ["create", "read"]
131
+ assert snapshot["metadata"] == {"tenant_id": "t1"}
132
+
133
+
134
+ def test_auth_context_round_trip():
135
+ """Serializing and deserializing an AuthContext preserves all fields."""
136
+ original = AuthContext(
137
+ user_id="usr_2",
138
+ roles=frozenset({"manager"}),
139
+ scopes=frozenset({"read:reports"}),
140
+ grants=(
141
+ ResourceGrant(
142
+ resource="reports",
143
+ actions=frozenset({Action.LIST, Action.READ}),
144
+ ),
145
+ ),
146
+ metadata={"department": "finance"},
147
+ )
148
+ snapshot = auth_context_to_snapshot(original)
149
+ restored = auth_context_from_snapshot(snapshot)
150
+
151
+ assert restored.user_id == original.user_id
152
+ assert restored.roles == original.roles
153
+ assert restored.scopes == original.scopes
154
+ assert len(restored.grants) == 1
155
+ assert restored.grants[0].resource == "reports"
156
+ assert Action.READ in restored.grants[0].actions
157
+ assert restored.metadata == original.metadata
158
+
159
+
160
+ def test_auth_context_from_snapshot_handles_missing_metadata():
161
+ """auth_context_from_snapshot() defaults to empty dict for missing metadata."""
162
+ snapshot = {"user_id": "usr_3", "roles": [], "scopes": [], "grants": []}
163
+ ctx = auth_context_from_snapshot(snapshot)
164
+ assert ctx.user_id == "usr_3"
165
+ assert ctx.metadata == {}
166
+
167
+
168
+ def test_auth_context_from_snapshot_handles_anonymous():
169
+ """auth_context_from_snapshot() handles None user_id (anonymous)."""
170
+ snapshot = auth_context_to_snapshot(AuthContext())
171
+ restored = auth_context_from_snapshot(snapshot)
172
+ assert restored.is_anonymous()
173
+
174
+
175
+ # ── VarcoLifespan ─────────────────────────────────────────────────────────────
176
+
177
+
178
+ async def test_varco_lifespan_starts_and_stops_components():
179
+ """VarcoLifespan starts components in order and stops them in reverse."""
180
+ from fastapi import FastAPI
181
+
182
+ from varco_fastapi.lifespan import VarcoLifespan
183
+
184
+ events: list[str] = []
185
+
186
+ class FakeComponent:
187
+ def __init__(self, name: str):
188
+ self.name = name
189
+
190
+ async def start(self):
191
+ events.append(f"start:{self.name}")
192
+
193
+ async def stop(self):
194
+ events.append(f"stop:{self.name}")
195
+
196
+ c1 = FakeComponent("first")
197
+ c2 = FakeComponent("second")
198
+
199
+ lifespan = VarcoLifespan(c1, c2)
200
+
201
+ app = FastAPI(lifespan=lifespan)
202
+
203
+ async with lifespan(app):
204
+ pass # Simulate app running
205
+
206
+ assert events == ["start:first", "start:second", "stop:second", "stop:first"]
207
+
208
+
209
+ async def test_varco_lifespan_register_raises_for_invalid_component():
210
+ """VarcoLifespan.register() raises TypeError for objects without start/stop."""
211
+ from varco_fastapi.lifespan import VarcoLifespan
212
+
213
+ lifespan = VarcoLifespan()
214
+ with pytest.raises(TypeError, match="AbstractLifecycle"):
215
+ lifespan.register(object())