Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/patrys/httmock
A mocking library for requests
https://github.com/patrys/httmock
http mock python requests
Last synced: 1 day ago
JSON representation
A mocking library for requests
- Host: GitHub
- URL: https://github.com/patrys/httmock
- Owner: patrys
- License: other
- Created: 2013-03-19T23:35:33.000Z (almost 12 years ago)
- Default Branch: master
- Last Pushed: 2023-09-29T20:58:48.000Z (over 1 year ago)
- Last Synced: 2025-01-02T19:14:18.222Z (9 days ago)
- Topics: http, mock, python, requests
- Language: Python
- Size: 70.3 KB
- Stars: 467
- Watchers: 12
- Forks: 57
- Open Issues: 17
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-python-testing - httmock - A mocking library for requests for Python 2.6+ and 3.2+. (Mock and Stub)
- starred-awesome - httmock - A mocking library for requests (Python)
README
httmock
=======A mocking library for `requests` for Python 2.7 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:```python
from httmock import urlmatch, HTTMock
import requests@urlmatch(netloc=r'(.*\.)?google\.com$')
def google_mock(url, request):
return 'Feeling lucky, punk?'with HTTMock(google_mock):
r = requests.get('http://google.com/')
print r.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:
```python
from httmock import all_requests, HTTMock
import requests@all_requests
def response_content(url, request):
return {'status_code': 200,
'content': 'Oh hai'}with HTTMock(response_content):
r = requests.get('https://foo_bar')print r.status_code
print r.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:
```python
from httmock import all_requests, response, HTTMock
import requests@all_requests
def response_content(url, request):
headers = {'content-type': 'application/json',
'Set-Cookie': 'foo=bar;'}
content = {'message': 'API rate limit exceeded'}
return response(403, content, headers, None, 5, request)with HTTMock(response_content):
r = requests.get('https://api.github.com/users/whatever')print r.json().get('message')
print r.cookies['foo']
```