unittest help needed!

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Thu Jan 14 13:46:13 EST 2010


On 06:33 pm, rolf.oltmans at gmail.com wrote:
>Hi Python gurus,
>
>I'm quite new to Python and have a problem. Following code resides in
>a file named test.py
>---
>import unittest
>
>
>class result(unittest.TestResult):
>    pass
>
>
>
>class tee(unittest.TestCase):
>    def test_first(self):
>        print 'first test'
>        print '-------------'
>    def test_second(self):
>        print 'second test'
>        print '-------------'
>    def test_final(self):
>        print 'final method'
>        print '-------------'
>
>r = result()
>suite = unittest.defaultTestLoader.loadTestsFromName('test.tee')
>
>suite.run(r)
>
>---
>
>Following is the output when I run it
>---
>final method
>-------------
>first test
>-------------
>second test
>-------------
>final method
>-------------
>first test
>-------------
>second test
>-------------
>
>---
>
>Looks like it's running every test twice, I cannot figure out why?

When you run test.py, it gets to the loadTestsFromName line.  There, it
imports the module named "test" in order to load tests from it.  To 
import
that module, it runs test.py again.  By the time it finishes running the
contents of test.py there, it has run all of your tests once, since part
of test.py is "suite.run(r)".  Having finished that, the import of the 
"test"
module is complete and the "loadTestsFromName" call completes.  Then, 
the
"suite.run(r)" line runs again, and all your tests run again.

You want to protect the suite stuff in test.py like this:

    if __name__ == '__main__':
        ...

Or you want to get rid of it entirely and use `python -m unittest 
test.py`
(with a sufficiently recent version of Python), or another runner, like
Twisted Trial or one of the many others available.

Jean-Paul



More information about the Python-list mailing list