简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM