如果你正在编写一个库或应用程序,那么单元测试文件应该放在哪里?
将测试文件与主应用程序代码分开是很好的,但将它们放在应用程序根目录中的“tests”子目录中是很尴尬的,因为这会使导入将要测试的模块变得更加困难。
这里是否存在最佳实践?
如果你正在编写一个库或应用程序,那么单元测试文件应该放在哪里?
将测试文件与主应用程序代码分开是很好的,但将它们放在应用程序根目录中的“tests”子目录中是很尴尬的,因为这会使导入将要测试的模块变得更加困难。
这里是否存在最佳实践?
当前回答
只有一个测试文件
如果只有1个测试文件,建议将其放在顶级目录中:
module/
lib/
__init__.py
module.py
test.py
在CLI下运行测试
python test.py
许多测试文件
如果有很多测试文件,将其放在tests文件夹中:
module/
lib/
__init__.py
module.py
tests/
test_module.py
test_module_function.py
# test_module.py
import unittest
from lib import module
class TestModule(unittest.TestCase):
def test_module(self):
pass
if __name__ == '__main__':
unittest.main()
在CLI下运行测试
# In top-level /module/ folder
python -m tests.test_module
python -m tests.test_module_function
使用单元测试发现
单元测试发现将在包文件夹中找到所有测试。
在tests/文件夹中创建__init__.py
module/
lib/
__init__.py
module.py
tests/
__init__.py
test_module.py
test_module_function.py
在CLI下运行测试
# In top-level /module/ folder
# -s, --start-directory (default current directory)
# -p, --pattern (default test*.py)
python -m unittest discover
参考
用于测试布局的pytest良好实践 unittest
单元测试框架
鼻子 nose2 pytest
其他回答
When writing a package called "foo", I will put unit tests into a separate package "foo_test". Modules and subpackages will then have the same name as the SUT package module. E.g. tests for a module foo.x.y are found in foo_test.x.y. The __init__.py files of each testing package then contain an AllTests suite that includes all test suites of the package. setuptools provides a convenient way to specify the main testing package, so that after "python setup.py develop" you can just use "python setup.py test" or "python setup.py test -s foo_test.x.SomeTestSuite" to the just a specific suite.
只有一个测试文件
如果只有1个测试文件,建议将其放在顶级目录中:
module/
lib/
__init__.py
module.py
test.py
在CLI下运行测试
python test.py
许多测试文件
如果有很多测试文件,将其放在tests文件夹中:
module/
lib/
__init__.py
module.py
tests/
test_module.py
test_module_function.py
# test_module.py
import unittest
from lib import module
class TestModule(unittest.TestCase):
def test_module(self):
pass
if __name__ == '__main__':
unittest.main()
在CLI下运行测试
# In top-level /module/ folder
python -m tests.test_module
python -m tests.test_module_function
使用单元测试发现
单元测试发现将在包文件夹中找到所有测试。
在tests/文件夹中创建__init__.py
module/
lib/
__init__.py
module.py
tests/
__init__.py
test_module.py
test_module_function.py
在CLI下运行测试
# In top-level /module/ folder
# -s, --start-directory (default current directory)
# -p, --pattern (default test*.py)
python -m unittest discover
参考
用于测试布局的pytest良好实践 unittest
单元测试框架
鼻子 nose2 pytest
我使用tests/目录,然后使用相对导入导入主要应用程序模块。在MyApp/tests/foo.py中,可能有:
from .. import foo
导入MyApp。foo模块。
在c#中,我通常将测试分离到单独的程序集中。
在Python中——到目前为止——我倾向于编写doctests,其中测试位于函数的文档字符串中,或者将它们放在模块底部的if __name__ == "__main__"块中。
我最近开始用Python编程,所以我还没有机会找到最佳实践。 但是,我已经写了一个模块,它可以找到所有的测试并运行它们。
所以,我有:
app/ appfile.py test/ appfileTest.py
当我进入更大的项目时,我得看看情况如何。