simple-module-test 0.0.42__tar.gz → 0.0.43__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 (31) hide show
  1. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/.gitignore +3 -0
  2. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/PKG-INFO +6 -5
  3. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/pyproject.toml +7 -5
  4. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/__init__.py +8 -0
  5. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/fixtures.py +6 -3
  6. simple_module_test-0.0.43/simple_module_test/inertia.py +13 -0
  7. simple_module_test-0.0.43/simple_module_test/inertia_page.py +194 -0
  8. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/setup_wizard.py +7 -1
  9. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/tenant_client.py +2 -0
  10. simple_module_test-0.0.43/tests/test_testing_inertia_headers.py +34 -0
  11. simple_module_test-0.0.43/tests/test_testing_inertia_page.py +251 -0
  12. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/LICENSE +0 -0
  13. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/README.md +0 -0
  14. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/_schema.py +0 -0
  15. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/app_factory.py +0 -0
  16. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/database.py +0 -0
  17. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/fake_events.py +0 -0
  18. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/mail.py +0 -0
  19. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/plugin.py +0 -0
  20. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/process_state.py +0 -0
  21. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/redis_server.py +0 -0
  22. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/routes.py +0 -0
  23. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/session_cookie.py +0 -0
  24. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/simple_module_test/waiting.py +0 -0
  25. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/tests/test_app_factory.py +0 -0
  26. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/tests/test_fake_events.py +0 -0
  27. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/tests/test_plugin_fixtures.py +0 -0
  28. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/tests/test_schema_reuse_pg.py +0 -0
  29. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/tests/test_testing_process_state.py +0 -0
  30. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/tests/test_waiting_helpers.py +0 -0
  31. {simple_module_test-0.0.42 → simple_module_test-0.0.43}/tests/test_worker_database.py +0 -0
@@ -22,6 +22,9 @@ node_modules/
22
22
 
23
23
  # Database
24
24
  *.db
25
+ *.db-wal
26
+ *.db-shm
27
+ *.db-journal
25
28
  *.sqlite3
26
29
 
27
30
  # Module-managed runtime state (e.g. uploaded dataset files,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simple_module_test
3
- Version: 0.0.42
3
+ Version: 0.0.43
4
4
  Summary: Shared pytest fixtures (app, client, db_session, authenticated_client) for writing simple_module module tests
5
5
  Project-URL: Homepage, https://github.com/antosubash/simple_module_python
6
6
  Project-URL: Repository, https://github.com/antosubash/simple_module_python
@@ -21,13 +21,14 @@ Classifier: Programming Language :: Python :: 3.12
21
21
  Classifier: Topic :: Software Development :: Testing
22
22
  Classifier: Typing :: Typed
23
23
  Requires-Python: >=3.12
24
- Requires-Dist: fastapi<0.160,>=0.140
24
+ Requires-Dist: fastapi<0.163,>=0.140
25
25
  Requires-Dist: httpx<0.29,>=0.27
26
26
  Requires-Dist: pytest-asyncio<2,>=0.24
27
27
  Requires-Dist: pytest<10,>=8.0
28
- Requires-Dist: simple-module-core==0.0.42
29
- Requires-Dist: simple-module-db==0.0.42
30
- Requires-Dist: simple-module-hosting==0.0.42
28
+ Requires-Dist: simple-module-core==0.0.43
29
+ Requires-Dist: simple-module-db==0.0.43
30
+ Requires-Dist: simple-module-hosting==0.0.43
31
+ Requires-Dist: simple-module-inertia==0.0.43
31
32
  Requires-Dist: sqlalchemy<3,>=2.0
32
33
  Description-Content-Type: text/markdown
33
34
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "simple_module_test"
3
- version = "0.0.42"
3
+ version = "0.0.43"
4
4
  description = "Shared pytest fixtures (app, client, db_session, authenticated_client) for writing simple_module module tests"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -21,13 +21,14 @@ classifiers = [
21
21
  "Typing :: Typed",
22
22
  ]
23
23
  dependencies = [
24
- "fastapi>=0.140,<0.160",
24
+ "fastapi>=0.140,<0.163",
25
25
  "httpx>=0.27,<0.29",
26
26
  "pytest>=8.0,<10",
27
27
  "pytest-asyncio>=0.24,<2",
28
- "simple_module_core==0.0.42",
29
- "simple_module_db==0.0.42",
30
- "simple_module_hosting==0.0.42",
28
+ "simple_module_core==0.0.43",
29
+ "simple_module_db==0.0.43",
30
+ "simple_module_hosting==0.0.43",
31
+ "simple_module_inertia==0.0.43",
31
32
  "sqlalchemy>=2.0,<3",
32
33
  ]
33
34
 
@@ -51,3 +52,4 @@ packages = ["simple_module_test"]
51
52
  simple_module_core = { workspace = true }
52
53
  simple_module_db = { workspace = true }
53
54
  simple_module_hosting = { workspace = true }
55
+ simple_module_inertia = { workspace = true }
@@ -11,6 +11,9 @@ Primary exports:
11
11
  so tests can assert on emitted events without wiring real subscribers.
12
12
  * :func:`build_test_app` — return a minimal FastAPI app loading exactly
13
13
  one module, with an in-memory SQLite DB.
14
+ * :func:`inertia_page` / :class:`InertiaPage` — parse an Inertia document or
15
+ ``X-Inertia`` response into fluent prop assertions and partial/deferred reloads.
16
+ * :func:`inertia_headers` — default ``X-Inertia-Version`` header for clients.
14
17
 
15
18
  The pytest plugin auto-registers these fixtures (no imports needed):
16
19
  ``fake_event_bus``, ``build_test_app``, ``settings``, ``db_state``,
@@ -27,6 +30,8 @@ in as an ``owner``/``admin``/``member`` of a real tenant — see
27
30
 
28
31
  from simple_module_test.app_factory import build_test_app
29
32
  from simple_module_test.fake_events import FakeEventBus, RecordedEvent
33
+ from simple_module_test.inertia import inertia_headers
34
+ from simple_module_test.inertia_page import InertiaPage, inertia_page
30
35
  from simple_module_test.routes import effective_route_paths
31
36
  from simple_module_test.session_cookie import forge_session_cookie
32
37
  from simple_module_test.tenant_client import TenantClient
@@ -34,11 +39,14 @@ from simple_module_test.waiting import wait_for, wait_for_sync
34
39
 
35
40
  __all__ = [
36
41
  "FakeEventBus",
42
+ "InertiaPage",
37
43
  "RecordedEvent",
38
44
  "TenantClient",
39
45
  "build_test_app",
40
46
  "effective_route_paths",
41
47
  "forge_session_cookie",
48
+ "inertia_headers",
49
+ "inertia_page",
42
50
  "wait_for",
43
51
  "wait_for_sync",
44
52
  ]
@@ -32,6 +32,7 @@ from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
32
32
 
33
33
  from simple_module_test._schema import _create_all_tables
34
34
  from simple_module_test.database import begin_test, database_url_for_tests, init_db_kwargs
35
+ from simple_module_test.inertia import inertia_headers
35
36
  from simple_module_test.session_cookie import forge_session_cookie
36
37
 
37
38
  _AUTH_PROVIDER_ENV = "SM_AUTH_PROVIDER"
@@ -132,8 +133,8 @@ SETUP_ADMIN_PASSWORD = "test-password"
132
133
  async def _seed_setup_admin(application) -> None:
133
134
  """Make the ``app`` fixture model a *configured* install.
134
135
 
135
- ``SetupMiddleware`` redirects every request to ``/setup`` until an
136
- administrator exists. That is right for a fresh deployment and wrong for a
136
+ ``SetupMiddleware`` redirects every request to ``/setup`` until a
137
+ local account exists. That is right for a fresh deployment and wrong for a
137
138
  suite asserting on ordinary pages — without this, every test using ``app``
138
139
  gets a 302.
139
140
 
@@ -195,7 +196,7 @@ def _disable_env_bootstrap(monkeypatch: pytest.MonkeyPatch) -> None:
195
196
  disk. A developer who followed ``.env.example`` has those set, so every app
196
197
  this plugin builds gets an admin whether the fixture asked for one or not.
197
198
  For ``setup_pending_app`` that is not a nuisance but the opposite of its
198
- contract: the setup gate releases the moment an administrator exists, so the
199
+ contract: the setup gate releases the moment a local account exists, so the
199
200
  wizard routes 404 and every test using it fails.
200
201
 
201
202
  They fail *locally only* — CI has no ``.env`` — which is the worst shape for
@@ -230,6 +231,7 @@ async def client(app) -> AsyncGenerator[httpx.AsyncClient, None]:
230
231
  async with httpx.AsyncClient(
231
232
  transport=transport,
232
233
  base_url="http://testserver",
234
+ headers=inertia_headers(app),
233
235
  ) as c:
234
236
  yield c
235
237
 
@@ -265,6 +267,7 @@ async def authenticated_client(app) -> AsyncGenerator[httpx.AsyncClient, None]:
265
267
  async with httpx.AsyncClient(
266
268
  transport=transport,
267
269
  base_url="http://testserver",
270
+ headers=inertia_headers(app),
268
271
  cookies={"session": signed},
269
272
  ) as c:
270
273
  yield c
@@ -0,0 +1,13 @@
1
+ """Client defaults that track the app's configured Inertia asset version."""
2
+
3
+ from typing import Any
4
+
5
+ from simple_module_inertia.config import resolved_version
6
+
7
+
8
+ def inertia_headers(app: Any) -> dict[str, str]:
9
+ """Current version header, or no defaults when the app has no Inertia."""
10
+ config = getattr(getattr(app.state, "sm", None), "inertia_config", None)
11
+ if config is None:
12
+ return {}
13
+ return {"X-Inertia-Version": resolved_version(config)}
@@ -0,0 +1,194 @@
1
+ """Fluent assertions and follow-up requests for Inertia page responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Sized
7
+ from copy import copy
8
+ from html.parser import HTMLParser
9
+ from typing import Any, Self
10
+
11
+ import httpx
12
+
13
+
14
+ class _PageScript(HTMLParser):
15
+ def __init__(self) -> None:
16
+ super().__init__(convert_charrefs=False)
17
+ self.collecting = False
18
+ self.chunks: list[str] = []
19
+ self.page_json: str | None = None
20
+
21
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
22
+ attributes = dict(attrs)
23
+ if tag == "script":
24
+ self.collecting = (
25
+ attributes.get("data-page") == "app"
26
+ and attributes.get("type") == "application/json"
27
+ )
28
+ if self.collecting:
29
+ self.chunks = []
30
+
31
+ def handle_data(self, data: str) -> None:
32
+ if self.collecting:
33
+ self.chunks.append(data)
34
+
35
+ def handle_endtag(self, tag: str) -> None:
36
+ if tag == "script" and self.collecting:
37
+ self.page_json = "".join(self.chunks)
38
+ self.collecting = False
39
+
40
+
41
+ _MISSING = object()
42
+
43
+
44
+ class InertiaPage:
45
+ """A page's props and protocol metadata, independent of its transport."""
46
+
47
+ def __init__(self, page: dict[str, Any]) -> None:
48
+ self.component: str = page["component"]
49
+ self.props: dict[str, Any] = page["props"]
50
+ self.url: str = page["url"]
51
+ self.version: str | None = page.get("version", "")
52
+ self.deferred_props: dict[str, list[str]] = page.get("deferredProps", {})
53
+ self.merge_props: list[str] = page.get("mergeProps", [])
54
+ self.prepend_props: list[str] = page.get("prependProps", [])
55
+ self.deep_merge_props: list[str] = page.get("deepMergeProps", [])
56
+ self.match_props_on: list[str] = page.get("matchPropsOn", [])
57
+ self.once_props: dict[str, Any] = page.get("onceProps", {})
58
+ self.scroll_props: dict[str, Any] = page.get("scrollProps", {})
59
+ self.shared_props: list[str] = page.get("sharedProps", [])
60
+ self.rescued_props: list[str] = page.get("rescuedProps", [])
61
+ self.encrypt_history: bool = page.get("encryptHistory", False)
62
+ self.clear_history: bool = page.get("clearHistory", False)
63
+ self.preserve_fragment: bool = page.get("preserveFragment", False)
64
+
65
+ @classmethod
66
+ def from_response(cls, response: httpx.Response) -> Self:
67
+ """Read an X-Inertia JSON response or the document's app page script."""
68
+ try:
69
+ if response.headers.get("X-Inertia", "").lower() == "true":
70
+ page = response.json()
71
+ else:
72
+ parser = _PageScript()
73
+ parser.feed(response.text)
74
+ if parser.page_json is None:
75
+ raise ValueError("no <script data-page='app' type='application/json'>")
76
+ page = json.loads(parser.page_json)
77
+ except ValueError as exc:
78
+ raise AssertionError(f"Not a valid Inertia response: {exc}") from exc
79
+ assert isinstance(page, dict), "Not a valid Inertia response: page must be an object"
80
+ assert isinstance(page.get("component"), str) and isinstance(page.get("url"), str), (
81
+ f"Not a valid Inertia response: expected component and url strings; "
82
+ f"available keys: {list(page)}"
83
+ )
84
+ assert isinstance(page.get("props"), dict), (
85
+ f"Not a valid Inertia response: expected props object; available keys: {list(page)}"
86
+ )
87
+ return cls(page)
88
+
89
+ def assert_component(self, name: str) -> Self:
90
+ assert self.component == name, f"Expected component {name!r}, got {self.component!r}"
91
+ return self
92
+
93
+ def assert_url(self, path: str) -> Self:
94
+ assert self.url == path, f"Expected url {path!r}, got {self.url!r}"
95
+ return self
96
+
97
+ def assert_version(self, version: str | None) -> Self:
98
+ assert self.version == version, f"Expected version {version!r}, got {self.version!r}"
99
+ return self
100
+
101
+ def _lookup(self, path: str) -> tuple[Any, str]:
102
+ # Dot-separated; a prop key that itself contains a dot cannot be addressed.
103
+ value: Any = self.props
104
+ for part in path.split("."):
105
+ if isinstance(value, dict):
106
+ available = f"Available keys: {list(value)}"
107
+ value = value.get(part, _MISSING)
108
+ elif isinstance(value, list):
109
+ available = f"Available indices: {list(range(len(value)))}"
110
+ index = int(part) if part.isascii() and part.isdigit() else -1
111
+ value = value[index] if 0 <= index < len(value) else _MISSING
112
+ else:
113
+ return _MISSING, f"Available keys: none ({value!r} is not a container)"
114
+ if value is _MISSING:
115
+ return _MISSING, available
116
+ return value, f"Available keys: {list(self.props)}"
117
+
118
+ def _value(self, path: str) -> Any:
119
+ value, available = self._lookup(path)
120
+ assert value is not _MISSING, f"Missing prop {path!r}. {available}"
121
+ return value
122
+
123
+ def has(self, path: str, count: int | None = None) -> Self:
124
+ """Assert presence, optionally checking the length of a prop."""
125
+ value = self._value(path)
126
+ if count is not None:
127
+ assert isinstance(value, Sized), f"Prop {path!r} has no count: {value!r}"
128
+ assert len(value) == count, f"Expected prop {path!r} count {count}, got {len(value)}"
129
+ return self
130
+
131
+ def missing(self, path: str) -> Self:
132
+ value, available = self._lookup(path)
133
+ assert value is _MISSING, f"Prop {path!r} is present: {value!r}. {available}"
134
+ return self
135
+
136
+ def where(self, path: str, expected_or_predicate: Any) -> Self:
137
+ value = self._value(path)
138
+ if callable(expected_or_predicate):
139
+ assert expected_or_predicate(value), f"Prop {path!r} failed predicate; got {value!r}"
140
+ else:
141
+ assert value == expected_or_predicate, (
142
+ f"Expected prop {path!r} to equal {expected_or_predicate!r}, got {value!r}"
143
+ )
144
+ return self
145
+
146
+ def deferred(self, group: str, *props: str) -> Self:
147
+ """Assert a deferred group exists and contains the named props."""
148
+ assert group in self.deferred_props, (
149
+ f"Missing deferred group {group!r}. Available groups: {list(self.deferred_props)}"
150
+ )
151
+ for prop in props:
152
+ assert prop in self.deferred_props[group], (
153
+ f"Missing deferred prop {prop!r} in {group!r}. "
154
+ f"Available props: {self.deferred_props[group]}"
155
+ )
156
+ return self
157
+
158
+ async def _reload(self, client: httpx.AsyncClient, header: str, props: tuple[str, ...]) -> Self:
159
+ # An empty partial header makes the server answer with the full page.
160
+ assert props, "Name at least one prop; an empty partial reload is a full visit"
161
+ response = await client.get(
162
+ self.url,
163
+ headers={
164
+ "X-Inertia": "true",
165
+ "X-Inertia-Version": self.version or "",
166
+ "X-Inertia-Partial-Component": self.component,
167
+ header: ",".join(props),
168
+ },
169
+ )
170
+ return self.from_response(response)
171
+
172
+ async def reload_only(self, client: httpx.AsyncClient, *props: str) -> Self:
173
+ """Request only these props; the result is the unmerged response page."""
174
+ return await self._reload(client, "X-Inertia-Partial-Data", props)
175
+
176
+ async def reload_except(self, client: httpx.AsyncClient, *props: str) -> Self:
177
+ """Request a partial page excluding these props."""
178
+ return await self._reload(client, "X-Inertia-Partial-Except", props)
179
+
180
+ async def load_deferred(self, client: httpx.AsyncClient, group: str | None = None) -> Self:
181
+ """Load one deferred group, or all groups when omitted."""
182
+ if group is not None:
183
+ self.deferred(group)
184
+ props = self.deferred_props[group]
185
+ else:
186
+ props = [prop for group_props in self.deferred_props.values() for prop in group_props]
187
+ if not props:
188
+ return copy(self)
189
+ return await self.reload_only(client, *props)
190
+
191
+
192
+ def inertia_page(response: httpx.Response) -> InertiaPage:
193
+ """Short form of :meth:`InertiaPage.from_response`."""
194
+ return InertiaPage.from_response(response)
@@ -11,10 +11,16 @@ from __future__ import annotations
11
11
  import httpx
12
12
  from simple_module_hosting.csrf import CSRF_HEADER
13
13
 
14
+ from simple_module_test.inertia import inertia_headers
15
+
14
16
 
15
17
  def wizard_client(app) -> httpx.AsyncClient:
16
18
  """An anonymous client for *app*; it keeps the session cookie between calls."""
17
- return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver")
19
+ return httpx.AsyncClient(
20
+ transport=httpx.ASGITransport(app=app),
21
+ base_url="http://testserver",
22
+ headers=inertia_headers(app),
23
+ )
18
24
 
19
25
 
20
26
  async def wizard_headers(client: httpx.AsyncClient) -> dict[str, str]:
@@ -33,6 +33,7 @@ import httpx
33
33
  import pytest
34
34
  from simple_module_core.tenancy import TenantRole
35
35
 
36
+ from simple_module_test.inertia import inertia_headers
36
37
  from simple_module_test.session_cookie import forge_session_cookie
37
38
 
38
39
 
@@ -89,6 +90,7 @@ async def session_client(app: Any, data: dict[str, Any]) -> AsyncGenerator[httpx
89
90
  async with httpx.AsyncClient(
90
91
  transport=httpx.ASGITransport(app=app),
91
92
  base_url="http://testserver",
93
+ headers=inertia_headers(app),
92
94
  cookies={"session": cookie},
93
95
  ) as client:
94
96
  yield client
@@ -0,0 +1,34 @@
1
+ """Shared clients send the configured version without enabling Inertia visits."""
2
+
3
+ from types import SimpleNamespace
4
+
5
+ import pytest
6
+ from fastapi import FastAPI
7
+ from simple_module_test import inertia_headers
8
+ from simple_module_test.setup_wizard import wizard_client
9
+ from simple_module_test.tenant_client import session_client
10
+
11
+
12
+ @pytest.mark.parametrize("version", ["build", lambda: "computed"])
13
+ def test_version_headers_follow_app_config(version):
14
+ app = FastAPI()
15
+ app.state.sm = SimpleNamespace(inertia_config=SimpleNamespace(version=version))
16
+ assert inertia_headers(app) == {
17
+ "X-Inertia-Version": version() if callable(version) else version
18
+ }
19
+
20
+
21
+ def test_app_without_inertia_has_no_version_header():
22
+ assert inertia_headers(FastAPI()) == {}
23
+
24
+
25
+ async def test_shared_clients_default_to_current_version(app, client, authenticated_client):
26
+ expected = inertia_headers(app)
27
+ assert expected
28
+ for http in (client, authenticated_client):
29
+ assert http.headers["X-Inertia-Version"] == expected["X-Inertia-Version"]
30
+ assert "X-Inertia" not in http.headers
31
+ async with wizard_client(app) as http:
32
+ assert http.headers["X-Inertia-Version"] == expected["X-Inertia-Version"]
33
+ async with session_client(app, {}) as http:
34
+ assert http.headers["X-Inertia-Version"] == expected["X-Inertia-Version"]
@@ -0,0 +1,251 @@
1
+ """Inertia assertions work for document loads and subsequent protocol visits."""
2
+
3
+ import httpx
4
+ import pytest
5
+ import simple_module_test
6
+ from fastapi.routing import APIRoute
7
+ from fastapi.templating import Jinja2Templates
8
+ from jinja2.utils import htmlsafe_json_dumps
9
+ from simple_module_core import ModuleBase, ModuleMeta
10
+ from simple_module_hosting.inertia_deps import InertiaDep
11
+ from simple_module_inertia import (
12
+ InertiaConfig,
13
+ defer,
14
+ inertia_dependency_factory,
15
+ merge,
16
+ optional,
17
+ )
18
+
19
+
20
+ def page_response(**fields):
21
+ return httpx.Response(
22
+ 200,
23
+ headers={"X-Inertia": "true"},
24
+ json={
25
+ "component": "Probe",
26
+ "props": {"auth": {"user": {"email": "a@test"}}, "items": [{"id": 1}], "nil": None},
27
+ "url": "/probe?q=1",
28
+ "version": "build",
29
+ **fields,
30
+ },
31
+ )
32
+
33
+
34
+ def test_json_page_assertions_chain():
35
+ page = simple_module_test.inertia_page(page_response(deferredProps={"slow": ["stats"]}))
36
+ assert (
37
+ page.assert_component("Probe")
38
+ .assert_url("/probe?q=1")
39
+ .assert_version("build")
40
+ .has("items", count=1)
41
+ .has("auth.user", count=1)
42
+ .has("nil")
43
+ .where("nil", None)
44
+ .where("auth.user.email", "a@test")
45
+ .where("items.0.id", lambda value: value > 0)
46
+ .missing("items.1")
47
+ .missing("items.-1")
48
+ .missing("nil.child")
49
+ .deferred("slow", "stats")
50
+ is page
51
+ )
52
+ assert page.component == "Probe"
53
+ assert page.props["items"] == [{"id": 1}]
54
+ assert page.url == "/probe?q=1"
55
+ assert page.version == "build"
56
+
57
+
58
+ @pytest.mark.parametrize("html", [False, True])
59
+ def test_parsing_preserves_html_safe_json_and_metadata(html):
60
+ fields = {
61
+ "props": {"text": "<script>&lt; ' snowman ☃"},
62
+ "deferredProps": {"default": ["slow"]},
63
+ "mergeProps": ["items"],
64
+ "prependProps": ["feed"],
65
+ "deepMergeProps": ["tree"],
66
+ "matchPropsOn": ["items.id"],
67
+ "preserveFragment": True,
68
+ "onceProps": {"key": {"prop": "lookup"}},
69
+ "scrollProps": {"items": {"currentPage": 1}},
70
+ "sharedProps": ["auth"],
71
+ "rescuedProps": ["slow"],
72
+ "encryptHistory": True,
73
+ "clearHistory": True,
74
+ }
75
+ response = page_response(**fields)
76
+ if html:
77
+ blob = htmlsafe_json_dumps(response.json())
78
+ response = httpx.Response(
79
+ 200,
80
+ text=f'<html><script>ignored</script><script type="application/json" '
81
+ f"data-page='app'>\n{blob}\n</script></html>",
82
+ )
83
+ page = simple_module_test.InertiaPage.from_response(response)
84
+ assert page.props == fields["props"]
85
+ assert page.deferred_props == fields["deferredProps"]
86
+ assert page.merge_props == fields["mergeProps"]
87
+ assert page.prepend_props == fields["prependProps"]
88
+ assert page.deep_merge_props == fields["deepMergeProps"]
89
+ assert page.match_props_on == fields["matchPropsOn"]
90
+ assert page.preserve_fragment is True
91
+ assert page.once_props == fields["onceProps"]
92
+ assert page.scroll_props == fields["scrollProps"]
93
+ assert page.shared_props == fields["sharedProps"]
94
+ assert page.rescued_props == fields["rescuedProps"]
95
+ assert page.encrypt_history is True
96
+ assert page.clear_history is True
97
+
98
+
99
+ def test_optional_page_fields_default_to_empty_or_false():
100
+ page = simple_module_test.inertia_page(page_response())
101
+ assert page.deferred_props == page.once_props == page.scroll_props == {}
102
+ assert page.merge_props == page.shared_props == page.rescued_props == []
103
+ assert page.encrypt_history is page.clear_history is page.preserve_fragment is False
104
+
105
+
106
+ @pytest.mark.parametrize(
107
+ "response",
108
+ [
109
+ httpx.Response(200, text="plain response"),
110
+ httpx.Response(200, json={"detail": "API response"}),
111
+ httpx.Response(200, headers={"X-Inertia": "true"}, text="bad JSON"),
112
+ page_response(component=None),
113
+ page_response(props=[]),
114
+ httpx.Response(200, headers={"X-Inertia": "true"}, json=[]),
115
+ httpx.Response(200, text='<script data-page="app" type="application/json">{</script>'),
116
+ httpx.Response(200, text='<script data-page="app" type="text/plain">{}</script>'),
117
+ httpx.Response(200, text='<script data-page="app" type="application/json">{}'),
118
+ ],
119
+ )
120
+ def test_invalid_responses_raise_clear_assertions(response):
121
+ with pytest.raises(AssertionError, match="Not a valid Inertia response"):
122
+ simple_module_test.inertia_page(response)
123
+
124
+
125
+ @pytest.mark.parametrize(
126
+ ("method", "args", "message"),
127
+ [
128
+ ("assert_component", ("Other",), "component.*Other.*Probe"),
129
+ ("assert_url", ("/other",), "url.*/other.*/probe"),
130
+ ("assert_version", ("stale",), "version.*stale.*build"),
131
+ ("has", ("auth.missing",), "auth.missing.*Available.*user"),
132
+ ("has", ("items.2",), "items.2.*Available.*0"),
133
+ ("has", ("items.bad",), "items.bad.*Available.*0"),
134
+ ("has", ("nil.child",), "nil.child.*Available"),
135
+ ("has", ("items", 2), "items.*2.*1"),
136
+ ("has", ("nil", 1), "nil.*count"),
137
+ ("missing", ("nil",), "nil.*present.*Available"),
138
+ ("where", ("items.0.id", 2), "items.0.id.*2.*1"),
139
+ ("where", ("items.0.id", lambda value: value < 0), "items.0.id.*predicate.*1"),
140
+ ("where", ("absent", None), "absent.*Available.*items"),
141
+ ("deferred", ("unknown",), "unknown.*Available.*slow"),
142
+ ("deferred", ("slow", "other"), "other.*Available.*stats"),
143
+ ],
144
+ )
145
+ def test_assertion_failures_are_actionable(method, args, message):
146
+ page = simple_module_test.inertia_page(page_response(deferredProps={"slow": ["stats"]}))
147
+ with pytest.raises(AssertionError, match=message):
148
+ getattr(page, method)(*args)
149
+
150
+
151
+ @pytest.fixture
152
+ async def helper_client(build_test_app, tmp_path):
153
+ class ProbeModule(ModuleBase):
154
+ meta = ModuleMeta(name="Probe")
155
+
156
+ app = build_test_app(ProbeModule)
157
+ (tmp_path / "index.html").write_text("{% inertia_body %}", encoding="utf-8")
158
+ config = InertiaConfig(templates=Jinja2Templates(directory=tmp_path), version="build")
159
+ app.state.inertia_dependency = inertia_dependency_factory(config)
160
+
161
+ async def probe(inertia: InertiaDep):
162
+ return await inertia.render(
163
+ "Probe",
164
+ {
165
+ "name": "Ada",
166
+ "extra": optional(lambda: "requested"),
167
+ "stats": defer(lambda: {"total": 3}),
168
+ "report": defer(lambda: "ready", group="reports"),
169
+ "items": merge([{"id": 1}]),
170
+ },
171
+ )
172
+
173
+ app.router.routes.insert(0, APIRoute("/inertia-helper-probe", probe, methods=["GET"]))
174
+ async with httpx.AsyncClient(
175
+ transport=httpx.ASGITransport(app=app),
176
+ base_url="http://test",
177
+ headers={"X-Inertia-Version": "build"},
178
+ ) as client:
179
+ yield client
180
+
181
+
182
+ @pytest.fixture
183
+ async def probe_page(helper_client):
184
+ response = await helper_client.get("/inertia-helper-probe?q=1")
185
+ assert response.status_code == 200
186
+ return simple_module_test.inertia_page(response)
187
+
188
+
189
+ async def test_real_document_and_json_visits(probe_page, helper_client):
190
+ probe_page.assert_component("Probe").where("name", "Ada").missing("extra")
191
+ probe_page.deferred("default", "stats").deferred("reports", "report")
192
+ assert probe_page.merge_props == ["items"]
193
+ response = await helper_client.get(probe_page.url, headers={"X-Inertia": "true"})
194
+ page = simple_module_test.inertia_page(response)
195
+ assert page.props == probe_page.props
196
+ assert page.deferred_props == probe_page.deferred_props
197
+
198
+
199
+ async def test_reload_only_and_except(probe_page, helper_client):
200
+ page = await probe_page.reload_only(helper_client, "extra", "items")
201
+ page.where("extra", "requested").has("items", 1).missing("name")
202
+ assert page is not probe_page
203
+ assert page.url == probe_page.url
204
+ page = await probe_page.reload_except(helper_client, "items")
205
+ page.where("name", "Ada").missing("items").where("extra", "requested")
206
+
207
+
208
+ async def test_load_deferred_group_and_all(probe_page, helper_client):
209
+ page = await probe_page.load_deferred(helper_client, "reports")
210
+ page.where("report", "ready").missing("stats").missing("name")
211
+ page = await probe_page.load_deferred(helper_client)
212
+ page.where("stats.total", 3).where("report", "ready").missing("name")
213
+ with pytest.raises(AssertionError, match=r"unknown.*Available.*reports"):
214
+ await probe_page.load_deferred(helper_client, "unknown")
215
+
216
+
217
+ async def test_followup_headers_use_page_version():
218
+ async def respond(request):
219
+ assert request.url.path == "/probe"
220
+ assert request.url.query == b"q=1"
221
+ assert request.headers["X-Inertia"] == "true"
222
+ assert request.headers["X-Inertia-Version"] == "build"
223
+ assert request.headers["X-Inertia-Partial-Component"] == "Probe"
224
+ assert request.headers["X-Inertia-Partial-Data"] == "auth.user,items"
225
+ assert "X-Inertia-Partial-Except" not in request.headers
226
+ return page_response()
227
+
228
+ async with httpx.AsyncClient(
229
+ transport=httpx.MockTransport(respond), base_url="http://test"
230
+ ) as client:
231
+ await simple_module_test.inertia_page(page_response()).reload_only(
232
+ client, "auth.user", "items"
233
+ )
234
+
235
+
236
+ async def test_no_deferred_props_does_not_reload():
237
+ async def unexpected(request):
238
+ pytest.fail("A page without deferred props must not issue a full reload")
239
+
240
+ async with httpx.AsyncClient(transport=httpx.MockTransport(unexpected)) as client:
241
+ page = simple_module_test.inertia_page(page_response())
242
+ loaded = await page.load_deferred(client)
243
+ assert loaded.props == page.props
244
+
245
+
246
+ @pytest.mark.parametrize("method", ["reload_only", "reload_except"])
247
+ async def test_partial_reload_needs_at_least_one_prop(method):
248
+ page = simple_module_test.inertia_page(page_response())
249
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda r: None)) as client:
250
+ with pytest.raises(AssertionError, match="at least one prop"):
251
+ await getattr(page, method)(client)