python如何进行单元测试_【Python】真实项目中如何使用pytest进行单元测试(结合PyCharm)...

本文详细介绍了如何在实际项目中使用pytest进行单元测试,包括创建项目、添加pytest依赖、构建测试目录、编写测试用例及结合PyCharm进行测试。通过一个具体的MathHelper类加法函数测试案例,展示了如何利用pytest进行错误类型检查和正确结果验证。
摘要由CSDN通过智能技术生成

使用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”窗口可以看到测试信息

如果报错找不到模块时,需要打开右上角的编辑启动项,先删除旧信息,否则会有缓存

参考文献

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值