safe_malloc
safe_malloc

Reputation: 886

Where to place python unittests

I have a directory structure as follows:

DirA
    __init__.py
    MyClass.py
    unittests   <------------------directory
        MyClassTest.py

MyClassTest.py is executable:

import unittest
from . import MyClass    

class MyClassTestCase(unittest.TestCase):
    """ Testcase """

...
.....

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

I get an error "Parent module '' not loaded, cannot perform relative import" at the line:

from . import MyClass

I would like to place unittests in a 'unittests' directory beside the modules being tested. Is there a way to do this and have access to all the modules in the parent directory which I am testing?

Upvotes: 1

Views: 1378

Answers (3)

gaborous
gaborous

Reputation: 16570

Use whatever layout you want, depending on your own preferences and the way you want your module to be imported:

To find your unittests folder, since the name is not the conventional one (unit test scripts by default look for a test folder), you can use the discover option of the unittest module to tell how to find your test scripts:

python -m unittest discover unittests

Note that the first unittest is the Python module, and the second unittests (with an s) is your directory where you have placed your testing scripts.

Another alternative is to use the nosetest module (or other new unit testing modules like pytest or tox) which should automatically find your testing script, wherever you place them:

nosetests -vv

And to fix your import error, you should use the full relative (or absolute) path:

from ..MyClass import MyClass # Relative path from the unittests folder
from MyClass import MyClass # Absolute path from the root folder, which will only work for some unit test modules or if you configure your unit test module to run the tests from the root

Upvotes: 1

jayant
jayant

Reputation: 2389

Have you tried running the tests like so:

cd DirA
python -m unittest discover unittests "*Test.py"

This should find your modules correctly. See Test Discovery

Upvotes: 2

idjaw
idjaw

Reputation: 26560

A suggested structure, would be to look at your structure like this:

my_app
    my_pkg
        __init__.py
        module_foo.py
    test
        __init__.py
        test_module_foo.py
    main.py

Run everything from within my_app, this way you will use all the same module references between your test code and core code.

Upvotes: 0

Related Questions