应用pytest进行单元测试(联合PyCharm)
目标
网上很多介绍pytest的文章,然而很少结合实际开发,多为简略demo。以下介绍结合实际我的项目如何应用。
次要内容
- 创立一般我的项目
- 增加pytest依赖
- 创立测试目录
- 执行测试
- 联合PyCharm
- 参考文献
创立一般我的项目
创立一个我的项目根目录”pytest-demo”
增加我的项目文件,目录构造如下
pytest-demo
-
demo
-
\_\_init\_\_.py
-
utils
- \_\_init\_\_.py
- math_helper.py
-
-
math_helper.py如下
class MathHelper(object):
def addition(self, first, second):
"""
加法
:param first: 第一个参数
:param second: 第二个参数
:return: 相加后的后果
"""
# 先判断传入类型
if not isinstance(first, (int, float)):
raise ValueError("first参数必须为数值")
if not isinstance(second, (int, float)):
raise ValueError("second参数必须为数值")
# 返回后果
return first + second
增加pytest依赖
$ pip install pytest
增加单元测试目录
在根目录下创立单元测试目录”tests”(留神要创立成package,不便全量测试)
对应增加测试类,测试类文件名必须为test_.py 或 _test.py,命名规定可查看pytest官网文档
最终目录构造如下
pytest-demo
-
demo
-
\_\_init\_\_.py
-
utils
- \_\_init\_\_.py
- math_helper.py
-
-
-
tests
-
demo
-
\_\_init\_\_.py
-
utils
- \_\_init\_\_.py
- test_math_helper.py
-
-
-
test_math_helper.py如下
import pytest
from demo.utils.math_helper import MathHelper
def test_addition():
# 初始化
helper = MathHelper()
# 输出谬误类型,预期接管ValueError的报错
with pytest.raises(ValueError):
helper.addition("1", 2)
with pytest.raises(ValueError):
helper.addition(1, "2")
# 正确调用
result = helper.addition(1, 2)
# 应用assert判断后果
assert result == 3
执行测试用例
$ pytest
即可执行所有测试,并给出后果
联合PyCharm
- 设置PyCharm默认测试类型
- 关上 File > Settings > Tools > Python Integrated Tools > Testing > Default test runner
- 批改下拉框,改为”pytest”
- 右键单元测试文件,点击”run”,即可执行测试,在下方的”Run”窗口也有相应的测试后果
- 设置执行所有测试
- 右键”tests”文件夹,抉择”Run”
- 接下来就间接跑目录下所有的测试用例了,在下方的”Run”窗口能够看到测试信息
- 如果报错找不到模块时,须要关上右上角的编辑启动项,先删除旧信息,否则会有缓存
参考文献
pytest官网文档
发表回复