如果你正在编写一个库或应用程序,那么单元测试文件应该放在哪里?
将测试文件与主应用程序代码分开是很好的,但将它们放在应用程序根目录中的“tests”子目录中是很尴尬的,因为这会使导入将要测试的模块变得更加困难。
这里是否存在最佳实践?
如果你正在编写一个库或应用程序,那么单元测试文件应该放在哪里?
将测试文件与主应用程序代码分开是很好的,但将它们放在应用程序根目录中的“tests”子目录中是很尴尬的,因为这会使导入将要测试的模块变得更加困难。
这里是否存在最佳实践?
当前回答
对于文件module.py,单元测试通常应该被称为test_module.py,遵循python命名约定。
test_module.py有几个常用的存放位置:
和module.py在同一个目录下。 在../tests/test_module.py中(与代码目录处于同一级别)。 在tests/test_module.py中(代码目录下的一级)。
我更喜欢#1,因为它很容易找到测试并导入它们。无论您使用什么构建系统,都可以轻松地配置为运行以test_开头的文件。实际上,用于测试发现的默认单元测试模式是test*.py。
其他回答
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.
我们使用
app/src/code.py
app/testing/code_test.py
app/docs/..
在每个测试文件中,我们插入../src/ sys.path。这不是最好的解决办法,但很有效。我认为如果有人提出类似java中的maven之类的东西,给你提供标准的约定,无论你在做什么项目,都可以工作,那就太好了。
我使用tests/目录,然后使用相对导入导入主要应用程序模块。在MyApp/tests/foo.py中,可能有:
from .. import foo
导入MyApp。foo模块。
我是怎么做的…
文件夹结构:
project/
src/
code.py
tests/
setup.py
Setup.py指向src/作为包含我的项目模块的位置,然后运行:
setup.py develop
它将我的项目添加到站点包中,指向我的工作副本。要运行测试,我使用:
setup.py tests
使用我配置的任何测试运行程序。
我最近开始用Python编程,所以我还没有机会找到最佳实践。 但是,我已经写了一个模块,它可以找到所有的测试并运行它们。
所以,我有:
app/ appfile.py test/ appfileTest.py
当我进入更大的项目时,我得看看情况如何。