Python中如何运行单元测试文件?

项目结构如下:

├── app
│   ├── __init__.py
│   └── utils.py
├── tests
│   ├── test_app.py

app/utils的内容如下:

class A:
	pass

tests/test_app内容如下:

from app.utils import A
def test_app():
	pass

直接运行py.test tests/test_app.py,会报找不到 app 这个模块,请问需要怎么修改,才能运行 tests 下面的测试。


Python中如何运行单元测试文件?

8 回复

lz 可以去搜一下 python 包管理 相对路径 绝对路径 ,搜完之后看看能不能解决~


直接上干货。在Python里跑单元测试,最常用的就是标准库里的 unittest 模块。

1. 最直接的方法:命令行运行 如果你的测试文件叫 test_example.py,并且里面用 unittest.TestCase 写好了测试类,直接在终端里用 python -m unittest 命令就行。

# 运行当前目录下所有以 test_ 开头的测试文件
python -m unittest discover

# 运行指定的测试文件
python -m unittest test_example.py

# 运行指定测试文件里的某个测试类
python -m unittest test_example.TestCalculator

# 甚至运行某个测试类里的特定测试方法
python -m unittest test_example.TestCalculator.test_addition

2. 在代码里直接运行 你也可以在测试文件的末尾加上这段代码,然后直接执行这个Python文件。

# 文件:test_example.py
import unittest

class TestCalculator(unittest.TestCase):
    def test_addition(self):
        self.assertEqual(1 + 1, 2)
    def test_subtraction(self):
        self.assertEqual(3 - 1, 2)

# 在文件底部添加:
if __name__ == '__main__':
    unittest.main()

然后执行:

python test_example.py

3. 如果你在用 pytest(更推荐) 现在很多人用 pytest,因为它更简洁。安装后,命令更简单:

# 安装
pip install pytest

# 运行所有测试(它会自动发现 test_*.py 文件和 *_test.py 文件)
pytest

# 运行特定文件
pytest test_example.py

# 运行特定函数
pytest test_example.py::test_addition

总结:新手用 python -m unittest discover,老手用 pytest

核心就是这些,根据你的项目选一种方式就行。

app 的 父目录里运行 python -m unittest tests.test_app

PYTHONPATH=. pytest tests/test_app.py

py.test

直接上 nose

回到顶部