Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
63 commits
Select commit Hold shift + click to select a range
753e381
feat: rebuild the testsuite on directory-owned databases
vistart Nov 14, 2026
dc6b1b7
feat(fixtures)!: L1 definition classes and per-directory L2 backend f…
vistart Nov 14, 2026
8ab0798
fix(fixtures): identity text is a bounded 255-byte VARCHAR
vistart Nov 14, 2026
c9e6240
feat(testsuite): add the pytest_plugin mechanism (P1a)
vistart Nov 15, 2026
118b1bb
fix(testsuite): answer a case's markers only where a dialect question…
vistart Nov 15, 2026
5ef5cfc
fix(testsuite): refuse a declared switch that needs an argument
vistart Nov 15, 2026
40c9dc2
refactor(testsuite): own a database in the DDL directory, and delete …
vistart Nov 15, 2026
1085d22
refactor(testsuite): name the mechanism by what a scope requires
vistart Nov 15, 2026
68e418e
refactor(testsuite): give the composite-key contract its own directory
vistart Nov 15, 2026
588db2e
refactor(testsuite): move the type vocabulary and the name derivation…
vistart Nov 15, 2026
119a6b6
refactor(testsuite): delete the core directory and the environment fi…
vistart Nov 16, 2026
b0b57e6
docs(testsuite): re-plan the basic fixtures as model-as-definition
vistart Nov 16, 2026
b683bc3
feat(testsuite): register what each fixture table asks of a dialect
vistart Nov 16, 2026
e3cae5c
refactor(testsuite): rename the substitution hook in the capability c…
vistart Nov 16, 2026
ad31735
feat(testsuite): take the framework's 24-type list as the contract list
vistart Nov 16, 2026
46904b0
docs(testsuite): re-plan the basic fixtures as model-as-definition
vistart Nov 16, 2026
6a3c67c
feat(testsuite): contract the suggested data-type tables
vistart Nov 16, 2026
b0f50fe
test(testsuite): hold the extras column table to the same rules as th…
vistart Nov 16, 2026
6982f5e
docs(testsuite): refresh basic fixtures README after the three-layer …
vistart Nov 16, 2026
05a82b6
refactor(testsuite): derive users and test_users from their models
vistart Nov 16, 2026
1bfd814
refactor(testsuite): derive the composite-key tables from their models
vistart Nov 16, 2026
f70af1e
refactor(testsuite): replace BASIC_DEFINITIONS with model-backed tables
vistart Nov 16, 2026
672a124
docs(testsuite): record query's borrow as temporary
vistart Nov 17, 2026
c6a9de4
refactor(testsuite): move composite-key model bodies into their group
vistart Nov 17, 2026
c8a1f20
refactor(testsuite): finish the basic fixture reorganisation
vistart Nov 17, 2026
19d032f
fix(testsuite): make basic fixtures portable across backends
vistart Nov 17, 2026
75dcccd
fix(testsuite): make parallel grouping declaration-driven
vistart Nov 17, 2026
3b07922
test(testsuite): cover declaration_for's nearest-ancestor lookup
vistart Nov 17, 2026
0e902c4
docs(testsuite): mark feature/ddl immature
vistart Nov 17, 2026
9a3e90f
test(basic): express generated integer PK without identity attribute
vistart Nov 17, 2026
0ea4ddc
test(basic): add bare/annotated type groups
vistart Nov 17, 2026
198d199
test(basic): declare basic/ddl as a serial parallel unit
vistart Nov 17, 2026
1713813
test(basic): finish the remaining fixture plan
vistart Nov 17, 2026
3197be8
test(basic): remove obsolete TypeCase/TypeTestModel fixtures
vistart Nov 17, 2026
a1dc01a
docs(basic): drop the query borrowing TODO from fixtures plan
vistart Nov 17, 2026
9ee8598
test: declare DB-backed non-basic directories as parallel units
vistart Nov 17, 2026
74fe5e9
fix(basic): import ClassVar on the 3.8 fallback path
vistart Nov 17, 2026
7a17b18
test(basic): gate new groups on backend capabilities
vistart Nov 18, 2026
427b3dc
test: follow suite declaration and auto-id contracts
vistart Nov 18, 2026
0b99340
feat(testsuite): mature basic contracts and opt-in DB declarations
vistart Nov 18, 2026
775fa78
fix(fixtures): auto_pk builds Column directly instead of passing attr…
vistart Nov 18, 2026
3dd8f6e
fix(testsuite): guard Annotated import for Python 3.8 in field-genera…
vistart Nov 18, 2026
9b523cb
refactor(feature): split query into cte/setop/query_integration; move…
vistart Nov 18, 2026
b25ba61
docs: describe mature feature topics; mark benchmark/realworld immature
vistart Nov 19, 2026
e3dd262
docs(feature): advise backends to test EXPLAIN thoroughly in query/ct…
vistart Nov 19, 2026
68d4f4f
test(explain): add 'can execute' EXPLAIN contracts to cte/setop/query…
vistart Nov 19, 2026
bd923cf
fix(test): import pytest in async set-op contract so capability skip …
vistart Nov 19, 2026
30c3c48
fix(cli): complete sync/async parity of DQL and set_cte CLI contracts
vistart Nov 19, 2026
1b33f7a
docs(realworld): reserve directory for real-app links, no test cases
vistart Nov 19, 2026
a4ce0f0
test(cli): contract set union-all/intersect/except with capability gates
vistart Nov 19, 2026
0c52901
test(cli): add portable migrate CLI contracts (sync/async)
vistart Nov 19, 2026
57957ed
fix(cli): make migrate dry-run table-name assertion case-insensitive
vistart Nov 19, 2026
0f542f5
fix(cli): gate migrate apply/rollback on DROP TABLE IF EXISTS support
vistart Nov 19, 2026
5302306
fix(adapters): repair NeutralTypesFixture DDL construction
vistart Nov 19, 2026
6e0b8f4
fix(features): repair long-dormant contract bugs exposed by bridging
vistart Nov 19, 2026
39c3d94
fix(adapters): skip directory when dialect cannot build neutral-types…
vistart Nov 19, 2026
c05f0f9
fix(json): probe JSON_TABLE formatter with a real expression, not None
vistart Nov 19, 2026
fe7c7d2
test(contract): use dialect placeholder in typed_column predicate ass…
vistart Nov 20, 2026
0a2758d
test(contract): make json-chaining assertion dialect-agnostic (tree s…
vistart Nov 20, 2026
17d60f6
test(contract): case-insensitive identifier check in migration dry-run
vistart Nov 20, 2026
4e10ec7
test(contract): case-insensitive identifier checks in statement deriv…
vistart Nov 20, 2026
e563cd7
test(contract): case-insensitive order/index checks in statement deri…
vistart Nov 20, 2026
8d90867
chore: add changelog fragment for PR #33
vistart Nov 20, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
87 changes: 72 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,92 @@ By separating the test definitions from the backend implementations, we can guar

## Testing Philosophy

Our testing strategy is built on three core pillars:
The suite's mature, actively maintained pillar is **feature tests**: a single
copy of each contract, shared by every backend through thin bridge files. The
other two categories exist but are **not mature and not documented here**:

1. **Feature Tests**: Validate individual functionality points (e.g., `where` queries, `save` methods, `BelongsTo` relationships).
2. **Real-world Scenarios**: Simulate actual business scenarios to verify complex interactions and data integrity.
3. **Performance Benchmarks**: Measure and compare backend performance under standardized loads.
- **Real-world scenarios** (`/realworld`) — not mature; not covered in this README.
- **Performance benchmarks** (`/benchmark`) — not mature; not covered in this
README. Backends run benchmarks in their own dedicated CI jobs.

## Structure

The test suite is organized into the following main categories, located in `src/rhosocial/activerecord/testsuite/`:

- `/feature`: Core feature tests.
- `/realworld`: Complex, real-world application scenarios.
- `/benchmark`: Performance and load tests.
Everything importable lives under `src/rhosocial/activerecord/testsuite/`:

- `/feature` — **mature**, the main subject of this suite (see below).
- `/realworld` — immature; out of scope for this document.
- `/benchmark` — immature; out of scope for this document.
- `/pytest_plugin` — the capability/parallelism plugin (see its own README).

### Feature topics

`feature/` is split into topic directories, each a self-contained contract unit
with its own fixtures and a directory-level `Declaration`. A backend imports a
topic by adding thin `conftest.py` + `test_*.py` bridges that star-import the
shared modules — the test bodies exist once.

| Topic | What it validates | Sync/async |
|-------|-------------------|------------|
| `basic/` | The core object model: CRUD, composite-PK CRUD, field types and type adapters, validation, connection/worker lifecycle, transactions, bulk CRUD, field generation, derived fields, DDL statements, materialized views, and keyless/read-only models. Also hosts `basic/events/` (model lifecycle events) and `basic/fixtures/` (the single definition site for shared models). | both |
| `query/` | `ActiveQuery` — construction, joins, aggregates, range/window queries, JSON/special/typed-column queries, query contexts and error handling. | both |
| `cte/` | `CTEQuery` — common table expressions (recursive, composite-PK). | both |
| `setop/` | `SetOperationQuery` — UNION / INTERSECT / EXCEPT. | both |
| `query_integration/` | Cross-type combinations of `ActiveQuery` / `CTEQuery` / `SetOperationQuery` (each paired query type contributes its own combined fixtures). | both |
| `query/relation/` | Model relationships — belongs-to / has-many / has-one, eager loading, descriptors, caching, modifiers, ordering, validation. (Historically `feature/relation`.) | both |
| `cli/` | The model CLI (`rhosocial.activerecord.cli`) — DML/DQL/bulk/read-only/soft-delete/validation/set-CTE commands, in-process. | both |
| `mixins/` | Reusable field mixins — timestamps, soft delete, optimistic lock, UUID, etc. | both |
| `adapters/`, `interface/`, `contracts/`, `backend/`, `ddl/` | Lower-level contracts: type adapters, interface compliance, shared contract helpers, backend capabilities, DDL source derivation. | varies |

> Note: `ddl/` is still maturing and is **not yet wired into any backend**; it is
> kept in the suite but excluded from backend CI.

Each topic may declare `uses_database`, `parallel`, and dialect `requires`
through its `DECLARATION`. Database use is opt-in: topics that only render SQL
or compute values declare nothing and never open a connection. See the
[plugin README](src/rhosocial/activerecord/testsuite/pytest_plugin/README.md)
for the full mechanism.

## Capability-based Testing

The test suite includes an integrated pytest plugin that automatically checks if the current backend supports required capabilities. Tests using the `@requires_capability` decorator will be automatically skipped if the backend doesn't support the required features.
An integrated pytest plugin evaluates what each backend dialect answers. Tests
marked `@requires_protocol(...)` are skipped only when the dialect genuinely
answers "no"; a dialect that does not implement a required probe fails loudly
instead of silently skipping a whole group. The plugin registers itself through
the package's `pytest11` entry point — installing this package is enough.

See [`pytest_plugin/README.md`](src/rhosocial/activerecord/testsuite/pytest_plugin/README.md)
for the full mechanism.

## Backend wiring and parallel units

Two parts of the suite are now considered mature:

- **Backend integration** — a backend supplies one `backend_scenario` fixture and
thin conftest/bridge files that import the shared directories; test bodies live
in exactly one place.
- **Minimum parallel unit** — each test directory declares its own unit
(`Declaration.parallel`, `uses_database`, `requires`). A directory sharing a
database is pinned to one xdist worker, and database use is opt-in: scopes that
only render or compute declare nothing and open no connection.

The plugin is registered automatically and available when the package is installed.
Both are documented in detail in the [plugin README](src/rhosocial/activerecord/testsuite/pytest_plugin/README.md).

## Usage for Backend Developers

If you are developing a database backend for RhoSocial ActiveRecord, you should include this test suite as a development dependency. Your backend's test runner will execute these tests against your implementation, using your provided database schema fixtures.
If you are developing a database backend for RhoSocial ActiveRecord, include this
suite as a development dependency. The plugin installs automatically; you provide
the scenarios and thin bridges, not a copy of the tests.

A typical workflow involves:
1. Adding `rhosocial-activerecord-testsuite` to your `pyproject.toml`.
2. Creating database schema fixtures that match the structure required by the tests.
3. Running the test suite against your backend to identify and fix compatibility issues.
4. Generating a compatibility report to document your backend's compliance level.
2. Defining a parametrized `backend_scenario` fixture that yields your scenarios
(each knows its backend classes, config factory and database reset).
3. Adding thin `conftest.py` files that star-import the corresponding shared
directory, plus bridge modules that import the shared test functions.
4. Running the suite; use `--dist=loadgroup` for parallel runs so tests sharing
one database stay on one worker.
5. Fixing dialect gaps reported loudly by the capability checks, and recording
your backend's compliance level.

For detailed instructions, please refer to the main project's [testing documentation](https://github.com/rhosocial/python-activerecord/blob/main/tests/rhosocial/activerecord_test/README.md).

Expand Down
1 change: 1 addition & 0 deletions changelog.d/33.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Rebuild the suite on directory-owned databases: retire the shared `core` environment fixture and introduce declaration-driven L1 definitions / per-directory L2 backend fixtures, a pytest plugin mechanism and declaration-driven parallel grouping; reorganise `basic` fixtures around model-as-definition tables and the framework's 24-type vocabulary, split `query` into `cte` / `setop` / `query_integration` with `relation` under `query` and `events` under `basic`, and add portable migrate CLI, set-operation and EXPLAIN contracts plus the bridging fixes they uncovered (JSON_TABLE, `NeutralTypesFixture` DDL, Python 3.8 compatibility, sync/async parity).
1 change: 1 addition & 0 deletions changelog.d/33.removed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Remove the `core` directory and the shared environment fixture it provided (breaking change): backends must move to directory-owned databases and the new per-directory L2 fixtures, and update bridge-tree import paths for the `query` split and the `relation` / `events` moves.
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ dependencies = [
# pytest-benchmark and pytest-xdist reach the backends without each one having
# to add a `-p` flag. See rhosocial/activerecord/testsuite/pytest_compat.py.
rhosocial_activerecord_pytest_compat = "rhosocial.activerecord.testsuite.pytest_compat"
# The shared suite's own plugin: directory contracts, environment fixture,
# per-scenario xdist pinning and capability skipping.
rhosocial_activerecord_testsuite = "rhosocial.activerecord.testsuite.plugin"

[project.optional-dependencies]
# Development dependencies
Expand Down
105 changes: 105 additions & 0 deletions scripts/gen_bridges.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# scripts/gen_bridges.py
"""Generate (or verify) the bridge files a backend needs for the shared suite.

A bridge is a file at the same feature-relative path as a testsuite test
module, containing one wildcard import. Keeping the path and stem identical is
what makes "this backend runs that feature" checkable rather than a matter of
trust.

Usage::

python scripts/gen_bridges.py --feature-root ../tests/rhosocial/x_test/feature
python scripts/gen_bridges.py --feature-root ... --check

``--check`` exits non-zero when a bridge is missing, so CI can enforce the
"every testsuite module is included" rule without rewriting files.
"""
import argparse
import sys
from pathlib import Path

SUITE_SRC = (
Path(__file__).resolve().parent.parent / "src" / "rhosocial" / "activerecord" / "testsuite"
)
FEATURE_ROOT = SUITE_SRC / "feature"


def testsuite_modules() -> list:
"""Feature-relative module paths the backend must mirror, ``a/b/test_x.py``."""
modules = []
for path in sorted(FEATURE_ROOT.rglob("test_*.py")):
if "__pycache__" in path.parts:
continue
if any(part.startswith((".", "_")) for part in path.relative_to(FEATURE_ROOT).parts):
continue
modules.append(path.relative_to(FEATURE_ROOT).as_posix())
return modules


def bridge_target(relative_module: str) -> str:
"""The importable target a bridge re-exports, ``suite.feature.a.b.test_x``."""
return "rhosocial.activerecord.testsuite." + relative_module[:-3].replace("/", ".")


def expected_bridges() -> list:
"""Every bridge path a complete backend tree has."""
return testsuite_modules()


def missing_bridges(feature_root: Path) -> list:
"""Expected bridge paths that do not exist under ``feature_root``."""
return [module for module in expected_bridges() if not (feature_root / module).exists()]

HEADER = """# {path}
# Generated bridge: do not add test logic here. Capability differences belong in
# the testsuite as @requires_protocol / @requires_functions markers.

from {target} import * # noqa: F401,F403
"""


def generate(feature_root: Path, force: bool = False) -> list:
created = []
for module in testsuite_modules():
target = feature_root / module
if target.exists() and not force:
continue
dotted = bridge_target(f"feature/{module}")
target.parent.mkdir(parents=True, exist_ok=True)
header_path = str(target).replace("\\", "/")
target.write_text(
HEADER.format(path=header_path, target=dotted),
encoding="utf-8",
)
created.append(module)
return created


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--feature-root", required=True, type=Path)
parser.add_argument("--check", action="store_true")
parser.add_argument("--force", action="store_true")
args = parser.parse_args()

root = args.feature_root.resolve()
if not root.is_dir():
print(f"feature root not found: {root}", file=sys.stderr)
return 2

if args.check:
missing = missing_bridges(root)
print(f"expected {len(expected_bridges())} bridges, missing {len(missing)}")
for path in missing:
print(f" missing: {path}")
return 1 if missing else 0

created = generate(root, force=args.force)
print(f"created {len(created)} bridge(s) under {root}")
for module in created:
print(f" + {module}")
return 0


if __name__ == "__main__":
raise SystemExit(main())
46 changes: 20 additions & 26 deletions src/rhosocial/activerecord/testsuite/benchmark/crud/conftest.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,63 @@
"""Pytest fixtures for CRUD benchmark scenarios."""

import asyncio

import pytest

from rhosocial.activerecord.testsuite.benchmark.crud.interfaces import (
UnsupportedBenchmarkScenario,
)
from rhosocial.activerecord.testsuite.core.registry import get_provider_registry

PROVIDER_KEY = "benchmark.crud.ICrudBenchmarkProvider"

from rhosocial.activerecord.testsuite.benchmark.registry import benchmarks

def _get_provider_class():
provider_registry = get_provider_registry()
return provider_registry.get_provider(PROVIDER_KEY)
FEATURE = "crud"


def _get_scenarios():
provider_class = _get_provider_class()
if not provider_class:
def _scenarios():
implementation = benchmarks.get(FEATURE)
if implementation is None:
return []
return provider_class().get_benchmark_scenarios()
return implementation.scenarios()


SCENARIO_PARAMS = _get_scenarios() or [
pytest.param("default", marks=pytest.mark.skip(reason="No CRUD benchmark provider found"))
SCENARIO_PARAMS = _scenarios() or [
pytest.param(
"default", marks=pytest.mark.skip(reason="No CRUD benchmark implementation registered")
)
]


@pytest.fixture(scope="function", params=SCENARIO_PARAMS)
def crud_sync_context(request, benchmark_size):
provider_class = _get_provider_class()
if not provider_class:
pytest.skip("No CRUD benchmark provider found")
provider = provider_class()
implementation = benchmarks.get(FEATURE)
if implementation is None:
pytest.skip("No CRUD benchmark implementation registered")
scenario = request.param
try:
context = provider.setup_benchmark_sync(scenario, benchmark_size)
context = implementation.sync_setup(scenario, benchmark_size)
except UnsupportedBenchmarkScenario as exc:
pytest.skip(str(exc))
if context is None:
pytest.skip(f"CRUD sync benchmark is not supported for scenario {scenario!r}")
yield context
provider.teardown_benchmark_sync(scenario, context)
implementation.sync_teardown(scenario, context)


@pytest.fixture(scope="function", params=SCENARIO_PARAMS)
def crud_async_context(request, benchmark_size):
provider_class = _get_provider_class()
if not provider_class:
pytest.skip("No CRUD benchmark provider found")
provider = provider_class()
implementation = benchmarks.get(FEATURE)
if implementation is None:
pytest.skip("No CRUD benchmark implementation registered")
scenario = request.param
loop = asyncio.new_event_loop()
try:
try:
context = loop.run_until_complete(
provider.setup_benchmark_async(scenario, benchmark_size)
implementation.async_setup(scenario, benchmark_size)
)
except UnsupportedBenchmarkScenario as exc:
pytest.skip(str(exc))
if context is None:
pytest.skip(f"CRUD async benchmark is not supported for scenario {scenario!r}")
yield context, loop.run_until_complete
loop.run_until_complete(provider.teardown_benchmark_async(scenario, context))
loop.run_until_complete(implementation.async_teardown(scenario, context))
finally:
loop.close()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# src/rhosocial/activerecord/testsuite/benchmark/crud/core/conftest.py
from rhosocial.activerecord.testsuite.benchmark.crud.conftest import * # noqa: F401,F403
Loading