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成功的

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

相关推荐
秭霏鱼7 分钟前
Python+大模型 day01
开发语言·python
学地理的小胖砸1 小时前
【Python 异常处理】
开发语言·python
小猪写代码1 小时前
Ubuntu 系统默认已安装 python,此处只需添加一个超链接即可
linux·python·ubuntu
老哥不老1 小时前
Python调用SQLite及pandas相关API详解
python·sqlite·pandas
蹦蹦跳跳真可爱5891 小时前
Python----神经网络(《Inverted Residuals and Linear Bottlenecks》论文概括和MobileNetV2网络)
网络·人工智能·python·深度学习·神经网络
微刻时光2 小时前
影刀RPA开发-CSS选择器介绍
css·python·低代码·自动化·rpa·影刀rpa·影刀实战
程序员拂雨2 小时前
Python知识框架
开发语言·python
灏瀚星空2 小时前
地磁-惯性-视觉融合制导系统设计:现代空战导航的抗干扰解决方案
图像处理·人工智能·python·深度学习·算法·机器学习·信息与通信
Code_流苏3 小时前
《Python星球日记》 第72天:问答系统与信息检索
python·微调·问答系统·bert·应用场景·基于检索·基于生成
敲键盘的小夜猫3 小时前
深入理解Python逻辑判断、循环与推导式(附实战案例)
开发语言·python