如果你正在编写一个库或应用程序,那么单元测试文件应该放在哪里?

将测试文件与主应用程序代码分开是很好的,但将它们放在应用程序根目录中的“tests”子目录中是很尴尬的,因为这会使导入将要测试的模块变得更加困难。

这里是否存在最佳实践?


当前回答

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开发测试框架的经验,我建议将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打包这些库时,您可以只打包主库模块(仅)。这有助于可维护性,特别是在敏捷环境中。

我也倾向于把我的单元测试放在文件本身中,正如Jeremy Cantrell上面所指出的,尽管我倾向于不把测试函数放在主体中,而是把所有东西都放在一个文件中

if __name__ == '__main__':
   do tests...

块。这最终会将文档添加到文件中,作为如何使用您正在测试的python文件的“示例代码”。

我应该补充一点,我倾向于编写非常紧凑的模块/类。如果你的模块需要大量的测试,你可以把它们放在另一个测试中,但即使这样,我仍然会补充:

if __name__ == '__main__':
   import tests.thisModule
   tests.thisModule.runtests

这让任何阅读源代码的人都知道到哪里去寻找测试代码。

我将测试放在与测试代码(CUT)相同的目录中。在项目中,我可以用我的插件调整pytest,对于foo.py,我使用foo.pt进行测试,这使得编辑特定的模块及其测试非常容易:vi foo.*。

在不能这样做的地方,我使用foo_ut.py或类似的方法。你仍然可以使用vi foo*,尽管它也会捕获foobar.py和foobar_ut.py(如果它们存在的话)。

在这两种情况下,我调整测试发现过程来找到这些。

这将测试放在目录列表中代码的旁边,使测试明显地存在于那里,并使打开测试尽可能容易,当它们位于单独的文件中时。(对于从命令行开始的编辑器,如上所述;对于GUI系统,单击代码文件和相邻的(或非常接近相邻的)测试文件。

正如其他人所指出的,这也使得重构和提取代码以供在其他地方使用变得更容易。

I really dislike the idea of putting tests in a completely different directory tree; why make it harder than necessary for developers to open up the tests when they're opening the file with the CUT? It's not like the vast majority of developers are so keen on writing or tweaking tests that they'll ignore any barrier to doing that, instead of using the barrier as an excuse. (Quite the opposite, in my experience; even when you make it as easy as possible I know many developers who can't be bothered to write tests.)

如果测试很简单,就把它们放在文档字符串中——大多数Python测试框架都可以使用它:

>>> import module
>>> module.method('test')
'testresult'

对于其他更复杂的测试,我将它们放在../tests/test_module.py或tests/test_module.py中。

我们在编写为Python程序生成单元测试的Pythoscope (https://pypi.org/project/pythoscope/)时遇到了同样的问题。在我们选择目录之前,我们对python列表中的测试进行了民意调查,有很多不同的意见。最后,我们选择将“tests”目录放在与源代码相同的目录中。在该目录中,我们为父目录中的每个模块生成一个测试文件。