1010from operator import attrgetter
1111from os import PathLike
1212from pathlib import Path , PurePath
13+ from random import random
1314from tempfile import mkdtemp
1415from typing import Any , Awaitable , Union , Optional , Callable , Iterable , TYPE_CHECKING
1516
@@ -33,6 +34,18 @@ class SVGImageExtension(SingleFileSnapshotExtension):
3334 _file_extension = "svg"
3435 _write_mode = WriteMode .TEXT
3536
37+ def _read_snapshot_data_from_location (self , * args , ** kwargs ) -> Optional ["SerializableData" ]:
38+ """Normalize SVG data right after they are loaded from persistent storage."""
39+ data = super ()._read_snapshot_data_from_location (* args , ** kwargs )
40+ if data is not None :
41+ data = normalize_svg (data )
42+ return data
43+
44+ def serialize (self , * args , ** kwargs ) -> "SerializedData" :
45+ """Normalize SVG data before they get compared against a snapshot and
46+ before they get persisted to storage."""
47+ return normalize_svg (super ().serialize (* args , ** kwargs ))
48+
3649
3750class TemporaryDirectory :
3851 """A temporary that survives forking.
@@ -71,10 +84,14 @@ class PseudoApp:
7184 console : PseudoConsole
7285
7386
74- def rename_styles (svg : str , suffix : str ) -> str :
75- """Rename style names to prevent clashes when combined in HTML report."""
76- return re .sub (r"terminal-(\d+)-r(\d+)" , rf"terminal-\1-r\2-{ suffix } " , svg )
87+ def individualize_svg (svg : str , unique_id : Optional [str ] = None ) -> str :
88+ """Inject a random id, à la rich.Console.export_svg()."""
89+ unique_id = str (int (random () * 1e10 )) if unique_id is None else unique_id
90+ return re .sub (r"\bterminal(?:-\d+)?-([\w-]+)" , rf"terminal-{ unique_id } -\1" , svg )
7791
92+ def normalize_svg (svg : str ) -> str :
93+ """Strip the unique id generated by rich.Console.export_svg()."""
94+ return re .sub (r"\bterminal-\d+-([\w-]+)" , r"terminal-\1" , svg )
7895
7996def pytest_addoption (parser ):
8097 parser .addoption (
@@ -301,8 +318,8 @@ def retrieve_svg_diffs(
301318 n += 1
302319 diffs .append (
303320 SvgSnapshotDiff (
304- snapshot = rename_styles (str (expect_svg_text ), f"exp { n } " ),
305- actual = rename_styles (svg_text , f"act { n } " ),
321+ snapshot = individualize_svg (str (expect_svg_text )),
322+ actual = individualize_svg (svg_text ),
306323 test_name = name ,
307324 path = full_path ,
308325 line_number = line_index + 1 ,
0 commit comments