Python测试框架 Pytest —— mock使用(pytest-mock)

pytest-mock

安装:pip install pytest-mock

这里的mock和unittest的mock基本上都是一样的,唯一的区别在于pytest.mock需要导入mock对象的详细路径。

复制代码
# weateher_r.py
class Mock_weather():
    def weather(self):
        '''天气接口'''
        pass
    def weather_result(self):
        '''模拟天气接口'''
        result = self.weather()
        if result['result'] == '雪':
            print('下雪了!!!')
        elif result['result'] == '雨':
            print('下雨了!!!')
        elif result['result'] == '晴天':
            print('晴天!!!!')
        else:
            print('返回值错误!')
        return result['status']

先将需要模拟的天气接口,以及需要模拟的场景的代码写好,然后在进行遵循pytest的用例规范进行书写关于mock的测试用例

复制代码
# test_01.py
import pytest
from test_01.weather_r import Mock_weather
 
 
def test_01(mocker):
    # 实例化
    p = Mock_weather()
    moke_value = {'result': "雪", 'status': '下雪了!'}
    # 通过object的方式进行查找需要mock的对象
    p.weather = mocker.patch.object(Mock_weather, "weather", return_value=moke_value)
    result =p.weather_result()
    assert result=='下雪了!'
     
def test_02(mocker):
    # 实例化
    product = Mock_weather()
    # Mock的返回值
    mock_value = {'result': "雨", 'status': '下雨了!'}
    # 第一个参数必须是模拟mock对象的完整路径
    product.weather = mocker.patch('test_01.weather_r.Mock_weather.weather',return_value=mock_value)
    result = product.weather_result()
    assert result=='下雨了!'
     
if __name__ == '__main__':
    pytest.main(['-vs'])

通过上述代码,提供pytest中mock的2中方法:第一种中的第一个参数是通过object的方式进行查找关于Mock_weather的类,然后在找到下面的需要mock的对象方法名称,第2个参数表示mock的值。

第二中方法中的第一个参数是通过完整的路径进行找到需要mock的对象,第2个参数是mock的值。通过执行发现,两种方法都是可以mock成功的

如果对你有帮助的话,点个赞收个藏,给作者一个鼓励。也方便你下次能够快速查找。

相关推荐
B站_计算机毕业设计之家5 分钟前
计算机毕业设计:Python农业数据可视化分析系统 气象数据 农业生产 粮食数据 播种数据 爬虫 Django框架 天气数据 降水量(源码+文档)✅
大数据·爬虫·python·机器学习·信息可视化·课程设计·农业
Q_Q51100828518 分钟前
python+uniapp基于微信小程序的旅游信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
鄃鳕20 分钟前
python迭代器解包【python】
开发语言·python
懷淰メ1 小时前
python3GUI--模仿百度网盘的本地文件管理器 By:PyQt5(详细分享)
开发语言·python·pyqt·文件管理·百度云·百度网盘·ui设计
Q_Q5110082851 小时前
python基于web的汽车班车车票管理系统/火车票预订系统/高铁预定系统 可在线选座
spring boot·python·django·flask·node.js·汽车·php
新子y1 小时前
【小白笔记】普通二叉树(General Binary Tree)和二叉搜索树的最近公共祖先(LCA)
开发语言·笔记·python
囚生CY1 小时前
【速写】优化的深度与广度(Adam & Moun)
人工智能·python·算法
Query*1 小时前
Java 设计模式——工厂模式:从原理到实战的系统指南
java·python·设计模式
爱学习的uu1 小时前
CURSOR最新使用指南及使用思路
人工智能·笔记·python·软件工程
叶凡要飞2 小时前
RTX5060Ti安装双系统ubuntu22.04各种踩坑点(黑屏,引导区修复、装驱动、server版本安装)
人工智能·python·yolo·ubuntu·机器学习·操作系统