如果你正在编写一个库或应用程序,那么单元测试文件应该放在哪里?
将测试文件与主应用程序代码分开是很好的,但将它们放在应用程序根目录中的“tests”子目录中是很尴尬的,因为这会使导入将要测试的模块变得更加困难。
这里是否存在最佳实践?
如果你正在编写一个库或应用程序,那么单元测试文件应该放在哪里?
将测试文件与主应用程序代码分开是很好的,但将它们放在应用程序根目录中的“tests”子目录中是很尴尬的,因为这会使导入将要测试的模块变得更加困难。
这里是否存在最佳实践?
当前回答
我们使用
app/src/code.py
app/testing/code_test.py
app/docs/..
在每个测试文件中,我们插入../src/ sys.path。这不是最好的解决办法,但很有效。我认为如果有人提出类似java中的maven之类的东西,给你提供标准的约定,无论你在做什么项目,都可以工作,那就太好了。
其他回答
根据我用Python开发测试框架的经验,我建议将Python单元测试放在一个单独的目录中。维护对称的目录结构。这将有助于只打包核心库,而不打包单元测试。下面是通过原理图实现的。
<Main Package>
/ \
/ \
lib tests
/ \
[module1.py, module2.py, [ut_module1.py, ut_module2.py,
module3.py module4.py, ut_module3.py, ut_module.py]
__init__.py]
通过这种方式,当您使用rpm打包这些库时,您可以只打包主库模块(仅)。这有助于可维护性,特别是在敏捷环境中。
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.
我最近开始用Python编程,所以我还没有机会找到最佳实践。 但是,我已经写了一个模块,它可以找到所有的测试并运行它们。
所以,我有:
app/ appfile.py test/ appfileTest.py
当我进入更大的项目时,我得看看情况如何。
我建议你在GitHub上查看一些主要的Python项目,并获得一些想法。
当你的代码变大,你添加了更多的库,最好在你有setup.py的同一个目录下创建一个测试文件夹,并为每种测试类型镜像你的项目目录结构(unittest, integration,…)
例如,如果你有一个这样的目录结构:
myPackage/
myapp/
moduleA/
__init__.py
module_A.py
moduleB/
__init__.py
module_B.py
setup.py
添加测试文件夹后,您将拥有如下目录结构:
myPackage/
myapp/
moduleA/
__init__.py
module_A.py
moduleB/
__init__.py
module_B.py
test/
unit/
myapp/
moduleA/
module_A_test.py
moduleB/
module_B_test.py
integration/
myapp/
moduleA/
module_A_test.py
moduleB/
module_B_test.py
setup.py
许多正确编写的Python包使用相同的结构。Boto包就是一个很好的例子。 检查https://github.com/boto/boto
我也倾向于把我的单元测试放在文件本身中,正如Jeremy Cantrell上面所指出的,尽管我倾向于不把测试函数放在主体中,而是把所有东西都放在一个文件中
if __name__ == '__main__':
do tests...
块。这最终会将文档添加到文件中,作为如何使用您正在测试的python文件的“示例代码”。
我应该补充一点,我倾向于编写非常紧凑的模块/类。如果你的模块需要大量的测试,你可以把它们放在另一个测试中,但即使这样,我仍然会补充:
if __name__ == '__main__':
import tests.thisModule
tests.thisModule.runtests
这让任何阅读源代码的人都知道到哪里去寻找测试代码。