[Tutor] Best way to setup Unit Testing?

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Jul 11 16:20:39 CEST 2013


On 11 July 2013 13:37, Srinivas Nyayapati <shireenrao at gmail.com> wrote:
>>> Projects/
>>>    MyApp/
>>>        __init__.py
>>>        myapp.py
>>>        tests/
>>>            __init__.py
>>>            test_myapp.py
>>
>> This gives a nice clean distinction between your main code and your
>> tests. It is also useful if you don't want to install the tests on the
>> target machines since you can just exclude the tests package in your
>> setup.py when creating an sdist.
>>
>> If you do include the tests and add a __main__.py in the tests folder
>> then users can still run tests with
>>
>> python -m MyApp.tests
>
> Love this idea! Would you know how I would run the test_*.py scripts
> from __main__.py


There are many different ways but for example let's say you're using
unittest and you have

Projects/
   Makefile
   MyApp/
       __init__.py
       myapp1.py
       myapp2.py
       tests/
           __init__.py
           __main__.py
           test_myapp1.py
           test_myapp2.py

Then e.g. test_myapp1.py looks like:

import unittest

from MyApp.myapp1 import stuff

class TestMyApp(unittest.TestCase):
    def test_stuff():
        self.assertTrue(False)
        # blah blah

if __name__ == "__main__":
    unittest.main()

Then __main__.py looks like:

import unittest
from MyApp.tests import test_myapp1, test_myapp2

tests = unittest.TestLoader()
suite1 = loadTestsFromModule(test_myapp1)
suite2 = loadTestsFromModule(test_myapp2)
alltests = unittest.TestSuite([suite1, suite2])

if __name__ == "__main__":
    unittest.TextTestRunner().run(alltests)

The above is mainly off the top of my head and may not actually work
but hopefully you get the idea. Now you can run just a few tests with:

$ python -m MyApp.tests.test_myapp1

or run all the tests with

$ python -m MyApp.tests

I would still put the above line into a Makefile and use 'make test'
while working on the code. That way I don't need to remember what to
type.

One last thing is that I wouldn't use CamelCase names for
packages/modules. My preference is for all package and module names to
be lower-case. When I see MyApp in the code it looks to me like a
class rather than a module.


Oscar


More information about the Tutor mailing list