Skip to content

Instantly share code, notes, and snippets.

@markscottwright
Created July 6, 2023 19:33
Show Gist options
  • Save markscottwright/c60df88052dbca3d95c6afed239c6bcf to your computer and use it in GitHub Desktop.
Save markscottwright/c60df88052dbca3d95c6afed239c6bcf to your computer and use it in GitHub Desktop.
Quick and dirty snapshot testing in python
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