Created
July 6, 2023 19:33
-
-
Save markscottwright/c60df88052dbca3d95c6afed239c6bcf to your computer and use it in GitHub Desktop.
Quick and dirty snapshot testing in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MySnapshot: | |
NO_ARGUMENT = object() | |
def __init__(self, expected_value=NO_ARGUMENT): | |
self.expected_value = expected_value | |
def __eq__(self, other): | |
if self.expected_value is self.NO_ARGUMENT: | |
from inspect import currentframe, getframeinfo | |
caller_frame = getframeinfo(currentframe().f_back) | |
calling_filename = caller_frame.filename | |
calling_line = caller_frame.lineno # calling line is 1 based | |
replaced_contents = [] | |
with open(calling_filename) as f: | |
for line_no, l in enumerate(f.readlines()): | |
if line_no+1 == calling_line: | |
l = l.replace("MySnapshot()", f"MySnapshot({repr(other)})") | |
replaced_contents.append(l) | |
with open(calling_filename, 'w') as f: | |
f.writelines(replaced_contents) | |
return True | |
else: | |
return other == self.expected_value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment