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的簡單使用,如果有更好的方法可以下方留言一起探討 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM