Posted By

manatlan on 10/21/09


Tagged

python tech unittests


Versions (?)

Python unittests with assert statement (with exceptions catching)


 / Published in: Python
 

method 'E' (in fact a decorator) catch the execption and return it, so it's possible to use the good old assert statement.

  1. import sys
  2.  
  3. def E(m):
  4. def _c(*a,**k):
  5. try:
  6. return m(*a,**k)
  7. except:
  8. return sys.exc_info()[0]
  9. return _c
  10.  
  11. def methodToTest(x):
  12. return 2/x
  13.  
  14. if __name__ == "__main__":
  15. assert methodToTest(2)==1
  16. assert methodToTest(1)==2
  17. assert E(methodToTest)(0)==ZeroDivisionError
  18.  
  19. # alternative way :
  20.  
  21. methodToTest = E(methodToTest) # force decoration
  22. assert methodToTest(1)==2
  23. assert methodToTest(2)==1
  24. assert methodToTest(0)==ZeroDivisionError

Report this snippet  

You need to login to post a comment.