simple-module-test 0.0.47__tar.gz → 0.0.49__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 (42) hide show
  1. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/.gitignore +6 -0
  2. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/PKG-INFO +26 -5
  3. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/README.md +20 -0
  4. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/pyproject.toml +7 -5
  5. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/__init__.py +3 -0
  6. simple_module_test-0.0.49/simple_module_test/_dotenv.py +36 -0
  7. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/app_factory.py +2 -0
  8. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/database.py +11 -7
  9. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/fixtures.py +5 -8
  10. simple_module_test-0.0.49/simple_module_test/layout.py +88 -0
  11. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/mail.py +1 -2
  12. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/plugin.py +6 -1
  13. simple_module_test-0.0.49/tests/test_schema_reuse_pg.py +185 -0
  14. simple_module_test-0.0.49/tests/test_testing_module_layout.py +32 -0
  15. simple_module_test-0.0.49/tests/test_testing_project_isolation.py +86 -0
  16. simple_module_test-0.0.47/tests/test_schema_reuse_pg.py +0 -75
  17. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/LICENSE +0 -0
  18. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/_compile_cache.py +0 -0
  19. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/_schema.py +0 -0
  20. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/_sqlite_template.py +0 -0
  21. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/fake_events.py +0 -0
  22. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/inertia.py +0 -0
  23. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/inertia_page.py +0 -0
  24. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/oidc_issuer.py +0 -0
  25. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/process_state.py +0 -0
  26. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/redis_server.py +0 -0
  27. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/routes.py +0 -0
  28. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/session_cookie.py +0 -0
  29. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/setup_wizard.py +0 -0
  30. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/tenant_client.py +0 -0
  31. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/simple_module_test/waiting.py +0 -0
  32. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_app_factory.py +0 -0
  33. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_fake_events.py +0 -0
  34. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_plugin_fixtures.py +0 -0
  35. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_shared_compile_cache.py +0 -0
  36. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_sqlite_schema_template.py +0 -0
  37. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_testing_inertia_headers.py +0 -0
  38. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_testing_inertia_page.py +0 -0
  39. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_testing_oidc_issuer.py +0 -0
  40. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_testing_process_state.py +0 -0
  41. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_waiting_helpers.py +0 -0
  42. {simple_module_test-0.0.47 → simple_module_test-0.0.49}/tests/test_worker_database.py +0 -0
@@ -67,3 +67,9 @@ host/client_app/.playwright-cli/*
67
67
  .verify/
68
68
  /openapi.json
69
69
  qa-shots/
70
+
71
+ host/client_app/.module-tsconfig
72
+
73
+ # Incremental generation cache
74
+ .smpy/gen.json
75
+ .smpy/gen.*.tmp
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simple_module_test
3
- Version: 0.0.47
3
+ Version: 0.0.49
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
@@ -24,13 +24,14 @@ Requires-Python: >=3.12
24
24
  Requires-Dist: cryptography>=42
25
25
  Requires-Dist: fastapi<0.163,>=0.140
26
26
  Requires-Dist: httpx<0.29,>=0.27
27
+ Requires-Dist: pydantic-settings<3,>=2.4
27
28
  Requires-Dist: pyjwt[crypto]<3,>=2.8
28
29
  Requires-Dist: pytest-asyncio<2,>=0.24
29
30
  Requires-Dist: pytest<10,>=8.0
30
- Requires-Dist: simple-module-core==0.0.47
31
- Requires-Dist: simple-module-db==0.0.47
32
- Requires-Dist: simple-module-hosting==0.0.47
33
- Requires-Dist: simple-module-inertia==0.0.47
31
+ Requires-Dist: simple-module-core==0.0.49
32
+ Requires-Dist: simple-module-db==0.0.49
33
+ Requires-Dist: simple-module-hosting==0.0.49
34
+ Requires-Dist: simple-module-inertia==0.0.49
34
35
  Requires-Dist: sqlalchemy<3,>=2.0
35
36
  Description-Content-Type: text/markdown
36
37
 
@@ -40,6 +41,11 @@ Shared pytest fixtures and helpers for writing tests against [simple_module](htt
40
41
 
41
42
  Fixtures are exposed via a `pytest11` entry point, so installing the package is enough — no `conftest.py` import needed.
42
43
 
44
+ The plugin ignores the invoking project's `.env` before collection, while exported
45
+ environment variables and temporary configuration-test files still work. Test imports
46
+ default to `importlib`, allowing repeated basenames. Add support directories to pytest's
47
+ `pythonpath` when using plain helper imports or `pytest_plugins`.
48
+
43
49
  ## Install
44
50
 
45
51
  ```bash
@@ -83,6 +89,21 @@ async def test_create_order(authenticated_client):
83
89
 
84
90
  No fixture imports, no `conftest.py` — the `pytest11` entry point auto-loads them.
85
91
 
92
+ To enforce the standard package and test layout, call the public helper from a test:
93
+
94
+ ```python
95
+ from pathlib import Path
96
+
97
+ from simple_module_test import assert_module_layout
98
+
99
+
100
+ def test_orders_layout():
101
+ assert_module_layout(Path("modules/orders"), "orders")
102
+ ```
103
+
104
+ For standalone module projects use `Path(".")`. Pass named domain directories with
105
+ `domain_areas={"fulfillment"}` and temporary compatibility files with `deprecated_root`.
106
+
86
107
  ## Depends on
87
108
 
88
109
  - `simple_module_core`, `simple_module_db`, `simple_module_hosting`
@@ -4,6 +4,11 @@ Shared pytest fixtures and helpers for writing tests against [simple_module](htt
4
4
 
5
5
  Fixtures are exposed via a `pytest11` entry point, so installing the package is enough — no `conftest.py` import needed.
6
6
 
7
+ The plugin ignores the invoking project's `.env` before collection, while exported
8
+ environment variables and temporary configuration-test files still work. Test imports
9
+ default to `importlib`, allowing repeated basenames. Add support directories to pytest's
10
+ `pythonpath` when using plain helper imports or `pytest_plugins`.
11
+
7
12
  ## Install
8
13
 
9
14
  ```bash
@@ -47,6 +52,21 @@ async def test_create_order(authenticated_client):
47
52
 
48
53
  No fixture imports, no `conftest.py` — the `pytest11` entry point auto-loads them.
49
54
 
55
+ To enforce the standard package and test layout, call the public helper from a test:
56
+
57
+ ```python
58
+ from pathlib import Path
59
+
60
+ from simple_module_test import assert_module_layout
61
+
62
+
63
+ def test_orders_layout():
64
+ assert_module_layout(Path("modules/orders"), "orders")
65
+ ```
66
+
67
+ For standalone module projects use `Path(".")`. Pass named domain directories with
68
+ `domain_areas={"fulfillment"}` and temporary compatibility files with `deprecated_root`.
69
+
50
70
  ## Depends on
51
71
 
52
72
  - `simple_module_core`, `simple_module_db`, `simple_module_hosting`
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "simple_module_test"
3
- version = "0.0.47"
3
+ version = "0.0.49"
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"
@@ -26,12 +26,14 @@ dependencies = [
26
26
  # OidcTestIssuer: sign ID tokens and publish a JWKS (#879).
27
27
  "cryptography>=42",
28
28
  "PyJWT[crypto]>=2.8,<3",
29
+ # The dotenv guard patches DotEnvSettingsSource._read_env_file (added in 2.4).
30
+ "pydantic-settings>=2.4,<3",
29
31
  "pytest>=8.0,<10",
30
32
  "pytest-asyncio>=0.24,<2",
31
- "simple_module_core==0.0.47",
32
- "simple_module_db==0.0.47",
33
- "simple_module_hosting==0.0.47",
34
- "simple_module_inertia==0.0.47",
33
+ "simple_module_core==0.0.49",
34
+ "simple_module_db==0.0.49",
35
+ "simple_module_hosting==0.0.49",
36
+ "simple_module_inertia==0.0.49",
35
37
  "sqlalchemy>=2.0,<3",
36
38
  ]
37
39
 
@@ -14,6 +14,7 @@ Primary exports:
14
14
  * :func:`inertia_page` / :class:`InertiaPage` — parse an Inertia document or
15
15
  ``X-Inertia`` response into fluent prop assertions and partial/deferred reloads.
16
16
  * :func:`inertia_headers` — default ``X-Inertia-Version`` header for clients.
17
+ * :func:`assert_module_layout` — enforce standard package and test directories.
17
18
 
18
19
  The pytest plugin auto-registers these fixtures (no imports needed):
19
20
  ``fake_event_bus``, ``build_test_app``, ``settings``, ``db_state``,
@@ -34,6 +35,7 @@ from simple_module_test.app_factory import build_test_app
34
35
  from simple_module_test.fake_events import FakeEventBus, RecordedEvent
35
36
  from simple_module_test.inertia import inertia_headers
36
37
  from simple_module_test.inertia_page import InertiaPage, inertia_page
38
+ from simple_module_test.layout import assert_module_layout
37
39
  from simple_module_test.oidc_issuer import OidcTestIssuer
38
40
  from simple_module_test.routes import effective_route_paths
39
41
  from simple_module_test.session_cookie import forge_session_cookie
@@ -46,6 +48,7 @@ __all__ = [
46
48
  "OidcTestIssuer",
47
49
  "RecordedEvent",
48
50
  "TenantClient",
51
+ "assert_module_layout",
49
52
  "build_test_app",
50
53
  "effective_route_paths",
51
54
  "forge_session_cookie",
@@ -0,0 +1,36 @@
1
+ """Ignore the invoking project's dotenv files, including during collection.
2
+
3
+ Keep lookup and SQLite anchoring intact, and allow temporary dotenv files used
4
+ by tests of configuration itself. Real environment variables still apply.
5
+ """
6
+
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+ from pydantic_settings import DotEnvSettingsSource
11
+ from simple_module_core import dotenv
12
+ from simple_module_hosting import _preapp_config
13
+
14
+
15
+ def isolate_project_dotenv(config: pytest.Config) -> None:
16
+ ignored = {
17
+ dotenv.find_env_file().resolve(),
18
+ (config.rootpath / ".env").resolve(),
19
+ (Path.cwd() / ".env").resolve(),
20
+ }
21
+ patch = pytest.MonkeyPatch()
22
+ config.add_cleanup(patch.undo)
23
+ parse = dotenv.parse_dotenv
24
+ read = DotEnvSettingsSource._read_env_file
25
+
26
+ def parse_dotenv(path: Path | None = None) -> dict[str, str]:
27
+ path = path if path is not None else dotenv.find_env_file()
28
+ return {} if path.resolve() in ignored else parse(path)
29
+
30
+ def read_env_file(source, path: Path):
31
+ return {} if path.resolve() in ignored else read(source, path)
32
+
33
+ patch.setattr(dotenv, "parse_dotenv", parse_dotenv)
34
+ # Hosting imports the parser before the pytest plugin is loaded.
35
+ patch.setattr(_preapp_config, "parse_dotenv", parse_dotenv)
36
+ patch.setattr(DotEnvSettingsSource, "_read_env_file", read_env_file)
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  from fastapi import FastAPI
6
6
  from simple_module_core import ModuleBase
7
+ from simple_module_hosting._module_routes import wire_fallback_routes
7
8
  from simple_module_hosting.app_builder import wire_module_routes
8
9
 
9
10
 
@@ -20,4 +21,5 @@ def build_test_app(module: ModuleBase | type[ModuleBase]) -> FastAPI:
20
21
  app = FastAPI()
21
22
  app.state.module = instance
22
23
  wire_module_routes(app, instance)
24
+ wire_fallback_routes(app, instance)
23
25
  return app
@@ -152,8 +152,8 @@ async def prepare_schema_once(engine: Any, tables: list[Any], build: Any) -> Non
152
152
  per-process copy of the first build (``_sqlite_template``), a file one runs
153
153
  ``build(engine)``.
154
154
  Postgres: when this process already built the schema and the catalog still
155
- matches it, delete every row and restart the sequences (~0.03 s) instead of
156
- dropping and rebuilding it (~0.25 s). Anything else (the first test, a
155
+ matches it, empty the tables with one TRUNCATE and restart the sequences
156
+ instead of dropping and rebuilding it. Anything else (the first test, a
157
157
  direct ``reset_schema`` call, a test's own DDL) resets and rebuilds.
158
158
  """
159
159
  global _reset_for, _built_schema
@@ -181,13 +181,17 @@ async def _fingerprint(engine: Any) -> str:
181
181
 
182
182
 
183
183
  async def _empty_tables(engine: Any, tables: list[Any]) -> None:
184
- from sqlalchemy.schema import sort_tables
184
+ """Empty a reused Postgres schema; SQLite is handled before this call."""
185
185
 
186
186
  async with engine.begin() as conn:
187
- quote = conn.dialect.identifier_preparer.format_table
188
- # Children first, so no foreign key refuses a parent's delete.
189
- for table in reversed(sort_tables(tables)):
190
- await conn.execute(text(f"DELETE FROM {quote(table)}"))
187
+ # A leaked reader must fail setup instead of waiting forever for TRUNCATE.
188
+ await conn.execute(text("SET LOCAL lock_timeout = '5s'"))
189
+ if tables:
190
+ quote = conn.dialect.identifier_preparer.format_table
191
+ names = ", ".join(quote(table) for table in tables)
192
+ # Refuse foreign-key dependants outside the caller's reset boundary.
193
+ await conn.execute(text(f"TRUNCATE {names} RESTART IDENTITY RESTRICT"))
194
+ # RESTART IDENTITY excludes unowned sequences; preserve their reset too.
191
195
  await conn.execute(_RESTART_SEQUENCES)
192
196
 
193
197
 
@@ -42,15 +42,13 @@ _AUTH_PROVIDER_ENV = "SM_AUTH_PROVIDER"
42
42
  def pinned_auth_provider() -> Iterator[str]:
43
43
  """Pin ``SM_AUTH_PROVIDER`` to the local-account provider for the suite.
44
44
 
45
- ``Settings`` reads the repo's ``.env``, and the README tells anyone running
46
- Keycloak locally to put ``SM_AUTH_PROVIDER=keycloak`` there. Nearly every
45
+ A shell may export ``SM_AUTH_PROVIDER=keycloak`` for local development. Nearly every
47
46
  test that boots an app expects the ``users`` provider — ``/users/login``,
48
47
  the admin pages, the seeded admin in ``authenticated_client`` — and the
49
48
  ``Settings(...)`` construction sites are spread across module conftests,
50
49
  so pinning it on each one would be a losing game.
51
50
 
52
- The real environment outranks ``.env`` in pydantic-settings, so setting it
53
- here covers every construction site at once. A test that wants a different
51
+ Setting it here covers every construction site at once. A test that wants a different
54
52
  provider can still ``monkeypatch.setenv`` or pass ``auth_provider=`` to
55
53
  ``Settings`` directly.
56
54
  """
@@ -84,10 +82,8 @@ def settings() -> Settings:
84
82
  Individual tests that want the tenant middleware absent construct
85
83
  their own ``Settings(multi_tenant=False, ...)`` in the test body.
86
84
 
87
- ``auth_provider`` is pinned for the same reason as the rest: a developer
88
- running Keycloak locally has ``SM_AUTH_PROVIDER=keycloak`` in ``.env``,
89
- which would otherwise swap the auth provider out from under every test
90
- that expects ``/users/login``.
85
+ Pin the auth provider and Vite URL even when the developer's shell exports
86
+ different values. Project dotenv files are ignored by the plugin.
91
87
  """
92
88
  return Settings(
93
89
  database_url=database_url_for_tests(),
@@ -96,6 +92,7 @@ def settings() -> Settings:
96
92
  multi_tenant=True,
97
93
  tenant_header="X-Tenant-ID",
98
94
  auth_provider="users",
95
+ vite_dev_url="http://localhost:5050",
99
96
  )
100
97
 
101
98
 
@@ -0,0 +1,88 @@
1
+ """Public pytest assertion for the standard module package and test layout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from collections.abc import Collection
7
+ from pathlib import Path
8
+
9
+ ALLOWED_ROOT = frozenset(
10
+ {
11
+ "__init__.py",
12
+ "__main__.py",
13
+ "py.typed",
14
+ "module.py",
15
+ "models.py",
16
+ "models",
17
+ "tasks.py",
18
+ "task_config.py",
19
+ "contracts",
20
+ "pages",
21
+ "locales",
22
+ "theme.css",
23
+ "styles.css",
24
+ "cli.py",
25
+ "core",
26
+ "web",
27
+ "ui",
28
+ }
29
+ )
30
+
31
+
32
+ def _is_layout_shim(path: Path) -> bool:
33
+ """A moved module's old path: a deprecated alias, allowed until its remove_in."""
34
+ text = path.read_text(encoding="utf-8")
35
+ return "deprecated_module(" in text and "sys.modules[__name__]" in text
36
+
37
+
38
+ def _only_bytecode(path: Path) -> bool:
39
+ """A directory an older checkout left behind holding only ``__pycache__``."""
40
+ return all(child.name == "__pycache__" for child in path.iterdir())
41
+
42
+
43
+ def _is_shim_package(path: Path) -> bool:
44
+ """An old package path kept only for its aliases: shims plus a docstring __init__."""
45
+ files = [f for f in path.glob("*.py") if f.name != "__init__.py"]
46
+ return bool(files) and all(_is_layout_shim(f) for f in files)
47
+
48
+
49
+ def assert_module_layout(
50
+ project: Path,
51
+ package_name: str,
52
+ *,
53
+ domain_areas: Collection[str] = (),
54
+ deprecated_root: Collection[str] = (),
55
+ ) -> None:
56
+ """Check a module project (package + tests + pyproject.toml).
57
+
58
+ Pass named domain directories and any temporary deprecated root files.
59
+ Test basenames may repeat: the plugin defaults to importlib mode.
60
+ """
61
+ package = project / package_name
62
+ assert package.is_dir(), f"Missing package for {package_name}"
63
+ entries = {
64
+ p.name
65
+ for p in package.iterdir()
66
+ if (p.suffix == ".py" and not _is_layout_shim(p))
67
+ or (
68
+ p.is_dir()
69
+ and p.name != "__pycache__"
70
+ and not _only_bytecode(p)
71
+ and not _is_shim_package(p)
72
+ )
73
+ }
74
+ deprecated = frozenset(deprecated_root)
75
+ assert deprecated <= {p.name for p in package.iterdir()}, (
76
+ f"{package_name}: remove expired DEPRECATED_ROOT entries"
77
+ )
78
+ allowed = ALLOWED_ROOT | frozenset(domain_areas) | deprecated
79
+ assert not entries - allowed, f"{package_name}: unexpected roots {entries - allowed}"
80
+ if (package / "cli.py").is_file():
81
+ metadata = tomllib.loads((project / "pyproject.toml").read_text())["project"]
82
+ targets = [
83
+ value for group in metadata.get("entry-points", {}).values() for value in group.values()
84
+ ]
85
+ assert any(value.split(":")[0] == f"{package_name}.cli" for value in targets)
86
+ # Tests mirror the package areas: tests/<area>/<feature>/test_*.py.
87
+ assert not list((project / "tests").glob("test_*.py")), package_name
88
+ assert not list((project / "tests").rglob("__init__.py")), package_name
@@ -32,8 +32,7 @@ def captured_mail() -> Iterator[CapturedMail]:
32
32
  """Install a recording sender that claims to deliver; yields it.
33
33
 
34
34
  Installed after any app fixture requested before it has started, so it wins
35
- over the ``mail`` module's sender. A ``settings_reloaded`` in the test
36
- reinstalls the real one; reinstall with ``install_mail_sender(captured)``.
35
+ over the ``mail`` module's sender, including after settings reloads.
37
36
  """
38
37
  captured = CapturedMail()
39
38
  install_mail_sender(captured)
@@ -50,14 +50,19 @@ def pytest_configure(config: pytest.Config) -> None:
50
50
 
51
51
  @pytest.hookimpl(tryfirst=True)
52
52
  def pytest_load_initial_conftests(early_config, parser, args) -> None:
53
- """Give each xdist worker its own Postgres database.
53
+ """Isolate configuration and give each xdist worker its own Postgres database.
54
54
 
55
55
  Every Postgres test drops and recreates ``public``. This runs before any
56
56
  conftest is imported (``pytest_configure`` runs after), so a conftest or
57
57
  test helper that reads the URL at import time already sees the worker's.
58
58
  """
59
+ from simple_module_test._dotenv import isolate_project_dotenv
59
60
  from simple_module_test.database import isolate_worker_database
60
61
 
62
+ isolate_project_dotenv(early_config)
63
+ if not any(arg == "--import-mode" or arg.startswith("--import-mode=") for arg in args):
64
+ args.insert(0, "--import-mode=importlib")
65
+ early_config.known_args_namespace.importmode = "importlib"
61
66
  isolate_worker_database()
62
67
 
63
68
 
@@ -0,0 +1,185 @@
1
+ """Postgres reuses the schema between tests, emptied of rows (``prepare_schema_once``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+
7
+ import pytest
8
+ from simple_module_test import database
9
+ from sqlalchemy import (
10
+ Column,
11
+ ForeignKey,
12
+ Identity,
13
+ Integer,
14
+ MetaData,
15
+ String,
16
+ Table,
17
+ func,
18
+ select,
19
+ text,
20
+ )
21
+ from sqlalchemy.exc import DBAPIError
22
+ from sqlalchemy.ext.asyncio import create_async_engine
23
+
24
+ pytestmark = pytest.mark.postgres
25
+
26
+ _metadata = MetaData()
27
+ _item = Table(
28
+ "reuse_probe_item",
29
+ _metadata,
30
+ Column("id", Integer, Identity(), primary_key=True),
31
+ Column("name", String(20)),
32
+ )
33
+
34
+
35
+ @pytest.fixture
36
+ async def engine(monkeypatch):
37
+ # The probe drives the per-test state itself; put it back afterwards.
38
+ for attr in ("_current_test", "_reset_for", "_built_schema"):
39
+ monkeypatch.setattr(database, attr, getattr(database, attr))
40
+ url = database.database_url_for_tests()
41
+ engine = create_async_engine(url, **database.init_db_kwargs(url))
42
+ try:
43
+ yield engine
44
+ finally:
45
+ await database.reset_schema(engine) # the next test rebuilds the real schema
46
+ await engine.dispose()
47
+
48
+
49
+ async def _next_test(engine, builds: list[int]) -> None:
50
+ async def build(engine) -> None:
51
+ builds.append(1)
52
+ async with engine.begin() as conn:
53
+ await conn.run_sync(_metadata.create_all)
54
+
55
+ database.begin_test(object())
56
+ await database.prepare_schema_once(engine, [_item], build)
57
+
58
+
59
+ async def _insert(engine) -> int:
60
+ async with engine.begin() as conn:
61
+ return (
62
+ await conn.execute(_item.insert().values(name="x").returning(_item.c.id))
63
+ ).scalar_one()
64
+
65
+
66
+ async def test_a_later_test_gets_the_same_schema_without_rows(engine):
67
+ builds: list[int] = []
68
+ await _next_test(engine, builds)
69
+ assert [await _insert(engine), await _insert(engine)] == [1, 2]
70
+
71
+ await _next_test(engine, builds)
72
+
73
+ assert builds == [1]
74
+ async with engine.connect() as conn:
75
+ assert await conn.scalar(select(func.count()).select_from(_item)) == 0
76
+ assert await _insert(engine) == 1 # sequences restart too
77
+
78
+
79
+ async def test_a_test_that_changes_the_schema_forces_a_rebuild(engine):
80
+ builds: list[int] = []
81
+ await _next_test(engine, builds)
82
+ async with engine.begin() as conn:
83
+ await conn.execute(text("CREATE TABLE reuse_probe_extra (x int)"))
84
+
85
+ await _next_test(engine, builds)
86
+
87
+ assert builds == [1, 1]
88
+ async with engine.connect() as conn:
89
+ assert await conn.scalar(text("SELECT to_regclass('reuse_probe_extra')")) is None
90
+
91
+
92
+ async def test_reset_bypasses_delete_row_triggers_and_restarts_identity(engine):
93
+ await _next_test(engine, [])
94
+ child = Table(
95
+ "reset probe child",
96
+ MetaData(),
97
+ Column("item_id", Integer, ForeignKey(_item.c.id), primary_key=True),
98
+ schema="public",
99
+ )
100
+ async with engine.begin() as conn:
101
+ await conn.run_sync(child.create)
102
+ await conn.execute(
103
+ text("""
104
+ CREATE FUNCTION refuse_probe_delete() RETURNS trigger
105
+ LANGUAGE plpgsql AS $$
106
+ BEGIN
107
+ RAISE EXCEPTION 'probe rows are immutable';
108
+ END;
109
+ $$
110
+ """)
111
+ )
112
+ await conn.execute(
113
+ text("""
114
+ CREATE TRIGGER refuse_probe_delete BEFORE DELETE ON reuse_probe_item
115
+ FOR EACH ROW EXECUTE FUNCTION refuse_probe_delete()
116
+ """)
117
+ )
118
+ assert [await _insert(engine), await _insert(engine)] == [1, 2]
119
+ async with engine.begin() as conn:
120
+ await conn.execute(child.insert().values(item_id=1))
121
+
122
+ # A quoted, schema-qualified child and parent-first input need no DELETE ordering.
123
+ await database._empty_tables(engine, [_item, child])
124
+
125
+ async with engine.connect() as conn:
126
+ assert await conn.scalar(select(func.count()).select_from(_item)) == 0
127
+ assert await conn.scalar(select(func.count()).select_from(child)) == 0
128
+ assert await _insert(engine) == 1
129
+
130
+
131
+ async def test_reset_restarts_sequences_without_a_table_owner(engine):
132
+ await _next_test(engine, [])
133
+ async with engine.begin() as conn:
134
+ await conn.execute(text("CREATE SEQUENCE reuse_probe_unowned"))
135
+ assert await conn.scalar(text("SELECT nextval('reuse_probe_unowned')")) == 1
136
+ assert await conn.scalar(text("SELECT nextval('reuse_probe_unowned')")) == 2
137
+
138
+ await database._empty_tables(engine, [_item])
139
+
140
+ async with engine.connect() as conn:
141
+ assert await conn.scalar(text("SELECT nextval('reuse_probe_unowned')")) == 1
142
+
143
+
144
+ async def test_reset_refuses_to_empty_tables_outside_the_passed_list(engine):
145
+ await _next_test(engine, [])
146
+ outside = Table(
147
+ "outside_probe",
148
+ MetaData(),
149
+ Column("id", Integer, primary_key=True),
150
+ Column("item_id", Integer, ForeignKey(_item.c.id)),
151
+ )
152
+ async with engine.begin() as conn:
153
+ await conn.run_sync(outside.create)
154
+ # DELETE on the empty parent would leave this unrelated row untouched.
155
+ await conn.execute(outside.insert().values(id=1, item_id=None))
156
+
157
+ with pytest.raises(DBAPIError, match="foreign key"):
158
+ await database._empty_tables(engine, [_item])
159
+
160
+ async with engine.connect() as conn:
161
+ assert await conn.scalar(select(outside.c.id)) == 1
162
+
163
+
164
+ async def test_reset_times_out_when_a_previous_reader_holds_a_lock(engine):
165
+ await _next_test(engine, [])
166
+ async with engine.connect() as reader:
167
+ await reader.execute(select(_item))
168
+ try:
169
+ with pytest.raises(DBAPIError, match="lock timeout"):
170
+ await asyncio.wait_for(database._empty_tables(engine, [_item]), timeout=10)
171
+ finally:
172
+ await reader.rollback()
173
+
174
+
175
+ async def test_reset_with_no_tables_preserves_the_migration_stamp(engine):
176
+ await _next_test(engine, [])
177
+ async with engine.begin() as conn:
178
+ await conn.execute(text("CREATE TABLE alembic_version (version_num text)"))
179
+ await conn.execute(text("INSERT INTO alembic_version VALUES ('probe')"))
180
+
181
+ await database._empty_tables(engine, [])
182
+ await database._empty_tables(engine, [_item])
183
+
184
+ async with engine.connect() as conn:
185
+ assert await conn.scalar(text("SELECT version_num FROM alembic_version")) == "probe"
@@ -0,0 +1,32 @@
1
+ """Consumers can enforce module layout without copying the framework's test."""
2
+
3
+ import pytest
4
+
5
+
6
+ def test_public_layout_helper_allows_duplicate_test_basenames(tmp_path):
7
+ from simple_module_test import assert_module_layout
8
+
9
+ package = tmp_path / "orders"
10
+ (package / "core").mkdir(parents=True)
11
+ (package / "__main__.py").touch()
12
+ for area in ("core", "web"):
13
+ tests = tmp_path / "tests" / area / "crud"
14
+ tests.mkdir(parents=True)
15
+ (tests / "test_crud.py").touch()
16
+ (package / "fulfillment").mkdir()
17
+ (package / "fulfillment" / "service.py").touch()
18
+ assert_module_layout(tmp_path, "orders", domain_areas={"fulfillment"})
19
+
20
+
21
+ @pytest.mark.parametrize(
22
+ "bad_path", ["orders/service.py", "tests/test_orders.py", "tests/__init__.py"]
23
+ )
24
+ def test_public_layout_helper_rejects_layout_drift(tmp_path, bad_path):
25
+ from simple_module_test import assert_module_layout
26
+
27
+ (tmp_path / "orders").mkdir()
28
+ target = tmp_path / bad_path
29
+ target.parent.mkdir(parents=True, exist_ok=True)
30
+ target.touch()
31
+ with pytest.raises(AssertionError):
32
+ assert_module_layout(tmp_path, "orders")
@@ -0,0 +1,86 @@
1
+ """The installed plugin isolates a consumer project before its conftest loads."""
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+
7
+
8
+ def _pytest(project):
9
+ env = os.environ.copy()
10
+ for key in (
11
+ "PYTEST_ADDOPTS",
12
+ "PYTEST_XDIST_WORKER",
13
+ "SM_PROJECT_ROOT",
14
+ "SM_VITE_DEV_URL",
15
+ "SM_PUBLIC_BASE_URL",
16
+ "SM_TEST_DOTENV_LEAK",
17
+ "SM_DEBUG",
18
+ ):
19
+ env.pop(key, None)
20
+ return subprocess.run(
21
+ [sys.executable, "-m", "pytest", "-q"],
22
+ cwd=project,
23
+ env=env,
24
+ capture_output=True,
25
+ text=True,
26
+ timeout=60,
27
+ )
28
+
29
+
30
+ def test_plugin_ignores_project_dotenv_before_conftest_and_in_fixtures(tmp_path):
31
+ (tmp_path / "pyproject.toml").write_text("[tool.pytest.ini_options]\n")
32
+ (tmp_path / ".env").write_text(
33
+ "SM_VITE_DEV_URL=http://localhost:9999\n"
34
+ "SM_PUBLIC_BASE_URL=https://dotenv.example\n"
35
+ "SM_TEST_DOTENV_LEAK=leaked\n"
36
+ )
37
+ (tmp_path / "conftest.py").write_text(
38
+ "from simple_module_hosting.settings import Settings\n"
39
+ "assert Settings().vite_dev_url == 'http://localhost:5050'\n"
40
+ )
41
+ (tmp_path / "test_settings.py").write_text(
42
+ "import os\n"
43
+ "import pytest\n"
44
+ "from simple_module_core.dotenv import load_dotenv_into_environ\n"
45
+ "from simple_module_hosting.settings import Settings\n"
46
+ "def test_settings(settings, monkeypatch, tmp_path):\n"
47
+ " load_dotenv_into_environ()\n"
48
+ " assert 'SM_TEST_DOTENV_LEAK' not in os.environ\n"
49
+ " assert settings.vite_dev_url == 'http://localhost:5050'\n"
50
+ " assert settings.public_base_url == ''\n"
51
+ " monkeypatch.setenv('SM_PUBLIC_BASE_URL', 'https://shell.example')\n"
52
+ " assert Settings().public_base_url == 'https://shell.example'\n"
53
+ " monkeypatch.setenv('SM_VITE_DEV_URL', 'http://localhost:8888')\n"
54
+ " assert Settings().vite_dev_url == 'http://localhost:8888'\n"
55
+ " custom = tmp_path / 'custom.env'\n"
56
+ " custom.write_text('SM_DEBUG=true\\n')\n"
57
+ " assert Settings(_env_file=custom).debug is True\n"
58
+ "@pytest.fixture\n"
59
+ "def vite_export(monkeypatch):\n"
60
+ " monkeypatch.setenv('SM_VITE_DEV_URL', 'http://localhost:8888')\n"
61
+ "def test_pinned_vite(vite_export, settings):\n"
62
+ " assert settings.vite_dev_url == 'http://localhost:5050'\n"
63
+ )
64
+ result = _pytest(tmp_path)
65
+ assert result.returncode == 0, result.stdout + result.stderr
66
+ assert "2 passed" in result.stdout
67
+
68
+
69
+ def test_plugin_imports_duplicate_basenames_with_conftests_and_plugins(tmp_path):
70
+ (tmp_path / "pyproject.toml").write_text('[tool.pytest.ini_options]\npythonpath = ["."]\n')
71
+ (tmp_path / "conftest.py").write_text('pytest_plugins = ["support"]\n')
72
+ (tmp_path / "support.py").write_text(
73
+ "import pytest\n@pytest.fixture\ndef shared():\n return 42\n"
74
+ )
75
+ for area in ("alpha", "beta"):
76
+ directory = tmp_path / area
77
+ directory.mkdir()
78
+ (directory / "conftest.py").write_text(
79
+ f"import pytest\n@pytest.fixture\ndef area():\n return '{area}'\n"
80
+ )
81
+ (directory / "test_same.py").write_text(
82
+ f"def test_value(shared, area):\n assert (shared, area) == (42, '{area}')\n"
83
+ )
84
+ result = _pytest(tmp_path)
85
+ assert result.returncode == 0, result.stdout + result.stderr
86
+ assert "2 passed" in result.stdout
@@ -1,75 +0,0 @@
1
- """Postgres reuses the schema between tests, emptied of rows (``prepare_schema_once``)."""
2
-
3
- from __future__ import annotations
4
-
5
- import pytest
6
- from simple_module_test import database
7
- from sqlalchemy import Column, Integer, MetaData, String, Table, func, select, text
8
- from sqlalchemy.ext.asyncio import create_async_engine
9
-
10
- pytestmark = pytest.mark.postgres
11
-
12
- _metadata = MetaData()
13
- _item = Table(
14
- "reuse_probe_item",
15
- _metadata,
16
- Column("id", Integer, primary_key=True),
17
- Column("name", String(20)),
18
- )
19
-
20
-
21
- @pytest.fixture
22
- async def engine(monkeypatch):
23
- # The probe drives the per-test state itself; put it back afterwards.
24
- for attr in ("_current_test", "_reset_for", "_built_schema"):
25
- monkeypatch.setattr(database, attr, getattr(database, attr))
26
- url = database.database_url_for_tests()
27
- engine = create_async_engine(url, **database.init_db_kwargs(url))
28
- try:
29
- yield engine
30
- finally:
31
- await database.reset_schema(engine) # the next test rebuilds the real schema
32
- await engine.dispose()
33
-
34
-
35
- async def _next_test(engine, builds: list[int]) -> None:
36
- async def build(engine) -> None:
37
- builds.append(1)
38
- async with engine.begin() as conn:
39
- await conn.run_sync(_metadata.create_all)
40
-
41
- database.begin_test(object())
42
- await database.prepare_schema_once(engine, [_item], build)
43
-
44
-
45
- async def _insert(engine) -> int:
46
- async with engine.begin() as conn:
47
- return (
48
- await conn.execute(_item.insert().values(name="x").returning(_item.c.id))
49
- ).scalar_one()
50
-
51
-
52
- async def test_a_later_test_gets_the_same_schema_without_rows(engine):
53
- builds: list[int] = []
54
- await _next_test(engine, builds)
55
- assert [await _insert(engine), await _insert(engine)] == [1, 2]
56
-
57
- await _next_test(engine, builds)
58
-
59
- assert builds == [1]
60
- async with engine.connect() as conn:
61
- assert await conn.scalar(select(func.count()).select_from(_item)) == 0
62
- assert await _insert(engine) == 1 # sequences restart too
63
-
64
-
65
- async def test_a_test_that_changes_the_schema_forces_a_rebuild(engine):
66
- builds: list[int] = []
67
- await _next_test(engine, builds)
68
- async with engine.begin() as conn:
69
- await conn.execute(text("CREATE TABLE reuse_probe_extra (x int)"))
70
-
71
- await _next_test(engine, builds)
72
-
73
- assert builds == [1, 1]
74
- async with engine.connect() as conn:
75
- assert await conn.scalar(text("SELECT to_regclass('reuse_probe_extra')")) is None