Files
romm/backend/tests/tools/test_generate_test_data.py
Stu Anderson 3ae27a67a1 chore(seed): realistic, fast, debuggable seeded images (#5253)
* feat(seed): realistic, fast, debuggable seeded images

generate_test_data.py can now seed a library whose images look like a real
one, quickly, so gallery, sizing and image-conversion work can be tested
without anyone's private cover art. The default (--image-fidelity 1) is
unchanged: same seed, byte-identical files.

- --image-fidelity 2: covers drawn at the real-world size mix (measured
  aggregates from one 8,396-cover library), the small cover made by RomM's
  own resize rule, and debug art on every image: the game's title, system
  and region; a box with rom id, size, kind and format; the original path;
  pure-colour corner pixels, named corners, percent ticks, crop boxes, a
  circle that shows stretching and a transparency ring.
- --image-fidelity 3: the same over texture calibrated to real bytes per
  pixel, with 22% of big.png holding JPEG bytes as in real libraries.
- --image-weighted-every N (default 10): at level 2, every Nth rom id is
  drawn at level 3, so one library serves layout and file-size work.
- --image-media: also write ScreenScraper media (sizes provisional).
- --image-workers / --image-limit: images are drawn in a process pool
  from a per-rom random stream (seed, rom id), identical to one process.
  2,000 roms with images seed in about 18 s instead of about 10 minutes.
- After a real run the seeder rotates the gallery's Redis cache, so a
  fresh seed never serves the previous library's lists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(seed): keep rows independent of image flags; survive a cache failure

- The screenshot count is drawn for every rom, whatever --images or
  --image-limit say, so those flags no longer shift the rows that follow
  (--no-images rows were already off in the previous seeder). With the
  defaults the draws are unchanged: level 1 output is still byte-identical.
- A Redis error while rotating the gallery cache prints a warning instead
  of aborting after the rows are committed, so the report still prints.
- Comments in seed_images.py trimmed to the repository's one-or-two-line rule.
- tests/tools/test_generate_test_data.py runs the seeder with inserts
  recorded instead of written: rows match with --image-limit and
  --no-images, and a cache failure still reports the saved seed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(seed): document seeding a test library in DEVELOPER_SETUP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(seed): code-review fixes for seeded images

pr-ready step 2 (code-review xhigh --fix):
- level-3 noise is drawn per channel and retuned, so PNG output reaches
  the measured 0.9 / 1.5 / 2.0 bytes per pixel spread
- --image-media is rejected at --image-fidelity 1, where it did nothing
- paths come from rom_fs_resources_path, get_media_resources_path,
  CoverSize and MetadataMediaType instead of being rebuilt
- drop the unused path_column parameter and a no-op ImageChops call
- draw a batch's images while the next batch is built and inserted
- the cache-failure test checks the rows of the failing run
- drop a duplicate media-off test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(seed): simplify pass over seeded images

pr-ready step 3 (simplify):
- extract small_cover_size from resize_cover_to_small, so the seeder
  draws the small cover at RomM's size instead of writing, reopening
  and overwriting it
- draw_rom_images returns nothing and follows plan_rom_images, and
  files_written is derived from the plan
- _fitted_size measures from a proportional guess instead of stepping
  down one point at a time (about a quarter of level-2 draw time)
- one draw path for the pool and inline cases
- drop the ink parameter, the CORNER_RING alias, the _fade_ring wrapper
  and the RomImageJob caption default; tighten comments
- trim media from the two slowest tests and use dataclasses.replace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(seed): humanizer pass over the seeding docs

pr-ready step 5 (humanizer).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(seed): one image pipeline, dry runs write nothing, main owns its cleanup

- level 1 mosaics go through plan_rom_images/draw_rom_images like the
  other levels, so they get media, workers and RomM's small-cover size
- --dry-run plans image paths but writes no files
- main() is a thin wrapper: it registers the UTC connect listener and
  removes it (disposing the pool) in a finally, and the image pool
  cancels queued draws on error; the test no longer patches SQLAlchemy
- the recommendation feed cache is rotated with the gallery cache

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-10-31 10:27:02 -04:00

133 lines
4.2 KiB
Python

import sys
from collections.abc import Callable
from datetime import datetime, tzinfo
from pathlib import Path
from typing import Any
import pytest
from redis.exceptions import RedisError
from sqlalchemy import event
from tools import generate_test_data
from handler.database import db_rom_handler
from handler.database.base_handler import sync_engine
from models.rom import Rom
IMAGE_FIELDS = {"path_cover_s", "path_cover_l", "path_screenshots"}
class _FrozenDatetime(datetime):
@classmethod
def now(cls, tz: tzinfo | None = None) -> "_FrozenDatetime":
return cls(2026, 1, 1, 12, 0, tzinfo=tz)
def _rom_rows(
monkeypatch: pytest.MonkeyPatch,
resources: Path,
*flags: str,
rotate_cache: Callable[[], None] = lambda: None,
rotate_feeds: Callable[[], None] = lambda: None,
) -> list[dict[str, Any]]:
"""Run the seeder, recording rom rows instead of inserting anything."""
rows: list[dict[str, Any]] = []
def record(conn: object, model: type, batch: list[dict[str, Any]]) -> None:
if model is Rom:
rows.extend(batch)
monkeypatch.setattr(generate_test_data, "bulk_insert", record)
monkeypatch.setattr(generate_test_data, "_advance_sequences", lambda *_: None)
monkeypatch.setattr(generate_test_data, "datetime", _FrozenDatetime)
monkeypatch.setattr(db_rom_handler, "invalidate_filter_values_cache", rotate_cache)
monkeypatch.setattr(generate_test_data, "invalidate_all_cached_feeds", rotate_feeds)
monkeypatch.setattr(
sys,
"argv",
[
"generate_test_data.py",
"--roms", "24",
"--platforms", "3",
"--users", "2",
"--collections", "2",
"--play-sessions", "4",
"--image-fidelity", "2",
"--image-workers", "1",
"--resources-path", str(resources),
*flags,
],
) # fmt: skip
assert generate_test_data.main() == 0
return rows
def _without_images(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [{k: v for k, v in row.items() if k not in IMAGE_FIELDS} for row in rows]
@pytest.mark.parametrize("flags", [("--image-limit", "5"), ("--no-images",)])
def test_image_flags_never_change_the_rows(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, flags: tuple[str, ...]
) -> None:
every = _rom_rows(monkeypatch, tmp_path / "every")
limited = _rom_rows(monkeypatch, tmp_path / "limited", *flags)
assert len(every) == len(limited) == 24
assert _without_images(every) == _without_images(limited)
@pytest.mark.parametrize("fidelity", ["1", "2"])
def test_a_dry_run_writes_no_image_files(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, fidelity: str
) -> None:
_rom_rows(monkeypatch, tmp_path, "--dry-run", "--image-fidelity", fidelity)
assert not tmp_path.exists() or not any(tmp_path.rglob("*"))
def test_a_seed_rotates_the_gallery_and_feed_caches(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
rotated: list[str] = []
_rom_rows(
monkeypatch,
tmp_path,
rotate_cache=lambda: rotated.append("gallery"),
rotate_feeds=lambda: rotated.append("feeds"),
)
assert rotated == ["gallery", "feeds"]
def test_the_utc_listener_is_removed_after_a_run(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
listeners: list[Callable[..., None]] = []
pin_utc = generate_test_data._pin_utc
def recorded(postgresql: bool) -> Callable[..., None]:
listeners.append(pin_utc(postgresql))
return listeners[-1]
monkeypatch.setattr(generate_test_data, "_pin_utc", recorded)
_rom_rows(monkeypatch, tmp_path)
assert listeners
assert not event.contains(sync_engine, "connect", listeners[0])
def test_a_cache_failure_still_reports_the_saved_seed(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
def unavailable() -> None:
raise RedisError("connection refused")
rows = _rom_rows(monkeypatch, tmp_path, rotate_cache=unavailable)
captured = capsys.readouterr()
assert "could not rotate the gallery cache" in captured.err
assert "Done in" in captured.out
assert len(rows) == 24