Skip to content

Instantly share code, notes, and snippets.

@PaulMaynard
Created May 16, 2020 20:45
Show Gist options
  • Save PaulMaynard/1089e9167fbe674f6c248c626ecf9810 to your computer and use it in GitHub Desktop.
Save PaulMaynard/1089e9167fbe674f6c248c626ecf9810 to your computer and use it in GitHub Desktop.
Barebones python testing framework
import sys
tests = set()
def run_tests():
succ = True
for fun in tests:
for n, a, k, e in fun._tests:
r = fun(*a, **k)
if r != e:
succ = False
print(f"Test failed: {n}\n Expected: {e}\n Got: {r}",
file=sys.stderr)
else:
print(f"Test suceeded: {n}")
if succ:
print("All tests passed!")
else:
print("Some tests failed!")
def test(args, res, name=None, *, kwargs=None):
def inner(fun):
tests.add(fun)
nonlocal name
nonlocal kwargs
if not hasattr(fun, '_tests'):
fun._tests = []
if kwargs is None:
kwargs = {}
if name is None:
name = f"{fun.__name__} test {len(fun._tests)}"
fun._tests.append((name, args, kwargs, res))
return fun
return inner
@test((1, 2), 3, "1 + 2 = 3")
@test((2, 2), 4, "2 + 2 = 4")
def add(x, y):
return x * y
run_tests()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment