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

pytest-mock

安装:pip install pytest-mock

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

python 复制代码
# 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的测试用例

python 复制代码
# 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成功的

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

相关推荐
Python×CATIA工业智造32 分钟前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco1 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
狐凄2 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
悦悦子a啊3 小时前
Python之--基本知识
开发语言·前端·python
笑稀了的野生俊4 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva4 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm
路来了5 小时前
Python小工具之PDF合并
开发语言·windows·python
蓝婷儿5 小时前
Python 机器学习核心入门与实战进阶 Day 3 - 决策树 & 随机森林模型实战
人工智能·python·机器学习
AntBlack5 小时前
拖了五个月 ,不当韭菜体验版算是正式发布了
前端·后端·python
.30-06Springfield6 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习