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

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

这里是否存在最佳实践?


当前回答

在c#中,我通常将测试分离到单独的程序集中。

在Python中——到目前为止——我倾向于编写doctests,其中测试位于函数的文档字符串中,或者将它们放在模块底部的if __name__ == "__main__"块中。

其他回答

只有一个测试文件

如果只有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

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

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

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

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

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

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

我是怎么做的…

文件夹结构:

project/
    src/
        code.py
    tests/
    setup.py

Setup.py指向src/作为包含我的项目模块的位置,然后运行:

setup.py develop

它将我的项目添加到站点包中,指向我的工作副本。要运行测试,我使用:

setup.py tests

使用我配置的任何测试运行程序。

我将测试放在与测试代码(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.)

我不相信存在既定的“最佳实践”。

我把我的测试放在应用程序代码之外的另一个目录中。然后,我将主应用程序目录添加到sys。路径(允许您从任何地方导入模块)在我的测试运行脚本(它也做一些其他的事情)之前运行所有的测试。这样,当我发布主代码时,我就不必从主代码中删除测试目录,节省了我的时间和精力,即使时间和精力非常少。