Debian Codegraph @

docs/api-guide/testing.md

raw
1 ---
2 source:
3 - test.py
4 ---
5
6 # Testing
7
8 > Code without tests is broken as designed.
9 >
10 > — [Jacob Kaplan-Moss][cite]
11
12 REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.
13
14 ## APIRequestFactory
15
16 Extends [Django's existing `RequestFactory` class][requestfactory].
17
18 ### Creating test requests
19
20 The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available.
21
22 from rest_framework.test import APIRequestFactory
23
24 # Using the standard RequestFactory API to create a form POST request
25 factory = APIRequestFactory()
26 request = factory.post('/notes/', {'title': 'new idea'})
27
28 # Using the standard RequestFactory API to encode JSON data
29 request = factory.post('/notes/', {'title': 'new idea'}, content_type='application/json')
30
31 #### Using the `format` argument
32
33 Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a wide set of request formats. When using this argument, the factory will select an appropriate renderer and its configured `content_type`. For example:
34
35 # Create a JSON POST request
36 factory = APIRequestFactory()
37 request = factory.post('/notes/', {'title': 'new idea'}, format='json')
38
39 By default the available formats are `'multipart'` and `'json'`. For compatibility with Django's existing `RequestFactory` the default format is `'multipart'`.
40
41 To support a wider set of request formats, or change the default format, [see the configuration section][configuration].
42
43 #### Explicitly encoding the request body
44
45 If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example:
46
47 request = factory.post('/notes/', yaml.dump({'title': 'new idea'}), content_type='application/yaml')
48
49 #### PUT and PATCH with form data
50
51 One difference worth noting between Django's `RequestFactory` and REST framework's `APIRequestFactory` is that multipart form data will be encoded for methods other than just `.post()`.
52
53 For example, using `APIRequestFactory`, you can make a form PUT request like so:
54
55 factory = APIRequestFactory()
56 request = factory.put('/notes/547/', {'title': 'remember to email dave'})
57
58 Using Django's `RequestFactory`, you'd need to explicitly encode the data yourself:
59
60 from django.test.client import encode_multipart, RequestFactory
61
62 factory = RequestFactory()
63 data = {'title': 'remember to email dave'}
64 content = encode_multipart('BoUnDaRyStRiNg', data)
65 content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
66 request = factory.put('/notes/547/', content, content_type=content_type)
67
68 ### Forcing authentication
69
70 When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.
71
72 To forcibly authenticate a request, use the `force_authenticate()` method.
73
74 from rest_framework.test import force_authenticate
75
76 factory = APIRequestFactory()
77 user = User.objects.get(username='olivia')
78 view = AccountDetail.as_view()
79
80 # Make an authenticated request to the view...
81 request = factory.get('/accounts/django-superstars/')
82 force_authenticate(request, user=user)
83 response = view(request)
84
85 The signature for the method is `force_authenticate(request, user=None, token=None)`. When making the call, either or both of the user and token may be set.
86
87 For example, when forcibly authenticating using a token, you might do something like the following:
88
89 user = User.objects.get(username='olivia')
90 request = factory.get('/accounts/django-superstars/')
91 force_authenticate(request, user=user, token=user.auth_token)
92
93 !!! note
94 `force_authenticate` directly sets `request.user` to the in-memory `user` instance. If you are reusing the same `user` instance across multiple tests that update the saved `user` state, you may need to call [`refresh_from_db()`][refresh_from_db_docs] between tests.
95
96 !!! note
97 When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called.
98
99 This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting `.token` directly will have no effect, and setting `.user` directly will only work if session authentication is being used.
100
101 # Request will only authenticate if `SessionAuthentication` is in use.
102 request = factory.get('/accounts/django-superstars/')
103 request.user = user
104 response = view(request)
105
106 If you want to test a request involving the REST framework’s 'Request' object, you’ll need to manually transform it first:
107
108 class DummyView(APIView):
109 ...
110
111 factory = APIRequestFactory()
112 request = factory.get('/', {'demo': 'test'})
113 drf_request = DummyView().initialize_request(request)
114 assert drf_request.query_params == {'demo': ['test']}
115
116 request = factory.post('/', {'example': 'test'})
117 drf_request = DummyView().initialize_request(request)
118 assert drf_request.data.get('example') == 'test'
119
120 ### Forcing CSRF validation
121
122 By default, requests created with `APIRequestFactory` will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the `enforce_csrf_checks` flag when instantiating the factory.
123
124 factory = APIRequestFactory(enforce_csrf_checks=True)
125
126 !!! note
127 It's worth noting that Django's standard `RequestFactory` doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.
128
129 ## APIClient
130
131 Extends [Django's existing `Client` class][client].
132
133 ### Making requests
134
135 The `APIClient` class supports the same request interface as Django's standard `Client` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example:
136
137 from rest_framework.test import APIClient
138
139 client = APIClient()
140 client.post('/notes/', {'title': 'new idea'}, format='json')
141
142 To support a wider set of request formats, or change the default format, [see the configuration section][configuration].
143
144 ### Authenticating
145
146 #### .login(**kwargs)
147
148 The `login` method functions exactly as it does with Django's regular `Client` class. This allows you to authenticate requests against any views which include `SessionAuthentication`.
149
150 # Make all requests in the context of a logged in session.
151 client = APIClient()
152 client.login(username='lauren', password='secret')
153
154 To logout, call the `logout` method as usual.
155
156 # Log out
157 client.logout()
158
159 The `login` method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.
160
161 #### .credentials(**kwargs)
162
163 The `credentials` method can be used to set headers that will then be included on all subsequent requests by the test client.
164
165 from rest_framework.authtoken.models import Token
166 from rest_framework.test import APIClient
167
168 # Include an appropriate `Authorization:` header on all requests.
169 token = Token.objects.get(user__username='lauren')
170 client = APIClient()
171 client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
172
173 Note that calling `credentials` a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.
174
175 # Stop including any credentials
176 client.credentials()
177
178 The `credentials` method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.
179
180 #### .force_authenticate(user=None, token=None)
181
182 Sometimes you may want to bypass authentication entirely and force all requests by the test client to be automatically treated as authenticated.
183
184 This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.
185
186 user = User.objects.get(username='lauren')
187 client = APIClient()
188 client.force_authenticate(user=user)
189
190 To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`.
191
192 client.force_authenticate(user=None)
193
194 ### CSRF validation
195
196 By default CSRF validation is not applied when using `APIClient`. If you need to explicitly enable CSRF validation, you can do so by setting the `enforce_csrf_checks` flag when instantiating the client.
197
198 client = APIClient(enforce_csrf_checks=True)
199
200 As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling `login()`.
201
202 ---
203
204 ## RequestsClient
205
206 REST framework also includes a client for interacting with your application
207 using the popular Python library, `requests`. This may be useful if:
208
209 * You are expecting to interface with the API primarily from another Python service,
210 and want to test the service at the same level as the client will see.
211 * You want to write tests in such a way that they can also be run against a staging or
212 live environment. (See "Live tests" below.)
213
214 This exposes exactly the same interface as if you were using a requests session
215 directly.
216
217 from rest_framework.test import RequestsClient
218
219 client = RequestsClient()
220 response = client.get('http://testserver/users/')
221 assert response.status_code == 200
222
223 Note that the requests client requires you to pass fully qualified URLs.
224
225 ### RequestsClient and working with the database
226
227 The `RequestsClient` class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API.
228
229 If you're using `RequestsClient` you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that `Customer.objects.count() == 3` you would list the customers endpoint, and ensure that it contains three records.
230
231 ### Headers & Authentication
232
233 Custom headers and authentication credentials can be provided in the same way
234 as [when using a standard `requests.Session` instance][session_objects].
235
236 from requests.auth import HTTPBasicAuth
237
238 client.auth = HTTPBasicAuth('user', 'pass')
239 client.headers.update({'x-test': 'true'})
240
241 ### CSRF
242
243 If you're using `SessionAuthentication` then you'll need to include a CSRF token
244 for any `POST`, `PUT`, `PATCH` or `DELETE` requests.
245
246 You can do so by following the same flow that a JavaScript based client would use.
247 First, make a `GET` request in order to obtain a CSRF token, then present that
248 token in the following request.
249
250 For example...
251
252 client = RequestsClient()
253
254 # Obtain a CSRF token.
255 response = client.get('http://testserver/homepage/')
256 assert response.status_code == 200
257 csrftoken = response.cookies['csrftoken']
258
259 # Interact with the API.
260 response = client.post('http://testserver/organizations/', json={
261 'name': 'MegaCorp',
262 'status': 'active'
263 }, headers={'X-CSRFToken': csrftoken})
264 assert response.status_code == 200
265
266 ### Live tests
267
268 With careful usage the `RequestsClient` provides the ability to write tests
269 that exercise your API views in a more end-to-end fashion than `APIClient`,
270 while still running entirely in-process against your local Django application.
271
272 Note that `RequestsClient` mounts a WSGI adapter and does not perform real
273 network I/O. It cannot be used to send HTTP requests to remote services such
274 as staging or production servers. For live tests against a deployed service,
275 you should instead use a plain `requests.Session` (or similar HTTP client)
276 configured with the appropriate base URL and authentication.
277 Using this style to create basic tests of a few core pieces of functionality is
278 a powerful way to validate your live service. Doing so may require some careful
279 attention to setup and teardown to ensure that the tests run in a way that they
280 do not directly affect customer data.
281
282 ---
283
284 ## API Test cases
285
286 REST framework includes the following test case classes, that mirror the existing [Django's test case classes][provided_test_case_classes], but use `APIClient` instead of Django's default `Client`.
287
288 * `APISimpleTestCase`
289 * `APITransactionTestCase`
290 * `APITestCase`
291 * `APILiveServerTestCase`
292
293 ### Example
294
295 You can use any of REST framework's test case classes as you would for the regular Django test case classes. The `self.client` attribute will be an `APIClient` instance.
296
297 from django.urls import reverse
298 from rest_framework import status
299 from rest_framework.test import APITestCase
300 from myproject.apps.core.models import Account
301
302 class AccountTests(APITestCase):
303 def test_create_account(self):
304 """
305 Ensure we can create a new account object.
306 """
307 url = reverse('account-list')
308 data = {'name': 'DabApps'}
309 response = self.client.post(url, data, format='json')
310 self.assertEqual(response.status_code, status.HTTP_201_CREATED)
311 self.assertEqual(Account.objects.count(), 1)
312 self.assertEqual(Account.objects.get().name, 'DabApps')
313
314 ---
315
316 ## URLPatternsTestCase
317
318 REST framework also provides a test case class for isolating `urlpatterns` on a per-class basis. Note that this inherits from Django's `SimpleTestCase`, and will most likely need to be mixed with another test case class.
319
320 ### Example
321
322 from django.urls import include, path, reverse
323 from rest_framework import status
324 from rest_framework.test import APITestCase, URLPatternsTestCase
325
326
327 class AccountTests(APITestCase, URLPatternsTestCase):
328 urlpatterns = [
329 path('api/', include('api.urls')),
330 ]
331
332 def test_create_account(self):
333 """
334 Ensure we can create a new account object.
335 """
336 url = reverse('account-list')
337 response = self.client.get(url, format='json')
338 self.assertEqual(response.status_code, status.HTTP_200_OK)
339 self.assertEqual(len(response.data), 1)
340
341 ---
342
343 ## Testing responses
344
345 ### Checking the response data
346
347 When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.
348
349 For example, it's easier to inspect `response.data`:
350
351 response = self.client.get('/users/4/')
352 self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})
353
354 Instead of inspecting the result of parsing `response.content`:
355
356 response = self.client.get('/users/4/')
357 self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})
358
359 ### Rendering responses
360
361 If you're testing views directly using `APIRequestFactory`, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access `response.content`, you'll first need to render the response.
362
363 view = UserDetail.as_view()
364 request = factory.get('/users/4')
365 response = view(request, pk='4')
366 response.render() # Cannot access `response.content` without this.
367 self.assertEqual(response.content, '{"username": "lauren", "id": 4}')
368
369 ---
370
371 ## Configuration
372
373 ### Setting the default format
374
375 The default format used to make test requests may be set using the `TEST_REQUEST_DEFAULT_FORMAT` setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your `settings.py` file:
376
377 REST_FRAMEWORK = {
378 ...
379 'TEST_REQUEST_DEFAULT_FORMAT': 'json'
380 }
381
382 ### Setting the available formats
383
384 If you need to test requests using something other than multipart or json requests, you can do so by setting the `TEST_REQUEST_RENDERER_CLASSES` setting.
385
386 For example, to add support for using `format='html'` in test requests, you might have something like this in your `settings.py` file.
387
388 REST_FRAMEWORK = {
389 ...
390 'TEST_REQUEST_RENDERER_CLASSES': [
391 'rest_framework.renderers.MultiPartRenderer',
392 'rest_framework.renderers.JSONRenderer',
393 'rest_framework.renderers.TemplateHTMLRenderer'
394 ]
395 }
396
397 [cite]: https://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper
398 [client]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client
399 [requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory
400 [configuration]: #configuration
401 [refresh_from_db_docs]: https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.refresh_from_db
402 [session_objects]: https://requests.readthedocs.io/en/latest/user/advanced/#session-objects
403 [provided_test_case_classes]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#provided-test-case-classes