Python单元测试放在哪里?

570 投票
18 回答
134401 浏览
提问于 2025-04-11 00:12

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

把测试文件和主程序代码分开是个好主意,但把它们放在应用程序根目录下的一个“tests”子目录里又有点麻烦,因为这样会让你在导入要测试的模块时变得困难。

这里有没有什么好的做法呢?

18 个回答

52

一个常见的做法是把测试文件夹放在和你的模块或包同一个父目录下。比如,如果你的模块叫做 foo.py,那么你的文件夹结构看起来会像这样:

parent_dir/
  foo.py
  tests/

当然,这并不是唯一的做法。你也可以创建一个 tests 子文件夹,然后使用 绝对导入来引入模块。

无论你把测试放在哪里,我建议你使用 nose 来运行它们。Nose 会在你的目录中搜索测试。这样一来,你可以把测试放在最合适的地方,方便管理。

104

只有一个测试文件

如果只有一个测试文件,建议把它放在顶层目录:

module/
    lib/
        __init__.py
        module.py
    test.py

在命令行中运行测试

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()

在命令行中运行测试

# In top-level /module/ folder
python -m tests.test_module
python -m tests.test_module_function

使用 unittest discovery

unittest discovery 会自动找到包文件夹中的所有测试。

tests/ 文件夹中创建一个 __init__.py 文件

module/
    lib/
        __init__.py
        module.py
    tests/
        __init__.py
        test_module.py
        test_module_function.py

在命令行中运行测试

# In top-level /module/ folder

# -s, --start-directory (default current directory)
# -p, --pattern (default test*.py)

python -m unittest discover

参考资料

单元测试框架

254

对于一个文件 module.py,它的单元测试通常应该叫 test_module.py,这样命名符合Python的习惯。

有几个常见的地方可以放 test_module.py

  1. module.py 在同一个文件夹里。
  2. 放在 ../tests/test_module.py(和代码文件夹在同一层级)。
  3. 放在 tests/test_module.py(在代码文件夹下面一层)。

我个人比较喜欢第一种方式,因为这样更简单,方便找到测试文件和导入它们。无论你使用什么构建系统,都可以很容易地设置,让它运行以 test_ 开头的文件。实际上,默认的 用于测试发现的 unittest 模式是 test*.py

撰写回答