pytest-mock
安裝:pip install pytest-mock
這里的mock和unittest的mock基本上都是一樣的,唯一的區(qū)別在于pytest.mock需要導(dǎo)入mock對(duì)象的詳細(xì)路徑。
# 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('返回值錯(cuò)誤!')
return result['status']
先將需要模擬的天氣接口,以及需要模擬的場(chǎng)景的代碼寫好,然后在進(jìn)行遵循pytest的用例規(guī)范進(jìn)行書寫關(guān)于mock的測(cè)試用例
# test_01.py
import pytest
from test_01.weather_r import Mock_weather
def test_01(mocker):
# 實(shí)例化
p = Mock_weather()
moke_value = {'result': "雪", 'status': '下雪了!'}
# 通過(guò)object的方式進(jìn)行查找需要mock的對(duì)象
p.weather = mocker.patch.object(Mock_weather, "weather", return_value=moke_value)
result =p.weather_result()
assert result=='下雪了!'
def test_02(mocker):
# 實(shí)例化
product = Mock_weather()
# Mock的返回值
mock_value = {'result': "雨", 'status': '下雨了!'}
# 第一個(gè)參數(shù)必須是模擬mock對(duì)象的完整路徑
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'])
通過(guò)上述代碼,提供pytest中mock的2中方法:第一種中的第一個(gè)參數(shù)是通過(guò)object的方式進(jìn)行查找關(guān)于Mock_weather的類,然后在找到下面的需要mock的對(duì)象方法名稱,第2個(gè)參數(shù)表示mock的值。
第二中方法中的第一個(gè)參數(shù)是通過(guò)完整的路徑進(jìn)行找到需要mock的對(duì)象,第2個(gè)參數(shù)是mock的值。通過(guò)執(zhí)行發(fā)現(xiàn),兩種方法都是可以mock成功的
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-706291.html
如果對(duì)你有幫助的話,點(diǎn)個(gè)贊收個(gè)藏,給作者一個(gè)鼓勵(lì)。也方便你下次能夠快速查找。?????文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-706291.html
到了這里,關(guān)于Python測(cè)試框架 Pytest —— mock使用(pytest-mock)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!