simple-module-test 0.0.43__tar.gz → 0.0.45__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 (35) hide show
  1. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/PKG-INFO +6 -6
  2. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/README.md +1 -1
  3. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/pyproject.toml +5 -5
  4. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/__init__.py +1 -1
  5. simple_module_test-0.0.45/simple_module_test/_compile_cache.py +77 -0
  6. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/_schema.py +8 -6
  7. simple_module_test-0.0.45/simple_module_test/_sqlite_template.py +74 -0
  8. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/database.py +9 -2
  9. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/fixtures.py +5 -5
  10. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/plugin.py +4 -2
  11. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/process_state.py +4 -0
  12. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/tenant_client.py +3 -3
  13. simple_module_test-0.0.45/tests/test_shared_compile_cache.py +115 -0
  14. simple_module_test-0.0.45/tests/test_sqlite_schema_template.py +157 -0
  15. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/.gitignore +0 -0
  16. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/LICENSE +0 -0
  17. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/app_factory.py +0 -0
  18. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/fake_events.py +0 -0
  19. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/inertia.py +0 -0
  20. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/inertia_page.py +0 -0
  21. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/mail.py +0 -0
  22. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/redis_server.py +0 -0
  23. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/routes.py +0 -0
  24. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/session_cookie.py +0 -0
  25. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/setup_wizard.py +0 -0
  26. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/simple_module_test/waiting.py +0 -0
  27. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/tests/test_app_factory.py +0 -0
  28. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/tests/test_fake_events.py +0 -0
  29. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/tests/test_plugin_fixtures.py +0 -0
  30. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/tests/test_schema_reuse_pg.py +0 -0
  31. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/tests/test_testing_inertia_headers.py +0 -0
  32. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/tests/test_testing_inertia_page.py +0 -0
  33. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/tests/test_testing_process_state.py +0 -0
  34. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/tests/test_waiting_helpers.py +0 -0
  35. {simple_module_test-0.0.43 → simple_module_test-0.0.45}/tests/test_worker_database.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simple_module_test
3
- Version: 0.0.43
3
+ Version: 0.0.45
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
@@ -25,10 +25,10 @@ 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.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
28
+ Requires-Dist: simple-module-core==0.0.45
29
+ Requires-Dist: simple-module-db==0.0.45
30
+ Requires-Dist: simple-module-hosting==0.0.45
31
+ Requires-Dist: simple-module-inertia==0.0.45
32
32
  Requires-Dist: sqlalchemy<3,>=2.0
33
33
  Description-Content-Type: text/markdown
34
34
 
@@ -56,7 +56,7 @@ All fixtures below are auto-registered via the `pytest11` entry point — instal
56
56
  - `db_state`, `engine`, `db_session` — fresh `DatabaseState` per test; `db_session` also creates all module tables and stamps `alembic_version` at head so the boot-time migration check passes.
57
57
  - `app` — a `create_app(settings)` instance with `lifespan` started and stopped.
58
58
  - `client` — an `httpx.AsyncClient` bound to the test app.
59
- - `authenticated_client` — same but with an admin user seeded and a forged session cookie attached. **Requires the `users` module** to be installed (it seeds the admin via `users.bootstrap`); apps scaffolded by `smpy` include it.
59
+ - `authenticated_client` — same but with an admin user seeded and a forged session cookie attached. **Requires the `users` module** to be installed (it seeds the admin via `users.core.bootstrap`); apps scaffolded by `smpy` include it.
60
60
  - `tenant_client` — factory: `async with tenant_client("member") as (client, tenant_id, user_id)` signs in a fresh user who is an `owner` / `admin` / `member` (default `owner`) of a new tenant — or of `tenant_id=` when given — with that tenant active. **Requires the `users` and `tenants` modules.**
61
61
 
62
62
  ## Usage
@@ -22,7 +22,7 @@ All fixtures below are auto-registered via the `pytest11` entry point — instal
22
22
  - `db_state`, `engine`, `db_session` — fresh `DatabaseState` per test; `db_session` also creates all module tables and stamps `alembic_version` at head so the boot-time migration check passes.
23
23
  - `app` — a `create_app(settings)` instance with `lifespan` started and stopped.
24
24
  - `client` — an `httpx.AsyncClient` bound to the test app.
25
- - `authenticated_client` — same but with an admin user seeded and a forged session cookie attached. **Requires the `users` module** to be installed (it seeds the admin via `users.bootstrap`); apps scaffolded by `smpy` include it.
25
+ - `authenticated_client` — same but with an admin user seeded and a forged session cookie attached. **Requires the `users` module** to be installed (it seeds the admin via `users.core.bootstrap`); apps scaffolded by `smpy` include it.
26
26
  - `tenant_client` — factory: `async with tenant_client("member") as (client, tenant_id, user_id)` signs in a fresh user who is an `owner` / `admin` / `member` (default `owner`) of a new tenant — or of `tenant_id=` when given — with that tenant active. **Requires the `users` and `tenants` modules.**
27
27
 
28
28
  ## Usage
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "simple_module_test"
3
- version = "0.0.43"
3
+ version = "0.0.45"
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"
@@ -25,10 +25,10 @@ dependencies = [
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.43",
29
- "simple_module_db==0.0.43",
30
- "simple_module_hosting==0.0.43",
31
- "simple_module_inertia==0.0.43",
28
+ "simple_module_core==0.0.45",
29
+ "simple_module_db==0.0.45",
30
+ "simple_module_hosting==0.0.45",
31
+ "simple_module_inertia==0.0.45",
32
32
  "sqlalchemy>=2.0,<3",
33
33
  ]
34
34
 
@@ -22,7 +22,7 @@ The pytest plugin auto-registers these fixtures (no imports needed):
22
22
  real broker (cross-worker cache invalidation) and skips when the binary is absent.
23
23
  See ``simple_module_test.plugin`` (and ``simple_module_test.fixtures``) for
24
24
  their definitions. ``authenticated_client`` additionally requires the ``users``
25
- module to be installed — it seeds an admin via ``users.bootstrap``.
25
+ module to be installed — it seeds an admin via ``users.core.bootstrap``.
26
26
  ``tenant_client`` (``users`` + ``tenants``) is a factory yielding a client signed
27
27
  in as an ``owner``/``admin``/``member`` of a real tenant — see
28
28
  ``simple_module_test.tenant_client``.
@@ -0,0 +1,77 @@
1
+ """Share SQLAlchemy's compiled-statement cache across in-memory SQLite test engines.
2
+
3
+ SQLAlchemy keeps compiled SQL per engine, keyed on the dialect object. Every
4
+ ``app`` and ``db_state`` fixture builds a new engine, so each test compiled
5
+ every statement it ran from scratch: the boot path, the admin seed and the test
6
+ body alike. A production process has one engine and pays this once.
7
+
8
+ Engines made by ``init_db`` for an in-memory SQLite URL with the same dialect
9
+ options are given the first such engine's dialect and compiled cache. The cache
10
+ key is the statement's structure with its values extracted as bound parameters,
11
+ which is what lets one production engine serve every request and tenant; the
12
+ databases behind the engines stay separate.
13
+
14
+ Patched at import, like the cheap password hashing in ``plugin``: test modules
15
+ build engines during collection, before any fixture runs. The patch is
16
+ process-wide, so a consumer suite that needs engines with separate dialects sets
17
+ ``SM_TEST_SEPARATE_COMPILE_CACHES`` to skip it.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ from typing import Any
24
+
25
+ from sqlalchemy.engine import URL
26
+ from sqlalchemy.ext.asyncio import AsyncEngine
27
+ from sqlalchemy.util import LRUCache
28
+
29
+ from simple_module_test._sqlite_template import is_memory_sqlite
30
+
31
+ # Engine options that change only how a connection is opened or logged, not the
32
+ # dialect, so engines differing in them can share one.
33
+ _NON_DIALECT_OPTIONS = frozenset({"echo", "connect_args", "poolclass"})
34
+
35
+ _shared: dict[tuple, tuple[Any, Any]] = {}
36
+
37
+
38
+ def _dialect_key(engine: Any, options: dict[str, Any]) -> tuple | None:
39
+ """The sharing key for a sync *engine*, or ``None`` when it must keep its own."""
40
+ if engine.url.get_backend_name() != "sqlite" or not is_memory_sqlite(engine):
41
+ return None
42
+ rest = tuple(sorted((k, repr(v)) for k, v in options.items() if k not in _NON_DIALECT_OPTIONS))
43
+ return (engine.url.drivername, rest)
44
+
45
+
46
+ def share_sqlite_compile_cache() -> None:
47
+ if os.environ.get("SM_TEST_SEPARATE_COMPILE_CACHES"):
48
+ return
49
+ import simple_module_db.session as session
50
+
51
+ original = session.create_async_engine
52
+
53
+ def create_async_engine(url: str | URL, **kw: Any) -> AsyncEngine:
54
+ engine = original(url, **kw)
55
+ sync = engine.sync_engine
56
+ key = _dialect_key(sync, kw)
57
+ if key is None or sync._compiled_cache is None: # None: query_cache_size=0
58
+ return engine
59
+ shared = _shared.get(key)
60
+ # A dialect is initialized by its own engine's first connection, so only
61
+ # one whose engine has connected can be handed on; until then the newest
62
+ # engine's dialect is the candidate.
63
+ if shared is None or shared[0].server_version_info is None:
64
+ # A cache of its own: the engine's would keep that engine (its size
65
+ # alert is a bound method) and its database alive for the whole run.
66
+ cache = LRUCache(sync._compiled_cache.capacity)
67
+ sync._compiled_cache = cache
68
+ _shared[key] = (sync.dialect, cache)
69
+ else:
70
+ # Swapped before the engine opens a connection, so the pool and every
71
+ # connection only ever see the shared dialect.
72
+ sync.dialect, sync._compiled_cache = shared
73
+ sync.pool._dialect = shared[0]
74
+ return engine
75
+
76
+ # ty types a module function by its own literal type, so any replacement is refused.
77
+ session.create_async_engine = create_async_engine # ty: ignore[invalid-assignment]
@@ -82,13 +82,15 @@ async def _create_all_tables(engine) -> None:
82
82
 
83
83
  await conn.run_sync(_sync_create_all)
84
84
  # Part of the build, so a reused Postgres schema's fingerprint covers it.
85
- if heads:
86
- await conn.execute(
87
- text(
88
- "CREATE TABLE IF NOT EXISTS alembic_version "
89
- "(version_num VARCHAR(32) NOT NULL PRIMARY KEY)"
90
- )
85
+ # Created even with no heads to stamp: the build is copied into later
86
+ # SQLite databases (``_sqlite_template``), and one that resolved no heads
87
+ # must not hand a schema without the table to a test that stamps it.
88
+ await conn.execute(
89
+ text(
90
+ "CREATE TABLE IF NOT EXISTS alembic_version "
91
+ "(version_num VARCHAR(32) NOT NULL PRIMARY KEY)"
91
92
  )
93
+ )
92
94
 
93
95
  tables = [table for base in bases for table in base.metadata.tables.values()]
94
96
  # Postgres reuses the schema built for an earlier test, emptied of rows.
@@ -0,0 +1,74 @@
1
+ """Copy a per-process template into each test's in-memory SQLite database.
2
+
3
+ Every ``app`` and ``db_session`` fixture gets a fresh ``:memory:`` database and
4
+ used to run ``create_all`` on it: DDL for every module's tables and indexes,
5
+ about a third of the fixture's cost. The schema is the same for every test in
6
+ a process, so the first build is copied into a plain ``sqlite3`` connection and
7
+ later databases are filled from it with SQLite's backup API, which copies the
8
+ pages instead of compiling and running the DDL again.
9
+
10
+ Each test still gets its own database: the copy only replaces an *empty* one.
11
+ A database that already has tables (a test calling the schema helper twice)
12
+ gets the ordinary ``create_all``, which leaves its rows alone. The template is
13
+ rebuilt whenever the set of tables changes, such as a test declaring a model.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import sqlite3
19
+ from typing import Any
20
+
21
+ from sqlalchemy import text
22
+
23
+ _template: tuple[frozenset, sqlite3.Connection] | None = None
24
+
25
+
26
+ def is_memory_sqlite(engine: Any) -> bool:
27
+ """Whether a SQLite *engine* is an in-memory database (the caller checked the dialect)."""
28
+ return engine.url.database in (None, "", ":memory:")
29
+
30
+
31
+ def _key(tables: list[Any]) -> frozenset:
32
+ return frozenset(
33
+ (t.fullname, tuple(t.columns.keys()), tuple(sorted(i.name or "" for i in t.indexes)))
34
+ for t in tables
35
+ )
36
+
37
+
38
+ async def _driver_connection(conn: Any) -> Any:
39
+ """The ``aiosqlite.Connection`` under an SQLAlchemy async connection."""
40
+ raw = await conn.get_raw_connection()
41
+ return raw.driver_connection
42
+
43
+
44
+ async def build_from_template(engine: Any, tables: list[Any], build: Any) -> None:
45
+ """Give *engine* the schema ``build`` creates, copying it when possible."""
46
+ global _template
47
+ async with engine.connect() as conn:
48
+ has_tables = await conn.scalar(text("SELECT count(*) FROM sqlite_master"))
49
+ if has_tables:
50
+ await build(engine)
51
+ return
52
+
53
+ key = _key(tables)
54
+ if _template is not None and _template[0] == key:
55
+ source = _template[1]
56
+ async with engine.connect() as conn:
57
+ target = await _driver_connection(conn)
58
+ # No public path: aiosqlite's ``backup`` only copies *out* of its own
59
+ # connection, and a template held as an aiosqlite connection would add a
60
+ # non-daemon worker thread that must be closed at exit. So run the stdlib
61
+ # ``backup`` on the target's worker thread, which owns ``_conn``, via
62
+ # the private ``_execute``/``_conn`` (present across the ``aiosqlite>=0.20,<0.23``
63
+ # range ``simple_module_db`` allows; the tests here fail loudly if they go).
64
+ await target._execute(source.backup, target._conn)
65
+ return
66
+
67
+ await build(engine)
68
+ # Read from aiosqlite worker threads of many connections, never concurrently.
69
+ copy = sqlite3.connect(":memory:", check_same_thread=False)
70
+ async with engine.connect() as conn:
71
+ await (await _driver_connection(conn)).backup(copy)
72
+ if _template is not None:
73
+ _template[1].close()
74
+ _template = (key, copy)
@@ -23,6 +23,8 @@ from sqlalchemy import text
23
23
  from sqlalchemy.engine import make_url
24
24
  from sqlalchemy.pool import NullPool
25
25
 
26
+ from simple_module_test._sqlite_template import build_from_template, is_memory_sqlite
27
+
26
28
  TEST_DATABASE_ENV = "SM_TEST_DATABASE_URL"
27
29
  SQLITE_MEMORY = "sqlite+aiosqlite:///:memory:"
28
30
  XDIST_WORKER_ENV = "PYTEST_XDIST_WORKER"
@@ -146,7 +148,9 @@ _RESTART_SEQUENCES = text(
146
148
  async def prepare_schema_once(engine: Any, tables: list[Any], build: Any) -> None:
147
149
  """Give this test empty ``tables``, at most once per test (see ``begin_test``).
148
150
 
149
- SQLite: ``build(engine)``, since every engine is a fresh in-memory database.
151
+ SQLite: every engine is a fresh database; an in-memory one is filled from a
152
+ per-process copy of the first build (``_sqlite_template``), a file one runs
153
+ ``build(engine)``.
150
154
  Postgres: when this process already built the schema and the catalog still
151
155
  matches it, delete every row and restart the sequences (~0.03 s) instead of
152
156
  dropping and rebuilding it (~0.25 s). Anything else (the first test, a
@@ -154,7 +158,10 @@ async def prepare_schema_once(engine: Any, tables: list[Any], build: Any) -> Non
154
158
  """
155
159
  global _reset_for, _built_schema
156
160
  if engine.dialect.name == "sqlite":
157
- await build(engine)
161
+ if is_memory_sqlite(engine):
162
+ await build_from_template(engine, tables, build)
163
+ else:
164
+ await build(engine)
158
165
  return
159
166
  if _current_test is not None and _reset_for is _current_test:
160
167
  return
@@ -12,7 +12,7 @@ passes.
12
12
  Module-scope imports here reference only framework packages
13
13
  (``simple_module_core`` / ``simple_module_db`` / ``simple_module_hosting``),
14
14
  which are this package's declared dependencies. The one plugin-module coupling
15
- — ``authenticated_client`` seeding an admin via ``users.bootstrap`` — is a lazy
15
+ — ``authenticated_client`` seeding an admin via ``users.core.bootstrap`` — is a lazy
16
16
  import inside the fixture body, so importing this module never requires the
17
17
  ``users`` module to be installed (mirroring ``plugin._bootstrap_eager_celery``,
18
18
  which soft-imports ``background_tasks``).
@@ -146,7 +146,7 @@ async def _seed_setup_admin(application) -> None:
146
146
  there is nothing to satisfy. Use ``setup_pending_app`` to exercise the gate.
147
147
  """
148
148
  try:
149
- from users.bootstrap import create_admin
149
+ from users.core.bootstrap import create_admin
150
150
  except ImportError:
151
151
  return
152
152
 
@@ -207,7 +207,7 @@ def _disable_env_bootstrap(monkeypatch: pytest.MonkeyPatch) -> None:
207
207
  if key.startswith("SM_USERS_BOOTSTRAP_"):
208
208
  monkeypatch.delenv(key, raising=False)
209
209
  try:
210
- from users import bootstrap as bootstrap_module
210
+ from users.core import bootstrap as bootstrap_module
211
211
  except ImportError:
212
212
  return # No local-accounts provider installed; nothing bootstraps.
213
213
  monkeypatch.setattr(bootstrap_module, "_read_dotenv_bootstrap_vars", dict)
@@ -241,11 +241,11 @@ async def authenticated_client(app) -> AsyncGenerator[httpx.AsyncClient, None]:
241
241
  """HTTPX client with a signed session cookie carrying a seeded admin user's id.
242
242
 
243
243
  Requires the ``users`` module to be installed — it seeds the admin via
244
- ``users.bootstrap.create_admin``. The import is deferred to here (not module
244
+ ``users.core.bootstrap.create_admin``. The import is deferred to here (not module
245
245
  scope) so this plugin imports cleanly without ``users``; a consumer app that
246
246
  uses this fixture without ``users`` gets a clear ImportError naming it.
247
247
  """
248
- from users.bootstrap import create_admin
248
+ from users.core.bootstrap import create_admin
249
249
 
250
250
  async with app.state.sm.db.session_factory() as session:
251
251
  # Idempotent: the `app` fixture already seeded this same admin so the
@@ -13,6 +13,7 @@ import os
13
13
 
14
14
  import pytest
15
15
 
16
+ from simple_module_test._compile_cache import share_sqlite_compile_cache
16
17
  from simple_module_test.app_factory import build_test_app as _build_test_app
17
18
  from simple_module_test.fake_events import FakeEventBus
18
19
 
@@ -92,8 +93,8 @@ def _bootstrap_eager_celery() -> None:
92
93
  """
93
94
  os.environ.setdefault("SM_BG_TASKS_BROADCAST_INVALIDATIONS", "false")
94
95
  with contextlib.suppress(ImportError):
95
- from background_tasks.celery_app import build_celery
96
- from background_tasks.settings import BackgroundTasksSettings
96
+ from background_tasks.core.settings import BackgroundTasksSettings
97
+ from background_tasks.worker.celery_app import build_celery
97
98
 
98
99
  build_celery(BackgroundTasksSettings(task_always_eager=True, task_eager_propagates=True))
99
100
 
@@ -142,6 +143,7 @@ def _cheap_password_hashing() -> None:
142
143
 
143
144
 
144
145
  _cheap_password_hashing()
146
+ share_sqlite_compile_cache()
145
147
 
146
148
 
147
149
  @pytest.fixture
@@ -5,6 +5,8 @@ from collections.abc import Iterator
5
5
  import pytest
6
6
  from simple_module_core.leases import reset_lease_backend
7
7
  from simple_module_core.mail import reset_mail_sender
8
+ from simple_module_core.settings_hydrate import env_supplied_fields
9
+ from simple_module_hosting._api_version import default_api_version
8
10
  from simple_module_hosting.sentry import reset_sentry
9
11
 
10
12
 
@@ -13,6 +15,8 @@ def reset_process_state() -> None:
13
15
  reset_mail_sender()
14
16
  reset_lease_backend()
15
17
  reset_sentry()
18
+ env_supplied_fields.cache_clear()
19
+ default_api_version.cache_clear()
16
20
 
17
21
 
18
22
  @pytest.fixture(autouse=True)
@@ -45,7 +45,7 @@ class TenantClient(NamedTuple):
45
45
 
46
46
  async def create_user(app: Any, email: str) -> str:
47
47
  """A real, active, non-superuser ``users`` row with the ``user`` role; its id."""
48
- from users.bootstrap import ensure_user_role
48
+ from users.core.bootstrap import ensure_user_role
49
49
  from users.models import User, UserRole
50
50
 
51
51
  async with app.state.sm.db.session_factory() as session:
@@ -69,7 +69,7 @@ async def create_user(app: Any, email: str) -> str:
69
69
 
70
70
  async def _join(app: Any, user_id: str, email: str, role: TenantRole, tenant_id: str | None) -> str:
71
71
  from tenants.models import Membership, Tenant
72
- from tenants.resolver import forget
72
+ from tenants.resolution.resolver import forget
73
73
 
74
74
  async with app.state.sm.db.session_factory() as session:
75
75
  if tenant_id is None:
@@ -104,7 +104,7 @@ def tenant_client(app: Any) -> Callable[..., AbstractAsyncContextManager[TenantC
104
104
  ``tenant_id`` when given — and yields a :class:`TenantClient` whose session
105
105
  has that tenant active.
106
106
  """
107
- from tenants.constants import SESSION_ACTIVE_TENANT
107
+ from tenants.core.constants import SESSION_ACTIVE_TENANT
108
108
 
109
109
  @asynccontextmanager
110
110
  async def factory(
@@ -0,0 +1,115 @@
1
+ """In-memory SQLite test engines share one dialect and compiled cache (``_compile_cache``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from types import SimpleNamespace
7
+
8
+ import pytest
9
+ from simple_module_db import init_db, session
10
+ from simple_module_test import _compile_cache
11
+ from simple_module_test.database import SQLITE_MEMORY
12
+ from sqlalchemy import Column, Integer, MetaData, String, Table, inspect, select
13
+ from sqlalchemy.engine import make_url
14
+
15
+ _metadata = MetaData()
16
+ _note = Table(
17
+ "compile_cache_probe_note",
18
+ _metadata,
19
+ Column("id", Integer, primary_key=True),
20
+ Column("body", String(20)),
21
+ )
22
+
23
+
24
+ @pytest.fixture(autouse=True)
25
+ def _fresh_share(monkeypatch):
26
+ # Start from no shared dialect, and leave the suite's for the tests after this.
27
+ monkeypatch.setattr(_compile_cache, "_shared", {})
28
+
29
+
30
+ @pytest.fixture
31
+ async def states():
32
+ made = []
33
+
34
+ def make(url: str = SQLITE_MEMORY, **options):
35
+ state = init_db(url, **options)
36
+ made.append(state)
37
+ return state
38
+
39
+ yield make
40
+ for state in made:
41
+ await state.engine.dispose()
42
+
43
+
44
+ async def _with_table(state) -> None:
45
+ async with state.engine.begin() as conn:
46
+ await conn.run_sync(_metadata.create_all)
47
+
48
+
49
+ class TestSharing:
50
+ async def test_memory_engines_share_the_dialect_and_cache(self, states) -> None:
51
+ first = states()
52
+ await _with_table(first) # connecting initializes the dialect it hands on
53
+ second = states().engine.sync_engine
54
+ assert first.engine.sync_engine.dialect is second.dialect
55
+ assert first.engine.sync_engine._compiled_cache is second._compiled_cache
56
+
57
+ async def test_an_engine_that_never_connected_hands_nothing_on(self, states) -> None:
58
+ """Its dialect was never initialized: reflection on the next engine needs
59
+ the SQLite version that initialization records."""
60
+ unused = states().engine.sync_engine
61
+ used = states()
62
+ await _with_table(used)
63
+ async with used.engine.connect() as conn:
64
+ columns = await conn.run_sync(
65
+ lambda sync_conn: inspect(sync_conn).get_columns("compile_cache_probe_note")
66
+ )
67
+ assert [column["name"] for column in columns] == ["id", "body"]
68
+ assert used.engine.sync_engine.dialect is not unused.dialect
69
+
70
+ async def test_a_statement_compiled_once_is_reused_by_the_next_engine(self, states) -> None:
71
+ first = states()
72
+ await _with_table(first)
73
+ second = states()
74
+ await _with_table(second)
75
+ query = select(_note.c.body).where(_note.c.id == 1)
76
+ async with first.engine.connect() as conn:
77
+ await conn.execute(query)
78
+ cached = len(first.engine.sync_engine._compiled_cache)
79
+
80
+ async with second.engine.connect() as conn:
81
+ await conn.execute(query)
82
+
83
+ assert len(second.engine.sync_engine._compiled_cache) == cached
84
+
85
+ async def test_the_databases_stay_separate(self, states) -> None:
86
+ first = states()
87
+ await _with_table(first)
88
+ second = states()
89
+ await _with_table(second)
90
+ async with first.engine.begin() as conn:
91
+ await conn.execute(_note.insert().values(body="only here"))
92
+ async with second.engine.connect() as conn:
93
+ assert (await conn.execute(select(_note.c.body))).all() == []
94
+
95
+
96
+ class TestNotShared:
97
+ async def test_a_file_database_keeps_its_own(self, states, tmp_path) -> None:
98
+ memory = states().engine.sync_engine
99
+ file = states(f"sqlite+aiosqlite:///{tmp_path / 'own.db'}").engine.sync_engine
100
+ assert file.dialect is not memory.dialect
101
+
102
+ async def test_other_dialect_options_keep_their_own(self, states) -> None:
103
+ # ``init_db`` passes no dialect options today; the guard covers a caller
104
+ # of the patched factory that does.
105
+ plain = states().engine.sync_engine
106
+ custom = session.create_async_engine(SQLITE_MEMORY, json_serializer=json.dumps)
107
+ try:
108
+ assert custom.sync_engine.dialect is not plain.dialect
109
+ finally:
110
+ await custom.dispose()
111
+
112
+
113
+ def test_server_databases_are_never_keyed() -> None:
114
+ server = SimpleNamespace(url=make_url("postgresql+asyncpg://u@h/db"))
115
+ assert _compile_cache._dialect_key(server, {}) is None
@@ -0,0 +1,157 @@
1
+ """In-memory SQLite test databases are filled from a per-process template."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+ from simple_module_test import _sqlite_template, database
7
+ from sqlalchemy import (
8
+ Column,
9
+ Index,
10
+ Integer,
11
+ MetaData,
12
+ String,
13
+ Table,
14
+ func,
15
+ inspect,
16
+ select,
17
+ text,
18
+ )
19
+ from sqlalchemy.ext.asyncio import create_async_engine
20
+
21
+ pytestmark = pytest.mark.skipif(
22
+ database.database_is_postgres(), reason="the template covers in-memory SQLite only"
23
+ )
24
+
25
+ _metadata = MetaData()
26
+ _item = Table(
27
+ "template_probe_item",
28
+ _metadata,
29
+ Column("id", Integer, primary_key=True),
30
+ Column("name", String(20)),
31
+ Index("ix_template_probe_item_name", "name"),
32
+ )
33
+
34
+
35
+ @pytest.fixture(autouse=True)
36
+ def _own_template(monkeypatch):
37
+ # Start cold and leave the real template for the tests after this one.
38
+ monkeypatch.setattr(_sqlite_template, "_template", None)
39
+ yield
40
+ if _sqlite_template._template is not None:
41
+ _sqlite_template._template[1].close()
42
+
43
+
44
+ @pytest.fixture
45
+ async def engines():
46
+ made = []
47
+
48
+ def make():
49
+ engine = create_async_engine(database.SQLITE_MEMORY)
50
+ made.append(engine)
51
+ return engine
52
+
53
+ yield make
54
+ for engine in made:
55
+ await engine.dispose()
56
+
57
+
58
+ def _counting_build(builds: list[int], metadata: MetaData = _metadata):
59
+ async def build(engine) -> None:
60
+ builds.append(1)
61
+ async with engine.begin() as conn:
62
+ await conn.run_sync(metadata.create_all)
63
+
64
+ return build
65
+
66
+
67
+ async def _count(engine, table: Table = _item) -> int:
68
+ async with engine.connect() as conn:
69
+ return await conn.scalar(select(func.count()).select_from(table))
70
+
71
+
72
+ class TestTheCopy:
73
+ async def test_only_the_first_database_runs_the_build(self, engines) -> None:
74
+ builds: list[int] = []
75
+ build = _counting_build(builds)
76
+ for _ in range(3):
77
+ engine = engines()
78
+ await _sqlite_template.build_from_template(engine, [_item], build)
79
+ assert await _count(engine) == 0
80
+ assert builds == [1]
81
+
82
+ async def test_the_copy_carries_the_indexes(self, engines) -> None:
83
+ build = _counting_build([])
84
+ await _sqlite_template.build_from_template(engines(), [_item], build)
85
+ copied = engines()
86
+ await _sqlite_template.build_from_template(copied, [_item], build)
87
+ async with copied.connect() as conn:
88
+ indexes = await conn.run_sync(
89
+ lambda sync_conn: inspect(sync_conn).get_indexes("template_probe_item")
90
+ )
91
+ names = [index["name"] for index in indexes]
92
+ assert names == ["ix_template_probe_item_name"]
93
+
94
+ async def test_each_database_is_its_own(self, engines) -> None:
95
+ build = _counting_build([])
96
+ first, second = engines(), engines()
97
+ await _sqlite_template.build_from_template(first, [_item], build)
98
+ async with first.begin() as conn:
99
+ await conn.execute(_item.insert().values(name="only here"))
100
+ await _sqlite_template.build_from_template(second, [_item], build)
101
+ assert await _count(first) == 1
102
+ assert await _count(second) == 0
103
+
104
+
105
+ class TestWhenNotToCopy:
106
+ async def test_a_database_with_tables_keeps_its_rows(self, engines) -> None:
107
+ """A second schema call in one test must not wipe what the first seeded."""
108
+ builds: list[int] = []
109
+ build = _counting_build(builds)
110
+ await _sqlite_template.build_from_template(engines(), [_item], build)
111
+ engine = engines()
112
+ await _sqlite_template.build_from_template(engine, [_item], build)
113
+ async with engine.begin() as conn:
114
+ await conn.execute(_item.insert().values(name="seeded"))
115
+
116
+ await _sqlite_template.build_from_template(engine, [_item], build)
117
+
118
+ assert await _count(engine) == 1
119
+ assert builds == [1, 1]
120
+
121
+ async def test_a_changed_table_set_rebuilds_the_template(self, engines) -> None:
122
+ builds: list[int] = []
123
+ await _sqlite_template.build_from_template(engines(), [_item], _counting_build(builds))
124
+
125
+ wider = MetaData()
126
+ item = _item.to_metadata(wider)
127
+ extra = Table("template_probe_extra", wider, Column("id", Integer, primary_key=True))
128
+ engine = engines()
129
+ await _sqlite_template.build_from_template(
130
+ engine, [item, extra], _counting_build(builds, wider)
131
+ )
132
+
133
+ assert builds == [1, 1]
134
+ assert await _count(engine, extra) == 0
135
+
136
+
137
+ class TestTheStampTable:
138
+ async def test_a_first_build_without_heads_still_lets_later_tests_stamp(
139
+ self, engines, monkeypatch
140
+ ) -> None:
141
+ """A worker whose first build resolved no Alembic heads (a test pointing
142
+ ``SM_PROJECT_ROOT`` elsewhere) must not copy a schema without
143
+ ``alembic_version`` into the tests that do stamp it."""
144
+ from simple_module_test import _schema
145
+
146
+ heads = _schema._alembic_heads()
147
+ assert heads, "the repository has migrations, so heads must resolve here"
148
+ monkeypatch.setattr(_schema, "_alembic_heads", lambda: ())
149
+ await _schema._create_all_tables(engines())
150
+
151
+ monkeypatch.setattr(_schema, "_alembic_heads", lambda: heads)
152
+ stamped = engines()
153
+ await _schema._create_all_tables(stamped)
154
+
155
+ async with stamped.connect() as conn:
156
+ rows = await conn.execute(text("SELECT version_num FROM alembic_version"))
157
+ assert {row[0] for row in rows} == set(heads)