Skip to content

Commit e1723b0

Browse files
test: the sync test mirror no longer drops the test after a skipped class (#150)
* test: the sync test mirror no longer drops the test after a skipped class A skip marker above a class sent _without_skipped into its decorator state, so it skipped the class and then the first test after it as well: regenerating lost test__partition_data__drains_default_into_monthly_partitions_in_batches from the sync suite. test_cli.py is left out of the mirror (the CLI runs the aio service on its own loop), and a section whose tests are all skipped loses its heading. Regenerating now brings in only the one assertion the sync suite had missed. * test: pin what the sync test mirror leaves out and keeps
1 parent 1f95e78 commit e1723b0

7 files changed

Lines changed: 163 additions & 19 deletions

File tree

‎.agents/project.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131

3232
- `CHANGELOG.md`: release-please writes the `## [x.y.z](…)` sections; never edit them. A user-visible change adds a hand-written section `## x.y.z — <one-line headline>` at the top of the entries, in the same pull request, with `x.y.z` the version it will ship in (#87, #89, #94). release-please then puts its own section above it. CONTRIBUTING.md and the pull request template say the same; the file has not used an `[Unreleased]` heading since 1.3.0.
3333
- The version lives in `pg_partsmith/__version__.py`, on the line marked `# x-release-please-version`, and in `.release-please-manifest.json`; release-please bumps both. Never change them by hand. To force a version, add a `Release-As: x.y.z` footer to a commit.
34-
- `pg_partsmith/sync/` is generated from `pg_partsmith/aio/` by `scripts/sync_mirror.py`. The exceptions are maintained by hand: the lock managers, `maintainer.py`, `command_hooks.py`, `python_hooks.py` and `repositories/{resolver,fk_manager,timeouts,pin}.py`. `tests/integration/sync/` is generated from `tests/integration/aio/` by `scripts/sync_tests_mirror.py`, except `test_concurrency.py`. Edit the aio side, regenerate, run `ruff check --fix` and `ruff format` on the output, then review the diff (CONTRIBUTING.md, "Keeping aio and sync in sync"). CI does not check the mirror.
34+
- `pg_partsmith/sync/` is generated from `pg_partsmith/aio/` by `scripts/sync_mirror.py`. The exceptions are maintained by hand: the lock managers, `maintainer.py`, `command_hooks.py`, `python_hooks.py` and `repositories/{resolver,fk_manager,timeouts,pin}.py`. `tests/integration/sync/` is generated from `tests/integration/aio/` by `scripts/sync_tests_mirror.py`, except `test_concurrency.py`, and `test_cli.py` has no sync twin (the CLI runs the aio service itself). Edit the aio side, regenerate, run `ruff check --fix` and `ruff format` on the output, then review the diff (CONTRIBUTING.md, "Keeping aio and sync in sync"). CI does not check the mirror.
3535
- `docs/agents.md` is part of the public API: it changes in the same pull request as the API (CONTRIBUTING.md, "The agents page").
3636
- `docs/changelog.md` is a copy of `CHANGELOG.md` made by the docs build, and git ignores it.
3737
- Files from the engineering-assets hub (`AGENTS.md` explains how it works): the copy-page files (`docs/assets/javascripts/copy-page.js`, `docs/assets/stylesheets/copy-page.css`, `overrides/main.html`, `scripts/emit_markdown.py`), `.github/workflows/docs.yml`, `.github/workflows/release-please.yml`, `.editorconfig` and `CODE_OF_CONDUCT.md`. Change them in the hub; a change here makes the file this repository's own. `.github/dependabot.yml` already belongs to this repository: it adds the `docker` ecosystem for the Dockerfile's base images.

‎CONTRIBUTING.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ uv run ruff check --fix tests/integration/sync && uv run ruff format tests/integ
170170
A test that drives two coroutines at once cannot be mirrored mechanically: put a
171171
`# sync-mirror: skip` line right above it and write its thread-based twin in
172172
`tests/integration/sync/test_concurrency.py`, the one hand-written module of that suite.
173+
`tests/integration/aio/test_cli.py` has no sync twin: the CLI runs the aio service itself.
173174
`tests/unit/sync/` mirrors `tests/unit/` by hand — only the modules touching the aio package
174175
have a sync twin.
175176

‎scripts/sync_tests_mirror.py‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313
concurrently, say) is marked in the aio suite with a ``# sync-mirror: skip``
1414
line right above it (above its decorators, if any) and is left out of the sync
1515
suite; its thread-based twin lives in ``tests/integration/sync/test_concurrency.py``,
16-
the one module of the sync suite that is written by hand. A module the aio
17-
suite no longer has is removed from the sync suite, that one excepted.
16+
the one module of the sync suite that is written by hand. ``test_cli.py`` has
17+
no sync twin: the CLI runs the aio service on an event loop of its own, so a
18+
mirror would run the same code again. A module the aio suite no longer has is
19+
removed from the sync suite, the hand-written one excepted.
1820
"""
1921

2022
from __future__ import annotations
@@ -28,9 +30,11 @@
2830
SYNC = ROOT / "tests" / "integration" / "sync"
2931

3032
HANDWRITTEN = frozenset({"test_concurrency.py"})
33+
AIO_ONLY = frozenset({"test_cli.py"})
3134
SKIP_MARKER = "# sync-mirror: skip"
32-
TOP_LEVEL = re.compile(r"^(async def |def |class |@|# ──)")
33-
DEFINITION = re.compile(r"^(async )?def ")
35+
SECTION = "# ──"
36+
TOP_LEVEL = re.compile(rf"^(async def |def |class |@|{SECTION})")
37+
DEFINITION = re.compile(r"^((async )?def |class )")
3438
FOR_LOOP = re.compile(r"^(?P<indent>\s*)for (?P<var>\w+) in (?P<rest>.*)$")
3539

3640
RULES: list[tuple[str, str]] = [
@@ -89,19 +93,18 @@
8993

9094
def transform(text: str) -> str:
9195
"""Turn one aio test module into its sync twin."""
92-
text = "\n".join(_without_skipped(text.split("\n")))
96+
text = "\n".join(_without_empty_sections(_without_skipped(text.split("\n"))))
9397
for pattern, repl in RULES:
9498
text = re.sub(pattern, repl, text)
9599
text = text.replace("import asyncio\n", "")
96100
return "\n".join(_yield_from(text.split("\n")))
97101

98102

99103
def _without_skipped(lines: list[str]) -> list[str]:
100-
"""Leave out every function under a ``# sync-mirror: skip`` line.
104+
"""Leave out every function or class under a ``# sync-mirror: skip`` line.
101105
102-
The marker sits right above the function -- above its decorators when it
103-
has any -- and the function ends at the next top-level definition,
104-
decorator or section heading.
106+
The marker sits right above it -- above its decorators when it has any --
107+
and it ends at the next top-level definition, decorator or section heading.
105108
"""
106109
kept: list[str] = []
107110
state = "keep"
@@ -126,6 +129,25 @@ def _without_skipped(lines: list[str]) -> list[str]:
126129
return kept
127130

128131

132+
def _without_empty_sections(lines: list[str]) -> list[str]:
133+
"""Drop a section heading, and the comments under it, when no code is left in its section."""
134+
kept: list[str] = []
135+
i = 0
136+
while i < len(lines):
137+
if lines[i].startswith(SECTION):
138+
end = i + 1
139+
while end < len(lines) and (
140+
not lines[end].strip() or (lines[end].startswith("#") and not lines[end].startswith(SECTION))
141+
):
142+
end += 1
143+
if end == len(lines) or lines[end].startswith(SECTION):
144+
i = end
145+
continue
146+
kept.append(lines[i])
147+
i += 1
148+
return kept
149+
150+
129151
def _yield_from(lines: list[str]) -> list[str]:
130152
"""Spell ``for x in gen(...): yield x`` -- what an ``async for`` becomes -- as ``yield from``."""
131153
out: list[str] = []
@@ -160,6 +182,8 @@ def main() -> None:
160182
SYNC.mkdir(parents=True, exist_ok=True)
161183
generated: set[str] = set()
162184
for source in sorted(AIO.glob("*.py")):
185+
if source.name in AIO_ONLY:
186+
continue
163187
target = SYNC / source.name
164188
target.write_text(transform(source.read_text(encoding="utf-8")), encoding="utf-8")
165189
generated.add(target.name)

‎tests/integration/sync/test_lifecycle_policies.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,7 @@ def test__detach_mode_auto__with_a_default_partition__is_planned_as_the_blocking
419419
detach = result.maintenance_plan.detaches[0]
420420
assert detach.mode is DetachMode.BLOCKING
421421
assert "DEFAULT partition" in detach.detail
422+
assert "ACCESS EXCLUSIVE on the parent" in detach.capabilities.lock
422423

423424

424425
def test__detach_mode_auto__without_a_default_partition__stays_concurrent(sync_db_engine: Engine, table: str) -> None:

‎tests/integration/sync/test_maintainer.py‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -279,12 +279,6 @@ def test__maintainer__run_maintenance_safe__never_raises_and_reports_the_error(
279279
assert result.created_count == 0
280280

281281

282-
# ── Two maintainers on the same table ────────────────────────────────────────────
283-
284-
285-
# ── An interrupted DETACH CONCURRENTLY ──────────────────────────────────────────
286-
287-
288282
# ── A hook must not be able to redirect a detach ────────────────────────────────
289283

290284

‎tests/integration/sync/test_safe_drop.py‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,3 @@ def test__drop_partition__expected_oid_of_another_relation__refused_and_the_tabl
227227
# The right identity still drops it
228228
repo.drop_partition(name, expected_oid=real_oid)
229229
assert not metadata.partition_exists(name)
230-
231-
232-
# ── retry on lock contention ──────────────────────────────────────────────────────
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
"""The generator of the sync integration suite: what it leaves out and what it must keep.
2+
3+
CI does not compare the sync suite with the aio one, so a test the generator
4+
drops by mistake just stops running, with nothing to say so.
5+
"""
6+
7+
from __future__ import annotations
8+
9+
from typing import TYPE_CHECKING
10+
11+
import pytest
12+
13+
from scripts import sync_tests_mirror
14+
from scripts.sync_tests_mirror import transform
15+
16+
if TYPE_CHECKING:
17+
from pathlib import Path
18+
19+
pytestmark = pytest.mark.unit
20+
21+
22+
def test__transform__a_skipped_class__keeps_the_heading_and_the_test_after_it() -> None:
23+
# Arrange
24+
source = """\
25+
# sync-mirror: skip
26+
class _Writer:
27+
async def write(self) -> None:
28+
await self.conn.execute(self.sql)
29+
30+
31+
# ── partition_data ──────────────────────────────────────────────────────────────
32+
33+
34+
async def test__drains(db_engine: AsyncEngine) -> None:
35+
assert await count(db_engine) == 0
36+
"""
37+
38+
expected = """\
39+
# ── partition_data ──────────────────────────────────────────────────────────────
40+
41+
42+
def test__drains(sync_db_engine: Engine) -> None:
43+
assert count(sync_db_engine) == 0
44+
"""
45+
46+
# Act
47+
mirrored = transform(source)
48+
49+
# Assert
50+
assert mirrored == expected
51+
52+
53+
def test__transform__a_skipped_decorated_test__keeps_the_test_after_it() -> None:
54+
# Arrange
55+
source = """\
56+
# sync-mirror: skip
57+
@pytest.mark.parametrize("n", [1, 2])
58+
async def test__races(db_engine: AsyncEngine, n: int) -> None:
59+
await asyncio.gather(work(db_engine), work(db_engine))
60+
61+
62+
async def test__plain(db_engine: AsyncEngine) -> None:
63+
assert await count(db_engine) == 0
64+
"""
65+
66+
expected = """\
67+
def test__plain(sync_db_engine: Engine) -> None:
68+
assert count(sync_db_engine) == 0
69+
"""
70+
71+
# Act
72+
mirrored = transform(source)
73+
74+
# Assert
75+
assert mirrored == expected
76+
77+
78+
def test__transform__a_section_whose_tests_are_all_skipped__loses_its_heading_and_comment() -> None:
79+
# Arrange
80+
source = """\
81+
# ── under a live writer ─────────────────────────────────────────────────────────
82+
#
83+
# Why these tests need two coroutines at once.
84+
85+
86+
# sync-mirror: skip
87+
async def test__races(db_engine: AsyncEngine) -> None:
88+
await asyncio.gather(work(db_engine), work(db_engine))
89+
90+
91+
# ── retry ───────────────────────────────────────────────────────────────────────
92+
93+
94+
async def test__retries(db_engine: AsyncEngine) -> None:
95+
assert await count(db_engine) == 0
96+
"""
97+
98+
expected = """\
99+
# ── retry ───────────────────────────────────────────────────────────────────────
100+
101+
102+
def test__retries(sync_db_engine: Engine) -> None:
103+
assert count(sync_db_engine) == 0
104+
"""
105+
106+
# Act
107+
mirrored = transform(source)
108+
109+
# Assert
110+
assert mirrored == expected
111+
112+
113+
def test__main__the_cli_module__gets_no_sync_twin(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
114+
# Arrange
115+
aio, sync = tmp_path / "aio", tmp_path / "sync"
116+
aio.mkdir()
117+
(aio / "test_cli.py").write_text("async def test__cli() -> None:\n pass\n", encoding="utf-8")
118+
(aio / "test_plan.py").write_text("async def test__plan() -> None:\n pass\n", encoding="utf-8")
119+
monkeypatch.setattr(sync_tests_mirror, "ROOT", tmp_path)
120+
monkeypatch.setattr(sync_tests_mirror, "AIO", aio)
121+
monkeypatch.setattr(sync_tests_mirror, "SYNC", sync)
122+
123+
# Act
124+
sync_tests_mirror.main()
125+
126+
# Assert
127+
assert sorted(path.name for path in sync.iterdir()) == ["test_plan.py"]

0 commit comments

Comments
 (0)