pip install requests-mock
- 简单GET请求模拟
import requests
import requests_mock
def test_simple_get():
with requests_mock.Mocker() as m:
m.get('http://test.com/api/v1/users', text='{"users":[]}')
response = requests.get('http://test.com/api/v1/users')
assert response.text == '{"users":[]}'
test_simple_get()
- POST请求模拟并验证请求体
def test_post_request():
with requests_mock.Mocker() as m:
m.post('http://test.com/api/v1/users', text='User created', status_code=201)
response = requests.post('http://test.com/api/v1/users', json={'username': 'testuser'})
assert m.last_request.json() == {'username': 'testuser'}
assert response.text == 'User created'
test_post_request()
- 模拟不同状态码响应
def test_status_code():
with requests_mock.Mocker() as m:
m.get('http://test.com/api/v1/resource', status_code=404)
response = requests.get('http://test.com/api/v1/resource')
assert response.status_code == 404
test_status_code()
- 使用正则表达式匹配URL
import re
def test_regex_url():
with requests_mock.Mocker() as m:
m.get(re.compile(r'http://test.com/api/v1/users/\d+'), text='User details')
response = requests.get('http://test.com/api/v1/users/123')
assert response.text == 'User details'
test_regex_url()
- 多次调用模拟不同响应
def test_multiple_responses():
with requests_mock.Mocker() as m:
m.get('http://test.com/api/v1/toggle', [{'text': 'On'}, {'text': 'Off'}])
response1 = requests.get('http://test.com/api/v1/toggle')
response2 = requests.get('http://test.com/api/v1/toggle')
assert response1.text == 'On'
assert response2.text == 'Off'
test_multiple_responses()
- 模拟JSON响应
def test_json_response():
with requests_mock.Mocker() as m:
m.get('http://test.com/api/v1/config', json={'key': 'value'})
response = requests.get('http://test.com/api/v1/config')
assert response.json()['key'] == 'value'
test_json_response()
- 处理HEAD请求
def test_head_request():
with requests_mock.Mocker() as m:
m.head('http://test.com/api/v1/check', headers={'ETag': '123abc'})
response = requests.head('http://test.com/api/v1/check')
assert response.headers['ETag'] == '123abc'
test_head_request()
- 异常模拟
def test_exception():
with requests_mock.Mocker() as m:
m.get('http://test.com/api/v1/error', exc=requests.exceptions.HTTPError)
try:
requests.get('http://test.com/api/v1/error')
except requests.exceptions.HTTPError:
assert True
else:
assert False
test_exception()
- 模拟带查询参数的请求
def test_query_params():
with requests_mock.Mocker() as m:
m.get('http://test.com/api/v1/search', text='Search results', params={'query': 'python'})
response = requests.get('http://test.com/api/v1/search', params={'query': 'python'})
assert response.text == 'Search results'
test_query_params()
- 模拟重定向
def test_redirect():
with requests_mock.Mocker() as m:
m.get('http://test.com/api/v1/redirect', status_code=302, headers={'Location': 'http://test.com/api/v1/newpath'})
response = requests.get('http://test.com/api/v1/redirect', allow_redirects=True)
assert response.url.endswith('/api/v1/newpath')
test_redirect()