File: examples.md

package info (click to toggle)
python-respx 0.21.1-2~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 872 kB
  • sloc: python: 4,378; makefile: 17
file content (199 lines) | stat: -rw-r--r-- 4,808 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# Test Case Examples

Here's some test case examples, not exactly *how-to*, but to be inspired from.

## pytest

### Built-in Fixture

RESPX includes the `respx_mock` pytest httpx *fixture*.

``` python
import httpx


def test_fixture(respx_mock):
    respx_mock.get("https://foo.bar/").mock(return_value=httpx.Response(204))
    response = httpx.get("https://foo.bar/")
    assert response.status_code == 204
```

### Built-in Marker

To configure the `respx_mock` fixture, use the `respx` *marker*.

``` python
import httpx
import pytest


@pytest.mark.respx(base_url="https://foo.bar")
def test_configured_fixture(respx_mock):
    respx_mock.get("/baz/").mock(return_value=httpx.Response(204))
    response = httpx.get("https://foo.bar/baz/")
    assert response.status_code == 204
```

> See router [configuration](api.md#configuration) reference for more details.


### Custom Fixtures
``` python
# conftest.py
import pytest
import respx

from httpx import Response


@pytest.fixture
def mocked_api():
    with respx.mock(
        base_url="https://foo.bar", assert_all_called=False
    ) as respx_mock:
        users_route = respx_mock.get("/users/", name="list_users")
        users_route.return_value = Response(200, json=[])
        ...
        yield respx_mock
```

``` python
# test_api.py
import httpx


def test_list_users(mocked_api):
    response = httpx.get("https://foo.bar/users/")
    assert response.status_code == 200
    assert response.json() == []
    assert mocked_api["list_users"].called
```

**Session Scoped Fixtures**

If a session scoped RESPX fixture is used in an async context, you also need to broaden the `pytest-asyncio`
 [event_loop](https://github.com/pytest-dev/pytest-asyncio#event_loop) fixture.
 You can use the `session_event_loop` utility for this. 

``` python
# conftest.py
import pytest
import respx

from respx.fixtures import session_event_loop as event_loop  # noqa: F401


@pytest.fixture(scope="session")
async def mocked_api(event_loop):  # noqa: F811
    async with respx.mock(base_url="https://foo.bar") as respx_mock:
        ...
        yield respx_mock
```

### Async Test Cases
``` python
import httpx
import respx


@respx.mock
async def test_async_decorator():
    async with httpx.AsyncClient() as client:
        route = respx.get("https://example.org/")
        response = await client.get("https://example.org/")
        assert route.called
        assert response.status_code == 200


async def test_async_ctx_manager():
    async with respx.mock:
        async with httpx.AsyncClient() as client:
            route = respx.get("https://example.org/")
            response = await client.get("https://example.org/")
            assert route.called
            assert response.status_code == 200
```


## unittest

### Regular Decoration

``` python
# test_api.py
import httpx
import respx
import unittest


class APITestCase(unittest.TestCase):
    @respx.mock
    def test_some_endpoint(self):
        respx.get("https://example.org/") % 202
        response = httpx.get("https://example.org/")
        self.assertEqual(response.status_code, 202)
```

### Reuse SetUp & TearDown

``` python
# testcases.py
import respx

from httpx import Response


class MockedAPIMixin:
    @classmethod
    def setUpClass(cls):
        cls.mocked_api = respx.mock(
            base_url="https://foo.bar", assert_all_called=False
        )
        users_route = cls.mocked_api.get("/users/", name="list_users")
        users_route.return_value = Response(200, json=[])
        ...

    def setUp(self):
        self.mocked_api.start()
        self.addCleanup(self.mocked_api.stop)
```
``` python
# test_api.py
import httpx
import unittest

from .testcases import MockedAPIMixin


class APITestCase(MockedAPIMixin, unittest.TestCase):
    def test_list_users(self):
        response = httpx.get("https://foo.bar/users/")
        self.assertEqual(response.status_code, 200)
        self.assertListEqual(response.json(), [])
        self.assertTrue(self.mocked_api["list_users"].called)
```

### Async Test Cases
``` python
import asynctest
import httpx
import respx


class MyTestCase(asynctest.TestCase):
    @respx.mock
    async def test_async_decorator(self):
        async with httpx.AsyncClient() as client:
            route = respx.get("https://example.org/")
            response = await client.get("https://example.org/")
            assert route.called
            assert response.status_code == 200

    async def test_async_ctx_manager(self):
        async with respx.mock:
            async with httpx.AsyncClient() as client:
                route = respx.get("https://example.org/")
                response = await client.get("https://example.org/")
                assert route.called
                assert response.status_code == 200
```