Skip to content

Repository files navigation

httmock

A mocking library for requests for Python 2.6, 2.7, 3.2, 3.3 and 3.4.

Installation

pip install httmock

Or, if you are a Gentoo user:

emerge dev-python/httmock

Usage

You can use it to mock third-party APIs and test libraries that use requests internally, conditionally using mocked replies with the urlmatch decorator:

fromhttmockimporturlmatch, HTTMockimportrequests@urlmatch(netloc=r'(.*\.)?google\.com$')defgoogle_mock(url, request):
return'Feeling lucky, punk?'withHTTMock(google_mock):
r=requests.get('http://google.com/')
printr.content# 'Feeling lucky, punk?'

The all_requests decorator doesn't conditionally block real requests. If you return a dictionary, it will map to the requests.Response object returned:

fromhttmockimportall_requests, HTTMockimportrequests@all_requestsdefresponse_content(url, request):
return {'status_code': 200,
'content': 'Oh hai'}
withHTTMock(response_content):
r=requests.get('https://foo_bar')
printr.status_codeprintr.content

If you pass in Set-Cookie headers, requests.Response.cookies will contain the values. You can also use response method directly instead of returning a dict:

fromhttmockimportall_requests, response, HTTMockimportrequests@all_requestsdefresponse_content(url, request):
headers= {'content-type': 'application/json',
'Set-Cookie': 'foo=bar;'}
content= {'message': 'API rate limit exceeded'}
returnresponse(403, content, headers, None, 5, request)
withHTTMock(response_content):
r=requests.get('https://api.github.com/users/whatever')
printr.json().get('message')
printr.cookies['foo']

About

A mocking library for requests

Resources

Stars

0 stars

Watchers

27 watching

Forks

Releases

Packages

Contributors

Languages