def write_snapshot(self, *, data: "SerializedData", index: int) -> None: """ Utility method for writing the contents of a snapshot assertion. Will call `_pre_write`, then perform `write` and finally `_post_write`. This method is _final_, do not override. You can override `_write_snapshot_fossil` in a subclass to change behaviour. """ self._pre_write(data=data, index=index) snapshot_location = self.get_location(index=index) if not self.test_location.matches_snapshot_location(snapshot_location): warning_msg = gettext( "{line_end}Can not relate snapshot location '{}' to the test location." "{line_end}Consider adding '{}' to the generated location." ).format( snapshot_location, self.test_location.filename, line_end="\n", ) warnings.warn(warning_msg) snapshot_name = self.get_snapshot_name(index=index) if not self.test_location.matches_snapshot_name(snapshot_name): warning_msg = gettext( "{line_end}Can not relate snapshot name '{}' to the test location." "{line_end}Consider adding '{}' to the generated name." ).format( snapshot_name, self.test_location.testname, line_end="\n", ) warnings.warn(warning_msg) snapshot_fossil = SnapshotFossil(location=snapshot_location) snapshot_fossil.add(Snapshot(name=snapshot_name, data=data)) self._write_snapshot_fossil(snapshot_fossil=snapshot_fossil) self._post_write(data=data, index=index)
def read_file(cls, filepath: str) -> "SnapshotFossil": """ Read the raw snapshot data (str) from the snapshot file into a dict of snapshot name to raw data. This does not attempt any deserialization of the snapshot data. """ name_marker_len = len(cls._marker_name) indent_len = len(cls._indent) snapshot_fossil = SnapshotFossil(location=filepath) try: with open(filepath, "r", encoding="utf-8", newline=None) as f: test_name = None snapshot_data = "" for line in f: if line.startswith(cls._marker_name): test_name = line[name_marker_len:].strip( f" {cls._marker_crn}") snapshot_data = "" continue elif test_name is not None: if line.startswith(cls._indent): snapshot_data += line[indent_len:] elif line.startswith( cls._marker_divider) and snapshot_data: snapshot_fossil.add( Snapshot( name=test_name, data=snapshot_data.rstrip(os.linesep), )) except FileNotFoundError: pass return snapshot_fossil
def test_does_not_write_non_binary(testdir, snapshot_single: "SnapshotAssertion"): snapshot_fossil = SnapshotFossil(location=str( Path(testdir.tmpdir).joinpath("snapshot_fossil.raw")), ) snapshot_fossil.add(Snapshot(name="snapshot_name", data="non binary data")) with pytest.raises(TypeError, match="Expected 'bytes', got 'str'"): snapshot_single.extension._write_snapshot_fossil( snapshot_fossil=snapshot_fossil) assert not Path(snapshot_fossil.location).exists()
def _read_snapshot_fossil(self, *, snapshot_location: str) -> "SnapshotFossil": snapshot_fossil = SnapshotFossil(location=snapshot_location) snapshot_fossil.add(Snapshot(name=Path(snapshot_location).stem)) return snapshot_fossil