[英]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: MyClassTest.py是可执行的:
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. 我想将unittests放在被测模块旁边的'unittests'目录中。 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: 要查找unittests
文件夹,由于名称不是常规名称(默认情况下单元测试脚本查找test
文件夹),您可以使用unittest
模块的discover
选项来告诉如何查找测试脚本:
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. 需要注意的是,第一unittest
是Python模块,第二unittests
(用s
)是你的目录,你已经把你的测试脚本。
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: 另一种方法是使用nosetest
模块(或其他新的单元测试模块,如pytest
或tox
),它们应该自动找到你的测试脚本,无论你放在哪里:
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. 从my_app
运行所有内容,这样您将在测试代码和核心代码之间使用所有相同的模块引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.