# coding=utf-8 """Tests de l'extension « Skull Pattern Fill » (pytest).""" import math import os import random import re import xml.etree.ElementTree as ET import pytest import boolean_ops from skull_fill_core import ( Region, _Placed, apply_matrix, distance_to_rings, estimate_count, loops_to_d, parse_color, parse_loops, placement_matrix, point_in_rings, polylines_to_d, random_size, rings_bbox, rings_to_d, simplify_ring, skull_geometry, skull_paths, skull_placements, skull_radius, visible_gaps, visible_skulls) 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") SQUARE = [[(0, 0), (100, 0), (100, 100), (0, 100)]] FRAME = [[(0, 0), (100, 0), (100, 100), (0, 100)], [(30, 30), (70, 30), (70, 70), (30, 70)]] # -------------------------------------------------------------------------- # 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 test_parse_loops_roundtrip(): d = "M 0,0 C 1,0 1,1 0,1 Z M 5,5 C 6,5 6,6 5,5 Z" loops = parse_loops(d) assert len(loops) == 2 # Fermeture implicite ajoutee quand le dernier point n'est pas le depart. assert loops[0][-1][3] == (0.0, 0.0) and len(loops[0]) == 2 assert len(loops[1]) == 1 assert parse_loops(loops_to_d(loops, precision=1)) == loops with pytest.raises(ValueError): parse_loops("M 0,0 L 1,1 Z") def test_skull_geometry_fits_unit_frame(): body, ink = skull_geometry() assert len(body) == 1 and len(ink) > 40 xs = [p[0] for seg in body[0] for p in seg] ys = [p[1] for seg in body[0] for p in seg] assert min(ys) == pytest.approx(-0.5, abs=1e-3) and max(ys) == pytest.approx(0.5, abs=1e-3) assert min(xs) == pytest.approx(-max(xs), abs=1e-3) # cadre centre assert 0.7 < max(xs) - min(xs) < 0.9 # L'encre reste dans le cadre de la silhouette. for loop in ink: for seg in loop: for x, y in seg: assert min(xs) - 1e-3 <= x <= max(xs) + 1e-3 assert min(ys) - 1e-3 <= y <= max(ys) + 1e-3 def test_skull_has_no_horns(): """Les cornes du dessin d'origine depassaient largement du crane.""" body, _ink = skull_geometry() top = [p for seg in body[0] for p in seg if p[1] < -0.45] # Seule la calotte atteint le haut du cadre, autour du milieu. assert top and all(-0.25 < x < 0.35 for x, _y in top) def test_ink_loops_are_closed_and_continuous(): _body, ink = skull_geometry() for loop in ink: assert loop[-1][3] == pytest.approx(loop[0][0], abs=1e-3) for a, b in zip(loop, loop[1:]): assert a[3] == b[0] def test_skull_is_seen_three_quarters(): """Crane tourne vers la gauche : le miroir donne une vraie variante.""" body, _ink = skull_geometry() chin = max((seg[0] for seg in body[0]), key=lambda p: p[1]) assert chin[0] < 0 def evenodd_area(rings, box=(-20, -20, 120, 120), step=1.0): """Aire d'anneaux en regle pair-impair, par comptage sur une grille.""" count = 0 y = box[1] + step / 2 while y < box[3]: x = box[0] + step / 2 while x < box[2]: count += point_in_rings((x, y), rings) x += step y += step return count * step * step def square(x, y, w, h): return [(x, y), (x + w, y), (x + w, y + h), (x, y + h)] # -- Moteur booleen ---------------------------------------------------------- def test_boolean_basic_operations(): a, b = [square(0, 0, 10, 10)], [square(5, 5, 10, 10)] box = (-1, -1, 16, 16) assert evenodd_area(boolean_ops.intersection(a, b), box, 0.25) == pytest.approx(25, abs=0.5) assert evenodd_area(boolean_ops.difference(a, b), box, 0.25) == pytest.approx(75, abs=0.5) assert evenodd_area(boolean_ops.union(a + b), box, 0.25) == pytest.approx(175, abs=0.5) def test_boolean_shared_and_identical_edges(): joined = boolean_ops.union([square(0, 0, 10, 10), square(10, 0, 10, 10)]) assert len(joined) == 1 and len(joined[0]) == 4 # cote commun efface assert boolean_ops.difference([square(0, 0, 10, 10)], [square(0, 0, 10, 10)]) == [] def test_boolean_nonzero_union_and_holes(): # Regle non nulle : deux carres de meme sens se reunissent. ring = square(0, 0, 10, 10) assert evenodd_area(boolean_ops.union([ring, square(5, 5, 10, 10)], "nonzero"), (-1, -1, 16, 16), 0.25) == pytest.approx(175, abs=0.5) # Trou du sujet (pair-impair) conserve. pieces = boolean_ops.intersection(FRAME, [square(-10, -10, 120, 120)]) assert evenodd_area(pieces) == pytest.approx(10000 - 1600) assert not point_in_rings((50, 50), pieces) def test_boolean_random_differences_match_sampling(): rng = random.Random(7) def blob(cx, cy, r, n): return [(cx + r * (0.6 + 0.4 * rng.random()) * math.cos(2 * math.pi * k / n), cy + r * (0.6 + 0.4 * rng.random()) * math.sin(2 * math.pi * k / n)) for k in range(n)] for _trial in range(15): a = [blob(rng.uniform(0, 30), rng.uniform(0, 30), rng.uniform(5, 15), rng.randint(5, 30))] b = [blob(rng.uniform(0, 30), rng.uniform(0, 30), rng.uniform(5, 15), rng.randint(5, 30)) for _ in range(rng.randint(1, 4))] result = boolean_ops.difference(a, b, "evenodd", "nonzero") for _ in range(200): p = (rng.uniform(-15, 45), rng.uniform(-15, 45)) expected = point_in_rings(p, a) and not any(point_in_rings(p, [r]) for r in b) assert point_in_rings(p, result) == expected # -- Geometrie visible ------------------------------------------------------- def test_rings_to_d_is_compact_and_exact(): d = rings_to_d([[(0, 0), (1.234, 0), (1.234, 1), (1.2341, 1.0001), (0, 1)]], precision=2) assert d == "M0,0l1.23,0 0,1 -1.23,0z" assert rings_to_d([[(0, 0), (0.001, 0), (0, 0.001)]], precision=2) == "" def test_simplify_ring_drops_collinear_points(): ring = [(0, 0), (5, 0), (10, 0), (10, 5), (10, 10), (5, 10), (0, 10), (0, 5)] assert sorted(simplify_ring(ring, 0.01)) == sorted([(0, 0), (10, 0), (10, 10), (0, 10)]) def bodies(placements): return [_Placed(p, 0.01).body for p in placements] def test_visible_ink_is_never_under_a_skull_above(): """Rien de cache n'est ecrit : un point d'encre visible n'est sous aucun crane pose plus haut.""" region = Region(SQUARE) placements = skull_placements(SQUARE, 20, 45, seed=3) order = {p: k for k, p in enumerate(placements)} outlines = bodies(placements) visible = visible_skulls(placements, region) assert visible rng = random.Random(1) checked = 0 for placement, rings in visible: k = order[placement] box = rings_bbox(rings) for _ in range(60): p = (rng.uniform(box[0], box[2]), rng.uniform(box[1], box[3])) if not point_in_rings(p, rings): continue checked += 1 assert 0 <= p[0] <= 100 and 0 <= p[1] <= 100 # dans la forme for above in outlines[k + 1:]: assert not point_in_rings(p, [above]) assert checked > 100 def test_visible_skull_on_top_keeps_all_its_ink(): region = Region(SQUARE) _body, ink = skull_geometry() alone = [(50, 50, 30, 10, True)] (placement, rings), = visible_skulls(alone, region) assert placement == alone[0] and len(rings) == len(_Placed(alone[0], 0.01).ink) def test_fully_hidden_skull_is_dropped(): region = Region(SQUARE) small, big = (50, 50, 8, 0, False), (50, 50, 40, 0, False) visible = visible_skulls([small, big], region) assert [p for p, _rings in visible] == [big] def test_skull_outside_the_shape_writes_nothing(): region = Region(SQUARE) assert visible_skulls([(140, 50, 30, 0, False)], region) == [] def test_gaps_are_the_shape_minus_the_skulls(): region = Region(SQUARE) placements = skull_placements(SQUARE, 20, 45, spacing=1.2, seed=3) outlines = bodies(placements) gaps = visible_gaps(placements, region) rng = random.Random(2) for _ in range(400): p = (rng.uniform(-5, 105), rng.uniform(-5, 105)) expected = point_in_rings(p, SQUARE) and not any(point_in_rings(p, [o]) for o in outlines) assert point_in_rings(p, gaps) == expected def test_placement_matrix_scale_rotation_mirror(): m = placement_matrix(10, 20, 2, 0, False) assert apply_matrix(m, (0, 0)) == (10, 20) assert apply_matrix(m, (1, 0)) == pytest.approx((12, 20)) m = placement_matrix(0, 0, 1, 90, False) # sens horaire a l'ecran assert apply_matrix(m, (1, 0)) == pytest.approx((0, 1)) m = placement_matrix(0, 0, 1, 0, True) assert apply_matrix(m, (1, 0)) == pytest.approx((-1, 0)) assert apply_matrix(m, (0, 1)) == pytest.approx((0, 1)) def test_loops_to_d_and_skull_paths(): loop = parse_loops("M 0,0 C 1,0 1,0 1,0 C 1,1 1,1 1,1 C 0,0 0,0 0,0 Z")[0] d = loops_to_d([loop], placement_matrix(5, 5, 1), precision=1) assert d.startswith("M 5.0,5.0 C") and d.endswith("Z") and d.count("C ") == 3 body, ink = skull_paths((50, 50, 20, 15, True)) assert "transform" not in body assert body.count("M ") == 1 and ink.count("M ") > 40 def test_rings_bbox_point_in_rings_with_hole(): assert rings_bbox(FRAME) == (0, 0, 100, 100) assert rings_bbox([]) is None assert point_in_rings((10, 10), FRAME) assert not point_in_rings((50, 50), FRAME) # dans le trou assert not point_in_rings((150, 50), FRAME) assert distance_to_rings((50, 50), FRAME) == pytest.approx(20) assert distance_to_rings((110, 50), SQUARE) == pytest.approx(10) def test_random_size_stays_in_range_and_favors_small(): import random rng = random.Random(3) sizes = [random_size(rng, 10, 40) for _ in range(2000)] assert min(sizes) >= 10 and max(sizes) <= 40 small = sum(1 for s in sizes if s < 20) assert small > 0.7 * len(sizes) assert random_size(rng, 10, 10) == 10 def test_placements_cover_region_and_are_sorted(): placements = skull_placements(SQUARE, 10, 30, spacing=0.7, seed=1) sizes = [p[2] for p in placements] assert sizes == sorted(sizes) # grands par-dessus assert all(10 <= s <= 30 for s in sizes) # Tout point de la region est proche du centre d'un crane. for x in range(5, 100, 10): for y in range(5, 100, 10): nearest = min(math.hypot(x - p[0], y - p[1]) for p in placements) assert nearest < 10 * 0.7 # Aucun crane loin de la region. for x, y, size, _a, _m in placements: assert point_in_rings((x, y), SQUARE) or distance_to_rings((x, y), SQUARE) <= skull_radius() * size def test_placements_respect_rotation_and_mirror(): placements = skull_placements(SQUARE, 10, 20, max_rotation=12, mirror=False) assert all(abs(p[3]) <= 12 for p in placements) assert not any(p[4] for p in placements) flips = [p[4] for p in skull_placements(SQUARE, 10, 20, mirror=True)] assert any(flips) and not all(flips) def test_placements_skip_holes(): placements = skull_placements(FRAME, 5, 5, spacing=0.7) assert not any(abs(p[0] - 50) < 10 and abs(p[1] - 50) < 10 for p in placements) def test_placements_reproducible_and_independent_of_region(): a = skull_placements(SQUARE, 10, 30, seed=4) assert a == skull_placements(SQUARE, 10, 30, seed=4) assert a != skull_placements(SQUARE, 10, 30, seed=5) # Une region plus grande contient les memes cranes au centre. big = skull_placements([[(-100, -100), (200, -100), (200, 200), (-100, 200)]], 10, 30, seed=4) centre = [p for p in a if 20 < p[0] < 80 and 20 < p[1] < 80] assert centre and all(p in big for p in centre) def test_placements_empty_inputs(): assert skull_placements([], 10, 20) == [] assert skull_placements(SQUARE, 0, 20) == [] assert estimate_count([], 10, 0.7) == 0 assert estimate_count(SQUARE, 10, 0.7) > 100 # -------------------------------------------------------------------------- # Bout en bout (necessite inkex) # -------------------------------------------------------------------------- def run_extension(tmp_path, *args, source=SHAPES): pytest.importorskip("inkex") from skull_fill import SkullFill out = tmp_path / "out.svg" SkullFill().run([*args, "--output={}".format(out), source]) # Apres un message d'erreur, inkex n'ecrit pas de fichier de sortie. return out.read_text(encoding="utf-8") if out.exists() else "" def written_rings(svg): """Anneaux de chaque chemin ecrit par l'extension (M ... l ... z).""" import inkex paths = [] for d in re.findall(r' d="(M[^"]*z)"', svg): rings = [] for segment in inkex.Path(d).to_absolute(): if segment.letter == "M": rings.append([(segment.x, segment.y)]) elif segment.letter == "L": rings[-1].append((segment.x, segment.y)) paths.append(rings) assert paths return paths def test_end_to_end_default(tmp_path): svg = run_extension(tmp_path, "--id=rect1") assert "Skull fill" in svg assert 'id="rect1"' in svg # Pret pour le laser : ni masque, ni clone, ni blanc, que des chemins pleins. for forbidden in ("clipPath", "clip-path", "", 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, memes defauts.""" root = ET.parse(os.path.join(HERE, "skull_fill.inx")).getroot() params = {elem.get("name"): (elem.text or "").strip() for elem in root.iter() if elem.tag.rsplit("}", 1)[-1] == "param"} with open(os.path.join(HERE, "skull_fill.py"), encoding="utf-8") as handle: source = handle.read() arguments = dict(re.findall(r'add_argument\("--(\w+)".*default="?([^")]+)"?\)', source)) assert set(params) == set(arguments) for name, default in arguments.items(): if name in ("tab", "unit", "motif"): continue inx = params[name] if default in ("True", "False"): assert inx == default.lower(), name else: assert float(inx) == float(default), name 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, "skull_fill.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