(
filename: str, result: str, keep_version: bool = False
)
| 53 | """ |
| 54 | |
| 55 | def snapshot( |
| 56 | filename: str, result: str, keep_version: bool = False |
| 57 | ) -> None: |
| 58 | filepath = Path(current_file).parent / "snapshots" / filename |
| 59 | |
| 60 | if not keep_version: |
| 61 | result = _sanitize_version(result) |
| 62 | |
| 63 | # If snapshot directory doesn't exist, create it |
| 64 | maybe_make_dirs(filepath) |
| 65 | |
| 66 | def normalize(string: str) -> str: |
| 67 | return string.replace("\r\n", "\n") |
| 68 | |
| 69 | result = normalize(result) |
| 70 | |
| 71 | # If doesn't exist, create snapshot |
| 72 | if not filepath.exists(): |
| 73 | filepath.write_text(result) |
| 74 | print("Snapshot updated") |
| 75 | return |
| 76 | |
| 77 | # Read snapshot |
| 78 | expected = normalize(filepath.read_text()) |
| 79 | |
| 80 | assert result, "Result is empty" |
| 81 | assert expected, "Expected is empty" |
| 82 | |
| 83 | def write_result() -> None: |
| 84 | filepath.write_text(result) |
| 85 | |
| 86 | is_json = filename.endswith(".json") |
| 87 | if is_json: |
| 88 | import json |
| 89 | |
| 90 | expected_json = json.loads(expected) |
| 91 | result_json = json.loads(result) |
| 92 | |
| 93 | if expected_json != result_json: |
| 94 | write_result() |
| 95 | print("Snapshot updated") |
| 96 | |
| 97 | assert expected_json == result_json |
| 98 | else: |
| 99 | text_diff = "\n".join( |
| 100 | list( |
| 101 | difflib.unified_diff( |
| 102 | expected.splitlines(), |
| 103 | result.splitlines(), |
| 104 | lineterm="", |
| 105 | ) |
| 106 | ) |
| 107 | ) |
| 108 | |
| 109 | if result != expected: |
| 110 | write_result() |
| 111 | print("Snapshot updated") |
| 112 |
searching dependent graphs…