[Python-Dev] Unittest PEP do's and don'ts (BDFL pronouncement)

Michael Foord fuzzyman at voidspace.org.uk
Wed Jul 16 23:37:46 CEST 2008


C. Titus Brown wrote:
> On Wed, Jul 16, 2008 at 02:15:29PM -0700, C. Titus Brown wrote:
> -> At this point I might suggest taking a look at the nose and py.test
> -> discovery rules and writing a simple test discovery system to find &
> -> wrap 'test_' functions/classes and doctests in a unittest wrapper.
> -> 
> -> Many people use nose and py.test (which use remarkably similar test
> -> discovery procedures, note) and the basic algorithm is pretty well
> -> worked out.  And, since nose wraps such tests in unittests anyway, it
> -> can be made entirely compatible with pre-existing TestRunner
> -> derivatives.
>
> Sorry for the second message, but... let's compare:
>
> test_sort.py:
>  #! /usr/bin/env python
>  import unittest
>  class Test(unittest.TestCase):
>   def test_me(self):
>      seq = [ 5, 4, 1, 3, 2 ]
>      seq.sort()
>      self.assertEqual(seq, [1, 2, 3, 4, 5])
>
>  if __name__ == '__main__':
>     unittest.main()
>
> with
>
> test_sort2.py :
>
>  def test_me():
>     seq = [ 5, 4, 1, 3 2 ]
>     seq.sort()
>     assert seq == [1, 2, 3, 4, 5]
>
> The *only value* that unittest adds here is in the 'assertEqual'
> statement, which (I think) returns a richer error message than 'assert'.
>
>   

But if you exclude the import and class definition (two lines), then the 
test methods themselves are identical - except with unittest you have 
the advantage of the 'assertEquals' error collecting and reporting.

The boilerplate at the end is useful for running the test file in 
isolation, but you don't include anything comparable in the second example.


> If I could run the second program by doing
>
> 	unittest.discover_tests('test_sort2.py')
>
> I would be a very happy man... right now it requires installing nose or
> py.test.
>
>   
What about if you could run all tests in a project (of the first kind) with:

tests = unittest.discover_tests('path/', filter='*test.py')
unittest.run_tests(tests)

(or even just the first line).

With 'discover_tests' recursively globbing the path provided and 
collecting test files as modules.

Michael



> cheers,
> --titus
>   


-- 
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/
http://www.trypython.org/
http://www.ironpython.info/
http://www.theotherdelia.co.uk/
http://www.resolverhacks.net/



More information about the Python-Dev mailing list