在哪里放置 python 个单元测试

Where to place python unittests

我的目录结构如下:

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

MyClassTest.py 可执行:

import unittest
from . import MyClass    

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

...
.....

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

我在以下行收到错误 "Parent module '' not loaded, cannot perform relative import":

from . import MyClass

我想将单元测试放在被测试模块旁边的 'unittests' 目录中。有没有办法做到这一点并访问我正在测试的父目录中的所有模块?

你试过运行这样的测试了吗:

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

这应该可以正确找到您的模块。参见 Test Discovery

建议的结构是这样查看您的结构:

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

运行 my_app 中的所有内容,这样您将在测试代码和核心代码之间使用所有相同的模块引用。

根据您自己的喜好和您希望导入模块的方式使用您想要的任何布局:

要找到你的 unittests 文件夹,因为名称不是常规名称(单元测试脚本默认查找 test 文件夹),你可以使用 discover 选项unittest 模块的说明如何找到您的测试脚本:

python -m unittest discover unittests

请注意,第一个 unittest 是 Python 模块,第二个 unittests(带有 s)是您放置测试脚本的目录.

另一种选择是使用 nosetest 模块(或其他新的单元测试模块,如 pytesttox),无论您将它们放在何处,它都会自动找到您的测试脚本:

nosetests -vv

要修复您的导入错误,您应该使用完整的相对(或绝对)路径:

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