simple-module-test 0.0.44__tar.gz → 0.0.46__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.
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/PKG-INFO +8 -5
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/README.md +1 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/pyproject.toml +8 -5
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/__init__.py +5 -1
- simple_module_test-0.0.46/simple_module_test/_compile_cache.py +77 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/_schema.py +8 -6
- simple_module_test-0.0.46/simple_module_test/_sqlite_template.py +74 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/database.py +9 -2
- simple_module_test-0.0.46/simple_module_test/oidc_issuer.py +84 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/plugin.py +3 -0
- simple_module_test-0.0.46/tests/test_shared_compile_cache.py +115 -0
- simple_module_test-0.0.46/tests/test_sqlite_schema_template.py +157 -0
- simple_module_test-0.0.46/tests/test_testing_oidc_issuer.py +28 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/.gitignore +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/LICENSE +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/app_factory.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/fake_events.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/fixtures.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/inertia.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/inertia_page.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/mail.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/process_state.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/redis_server.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/routes.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/session_cookie.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/setup_wizard.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/tenant_client.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/waiting.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/tests/test_app_factory.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/tests/test_fake_events.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/tests/test_plugin_fixtures.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/tests/test_schema_reuse_pg.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/tests/test_testing_inertia_headers.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/tests/test_testing_inertia_page.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/tests/test_testing_process_state.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/tests/test_waiting_helpers.py +0 -0
- {simple_module_test-0.0.44 → simple_module_test-0.0.46}/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.
|
|
3
|
+
Version: 0.0.46
|
|
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,14 +21,16 @@ 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: cryptography>=42
|
|
24
25
|
Requires-Dist: fastapi<0.163,>=0.140
|
|
25
26
|
Requires-Dist: httpx<0.29,>=0.27
|
|
27
|
+
Requires-Dist: pyjwt[crypto]<3,>=2.8
|
|
26
28
|
Requires-Dist: pytest-asyncio<2,>=0.24
|
|
27
29
|
Requires-Dist: pytest<10,>=8.0
|
|
28
|
-
Requires-Dist: simple-module-core==0.0.
|
|
29
|
-
Requires-Dist: simple-module-db==0.0.
|
|
30
|
-
Requires-Dist: simple-module-hosting==0.0.
|
|
31
|
-
Requires-Dist: simple-module-inertia==0.0.
|
|
30
|
+
Requires-Dist: simple-module-core==0.0.46
|
|
31
|
+
Requires-Dist: simple-module-db==0.0.46
|
|
32
|
+
Requires-Dist: simple-module-hosting==0.0.46
|
|
33
|
+
Requires-Dist: simple-module-inertia==0.0.46
|
|
32
34
|
Requires-Dist: sqlalchemy<3,>=2.0
|
|
33
35
|
Description-Content-Type: text/markdown
|
|
34
36
|
|
|
@@ -58,6 +60,7 @@ All fixtures below are auto-registered via the `pytest11` entry point — instal
|
|
|
58
60
|
- `client` — an `httpx.AsyncClient` bound to the test app.
|
|
59
61
|
- `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
62
|
- `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.**
|
|
63
|
+
- `oidc_test_issuer` — an in-process OpenID Connect issuer (`OidcTestIssuer`): an RSA signing key with `jwks()`, `discovery()` and `sign(claims)`, for testing an OIDC sign-in through `httpx_mock` without an IdP.
|
|
61
64
|
|
|
62
65
|
## Usage
|
|
63
66
|
|
|
@@ -24,6 +24,7 @@ All fixtures below are auto-registered via the `pytest11` entry point — instal
|
|
|
24
24
|
- `client` — an `httpx.AsyncClient` bound to the test app.
|
|
25
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
|
+
- `oidc_test_issuer` — an in-process OpenID Connect issuer (`OidcTestIssuer`): an RSA signing key with `jwks()`, `discovery()` and `sign(claims)`, for testing an OIDC sign-in through `httpx_mock` without an IdP.
|
|
27
28
|
|
|
28
29
|
## Usage
|
|
29
30
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "simple_module_test"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.46"
|
|
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"
|
|
@@ -23,12 +23,15 @@ classifiers = [
|
|
|
23
23
|
dependencies = [
|
|
24
24
|
"fastapi>=0.140,<0.163",
|
|
25
25
|
"httpx>=0.27,<0.29",
|
|
26
|
+
# OidcTestIssuer: sign ID tokens and publish a JWKS (#879).
|
|
27
|
+
"cryptography>=42",
|
|
28
|
+
"PyJWT[crypto]>=2.8,<3",
|
|
26
29
|
"pytest>=8.0,<10",
|
|
27
30
|
"pytest-asyncio>=0.24,<2",
|
|
28
|
-
"simple_module_core==0.0.
|
|
29
|
-
"simple_module_db==0.0.
|
|
30
|
-
"simple_module_hosting==0.0.
|
|
31
|
-
"simple_module_inertia==0.0.
|
|
31
|
+
"simple_module_core==0.0.46",
|
|
32
|
+
"simple_module_db==0.0.46",
|
|
33
|
+
"simple_module_hosting==0.0.46",
|
|
34
|
+
"simple_module_inertia==0.0.46",
|
|
32
35
|
"sqlalchemy>=2.0,<3",
|
|
33
36
|
]
|
|
34
37
|
|
|
@@ -25,13 +25,16 @@ their definitions. ``authenticated_client`` additionally requires the ``users``
|
|
|
25
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
|
-
``simple_module_test.tenant_client``.
|
|
28
|
+
``simple_module_test.tenant_client``. ``oidc_test_issuer`` is an in-process
|
|
29
|
+
OpenID Connect issuer (:class:`OidcTestIssuer`: signing key, JWKS, discovery
|
|
30
|
+
document and ``sign(claims)``) for testing an OIDC sign-in without an IdP.
|
|
29
31
|
"""
|
|
30
32
|
|
|
31
33
|
from simple_module_test.app_factory import build_test_app
|
|
32
34
|
from simple_module_test.fake_events import FakeEventBus, RecordedEvent
|
|
33
35
|
from simple_module_test.inertia import inertia_headers
|
|
34
36
|
from simple_module_test.inertia_page import InertiaPage, inertia_page
|
|
37
|
+
from simple_module_test.oidc_issuer import OidcTestIssuer
|
|
35
38
|
from simple_module_test.routes import effective_route_paths
|
|
36
39
|
from simple_module_test.session_cookie import forge_session_cookie
|
|
37
40
|
from simple_module_test.tenant_client import TenantClient
|
|
@@ -40,6 +43,7 @@ from simple_module_test.waiting import wait_for, wait_for_sync
|
|
|
40
43
|
__all__ = [
|
|
41
44
|
"FakeEventBus",
|
|
42
45
|
"InertiaPage",
|
|
46
|
+
"OidcTestIssuer",
|
|
43
47
|
"RecordedEvent",
|
|
44
48
|
"TenantClient",
|
|
45
49
|
"build_test_app",
|
|
@@ -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
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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:
|
|
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
|
-
|
|
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
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""An in-process OpenID Connect issuer for tests: a signing key, JWKS and discovery.
|
|
2
|
+
|
|
3
|
+
Lets a module test an OIDC sign-in end to end without a real IdP (#879)::
|
|
4
|
+
|
|
5
|
+
issuer = OidcTestIssuer("https://idp.test/tenant/v2.0")
|
|
6
|
+
httpx_mock.add_response(url=issuer.discovery_url, json=issuer.discovery())
|
|
7
|
+
httpx_mock.add_response(url=issuer.jwks_url, json=issuer.jwks())
|
|
8
|
+
id_token = issuer.sign({"aud": "client", "sub": "user-1", "nonce": nonce})
|
|
9
|
+
|
|
10
|
+
``sign`` fills ``iss``, ``iat`` and ``exp``; pass ``None`` for a claim to drop it.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import functools
|
|
16
|
+
import json
|
|
17
|
+
import time
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
import jwt
|
|
21
|
+
import pytest
|
|
22
|
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
23
|
+
from jwt.algorithms import RSAAlgorithm
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@functools.cache
|
|
27
|
+
def _signing_key() -> rsa.RSAPrivateKey:
|
|
28
|
+
"""One RSA key per process: generating 2048-bit keys per test is slow."""
|
|
29
|
+
return rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class OidcTestIssuer:
|
|
33
|
+
"""A fake IdP whose endpoints live under ``issuer`` and whose tokens verify."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, issuer: str = "https://idp.test/realms/test", kid: str = "test-key") -> None:
|
|
36
|
+
self.issuer = issuer.rstrip("/")
|
|
37
|
+
self.kid = kid
|
|
38
|
+
self._key = _signing_key()
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def discovery_url(self) -> str:
|
|
42
|
+
return f"{self.issuer}/.well-known/openid-configuration"
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def jwks_url(self) -> str:
|
|
46
|
+
return f"{self.issuer}/keys"
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def authorization_endpoint(self) -> str:
|
|
50
|
+
return f"{self.issuer}/authorize"
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def token_endpoint(self) -> str:
|
|
54
|
+
return f"{self.issuer}/token"
|
|
55
|
+
|
|
56
|
+
def discovery(self) -> dict[str, Any]:
|
|
57
|
+
"""The discovery document for this issuer."""
|
|
58
|
+
return {
|
|
59
|
+
"issuer": self.issuer,
|
|
60
|
+
"authorization_endpoint": self.authorization_endpoint,
|
|
61
|
+
"token_endpoint": self.token_endpoint,
|
|
62
|
+
"jwks_uri": self.jwks_url,
|
|
63
|
+
"response_types_supported": ["code"],
|
|
64
|
+
"code_challenge_methods_supported": ["S256"],
|
|
65
|
+
"id_token_signing_alg_values_supported": ["RS256"],
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
def jwks(self) -> dict[str, Any]:
|
|
69
|
+
"""The public signing key as a JWKS document."""
|
|
70
|
+
jwk = json.loads(RSAAlgorithm.to_jwk(self._key.public_key()))
|
|
71
|
+
return {"keys": [{**jwk, "kid": self.kid, "use": "sig", "alg": "RS256"}]}
|
|
72
|
+
|
|
73
|
+
def sign(self, claims: dict[str, Any], *, lifetime: int = 300) -> str:
|
|
74
|
+
"""An RS256 ID token from this issuer; ``None`` values drop a claim."""
|
|
75
|
+
now = int(time.time())
|
|
76
|
+
payload = {"iss": self.issuer, "iat": now, "exp": now + lifetime, **claims}
|
|
77
|
+
payload = {k: v for k, v in payload.items() if v is not None}
|
|
78
|
+
return jwt.encode(payload, self._key, algorithm="RS256", headers={"kid": self.kid})
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@pytest.fixture
|
|
82
|
+
def oidc_test_issuer() -> OidcTestIssuer:
|
|
83
|
+
"""A fresh :class:`OidcTestIssuer` per test."""
|
|
84
|
+
return OidcTestIssuer()
|
|
@@ -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
|
|
|
@@ -34,6 +35,7 @@ from simple_module_test.fixtures import ( # noqa: F401
|
|
|
34
35
|
setup_pending_app,
|
|
35
36
|
)
|
|
36
37
|
from simple_module_test.mail import captured_mail # noqa: F401
|
|
38
|
+
from simple_module_test.oidc_issuer import oidc_test_issuer # noqa: F401
|
|
37
39
|
from simple_module_test.process_state import _reset_process_state # noqa: F401
|
|
38
40
|
from simple_module_test.redis_server import redis_server # noqa: F401
|
|
39
41
|
from simple_module_test.tenant_client import tenant_client # noqa: F401
|
|
@@ -142,6 +144,7 @@ def _cheap_password_hashing() -> None:
|
|
|
142
144
|
|
|
143
145
|
|
|
144
146
|
_cheap_password_hashing()
|
|
147
|
+
share_sqlite_compile_cache()
|
|
145
148
|
|
|
146
149
|
|
|
147
150
|
@pytest.fixture
|
|
@@ -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)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""``OidcTestIssuer`` issues tokens its own JWKS verifies (#879)."""
|
|
2
|
+
|
|
3
|
+
import jwt
|
|
4
|
+
from jwt.algorithms import RSAAlgorithm
|
|
5
|
+
from simple_module_test import OidcTestIssuer
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_signed_tokens_verify_against_the_published_jwks(oidc_test_issuer):
|
|
9
|
+
token = oidc_test_issuer.sign({"aud": "client", "sub": "user-1", "nonce": "n"})
|
|
10
|
+
key = RSAAlgorithm.from_jwk(oidc_test_issuer.jwks()["keys"][0])
|
|
11
|
+
claims = jwt.decode(
|
|
12
|
+
token, key, algorithms=["RS256"], audience="client", issuer=oidc_test_issuer.issuer
|
|
13
|
+
)
|
|
14
|
+
assert (claims["sub"], claims["nonce"]) == ("user-1", "n")
|
|
15
|
+
assert jwt.get_unverified_header(token)["kid"] == oidc_test_issuer.kid
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_discovery_points_at_the_issuer_endpoints():
|
|
19
|
+
issuer = OidcTestIssuer("https://idp.test/tenant/v2.0/")
|
|
20
|
+
doc = issuer.discovery()
|
|
21
|
+
assert doc["issuer"] == "https://idp.test/tenant/v2.0"
|
|
22
|
+
assert doc["jwks_uri"] == issuer.jwks_url
|
|
23
|
+
assert issuer.discovery_url.endswith("/.well-known/openid-configuration")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_none_drops_a_claim(oidc_test_issuer):
|
|
27
|
+
token = oidc_test_issuer.sign({"sub": "x", "exp": None})
|
|
28
|
+
assert "exp" not in jwt.decode(token, options={"verify_signature": False})
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{simple_module_test-0.0.44 → simple_module_test-0.0.46}/simple_module_test/session_cookie.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{simple_module_test-0.0.44 → simple_module_test-0.0.46}/tests/test_testing_inertia_headers.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|