Skip to content

Instantly share code, notes, and snippets.

@timm
Last active August 29, 2015 14:18
Show Gist options
  • Select an option

  • Save timm/67ffa3b8bd0f293974d8 to your computer and use it in GitHub Desktop.

Select an option

Save timm/67ffa3b8bd0f293974d8 to your computer and use it in GitHub Desktop.
Simple python unit test engine. Inspired by Kent Beck's video https://www.youtube.com/watch?v=nIonZ6-4nuU.
"""
ok : a simple python unit test engine
Copyright (c) Tim Menzies, 2015, WTFPL http://www.wtfpl.net/
Inspired by Kent Beck's video
https://www.youtube.com/watch?v=nIonZ6-4nuU.
For example usage, see the _ok function (at end).
For help, see [email protected].
"""
##-- top-level driver - ----------------------------
def ok(*lst):
for one in items(lst):
unittest(one)
return one
class unittest:
tries = fails = 0 # tracks the record so far
def __init__(i,test):
unittest.tries += 1
try:
test()
except Exception,e:
unittest.fails += 1
i.report(e,test)
def report(i,e,test):
print "# TRIES= %s FAIL= %s TEST= %s : %s" % (
unittest.tries, unittest.fails,
test.__name__, e)
#---| misc support code |--------------------------
def items(x):
"Recursively yield non-list items in nested list"
def listp(x): return isinstance(x,(list,tuple))
if listp(x):
for y in x:
for z in items(y):
yield z
else:
yield x
#---| example calls |------------------------------
# how to always run+test something at load time
@ok
def noop(): return True
@ok
def oops(): 5/0
def _ok():
ok(oops,noop,lambda: 1+1,lambda: 4/0)
ok(oops)
ok([oops,noop])
assert unittest.tries == 9
assert unittest.fails == 5
#---| maybe, test the test engine |---------------
if __name__ == '__main__':
_ok()
print "Success!!!"
@timm
Copy link
Author

timm commented Apr 1, 2015

Sample output:

$ python unittest.py
Traceback (most recent call last):
  File "unittest.py", line 34, in run
    test()
  File "unittest.py", line 44, in oops
    5/0
ZeroDivisionError: integer division or modulo by zero
Done

@timm
Copy link
Author

timm commented Apr 1, 2015

I changed the print routines to be more succinct and i checked this can run lambda bodies.

And I allows "ok" to be a decorator so we can (optionally) run and test things at load time.

And I added a few more uses cases (sample of how to call this) into the _ok function

Now. some sample output is:

# TRIES= 2 FAIL= 1 TEST= oops : integer division or modulo by zero
# TRIES= 3 FAIL= 2 TEST= oops : integer division or modulo by zero
# TRIES= 6 FAIL= 3 TEST= <lambda> : integer division or modulo by zero
# TRIES= 7 FAIL= 4 TEST= oops : integer division or modulo by zero
# TRIES= 8 FAIL= 5 TEST= oops : integer division or modulo by zero
Success!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment