# coding=utf-8 """Tests de l'extension « Dog Bandana » (pytest).""" import os import re import xml.etree.ElementTree as ET import pytest import math import numpy as np from dog_bandana_core import (chain_polylines, erode, grid_pixels, laser_order, order_polylines, parse_color, polylines_to_d, rasterize, simplify_polyline, skeletonize, smooth_polyline, trace_skeleton, travel_length, turing_pattern) HERE = os.path.dirname(os.path.abspath(__file__)) SHAPES = os.path.join(HERE, "tests", "data", "shapes.svg") SCALED = os.path.join(HERE, "tests", "data", "scaled.svg") # -------------------------------------------------------------------------- # Noyau (sans inkex) # -------------------------------------------------------------------------- def test_parse_color_inkscape_integer(): assert parse_color("3014898687") == ("#b3b3b3", 1.0) assert parse_color(str(0xFF000080)) == ("#ff0000", round(0x80 / 255, 4)) def test_parse_color_hex_and_invalid(): assert parse_color("#123456") == ("#123456", 1.0) assert parse_color("#abc") == ("#aabbcc", 1.0) assert parse_color("pas une couleur") == ("#b3b3b3", 1.0) def test_polylines_to_d(): d = polylines_to_d([[(0, 0), (1, 2)], [(3, 4), (5, 6)]], precision=1) assert d == "M 0.0,0.0 L 1.0,2.0 M 3.0,4.0 L 5.0,6.0" def covered_segments(polylines): """Segments (arrondis, sens indifferent) couverts par des polylignes.""" out = [] for line in polylines: for p, q in zip(line, line[1:]): a, b = tuple(round(v, 6) for v in p), tuple(round(v, 6) for v in q) out.append(min((a, b), (b, a))) return sorted(out) def test_chain_polylines_joins_touching_lines(): # Un « Y » (4 noeuds impairs : 2 traits au minimum) et un trait isole. y_shape = [[(0, 0), (0, -1)], [(0, 0), (1, 1)], [(-1, 1), (0, 0)]] lone = [[(5, 5), (6, 5), (7, 6)]] chained = chain_polylines(y_shape + lone) assert len(chained) == 3 assert covered_segments(chained) == covered_segments(y_shape + lone) def test_chain_polylines_closed_circuit(): square = [[(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), (0, 1)], [(0, 1), (0, 0)]] chained = chain_polylines(square) assert len(chained) == 1 and len(chained[0]) == 5 assert chained[0][0] == chained[0][-1] def test_order_polylines_nearest_and_reversed(): lines = [[(10, 0), (20, 0)], [(3, 0), (1, 0)], [(30, 0), (21, 0)]] ordered = order_polylines(lines, start=(0, 0)) assert ordered == [[(1, 0), (3, 0)], [(10, 0), (20, 0)], [(21, 0), (30, 0)]] assert travel_length(ordered) == pytest.approx(1 + 7 + 1) def test_order_polylines_rotates_loops(): loop = [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)] ordered = order_polylines([loop], start=(11, 11)) assert ordered[0][0] == ordered[0][-1] == (10, 10) assert len(ordered[0]) == 5 def test_laser_order_cuts_travel_on_a_grid(): # Quadrillage de segments unitaires dans un ordre defavorable. segments = [[(x, y), (x + 1, y)] for x in range(20) for y in range(0, 20, 2)] segments += [[(x, y), (x, y + 1)] for y in range(20) for x in range(0, 20, 2)] segments = segments[::2] + segments[1::2] ordered = laser_order(segments) assert covered_segments(ordered) == covered_segments(segments) assert travel_length(ordered) < travel_length(segments) / 4 # -------------------------------------------------------------------------- # Motif de Turing : etapes # -------------------------------------------------------------------------- def test_rasterize_square_with_hole_even_odd(): outer = [(0, 0), (10, 0), (10, 10), (0, 10)] hole = [(3, 3), (7, 3), (7, 7), (3, 7)] mask = rasterize([outer, hole], 0, 0, 1.0, 12, 12) assert mask.sum() == 100 - 16 assert mask[1, 1] and not mask[5, 5] and not mask[11, 11] def test_rasterize_vertex_on_scanline_counted_once(): # Sommets de ce losange exactement sur les centres de lignes de pixels. diamond = [(5, 0.5), (9.5, 5.5), (5, 10.5), (0.5, 5.5)] mask = rasterize([diamond], 0, 0, 1.0, 10, 11) for row in mask: # chaque ligne : un seul segment assert np.count_nonzero(np.diff(row.astype(int))) <= 2 def test_erode_shrinks_by_radius(): mask = np.zeros((40, 40), dtype=bool) mask[10:30, 10:30] = True eroded = erode(mask, 3) rows = np.nonzero(eroded.any(axis=1))[0] assert rows[0] == 13 and rows[-1] == 26 assert erode(mask, 0).sum() == mask.sum() def test_skeletonize_bar_to_single_line(): bar = np.zeros((15, 40), dtype=bool) bar[5:10, 5:35] = True skeleton = skeletonize(bar) assert skeleton.any() assert skeleton.sum(axis=0).max() == 1 # un pixel par colonne assert (skeleton <= bar).all() def test_trace_skeleton_line_cross_dot_and_loop(): img = np.zeros((30, 30), dtype=bool) img[2, 2:12] = True # segment img[20, 5] = True # point isole lines = trace_skeleton(img) assert sorted(len(line) for line in lines) == [1, 10] cross = np.zeros((21, 21), dtype=bool) cross[10, :] = True cross[:, 10] = True assert len(trace_skeleton(cross)) == 4 loop = np.zeros((12, 12), dtype=bool) loop[2, 2:9] = loop[8, 2:9] = loop[2:9, 2] = loop[2:9, 8] = True lines = trace_skeleton(loop) assert len(lines) == 1 and lines[0][0] == lines[0][-1] def test_trace_skeleton_prunes_short_spurs(): img = np.zeros((20, 30), dtype=bool) img[10, 2:28] = True img[8:10, 15] = True # ergot de 2 pixels assert len(trace_skeleton(img)) == 3 assert len(trace_skeleton(img, min_spur=4)) == 2 def test_smooth_keeps_ends_and_loops(): zigzag = [(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)] smooth = smooth_polyline(zigzag, 3) assert smooth[0] == (0, 0) and smooth[-1] == (4, 0) assert max(y for _x, y in smooth[1:-1]) < 1 loop = [(0, 0), (4, 0), (4, 4), (0, 4), (0, 0)] smooth = smooth_polyline(loop, 2) assert smooth[0] == smooth[-1] and len(smooth) == 5 def test_simplify_straight_line(): line = [(x, 0.001 * (x % 2)) for x in range(20)] assert simplify_polyline(line, 0.01) == [(0.0, 0.0), (19.0, 0.001)] corner = [(0, 0), (5, 0), (5, 5)] assert len(simplify_polyline(corner, 0.1)) == 3 # -------------------------------------------------------------------------- # Motif de Turing : resultat # -------------------------------------------------------------------------- RECT = [[(0, 0), (60, 0), (60, 40), (0, 40)]] def polyline_length(line): return sum(math.hypot(q[0] - p[0], q[1] - p[1]) for p, q in zip(line, line[1:])) @pytest.mark.parametrize("edge", ["cut", "follow"]) def test_pattern_stays_inside_with_margin(edge): period, width, margin = 4.0, 2.0, 1.5 lines = turing_pattern(RECT, period, width, margin, seed=3, edge=edge) assert lines inset = margin + width / 2 tolerance = period / 8 # un pixel de calcul for line in lines: for x, y in line: assert inset - tolerance <= x <= 60 - inset + tolerance assert inset - tolerance <= y <= 40 - inset + tolerance def test_pattern_density_matches_period(): """Longueur des lignes ~ aire / periode : bandes espacees d'une periode.""" period = 4.0 lines = turing_pattern(RECT, period, 2.0, seed=1) total = sum(polyline_length(line) for line in lines) ratio = total * period / (60 * 40) assert 0.6 < ratio < 1.2 def test_pattern_reproducible_and_seeded(): a = turing_pattern(RECT, 4.0, 2.0, seed=7) assert a == turing_pattern(RECT, 4.0, 2.0, seed=7) assert a != turing_pattern(RECT, 4.0, 2.0, seed=8) def test_more_iterations_give_fewer_longer_lines(): few = turing_pattern(RECT, 4.0, 2.0, seed=2, steps=30) many = turing_pattern(RECT, 4.0, 2.0, seed=2, steps=300) assert len(many) < len(few) def test_pattern_respects_holes(): outer = [(0, 0), (60, 0), (60, 60), (0, 60)] hole = [(20, 20), (40, 20), (40, 40), (20, 40)] lines = turing_pattern([outer, hole], 4.0, 2.0, seed=1) inside = [(x, y) for line in lines for x, y in line if 21.5 < x < 38.5 and 21.5 < y < 38.5] assert not inside def test_pattern_empty_cases(): assert turing_pattern([], 4.0, 2.0) == [] assert turing_pattern(RECT, 0, 2.0) == [] # Bande plus etroite que le trait : rien a dessiner. assert turing_pattern([[(0, 0), (60, 0), (60, 1.5), (0, 1.5)]], 4.0, 2.0) == [] def test_dots_are_two_point_polylines(): lines = turing_pattern(RECT, 4.0, 2.0, seed=1, steps=20) assert all(len(line) >= 2 for line in lines) def test_grid_pixels(): assert grid_pixels([], 4.0) == 0 assert grid_pixels(RECT, 4.0) == (120 + 32) * (80 + 32) def test_laser_order_cuts_travel_on_pattern(): lines = turing_pattern(RECT, 4.0, 2.0, seed=1) ordered = laser_order(lines) assert travel_length(ordered) < travel_length(lines) / 3 # -------------------------------------------------------------------------- # Bout en bout (necessite inkex) # -------------------------------------------------------------------------- def run_extension(tmp_path, *args, source=SHAPES): pytest.importorskip("inkex") from dog_bandana import DogBandana out = tmp_path / "out.svg" DogBandana().run([*args, "--output={}".format(out), source]) return out.read_text(encoding="utf-8") def test_end_to_end_default(tmp_path): svg = run_extension(tmp_path, "--id=rect1") assert "Dog Bandana pattern" in svg assert 'id="rect1"' in svg assert "stroke-linecap:round" in svg def test_end_to_end_group_and_holes(tmp_path): svg = run_extension(tmp_path, "--id=group1", "--id=path2") assert svg.count("Dog Bandana pattern") == 2 @pytest.mark.parametrize("args, message", [ (["--line_width=5", "--period=4"], "smaller than the period"), (["--margin=30"], "too narrow"), ]) def test_end_to_end_errors(tmp_path, capsys, args, message): # Document inchange : inkex n'ecrit pas de sortie, seul le message compte. pytest.importorskip("inkex") from dog_bandana import DogBandana DogBandana().run(["--id=rect1", *args, "--output={}".format(tmp_path / "out.svg"), SHAPES]) assert message in capsys.readouterr().err def test_end_to_end_non_standard_document_scale(tmp_path): """Page de 400 mm pour 538,72 unites : svg.unittouu() s'y tromperait.""" svg = run_extension(tmp_path, "--id=rect1", source=SCALED) width = re.search(r"stroke-width:([\d.]+)", svg) assert float(width.group(1)) == pytest.approx(2.0 * 538.72053 / 400, abs=0.001) def test_end_to_end_removes_original(tmp_path): svg = run_extension(tmp_path, "--id=rect1", "--keep_original=false") assert 'id="rect1"' not in svg def test_end_to_end_color(tmp_path): svg = run_extension(tmp_path, "--id=rect1", "--stroke_color={}".format(0x336699FF)) assert re.search(r"stroke:#336699", svg) # -------------------------------------------------------------------------- # Traductions # -------------------------------------------------------------------------- def test_translations_up_to_date_and_complete(): """Chaque texte du .inx et des .py a sa traduction dans chaque catalogue.""" import gettext import i18n msgids = [msgid for msgid, _refs in i18n.extract()] assert "Dog Bandana Pattern Fill" in msgids assert "mm" not in msgids # unites marquees translatable="no" for language in i18n.LANGUAGES: entries = i18n.read_po(i18n.po_path(language)) missing = [m for m in msgids if not entries.get(m, ("", False))[0]] assert not missing, "{}.po incomplet : {}".format(language, missing) catalog = gettext.translation(i18n.DOMAIN, i18n.LOCALE_DIR, [language]) for msgid in msgids: assert catalog.gettext(msgid) == entries[msgid][0], \ "{} : .mo a recompiler (python i18n.py)".format(language) def test_po_roundtrip(tmp_path): import i18n messages = [("Simple", ["a"]), ('Quote "x" and \\ back', ["a"]), ("Two\nlines", ["a"]), ("Tab\tend\n", ["a"])] path = str(tmp_path / "xx.po") i18n.write_po(path, "fr", messages, {m: ("<" + m + ">", False) for m, _r in messages}) entries = i18n.read_po(path) for msgid, _refs in messages: assert entries[msgid] == ("<" + msgid + ">", False) def test_inx_matches_arguments(): """Chaque du .inx a son add_argument, et inversement.""" root = ET.parse(os.path.join(HERE, "dog_bandana.inx")).getroot() params = {elem.get("name") for elem in root.iter() if elem.tag.rsplit("}", 1)[-1] == "param"} with open(os.path.join(HERE, "dog_bandana.py"), encoding="utf-8") as handle: arguments = set(re.findall(r'add_argument\("--(\w+)"', handle.read())) assert params == arguments def test_inx_images_exist(): """Les images de la boite de dialogue sont presentes (chemin relatif au .inx).""" root = ET.parse(os.path.join(HERE, "dog_bandana.inx")).getroot() for elem in root.iter(): if elem.tag.rsplit("}", 1)[-1] == "image": assert os.path.isfile(os.path.join(HERE, elem.text.strip())), elem.text