使用pook模拟 HTTP 请求结果的库

Published on
11

pook官方文档

安装

pip install pook

Getting started

通过使用@pook.on装饰器的方式:

import pook
import requests

@pook.on
def test_my_api():
    mock = pook.get('http://baidu.com/api/1/foobar', reply=404, response_json={'error': 'not found'})

    resp = requests.get('http://baidu.com/api/1/foobar')
    print(resp.status_code)
    print(resp.json())
    print(mock.calls)

test_my_api()

通过使用@pook.get装饰器的方式:

import pook
import requests
import json

@pook.get('http://httpbin.org/status/500', reply=204, response_json={"1":"123"})
@pook.get('http://httpbin.org/status/400', reply=200,response_json={"1":"123"})
def fetch(url):
    return requests.get(url)

res = fetch('http://httpbin.org/status/400')
print('#1 status:', res.status_code)
print(res.json())

res = fetch('http://httpbin.org/status/500')
print('#2 status:', res.status_code)

使用请求的基本mock方式:

import pook
import requests


# Enable mock engine
pook.on()

pook.get('httpbin.org/ip',
         reply=403, response_type='json',
         response_headers={'server': 'pook'},
         response_json={'error': 'not found'})

pook.get('httpbin.org/headers',
         reply=404, response_type='json',
         response_headers={'server': 'pook'},
         response_json={'error': 'not found'})

res = requests.get('http://httpbin.org/ip')
print('Status:', res.status_code)
print('Headers:', res.headers)
print('Body:', res.json())

res = requests.get('http://httpbin.org/headers')
print('Status:', res.status_code)
print('Headers:', res.headers)
print('Body:', res.json())

print('Is done:', pook.isdone())
print('Pending mocks:', pook.pending_mocks())
print('Unmatched requests:', pook.unmatched_requests())

可链接API DSL,模拟访问post请求:

import json
import pook
import requests


# Enable mock engine
pook.on()

(pook.post('httpbin.org/post')
    .json({'foo': 'bar'})
    .type('json')
    .header('Client', 'requests')
    .reply(204)
    .headers({'server': 'pook'})
    .json({'error': 'simulated'}))

res = requests.post('http://httpbin.org/post',
                    data=json.dumps({'foo': 'bar'}),
                    headers={'Client': 'requests',
                             'Content-Type': 'application/json'})

print('Status:', res.status_code)
print('Body:', res.json())

print('Is done:', pook.isdone())
print('Pending mocks:', pook.pending_mocks())

更多API说明: https://pook.readthedocs.io/en/latest/api.html#core-api