| 1 |
import difflib |
| 2 |
import os |
| 3 |
from pathlib import Path |
| 4 |
from typing import Callable |
| 5 |
from typing import List |
| 6 |
from typing import Optional |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
|
| 11 |
def import_error_message(libname: str) -> str: |
| 12 |
return f"'{libname}' library is an optional dependency and must be installed explicitly when the fixture 'check' is used" |
| 13 |
|
| 14 |
|
| 15 |
def check_text_files( |
| 16 |
obtained_fn: "os.PathLike[str]", |
| 17 |
expected_fn: "os.PathLike[str]", |
| 18 |
fix_callback: Callable[[List[str]], List[str]] = lambda x: x, |
| 19 |
encoding: Optional[str] = None, |
| 20 |
) -> None: |
| 21 |
""" |
| 22 |
Compare two files contents. If the files differ, show the diff and write a nice HTML |
| 23 |
diff file into the data directory. |
| 24 |
|
| 25 |
:param obtained_fn: path to obtained file during current testing. |
| 26 |
|
| 27 |
:param expected_fn: path to the expected file, obtained from previous testing. |
| 28 |
|
| 29 |
:param encoding: encoding used to open the files. |
| 30 |
|
| 31 |
:param fix_callback: |
| 32 |
A callback to "fix" the contents of the obtained (first) file. |
| 33 |
This callback receives a list of strings (lines) and must also return a list of lines, |
| 34 |
changed as needed. |
| 35 |
The resulting lines will be used to compare with the contents of expected_fn. |
| 36 |
""" |
| 37 |
__tracebackhide__ = True |
| 38 |
|
| 39 |
obtained_fn = Path(obtained_fn) |
| 40 |
expected_fn = Path(expected_fn) |
| 41 |
obtained_lines = fix_callback(obtained_fn.read_text(encoding=encoding).splitlines()) |
| 42 |
expected_lines = expected_fn.read_text(encoding=encoding).splitlines() |
| 43 |
|
| 44 |
if obtained_lines != expected_lines: |
| 45 |
diff_lines = list( |
| 46 |
difflib.unified_diff(expected_lines, obtained_lines, lineterm="") |
| 47 |
) |
| 48 |
if len(diff_lines) <= 500: |
| 49 |
html_fn = obtained_fn.with_suffix(".diff.html") |
| 50 |
try: |
| 51 |
differ = difflib.HtmlDiff() |
| 52 |
html_diff = differ.make_file( |
| 53 |
fromlines=expected_lines, |
| 54 |
fromdesc=str(expected_fn), |
| 55 |
tolines=obtained_lines, |
| 56 |
todesc=str(obtained_fn), |
| 57 |
) |
| 58 |
except Exception as e: |
| 59 |
html_msg = "(failed to generate html diff: %s)" % e |
| 60 |
else: |
| 61 |
html_fn.write_text(html_diff, encoding="UTF-8") |
| 62 |
html_msg = str(html_fn) |
| 63 |
|
| 64 |
diff = ["FILES DIFFER:", str(expected_fn), str(obtained_fn)] |
| 65 |
diff += ["HTML DIFF: %s" % html_msg] |
| 66 |
diff += diff_lines |
| 67 |
raise AssertionError("\n".join(diff)) |
| 68 |
else: |
| 69 |
|
| 70 |
|
| 71 |
msg = [ |
| 72 |
"Files are different, but diff is too big ({} lines)".format( |
| 73 |
len(diff_lines) |
| 74 |
), |
| 75 |
f"- obtained: {obtained_fn}", |
| 76 |
f"- expected: {expected_fn}", |
| 77 |
] |
| 78 |
raise AssertionError("\n".join(msg)) |
| 79 |
|
| 80 |
|
| 81 |
def perform_regression_check( |
| 82 |
datadir: Path, |
| 83 |
original_datadir: Path, |
| 84 |
request: pytest.FixtureRequest, |
| 85 |
check_fn: Callable[[Path, Path], None], |
| 86 |
dump_fn: Callable[[Path], None], |
| 87 |
extension: str, |
| 88 |
basename: Optional[str] = None, |
| 89 |
fullpath: Optional["os.PathLike[str]"] = None, |
| 90 |
force_regen: bool = False, |
| 91 |
with_test_class_names: bool = False, |
| 92 |
obtained_filename: Optional["os.PathLike[str]"] = None, |
| 93 |
dump_aux_fn: Callable[[Path], List[str]] = lambda filename: [], |
| 94 |
) -> None: |
| 95 |
""" |
| 96 |
First run of this check will generate a expected file. Following attempts will always try to |
| 97 |
match obtained files with that expected file. |
| 98 |
|
| 99 |
If expected file needs to be updated, just enable `force_regen` argument. |
| 100 |
|
| 101 |
:param datadir: Fixture embed_data. |
| 102 |
:param original_datadir: Fixture embed_data. |
| 103 |
:param request: Pytest request object. |
| 104 |
:param check_fn: A function that receives as arguments, respectively, absolute path to |
| 105 |
obtained file and absolute path to expected file. It must assert if contents of file match. |
| 106 |
Function can safely assume that obtained file is already dumped and only care about |
| 107 |
comparison. |
| 108 |
:param dump_fn: A function that receive an absolute file path as argument. Implementor |
| 109 |
must dump file in this path. |
| 110 |
:param dump_aux_fn: A function that receives the same file path as ``dump_fn``, but may |
| 111 |
dump additional files to help diagnose this regression later (for example dumping image of |
| 112 |
3d views and plots to compare later). Must return the list of file names written (used to display). |
| 113 |
:param extension: Extension of files compared by this check. |
| 114 |
:param force_regen: if true it will regenerate expected file. |
| 115 |
:param with_test_class_names: if true it will use the test class name (if any) to compose |
| 116 |
the basename. |
| 117 |
:param obtained_filename: complete path to use to write the obtained file. By |
| 118 |
default will prepend `.obtained` before the file extension. |
| 119 |
..see: `data_regression.Check` for `basename` and `fullpath` arguments. |
| 120 |
""" |
| 121 |
import re |
| 122 |
|
| 123 |
assert not (basename and fullpath), "pass either basename or fullpath, but not both" |
| 124 |
|
| 125 |
__tracebackhide__ = True |
| 126 |
|
| 127 |
with_test_class_names = with_test_class_names or request.config.getoption( |
| 128 |
"with_test_class_names" |
| 129 |
) |
| 130 |
if basename is None: |
| 131 |
if (request.node.cls is not None) and (with_test_class_names): |
| 132 |
basename = re.sub(r"[\W]", "_", request.node.cls.__name__) + "_" |
| 133 |
else: |
| 134 |
basename = "" |
| 135 |
basename += re.sub(r"[\W]", "_", request.node.name) |
| 136 |
|
| 137 |
if fullpath: |
| 138 |
filename = source_filename = Path(fullpath) |
| 139 |
else: |
| 140 |
filename = datadir / (basename + extension) |
| 141 |
source_filename = original_datadir / (basename + extension) |
| 142 |
|
| 143 |
def make_location_message(banner: str, filename: Path, aux_files: List[str]) -> str: |
| 144 |
msg = [banner, f"- {filename}"] |
| 145 |
if aux_files: |
| 146 |
msg.append("Auxiliary:") |
| 147 |
msg += [f"- {x}" for x in aux_files] |
| 148 |
return "\n".join(msg) |
| 149 |
|
| 150 |
force_regen = force_regen or request.config.getoption("force_regen") |
| 151 |
regen_all = request.config.getoption("regen_all") |
| 152 |
if regen_all: |
| 153 |
source_filename.parent.mkdir(parents=True, exist_ok=True) |
| 154 |
dump_fn(source_filename) |
| 155 |
dump_aux_fn(source_filename) |
| 156 |
elif not filename.is_file(): |
| 157 |
source_filename.parent.mkdir(parents=True, exist_ok=True) |
| 158 |
dump_fn(source_filename) |
| 159 |
aux_created = dump_aux_fn(source_filename) |
| 160 |
|
| 161 |
msg = make_location_message( |
| 162 |
"File not found in data directory, created:", source_filename, aux_created |
| 163 |
) |
| 164 |
pytest.fail(msg) |
| 165 |
else: |
| 166 |
if obtained_filename is None: |
| 167 |
if fullpath: |
| 168 |
obtained_filename = (datadir / basename).with_suffix( |
| 169 |
".obtained" + extension |
| 170 |
) |
| 171 |
else: |
| 172 |
obtained_filename = filename.with_suffix(".obtained" + extension) |
| 173 |
|
| 174 |
dump_fn(Path(obtained_filename)) |
| 175 |
|
| 176 |
try: |
| 177 |
check_fn(Path(obtained_filename), Path(filename)) |
| 178 |
except AssertionError: |
| 179 |
if force_regen: |
| 180 |
dump_fn(source_filename) |
| 181 |
aux_created = dump_aux_fn(source_filename) |
| 182 |
msg = make_location_message( |
| 183 |
"Files differ and --force-regen set, regenerating file at:", |
| 184 |
source_filename, |
| 185 |
aux_created, |
| 186 |
) |
| 187 |
pytest.fail(msg) |
| 188 |
else: |
| 189 |
dump_aux_fn(Path(obtained_filename)) |
| 190 |
raise |