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

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

相关推荐
秋邱2 小时前
智启未来:AGI 教育融合 × 跨平台联盟 × 个性化空间,重构教育 AI 新范式开篇:一场 “教育 ×AI” 的范式革命
人工智能·python·重构·推荐算法·agi
爱吃泡芙的小白白2 小时前
vscode、anaconda、git、python配置安装(自用)
ide·git·vscode·python·anaconda·学习记录
谷隐凡二2 小时前
Kubernetes主从架构简单解析:基于Python的模拟实现
python·架构·kubernetes
老歌老听老掉牙2 小时前
Matplotlib Pyplot 数据可视化完全指南
python·信息可视化·matplotlib
Sunhen_Qiletian2 小时前
《Python开发之语言基础》第六集:操作文件
前端·数据库·python
Python编程学习圈3 小时前
Python真的要一统天下了?
python
Hacker_Oldv3 小时前
Python技能进阶:探索Selenium库,实现网页自动化测试与爬虫
自动化测试·软件测试·爬虫·python·selenium·职场和发展
天天爱吃肉82183 小时前
电机控制技术深度解析:从基础原理到前沿实战
python·嵌入式硬件·汽车
西游音月4 小时前
(5)pytest+Selenium自动化测试-元素定位之XPath定位
selenium·测试工具·pytest
银河邮差4 小时前
python实战-用海外代理IP抓LinkedIn热门岗位数据
后端·python