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

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

相关推荐
喵手1 分钟前
Python爬虫实战:降维打击 - 用 Playwright 嗅探网络层抓取douyin无水印视频!
爬虫·python·爬虫实战·抖音·playwright·零基础python爬虫教学·采集抖音无水印视频
Fuliy963 分钟前
第三阶段:进化与群体智能 (Evolutionary & Swarm Intelligence)
人工智能·笔记·python·学习·算法
淘矿人3 分钟前
【claude】05_Claude Skill 实战案例精选(上):开发类技能+weelinking中转服务
大数据·人工智能·python·elasticsearch·搜索引擎·cloudera
一碗烈酒5 分钟前
【使用Python临时搭建代理转发服务,内网穿透】
python·测试工具·代理模式
测试19987 分钟前
软件测试之压力测试详解
自动化测试·软件测试·python·测试用例·接口测试·压力测试·性能测试
深耕AI7 分钟前
【 从零开始的VS Code Python环境配置:uv】
开发语言·python·uv
七夜zippoe13 分钟前
Python配置管理革命:pydantic-settings + 动态热更新实战
python·热更新·配置中心·配置管理·pydantic·类型安全
DarkAthena16 分钟前
【GaussDB】排查ARM64环境上gaussdb的python驱动(psycopg3)coredump的问题
python·gaussdb
SEO-狼术16 分钟前
Convert HTML Tables to PDF in Python
开发语言·python·pdf
von Neumann17 分钟前
大模型从入门到应用——HuggingFace:Transformers-[零基础快速上手:自然语言处理任务]
人工智能·python·ai·自然语言处理·大模型·aigc·transformer