Python单元测试放在哪里?
如果你在写一个库或者应用程序,单元测试文件应该放在哪里呢?
把测试文件和主程序代码分开是个好主意,但把它们放在应用程序根目录下的一个“tests”子目录里又有点麻烦,因为这样会让你在导入要测试的模块时变得困难。
这里有没有什么好的做法呢?
18 个回答
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
参考资料
pytest
的良好实践,关于测试布局unittest
单元测试框架
254
对于一个文件 module.py
,它的单元测试通常应该叫 test_module.py
,这样命名符合Python的习惯。
有几个常见的地方可以放 test_module.py
:
- 和
module.py
在同一个文件夹里。 - 放在
../tests/test_module.py
(和代码文件夹在同一层级)。 - 放在
tests/test_module.py
(在代码文件夹下面一层)。
我个人比较喜欢第一种方式,因为这样更简单,方便找到测试文件和导入它们。无论你使用什么构建系统,都可以很容易地设置,让它运行以 test_
开头的文件。实际上,默认的 用于测试发现的 unittest
模式是 test*.py
。