First version
CI / quality (3.11) (push) Has been cancelled
CI / quality (3.12) (push) Has been cancelled

This commit is contained in:
2026-10-15 17:37:05 +02:00
commit d651455499
41 changed files with 3830 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
"""Shared pytest fixtures."""
from __future__ import annotations
import json
from collections.abc import Iterator
from pathlib import Path
import pytest
from genshin_tcg.config import Settings
from genshin_tcg.data.catalog import Catalog
from genshin_tcg.models import parse_catalog
FIXTURES_DIR = Path(__file__).parent / "fixtures"
class FakeConverter:
"""A stub :class:`~genshin_tcg.rendering.converters.HtmlConverter`."""
def __init__(self) -> None:
self.calls: list[tuple[Path, Path]] = []
def convert(self, html_path: Path, image_path: Path) -> None:
self.calls.append((html_path, image_path))
image_path.parent.mkdir(parents=True, exist_ok=True)
image_path.write_bytes(b"fake-png")
def close(self) -> None: # pragma: no cover - trivial
pass
def __enter__(self) -> FakeConverter:
return self
def __exit__(self, *exc: object) -> None: # pragma: no cover - trivial
return None
@pytest.fixture
def fake_converter() -> FakeConverter:
return FakeConverter()
@pytest.fixture
def sample_payload() -> list[dict[str, object]]:
raw = (FIXTURES_DIR / "sample_fr.json").read_text(encoding="utf-8")
payload = json.loads(raw)
assert isinstance(payload, list)
return payload
@pytest.fixture
def sample_catalog(sample_payload: list[dict[str, object]]) -> Catalog:
return Catalog(cards=tuple(parse_catalog(sample_payload)))
@pytest.fixture
def settings(tmp_path: Path) -> Iterator[Settings]:
yield Settings(
language="fr",
assets_dir=tmp_path / "assets",
build_dir=tmp_path / "build",
)
+78
View File
@@ -0,0 +1,78 @@
[
{
"_id": 9001,
"id": "test_pyro",
"type": "character",
"name": "Test Pyro",
"hp": 10,
"energy": 3,
"element": "pyro",
"weapon": "claymore",
"skills": [
{
"_id": 90011,
"type": "Attaque normale",
"name": "Frappe de test",
"desc": "Inflige 2 pts de <span style=\"color: #FFFFFFFF;\">DGT physiques</span>\\nEt rien d'autre.",
"cost": [
{ "type": "pyro", "count": 1 },
{ "type": "void", "count": 2 }
]
},
{
"_id": 90012,
"type": "Compétence élémentaire",
"name": "Gerbe de flammes",
"desc": "Inflige 3 pts de <span style=\"color: #FFFFFFFF;\">DGT Pyro</span>.",
"cost": [{ "type": "pyro", "count": 3 }],
"sub": {
"_id": 900121,
"id": "test_summon",
"name": "Flamme éternelle",
"desc": "<span style=\"color: #FFFFFFFF;\">Phase finale : </span>Inflige 1 pt de <span style=\"color: #99FFFFFF;\">DGT Pyro</span>."
}
},
{
"_id": 90013,
"type": "Déchaînement élémentaire",
"name": "Explosion finale",
"desc": "Inflige 5 pts de <span style=\"color: #FFFFFFFF;\">DGT Pyro</span>.",
"cost": [
{ "type": "pyro", "count": 3 },
{ "type": "energy", "count": 3 }
]
}
]
},
{
"_id": 9002,
"id": "test_talent",
"type": "talent",
"name": "Talent de test",
"requirement": "test_pyro",
"skills": {
"cost": [{ "type": "pyro", "count": 4 }],
"desc": "<color=#FFD700>Action de combat</color> : équipe cette carte.\\n(Votre deck doit contenir Test Pyro)"
}
},
{
"_id": 9003,
"id": "test_artifact",
"type": "artifact",
"name": "Artefact de test",
"skills": {
"cost": [],
"desc": "Les <span style=\"color: #FFFFFFFF; text-decoration: underline;\">DGT</span> infligés +1."
}
},
{
"_id": 9004,
"id": "test_food",
"type": "food",
"name": "Plat de test",
"skills": {
"cost": [{ "type": "same", "count": 2 }],
"desc": "Soigne 2 pts."
}
}
]
+70
View File
@@ -0,0 +1,70 @@
"""Tests for asset discovery and URL resolution."""
from __future__ import annotations
from pathlib import Path
from genshin_tcg.constants import AssetPaths, CardType, CostType, Element, WeaponType
from genshin_tcg.data.assets import (
illustration_key,
iter_required_keys,
skill_keys,
static_icon_keys,
)
from genshin_tcg.data.catalog import Catalog
from genshin_tcg.models import CharacterCard
from genshin_tcg.rendering.context import AssetUrlResolver
def test_static_icons_cover_domain_vocabulary() -> None:
keys = set(static_icon_keys())
assert AssetPaths.HP_ICON in keys
assert AssetPaths.ENERGY_CARD_ICON in keys
assert AssetPaths.cost_die(CostType.VOID) in keys
assert AssetPaths.element(Element.PYRO) in keys
assert AssetPaths.weapon(WeaponType.BOW) in keys
def test_static_icons_exclude_character_type_icon() -> None:
# No ``types/character.png`` exists upstream.
assert AssetPaths.card_type(CardType.CHARACTER) not in static_icon_keys()
def test_required_keys_include_illustration_and_skills(sample_catalog: Catalog) -> None:
keys = set(iter_required_keys(sample_catalog.cards))
assert "tcg/test_pyro.png" in keys
assert "tcg/skills/test_pyro/skill_1.png" in keys
assert "tcg/skills/test_pyro/skill_3.png" in keys
assert "tcg/skills/test_pyro/skill_4.png" not in keys
assert "tcg/test_food.png" in keys
def test_skill_keys_follow_skill_order(sample_catalog: Catalog) -> None:
character = next(iter(sample_catalog.characters))
assert isinstance(character, CharacterCard)
assert skill_keys(character) == [
"tcg/skills/test_pyro/skill_1.png",
"tcg/skills/test_pyro/skill_2.png",
"tcg/skills/test_pyro/skill_3.png",
]
def test_illustration_key_uses_card_id(sample_catalog: Catalog) -> None:
assert illustration_key(sample_catalog.get("test_food")) == "tcg/test_food.png"
def test_asset_url_resolver_builds_relative_urls(tmp_path: Path) -> None:
assets = tmp_path / "assets"
html_dir = tmp_path / "build" / "html"
resolver = AssetUrlResolver(assets, html_dir)
url = resolver.url("tcg/test_pyro.png")
assert url == "../../assets/tcg/test_pyro.png"
def test_asset_url_resolver_exists(tmp_path: Path) -> None:
assets = tmp_path / "assets"
(assets / "tcg").mkdir(parents=True)
(assets / "tcg" / "x.png").write_bytes(b"x")
resolver = AssetUrlResolver(assets, tmp_path / "build" / "html")
assert resolver.exists("tcg/x.png")
assert not resolver.exists("tcg/missing.png")
+86
View File
@@ -0,0 +1,86 @@
"""Tests for the domain models and catalogue."""
from __future__ import annotations
from pathlib import Path
import pytest
from pydantic import ValidationError
from genshin_tcg.constants import CardType, Element, WeaponType
from genshin_tcg.data.catalog import Catalog, load_catalog, save_catalog
from genshin_tcg.models import ActionCard, CharacterCard, parse_catalog
def test_parse_catalog_classifies_cards(sample_payload: list[dict[str, object]]) -> None:
cards = parse_catalog(sample_payload)
assert len(cards) == 4
characters = [c for c in cards if isinstance(c, CharacterCard)]
actions = [c for c in cards if isinstance(c, ActionCard)]
assert len(characters) == 1
assert len(actions) == 3
def test_character_card_parsing(sample_payload: list[dict[str, object]]) -> None:
character = next(
card for card in parse_catalog(sample_payload) if isinstance(card, CharacterCard)
)
assert character.id == "test_pyro"
assert character.element is Element.PYRO
assert character.weapon is WeaponType.CLAYMORE
assert character.hp == 10
assert character.energy == 3
assert len(character.skills) == 3
assert character.skills[0].cost[0].count == 1
assert character.skills[1].sub is not None
assert character.skills[1].sub.name == "Flamme éternelle"
def test_action_card_flattens_skills_object(sample_payload: list[dict[str, object]]) -> None:
talent = next(
card
for card in parse_catalog(sample_payload)
if isinstance(card, ActionCard) and card.id == "test_talent"
)
assert talent.type is CardType.TALENT
assert talent.requirement == "test_pyro"
assert talent.cost[0].count == 4
assert "Action de combat" in talent.description
def test_action_card_with_empty_cost(sample_payload: list[dict[str, object]]) -> None:
artifact = next(
card
for card in parse_catalog(sample_payload)
if isinstance(card, ActionCard) and card.id == "test_artifact"
)
assert artifact.cost == ()
def test_unknown_card_shape_raises() -> None:
with pytest.raises(ValidationError):
parse_catalog([{"_id": 1, "id": "x", "type": "character", "name": "x"}])
def test_catalog_queries(sample_catalog: Catalog) -> None:
assert len(sample_catalog) == 4
assert len(sample_catalog.characters) == 1
assert len(sample_catalog.actions) == 3
assert sample_catalog.get("test_food").name == "Plat de test"
subset = sample_catalog.select(["test_food", "test_pyro"])
assert [card.id for card in subset] == ["test_food", "test_pyro"]
def test_catalog_duplicate_ids_warn(sample_payload: list[dict[str, object]]) -> None:
duplicated = [*sample_payload, sample_payload[0]]
catalog = Catalog(cards=tuple(parse_catalog(duplicated)))
assert len(catalog.cards) == 5
assert len(catalog._by_id) == 4
def test_catalog_round_trip(sample_catalog: Catalog, tmp_path: Path) -> None:
path = tmp_path / "catalog.json"
save_catalog(sample_catalog, path)
reloaded = load_catalog(path)
assert [card.id for card in reloaded] == [card.id for card in sample_catalog]
assert reloaded.get("test_pyro") == sample_catalog.get("test_pyro")
+42
View File
@@ -0,0 +1,42 @@
"""Tests for the Typer CLI."""
from __future__ import annotations
from pathlib import Path
from typer.testing import CliRunner
from genshin_tcg import __version__
from genshin_tcg.cli import app
from genshin_tcg.data.catalog import Catalog, save_catalog
runner = CliRunner()
def test_version_flag() -> None:
result = runner.invoke(app, ["--version"])
assert result.exit_code == 0
assert __version__ in result.output
def test_list_without_catalogue_errors(tmp_path: Path) -> None:
result = runner.invoke(
app,
["--build-dir", str(tmp_path / "build"), "--assets-dir", str(tmp_path / "assets"), "list"],
)
assert result.exit_code == 1
assert "Error" in result.output
def test_list_prints_catalogue(tmp_path: Path, sample_catalog: Catalog) -> None:
build_dir = tmp_path / "build"
build_dir.mkdir(parents=True)
save_catalog(sample_catalog, build_dir / "catalog.json")
result = runner.invoke(
app,
["--build-dir", str(build_dir), "--assets-dir", str(tmp_path / "assets"), "list"],
)
assert result.exit_code == 0
assert "test_pyro" in result.output
assert "Test Pyro" in result.output
+62
View File
@@ -0,0 +1,62 @@
"""Tests for :mod:`genshin_tcg.config`."""
from __future__ import annotations
from pathlib import Path
import pytest
from pydantic import ValidationError
from genshin_tcg.config import CardSettings, Settings
def test_design_pixels_for_poker_format() -> None:
card = CardSettings(width_mm=63, height_mm=88, dpi=300)
assert card.design_width_px == 744
assert card.design_height_px == 1039
assert card.scale_factor == 1.0
assert card.output_width_px == 744
def test_scale_factor_tracks_dpi() -> None:
card = CardSettings(dpi=600)
assert card.scale_factor == 2.0
assert card.output_width_px == 1488
assert card.output_height_px == 2078
def test_dpi_below_baseline_is_rejected() -> None:
with pytest.raises(ValidationError):
CardSettings(dpi=150)
def test_derived_paths(tmp_path: Path) -> None:
settings = Settings(language="en", assets_dir=tmp_path / "a", build_dir=tmp_path / "b")
assert settings.source_json == tmp_path / "a" / "source" / "en.json"
assert settings.tags_json == tmp_path / "a" / "source" / "tags_en.json"
assert settings.catalog_path == tmp_path / "b" / "catalog.json"
assert settings.pdf_path == tmp_path / "b" / "cards-en.pdf"
assert settings.factions_override == tmp_path / "a" / "overrides" / "factions.json"
def test_ensure_directories(tmp_path: Path) -> None:
settings = Settings(assets_dir=tmp_path / "a", build_dir=tmp_path / "b")
settings.ensure_directories()
assert settings.source_dir.is_dir()
assert settings.tcg_dir.is_dir()
assert settings.html_dir.is_dir()
assert settings.png_dir.is_dir()
def test_nested_env_override() -> None:
import os
os.environ["GTCG_CARD__DPI"] = "600"
os.environ["GTCG_PAGE__CUT_MARKS"] = "false"
try:
settings = Settings()
assert settings.card.dpi == 600
assert settings.page.cut_marks is False
finally:
os.environ.pop("GTCG_CARD__DPI", None)
os.environ.pop("GTCG_PAGE__CUT_MARKS", None)
+180
View File
@@ -0,0 +1,180 @@
"""Tests for the template view builder."""
from __future__ import annotations
from pathlib import Path
from genshin_tcg.data.catalog import Catalog
from genshin_tcg.rendering.context import (
ActionView,
CharacterView,
build_view,
load_faction_overrides,
load_labels,
)
def _character(catalog: Catalog) -> CharacterView:
view = build_view(
catalog.get("test_pyro"),
assets_dir=Path("assets"),
html_dir=Path("build") / "html",
width_px=744,
height_px=1039,
)
assert isinstance(view, CharacterView)
return view
def _action(catalog: Catalog) -> ActionView:
view = build_view(
catalog.get("test_talent"),
assets_dir=Path("assets"),
html_dir=Path("build") / "html",
width_px=744,
height_px=1039,
)
assert isinstance(view, ActionView)
return view
def test_character_view_fields(sample_catalog: Catalog) -> None:
view = _character(sample_catalog)
assert view.kind == "character"
assert view.name == "Test Pyro"
assert view.hp == 10
assert view.energy == 3
assert view.css_class == "el-pyro"
assert view.width_px == 744
assert view.illustration == "../../assets/tcg/test_pyro.png"
assert view.energy_icon.endswith("assets/tcg/icons/energy_card.png")
assert view.hp_icon.endswith("assets/tcg/icons/hp.png")
def test_character_tags_include_element_and_weapon(sample_catalog: Catalog) -> None:
view = _character(sample_catalog)
kinds = [tag.kind for tag in view.tags]
assert kinds == ["element", "weapon"]
assert view.tags[0].label == "Pyro"
element_icon = view.tags[0].icon
assert element_icon is not None
assert element_icon.endswith("assets/tcg/icons/elements/pyro.png")
assert view.tags[1].label == "Épée à deux mains"
def test_character_skills_and_costs(sample_catalog: Catalog) -> None:
view = _character(sample_catalog)
assert len(view.skills) == 3
first = view.skills[0]
assert first.name == "Frappe de test"
assert first.icon is not None and first.icon.endswith("skills/test_pyro/skill_1.png")
assert [die.count for die in first.cost] == [1, 2]
assert first.cost[0].icon.endswith("assets/tcg/icons/pyro.png")
assert first.cost[1].icon.endswith("assets/tcg/icons/void.png")
def test_character_description_is_cleaned_and_highlighted(sample_catalog: Catalog) -> None:
view = _character(sample_catalog)
assert "<br/>" in view.skills[0].description_html
assert '<span style="color: #FFFFFFFF">DGT ' in view.skills[1].description_html
assert "inline-die" in view.skills[1].description_html
assert view.skills[1].sub_name == "Flamme éternelle"
assert view.skills[1].sub_description_html is not None
def test_inline_element_icons_can_be_disabled(sample_catalog: Catalog) -> None:
with_icons = _character(sample_catalog)
assert "inline-die" in with_icons.skills[1].description_html
without = build_view(
sample_catalog.get("test_pyro"),
assets_dir=Path("assets"),
html_dir=Path("build") / "html",
width_px=744,
height_px=1039,
inline_element_icons=False,
)
assert isinstance(without, CharacterView)
assert "inline-die" not in without.skills[1].description_html
def test_action_view_fields(sample_catalog: Catalog) -> None:
view = _action(sample_catalog)
assert view.kind == "action"
assert view.css_class == "type-talent"
assert view.type_label == "Aptitude"
assert view.type_icon.endswith("assets/tcg/icons/types/talent.png")
assert view.requirement == "test_pyro"
assert [die.count for die in view.cost] == [4]
assert "<br/>" in view.description_html
assert '<span style="color: #FFD700">Action de combat</span>' in view.description_html
def test_action_without_cost_gets_placeholder_die(sample_catalog: Catalog) -> None:
view = build_view(
sample_catalog.get("test_artifact"),
assets_dir=Path("assets"),
html_dir=Path("build") / "html",
width_px=744,
height_px=1039,
)
assert isinstance(view, ActionView)
assert len(view.cost) == 1
assert view.cost[0].count == 0
assert view.cost[0].icon.endswith("assets/tcg/icons/same.png")
def test_faction_override_without_icon(tmp_path: Path, sample_catalog: Catalog) -> None:
view = build_view(
sample_catalog.get("test_pyro"),
assets_dir=tmp_path / "assets",
html_dir=tmp_path / "build" / "html",
factions={"test_pyro": "liyue"},
width_px=744,
height_px=1039,
)
assert isinstance(view, CharacterView)
faction = next(tag for tag in view.tags if tag.kind == "faction")
assert faction.label == "Liyue"
assert faction.icon is None
def test_faction_override_with_icon(tmp_path: Path, sample_catalog: Catalog) -> None:
icon = tmp_path / "assets" / "tcg" / "icons" / "factions" / "liyue.png"
icon.parent.mkdir(parents=True)
icon.write_bytes(b"x")
view = build_view(
sample_catalog.get("test_pyro"),
assets_dir=tmp_path / "assets",
html_dir=tmp_path / "build" / "html",
factions={"test_pyro": "liyue"},
width_px=744,
height_px=1039,
)
assert isinstance(view, CharacterView)
faction = next(tag for tag in view.tags if tag.kind == "faction")
assert faction.icon is not None and faction.icon.endswith("factions/liyue.png")
def test_load_labels_merges_file(tmp_path: Path) -> None:
path = tmp_path / "tags_fr.json"
path.write_text('{"pyro": "Feu", "unique": "Unique"}', encoding="utf-8")
labels = load_labels(path)
assert labels["pyro"] == "Feu"
assert labels["unique"] == "Unique"
assert labels["talent"] == "Aptitude" # built-in fallback retained
def test_load_labels_missing_file_uses_defaults(tmp_path: Path) -> None:
labels = load_labels(tmp_path / "nope.json")
assert labels["cryo"] == "Cryo"
def test_load_faction_overrides(tmp_path: Path) -> None:
path = tmp_path / "factions.json"
path.write_text('{"ganyu": "liyue"}', encoding="utf-8")
assert load_faction_overrides(path) == {"ganyu": "liyue"}
def test_load_faction_overrides_missing(tmp_path: Path) -> None:
assert load_faction_overrides(tmp_path / "nope.json") == {}
+93
View File
@@ -0,0 +1,93 @@
"""Tests for A4 imposition."""
from __future__ import annotations
from pathlib import Path
import pytest
from PIL import Image
from genshin_tcg.pdf.imposition import ImpositionGrid, impose_pdf
def test_default_grid_geometry() -> None:
grid = ImpositionGrid()
assert grid.capacity == 9
assert grid.content_width_mm == pytest.approx(189.0)
assert grid.content_height_mm == pytest.approx(264.0)
assert grid.offset_x_mm == pytest.approx(10.5)
assert grid.offset_y_mm == pytest.approx(16.5)
def test_cell_positions() -> None:
grid = ImpositionGrid()
assert grid.cell_top_left_mm(0) == pytest.approx((10.5, 16.5))
assert grid.cell_top_left_mm(2) == pytest.approx((10.5 + 2 * 63, 16.5))
assert grid.cell_top_left_mm(3) == pytest.approx((10.5, 16.5 + 88))
assert grid.cell_top_left_mm(8) == pytest.approx((10.5 + 2 * 63, 16.5 + 2 * 88))
def test_cell_index_bounds() -> None:
grid = ImpositionGrid()
with pytest.raises(IndexError):
grid.cell_top_left_mm(9)
def test_page_count() -> None:
grid = ImpositionGrid()
assert grid.page_count(0) == 0
assert grid.page_count(1) == 1
assert grid.page_count(9) == 1
assert grid.page_count(10) == 2
assert grid.page_count(18) == 2
assert grid.page_count(19) == 3
def test_grid_too_large_raises() -> None:
with pytest.raises(ValueError):
ImpositionGrid(page_width_mm=100.0)
def test_explicit_margin() -> None:
grid = ImpositionGrid(margin_mm=5.0)
assert grid.offset_x_mm == 5.0
assert grid.offset_y_mm == 5.0
def test_gutter_shifts_cells() -> None:
grid = ImpositionGrid(gutter_mm=2.0, margin_mm=1.0)
assert grid.content_width_mm == pytest.approx(3 * 63 + 2 * 2)
assert grid.cell_top_left_mm(1) == pytest.approx((1.0 + 65.0, 1.0))
def _make_pngs(directory: Path, count: int) -> list[Path]:
directory.mkdir(parents=True, exist_ok=True)
paths: list[Path] = []
for index in range(count):
path = directory / f"card_{index}.png"
Image.new("RGB", (74, 104), (index * 10 % 256, 0, 0)).save(path)
paths.append(path)
return paths
def test_impose_pdf_writes_multiple_pages(tmp_path: Path) -> None:
images = _make_pngs(tmp_path / "png", 10)
output = tmp_path / "out.pdf"
result = impose_pdf(images, output, ImpositionGrid())
assert result.pages == 2
assert result.cards == 10
assert output.is_file()
assert output.stat().st_size > 1000
def test_impose_pdf_single_page(tmp_path: Path) -> None:
images = _make_pngs(tmp_path / "png", 3)
output = tmp_path / "out.pdf"
result = impose_pdf(images, output, ImpositionGrid(cut_marks=False))
assert result.pages == 1
assert output.is_file()
def test_impose_pdf_missing_image_raises(tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError):
impose_pdf([tmp_path / "nope.png"], tmp_path / "out.pdf", ImpositionGrid())
+58
View File
@@ -0,0 +1,58 @@
"""Tests for :mod:`genshin_tcg.markup`."""
from __future__ import annotations
from genshin_tcg.markup import clean_markup, inline_symbols, sanitize, strip_markup
def test_clean_markup_converts_color_tags() -> None:
assert clean_markup("<color=#FFD700>Or</color>") == '<span style="color: #FFD700">Or</span>'
def test_clean_markup_converts_escaped_newlines() -> None:
assert clean_markup("a\\nb") == "a<br/>b"
def test_clean_markup_keeps_colour_and_underline_spans() -> None:
raw = '<span style="color: #80C0FFFF; text-decoration: underline;">DGT</span>'
expected = '<span style="color: #80C0FFFF; text-decoration: underline">DGT</span>'
assert clean_markup(raw) == expected
def test_sanitize_removes_script_and_event_handlers() -> None:
dirty = '<script>alert(1)</script><span onclick="x()" style="color: red;">ok</span>'
cleaned = sanitize(dirty)
assert "script" not in cleaned
assert "alert" not in cleaned
assert "onclick" not in cleaned
assert cleaned == '<span style="color: red">ok</span>'
def test_sanitize_unwraps_unknown_tags_but_keeps_text() -> None:
assert sanitize("<div>hello <em>world</em></div>") == "hello <em>world</em>"
def test_sanitize_drops_non_allowlisted_styles() -> None:
cleaned = sanitize('<span style="position: fixed; color: blue;">x</span>')
assert cleaned == '<span style="color: blue">x</span>'
def test_strip_markup_returns_plain_text() -> None:
assert strip_markup("<span>a</span>\\nb") == "a b"
def test_inline_symbols_prefixes_keyword_only_in_text() -> None:
html = 'DGT <span style="color: red;">Pyro</span>'
result = inline_symbols(html, {"Pyro": "[ICON]"})
assert result == 'DGT <span style="color: red;">[ICON]Pyro</span>'
def test_inline_symbols_respects_word_boundaries_and_attributes() -> None:
html = '<span title="Pyro">Pyromane</span>'
result = inline_symbols(html, {"Pyro": "[ICON]"})
# "Pyro" inside the attribute and inside "Pyromane" must not match.
assert result == html
def test_inline_symbols_no_symbols_is_identity() -> None:
assert inline_symbols("<b>x</b>", {}) == "<b>x</b>"
+71
View File
@@ -0,0 +1,71 @@
"""Tests for the pipeline orchestration (offline: no network, no browser)."""
from __future__ import annotations
import pytest
from PIL import Image
from genshin_tcg import pipeline
from genshin_tcg.config import Settings
from genshin_tcg.data.catalog import Catalog, save_catalog
from genshin_tcg.rendering.converters import HtmlConverter
from genshin_tcg.rendering.renderer import safe_name
def _prepare_catalogue(settings: Settings, catalog: Catalog) -> None:
settings.ensure_directories()
save_catalog(catalog, settings.catalog_path)
def _make_pngs(settings: Settings, catalog: Catalog) -> None:
settings.png_dir.mkdir(parents=True, exist_ok=True)
for card in catalog:
Image.new("RGB", (74, 104), (10, 20, 30)).save(
settings.png_dir / f"{safe_name(card.id)}.png"
)
def test_render_without_screenshot(settings: Settings, sample_catalog: Catalog) -> None:
_prepare_catalogue(settings, sample_catalog)
rendered = pipeline.render(settings, screenshot=False)
assert len(rendered) == 4
assert all(item.html_path.is_file() for item in rendered)
assert all(not item.png_path.exists() for item in rendered)
def test_render_with_injected_converter(
settings: Settings, sample_catalog: Catalog, fake_converter: HtmlConverter
) -> None:
_prepare_catalogue(settings, sample_catalog)
rendered = pipeline.render(settings, converter=fake_converter)
assert len(rendered) == 4
assert all(item.png_path.is_file() for item in rendered)
def test_render_only_subset(settings: Settings, sample_catalog: Catalog) -> None:
_prepare_catalogue(settings, sample_catalog)
rendered = pipeline.render(settings, only=["test_pyro"], screenshot=False)
assert [item.card_id for item in rendered] == ["test_pyro"]
def test_impose_from_generated_pngs(settings: Settings, sample_catalog: Catalog) -> None:
_prepare_catalogue(settings, sample_catalog)
_make_pngs(settings, sample_catalog)
result = pipeline.impose(settings)
assert result.cards == 4
assert result.pages == 1
assert result.output.is_file()
def test_impose_custom_output(settings: Settings, sample_catalog: Catalog) -> None:
_prepare_catalogue(settings, sample_catalog)
_make_pngs(settings, sample_catalog)
output = settings.build_dir / "custom.pdf"
result = pipeline.impose(settings, output=output)
assert result.output == output
assert output.is_file()
def test_render_without_catalogue_raises(settings: Settings) -> None:
with pytest.raises(FileNotFoundError):
pipeline.render(settings, screenshot=False)
+70
View File
@@ -0,0 +1,70 @@
"""Tests for the HTML renderer (no browser required)."""
from __future__ import annotations
from genshin_tcg.config import Settings
from genshin_tcg.data.catalog import Catalog
from genshin_tcg.rendering.converters import HtmlConverter, Viewport
from genshin_tcg.rendering.renderer import CardRenderer
def test_write_html_creates_standalone_documents(
settings: Settings, sample_catalog: Catalog
) -> None:
renderer = CardRenderer(settings)
rendered = renderer.write_html(renderer.build_views(sample_catalog))
assert len(rendered) == 4
character = next(item for item in rendered if item.card_id == "test_pyro")
document = character.html_path.read_text(encoding="utf-8")
assert "<style>" in document
assert "--card-w: 744px" in document
assert 'class="card el-pyro"' in document
assert "../../assets/tcg/test_pyro.png" in document
action = next(item for item in rendered if item.card_id == "test_talent")
action_document = action.html_path.read_text(encoding="utf-8")
assert 'class="card type-talent"' in action_document
def test_safe_names_for_special_ids() -> None:
from genshin_tcg.rendering.renderer import safe_name
assert safe_name("shaken,_not_purred") == "shaken__not_purred"
assert safe_name("the_bestest_travel_companion!") == "the_bestest_travel_companion"
assert safe_name("wellspring_of_war-lust") == "wellspring_of_war-lust"
def test_rasterise_writes_png_and_keeps_html(
settings: Settings, sample_catalog: Catalog, fake_converter: HtmlConverter
) -> None:
renderer = CardRenderer(settings)
rendered = renderer.write_html(renderer.build_views(sample_catalog))
result = renderer.rasterise(rendered, fake_converter)
assert len(result) == 4
assert all(item.png_path.exists() for item in result)
assert all(item.html_path.exists() for item in result)
assert (result[0].png_path.read_bytes()) == b"fake-png"
def test_rasterise_removes_html_when_disabled(
settings: Settings, sample_catalog: Catalog, fake_converter: HtmlConverter
) -> None:
settings.render.keep_html = False
renderer = CardRenderer(settings)
rendered = renderer.write_html(renderer.build_views(sample_catalog))
result = renderer.rasterise(rendered, fake_converter)
assert all(not item.html_path.exists() for item in result)
assert all(item.png_path.exists() for item in result)
def test_viewport_from_settings(settings: Settings) -> None:
vp = Viewport(
width_px=settings.card.design_width_px,
height_px=settings.card.design_height_px,
scale_factor=settings.card.scale_factor,
)
assert (vp.width_px, vp.height_px, vp.scale_factor) == (744, 1039, 1.0)