最近做接口自动化测试的时候,针对第三方接口,想通过mock形式实现,网上大多资料都是关于unittest.mock的方法。
本文主要总结利用pytest_mock实现模拟过程
官方文档中对pytest_mock的介绍,使用方法类似unittest.mock,他们具有相同的api和参数
官方文档:https://pypi.org/project/pytest-mock/
unittest.mock的中文官方文档:https://docs.python.org/zh-cn/dev/library/unittest.mock.html
导图

代码样例:
common包内的mock_data.py
import requests
class PaymentType():
def payapi(self):
url = 'http://..........'
headers = '{"Content-Type": "application/json"}'
request_data = {
"memberId": "#############",
"wxOpenid": "#########",
"sourceCode": "wxapp"
}
res = requests.post(url=url,headers=eval(headers),json=request_data)
result = res.json()
return result['obj']['paymentTypeV2'] #返回具体的支付方式代码
def paymenttype(self):
res = self.payapi()
if res == {'SCORE': 1}:
print('-------')
print('支付分')
return '支付分'
elif res == {'SCORE': 0,'online': 1}:
return '在线支付'
测试用例:
import pytest
from common import mock_data
class TestMock():
def test_payment_type(self,mocker):
pay=mock_data.PaymentType()
pay.payapi=mocker.patch('common.mock_data.PaymentType.payapi',return_value={'SCORE': 1})
status = pay.paymenttype()
print('======')
print(status)
assert status == '支付分'
print('成功')
if __name__ == '__main__':
command = '-q test_mock_data.py::TestMock::test_payment_type'
pytest.main(command)
值得注意的是:mocker.patch 的第一个参数必须是模拟对象的具体路径,第二个参数用来指定返回值
参考:https://note.qidong.name/2018/02/pytest-mock/
https://www.cnblogs.com/linuxchao/p/linuxchao-mock.html
http://www.voidcn.com/article/p-cdwrlyha-b.html

本文详细介绍了如何使用pytest_mock进行接口自动化测试中的模拟操作,重点在于mocker.patch的使用,强调了模拟对象路径及返回值的设置,提供了多个参考资料链接作为进一步学习的入口。
846

被折叠的 条评论
为什么被折叠?



