requests---requests-mock的简单介绍
前言
pip install requests-mock
# coding:utf-8 import requests import requests_mock def test_01(): with requests_mock.Mocker() as m: # 模拟post请求内容,返回的json格式,返回码为200 m.post('https://www.anjing.com',json={'name':'anjing'},status_code=200) # 根据模拟的请求进行通过requests进行发送模拟信息,查看返回结果内容 r = requests.post('https://www.anjing.com',json={'name':'anjing'}) print(r.text) assert r.status_code == 200 assert r.json()['name']=='anjing'
# coding:utf-8 import requests import requests_mock def test_01(): with requests_mock.Mocker() as m: # 模拟post请求内容,返回的json格式,返回码为200 def echo_response(request,context): data = request.json() return {'json':data,'status_code': 200} m.post('https://www.anjing.com',json=echo_response) data = { 'name':'anjing' } r = requests.post('https://www.anjing.com', json=data) print(r.text) assert r.status_code == 200 assert r.json()['json']['name']=='anjing'
# coding:utf-8 import pytest import requests import requests_mock from requests.exceptions import ConnectionError, Timeout def test_01(): with requests_mock.Mocker() as m: # 模拟请求超时处理 m.get('https://www.anjing.com',exc=Timeout) # 通过pytest.raises进行捕捉异常,如果存在异常,则判断为pass with pytest.raises(Timeout): requests.get('https://www.anjing.com',timeout=1) # 模拟服务器错误 m.get('https://www.anjing.com/api', exc=ConnectionError) # 发送请求并断言是否抛出了预期的异常 with pytest.raises(ConnectionError): requests.get('https://www.anjing.com/api')