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

将测试文件与主应用程序代码分开是很好的,但将它们放在应用程序根目录中的“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

其他回答

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

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

我建议你在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

一种常见的做法是将测试目录放在与模块/包相同的父目录中。因此,如果你的模块名为foo.py,你的目录布局将如下所示:

parent_dir/
  foo.py
  tests/

当然,没有一种方法可以做到这一点。您还可以创建一个tests子目录,并使用绝对导入导入模块。

无论您在哪里进行测试,我都建议您使用nose来运行它们。Nose在您的目录中搜索测试。这样,您就可以把测试放在组织上最有意义的地方。

我最近开始用Python编程,所以我还没有机会找到最佳实践。 但是,我已经写了一个模块,它可以找到所有的测试并运行它们。

所以,我有:

app/
 appfile.py
test/
 appfileTest.py

当我进入更大的项目时,我得看看情况如何。

对于文件module.py,单元测试通常应该被称为test_module.py,遵循python命名约定。

test_module.py有几个常用的存放位置:

和module.py在同一个目录下。 在../tests/test_module.py中(与代码目录处于同一级别)。 在tests/test_module.py中(代码目录下的一级)。

我更喜欢#1,因为它很容易找到测试并导入它们。无论您使用什么构建系统,都可以轻松地配置为运行以test_开头的文件。实际上,用于测试发现的默认单元测试模式是test*.py。