zoukankan      html  css  js  c++  java
  • pytest---mock使用(pytest-mock)

    前言

    上一篇介绍了unittest中的mock,既然unittest中存在mock模块,那么pytest中也存在mock模块,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成功的

     

    上述内容为pytest中的pytest-mock的简单使用,如果有更好的方法可以下方留言一起探讨 

  • 相关阅读:
    k3 cloud点击按钮单开单据
    k3 cloud _LK表字段代表的意思
    sql server根据触发器名称查看代码
    sql server中查询所有触发器已经对应的表名称
    面向架构编程
    领域设计:领域事件
    QApplication: No such file or directory 完美解决方案
    C++ GUI Qt4编程(第二版) 源代码 下载
    ArcMap进行天空开阔度(SVF)分析
    wpf 高性能自定义chart
  • 原文地址:https://www.cnblogs.com/qican/p/14676854.html
Copyright © 2011-2022 走看看