testing.py 852 Bytes
Newer Older
1
2
from past.builtins import basestring

3
4
import os
import responses as requestmock
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
5
6
7
8

from .models import BaseModel


9
10
MOCK_REQUESTS = os.environ.get('MOCK_REQUESTS', '').lower() in ['no', 'false']

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
11

12
def patch_all_requests(responses):
13

14
    patched = requestmock.RequestsMock()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
15

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    for response in responses or []:
        args = response.copy()
        if 'json' in args and isinstance(args['json'], BaseModel):
            args['json'] = args['json'].jsonld()
        args['method'] = getattr(requestmock, args.get('method', 'GET'))
        patched.add(**args)
    return patched


def patch_requests(url, response, method='GET', status=200):
    args = {'url': url, 'method': method, 'status': status}
    if isinstance(response, basestring):
        args['body'] = response
    else:
        args['json'] = response
    return patch_all_requests([args])