Skip to content

Instantly share code, notes, and snippets.

@zeebo
Last active September 2, 2018 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeebo/a09b734d49cb79edc758183f12e36b4e to your computer and use it in GitHub Desktop.
Save zeebo/a09b734d49cb79edc758183f12e36b4e to your computer and use it in GitHub Desktop.
Minimal Go like testing in Python
import inspect
import sys
import time
import traceback
def objects(x):
return (getattr(x, n) for n in dir(x))
def isTest(obj):
return inspect.isfunction(obj) and obj.__name__.startswith("test") and \
len(inspect.signature(obj).parameters) == 0
def collectTests(mod):
return [obj for obj in objects(mod) if isTest(obj)]
def dur(start, end):
return '({:.02f}s)'.format(end - start)
def formatException(ex):
info = traceback.extract_tb(sys.exc_info()[-1])[-1]
name, msg = ex.__class__.__name__, str(ex)
if name == "AssertionError" and msg == "": # no assert args? use expr
msg = info.line.strip()[7:]
return "{}:{}: {}: {}".format(info.filename, info.lineno, name, msg)
def p(fmt, *args):
print(fmt.format(*args))
def main():
try:
assert False
print("Assertions must be enabled in tests")
sys.exit(1)
except AssertionError:
pass
mod = inspect.getmodule(inspect.stack()[1][0])
verbose = "-v" in sys.argv
failed = False
mstart = time.time()
for test in collectTests(mod):
name = test.__name__
try:
if verbose:
p("=== RUN {}", name)
start = time.time()
test()
end = time.time()
if verbose:
p("--- PASS: {} {}", name, dur(start, end))
except Exception as ex:
end = time.time()
p("--- FAIL: {} {}", name, dur(start, end))
p(" {}", formatException(ex))
failed = True
mend = time.time()
if failed:
p("FAIL\t{}\t{}", mod.__file__, dur(mstart, mend))
sys.exit(1)
p("ok\t{}\t{}", mod.__file__, dur(mstart, mend))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment