• 【pytest学习11】mock函数pytest-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的测试用例

     

    下面的实例提供pytest中mock的2种方法:

    第一种中的第一个参数是通过object的方式进行查找关于Mock_weather的类,然后在找到下面的需要mock的对象方法名称,第2个参数表示mock的值。

    第二种方法中的第一个参数是通过完整的路径进行找到需要mock的对象,第2个参数是mock的值。通过执行发现,两种方法都是可以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'])
    复制代码

     

    声明 欢迎转载,但请保留文章原始出处:) 博客园:https://www.cnblogs.com/chenxiaomeng/ 如出现转载未声明 将追究法律责任~谢谢合作
  • 相关阅读:
    Spring Boot中只能有一个WebMvcConfigurationSupport配置类
    【原创】(六)Linux进程调度-实时调度器
    【原创】(二)Linux进程调度器-CPU负载
    【原创】(十二)Linux内存管理之vmap与vmalloc
    【原创】(十一)Linux内存管理slub分配器
    【原创】(七)Linux内存管理
    【原创】(五)Linux内存管理zone_sizes_init
    【原创】(三)Linux paging_init解析
    【原创】(二)Linux物理内存初始化
    【原创】(一)ARMv8 MMU及Linux页表映射
  • 原文地址:https://www.cnblogs.com/chenxiaomeng/p/14831737.html
Copyright © 2020-2023  润新知