testing.py 878 Bytes
Newer Older
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
1
2
3
4
5
try:
    from unittest.mock import patch, MagicMock
except ImportError:
    from mock import patch, MagicMock

6
7
from past.builtins import basestring

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
8
9
10
11
12
13
14
15
16
17
18
19

import json
from contextlib import contextmanager

from .models import BaseModel


@contextmanager
def patch_requests(value, code=200):
    success = MagicMock()
    if isinstance(value, BaseModel):
        value = value.jsonld()
20
21
22
23
    if not isinstance(value, basestring):
        data = json.dumps(value)
    else:
        data = value
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
24
25

    success.json.return_value = value
26

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
27
    success.status_code = code
28
29
    success.content = data
    success.text = data
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
30
31
32
33
34
35
36

    method_mocker = MagicMock()
    method_mocker.return_value = success
    with patch.multiple('requests', request=method_mocker,
                        get=method_mocker, post=method_mocker):
        yield method_mocker, success
        assert method_mocker.called