| 1 |
""" |
| 2 |
Testing using the Test Client |
| 3 |
|
| 4 |
The test client is a class that can act like a simple |
| 5 |
browser for testing purposes. |
| 6 |
|
| 7 |
It allows the user to compose GET and POST requests, and |
| 8 |
obtain the response that the server gave to those requests. |
| 9 |
The server Response objects are annotated with the details |
| 10 |
of the contexts and templates that were rendered during the |
| 11 |
process of serving the request. |
| 12 |
|
| 13 |
``Client`` objects are stateful - they will retain cookie (and |
| 14 |
thus session) details for the lifetime of the ``Client`` instance. |
| 15 |
|
| 16 |
This is not intended as a replacement for Twill, Selenium, or |
| 17 |
other browser automation frameworks - it is here to allow |
| 18 |
testing against the contexts and templates produced by a view, |
| 19 |
rather than the HTML rendered to the end-user. |
| 20 |
|
| 21 |
""" |
| 22 |
|
| 23 |
import copy |
| 24 |
import itertools |
| 25 |
import tempfile |
| 26 |
from unittest import mock |
| 27 |
|
| 28 |
from django.contrib.auth.models import User |
| 29 |
from django.core import mail |
| 30 |
from django.http import HttpResponse, HttpResponseNotAllowed |
| 31 |
from django.test import ( |
| 32 |
AsyncRequestFactory, |
| 33 |
Client, |
| 34 |
RequestFactory, |
| 35 |
SimpleTestCase, |
| 36 |
TestCase, |
| 37 |
modify_settings, |
| 38 |
override_settings, |
| 39 |
) |
| 40 |
from django.urls import reverse_lazy |
| 41 |
from django.utils.decorators import async_only_middleware |
| 42 |
from django.views.generic import RedirectView |
| 43 |
|
| 44 |
from .views import TwoArgException, get_view, post_view, trace_view |
| 45 |
|
| 46 |
|
| 47 |
def middleware_urlconf(get_response): |
| 48 |
def middleware(request): |
| 49 |
request.urlconf = "test_client.urls_middleware_urlconf" |
| 50 |
return get_response(request) |
| 51 |
|
| 52 |
return middleware |
| 53 |
|
| 54 |
|
| 55 |
@async_only_middleware |
| 56 |
def async_middleware_urlconf(get_response): |
| 57 |
async def middleware(request): |
| 58 |
request.urlconf = "test_client.urls_middleware_urlconf" |
| 59 |
return await get_response(request) |
| 60 |
|
| 61 |
return middleware |
| 62 |
|
| 63 |
|
| 64 |
@override_settings(ROOT_URLCONF="test_client.urls") |
| 65 |
class ClientTest(TestCase): |
| 66 |
@classmethod |
| 67 |
def setUpTestData(cls): |
| 68 |
cls.u1 = User.objects.create_user(username="testclient", password="password") |
| 69 |
cls.u2 = User.objects.create_user( |
| 70 |
username="inactive", password="password", is_active=False |
| 71 |
) |
| 72 |
|
| 73 |
def test_get_view(self): |
| 74 |
"GET a view" |
| 75 |
# The data is ignored, but let's check it doesn't crash the system |
| 76 |
# anyway. |
| 77 |
data = {"var": "\xf2"} |
| 78 |
response = self.client.get("/get_view/", data) |
| 79 |
|
| 80 |
# Check some response details |
| 81 |
self.assertContains(response, "This is a test") |
| 82 |
self.assertEqual(response.context["var"], "\xf2") |
| 83 |
self.assertEqual(response.templates[0].name, "GET Template") |
| 84 |
|
| 85 |
def test_copy_response(self): |
| 86 |
tests = ["/cbv_view/", "/get_view/"] |
| 87 |
for url in tests: |
| 88 |
with self.subTest(url=url): |
| 89 |
response = self.client.get(url) |
| 90 |
response_copy = copy.copy(response) |
| 91 |
self.assertEqual(repr(response), repr(response_copy)) |
| 92 |
self.assertIs(response_copy.client, response.client) |
| 93 |
self.assertIs(response_copy.resolver_match, response.resolver_match) |
| 94 |
self.assertIs(response_copy.wsgi_request, response.wsgi_request) |
| 95 |
|
| 96 |
async def test_copy_response_async(self): |
| 97 |
response = await self.async_client.get("/async_get_view/") |
| 98 |
response_copy = copy.copy(response) |
| 99 |
self.assertEqual(repr(response), repr(response_copy)) |
| 100 |
self.assertIs(response_copy.client, response.client) |
| 101 |
self.assertIs(response_copy.resolver_match, response.resolver_match) |
| 102 |
self.assertIs(response_copy.asgi_request, response.asgi_request) |
| 103 |
|
| 104 |
def test_query_string_encoding(self): |
| 105 |
# WSGI requires latin-1 encoded strings. |
| 106 |
response = self.client.get("/get_view/?var=1\ufffd") |
| 107 |
self.assertEqual(response.context["var"], "1\ufffd") |
| 108 |
|
| 109 |
def test_get_data_none(self): |
| 110 |
msg = ( |
| 111 |
"Cannot encode None for key 'value' in a query string. Did you " |
| 112 |
"mean to pass an empty string or omit the value?" |
| 113 |
) |
| 114 |
with self.assertRaisesMessage(TypeError, msg): |
| 115 |
self.client.get("/get_view/", {"value": None}) |
| 116 |
|
| 117 |
def test_get_post_view(self): |
| 118 |
"GET a view that normally expects POSTs" |
| 119 |
response = self.client.get("/post_view/", {}) |
| 120 |
|
| 121 |
# Check some response details |
| 122 |
self.assertEqual(response.status_code, 200) |
| 123 |
self.assertEqual(response.templates[0].name, "Empty GET Template") |
| 124 |
self.assertTemplateUsed(response, "Empty GET Template") |
| 125 |
self.assertTemplateNotUsed(response, "Empty POST Template") |
| 126 |
|
| 127 |
def test_empty_post(self): |
| 128 |
"POST an empty dictionary to a view" |
| 129 |
response = self.client.post("/post_view/", {}) |
| 130 |
|
| 131 |
# Check some response details |
| 132 |
self.assertEqual(response.status_code, 200) |
| 133 |
self.assertEqual(response.templates[0].name, "Empty POST Template") |
| 134 |
self.assertTemplateNotUsed(response, "Empty GET Template") |
| 135 |
self.assertTemplateUsed(response, "Empty POST Template") |
| 136 |
|
| 137 |
def test_post(self): |
| 138 |
"POST some data to a view" |
| 139 |
post_data = {"value": 37} |
| 140 |
response = self.client.post("/post_view/", post_data) |
| 141 |
|
| 142 |
# Check some response details |
| 143 |
self.assertContains(response, "Data received") |
| 144 |
self.assertEqual(response.context["data"], "37") |
| 145 |
self.assertEqual(response.templates[0].name, "POST Template") |
| 146 |
|
| 147 |
def test_post_data_none(self): |
| 148 |
msg = ( |
| 149 |
"Cannot encode None for key 'value' as POST data. Did you mean " |
| 150 |
"to pass an empty string or omit the value?" |
| 151 |
) |
| 152 |
with self.assertRaisesMessage(TypeError, msg): |
| 153 |
self.client.post("/post_view/", {"value": None}) |
| 154 |
|
| 155 |
def test_json_serialization(self): |
| 156 |
"""The test client serializes JSON data.""" |
| 157 |
methods = ("post", "put", "patch", "delete") |
| 158 |
tests = ( |
| 159 |
({"value": 37}, {"value": 37}), |
| 160 |
([37, True], [37, True]), |
| 161 |
((37, False), [37, False]), |
| 162 |
) |
| 163 |
for method in methods: |
| 164 |
with self.subTest(method=method): |
| 165 |
for data, expected in tests: |
| 166 |
with self.subTest(data): |
| 167 |
client_method = getattr(self.client, method) |
| 168 |
method_name = method.upper() |
| 169 |
response = client_method( |
| 170 |
"/json_view/", data, content_type="application/json" |
| 171 |
) |
| 172 |
self.assertContains(response, "Viewing %s page." % method_name) |
| 173 |
self.assertEqual(response.context["data"], expected) |
| 174 |
|
| 175 |
def test_json_encoder_argument(self): |
| 176 |
"""The test Client accepts a json_encoder.""" |
| 177 |
mock_encoder = mock.MagicMock() |
| 178 |
mock_encoding = mock.MagicMock() |
| 179 |
mock_encoder.return_value = mock_encoding |
| 180 |
mock_encoding.encode.return_value = '{"value": 37}' |
| 181 |
|
| 182 |
client = self.client_class(json_encoder=mock_encoder) |
| 183 |
# Vendored tree JSON content types are accepted. |
| 184 |
client.post( |
| 185 |
"/json_view/", {"value": 37}, content_type="application/vnd.api+json" |
| 186 |
) |
| 187 |
self.assertTrue(mock_encoder.called) |
| 188 |
self.assertTrue(mock_encoding.encode.called) |
| 189 |
|
| 190 |
def test_put(self): |
| 191 |
response = self.client.put("/put_view/", {"foo": "bar"}) |
| 192 |
self.assertEqual(response.status_code, 200) |
| 193 |
self.assertEqual(response.templates[0].name, "PUT Template") |
| 194 |
self.assertEqual(response.context["data"], "{'foo': 'bar'}") |
| 195 |
self.assertEqual(response.context["Content-Length"], "14") |
| 196 |
|
| 197 |
def test_trace(self): |
| 198 |
"""TRACE a view""" |
| 199 |
response = self.client.trace("/trace_view/") |
| 200 |
self.assertEqual(response.status_code, 200) |
| 201 |
self.assertEqual(response.context["method"], "TRACE") |
| 202 |
self.assertEqual(response.templates[0].name, "TRACE Template") |
| 203 |
|
| 204 |
def test_response_headers(self): |
| 205 |
"Check the value of HTTP headers returned in a response" |
| 206 |
response = self.client.get("/header_view/") |
| 207 |
|
| 208 |
self.assertEqual(response.headers["X-DJANGO-TEST"], "Slartibartfast") |
| 209 |
|
| 210 |
def test_response_attached_request(self): |
| 211 |
""" |
| 212 |
The returned response has a ``request`` attribute with the originating |
| 213 |
environ dict and a ``wsgi_request`` with the originating WSGIRequest. |
| 214 |
""" |
| 215 |
response = self.client.get("/header_view/") |
| 216 |
|
| 217 |
self.assertTrue(hasattr(response, "request")) |
| 218 |
self.assertTrue(hasattr(response, "wsgi_request")) |
| 219 |
for key, value in response.request.items(): |
| 220 |
self.assertIn(key, response.wsgi_request.environ) |
| 221 |
self.assertEqual(response.wsgi_request.environ[key], value) |
| 222 |
|
| 223 |
def test_response_resolver_match(self): |
| 224 |
""" |
| 225 |
The response contains a ResolverMatch instance. |
| 226 |
""" |
| 227 |
response = self.client.get("/header_view/") |
| 228 |
self.assertTrue(hasattr(response, "resolver_match")) |
| 229 |
|
| 230 |
def test_response_resolver_match_redirect_follow(self): |
| 231 |
""" |
| 232 |
The response ResolverMatch instance contains the correct |
| 233 |
information when following redirects. |
| 234 |
""" |
| 235 |
response = self.client.get("/redirect_view/", follow=True) |
| 236 |
self.assertEqual(response.resolver_match.url_name, "get_view") |
| 237 |
|
| 238 |
def test_response_resolver_match_regular_view(self): |
| 239 |
""" |
| 240 |
The response ResolverMatch instance contains the correct |
| 241 |
information when accessing a regular view. |
| 242 |
""" |
| 243 |
response = self.client.get("/get_view/") |
| 244 |
self.assertEqual(response.resolver_match.url_name, "get_view") |
| 245 |
|
| 246 |
def test_response_resolver_match_class_based_view(self): |
| 247 |
""" |
| 248 |
The response ResolverMatch instance can be used to access the CBV view |
| 249 |
class. |
| 250 |
""" |
| 251 |
response = self.client.get("/accounts/") |
| 252 |
self.assertIs(response.resolver_match.func.view_class, RedirectView) |
| 253 |
|
| 254 |
@modify_settings(MIDDLEWARE={"prepend": "test_client.tests.middleware_urlconf"}) |
| 255 |
def test_response_resolver_match_middleware_urlconf(self): |
| 256 |
response = self.client.get("/middleware_urlconf_view/") |
| 257 |
self.assertEqual(response.resolver_match.url_name, "middleware_urlconf_view") |
| 258 |
|
| 259 |
def test_raw_post(self): |
| 260 |
"POST raw data (with a content type) to a view" |
| 261 |
test_doc = """<?xml version="1.0" encoding="utf-8"?> |
| 262 |
<library><book><title>Blink</title><author>Malcolm Gladwell</author></book> |
| 263 |
</library> |
| 264 |
""" |
| 265 |
response = self.client.post( |
| 266 |
"/raw_post_view/", test_doc, content_type="text/xml" |
| 267 |
) |
| 268 |
self.assertEqual(response.status_code, 200) |
| 269 |
self.assertEqual(response.templates[0].name, "Book template") |
| 270 |
self.assertEqual(response.content, b"Blink - Malcolm Gladwell") |
| 271 |
|
| 272 |
def test_insecure(self): |
| 273 |
"GET a URL through http" |
| 274 |
response = self.client.get("/secure_view/", secure=False) |
| 275 |
self.assertFalse(response.test_was_secure_request) |
| 276 |
self.assertEqual(response.test_server_port, "80") |
| 277 |
|
| 278 |
def test_secure(self): |
| 279 |
"GET a URL through https" |
| 280 |
response = self.client.get("/secure_view/", secure=True) |
| 281 |
self.assertTrue(response.test_was_secure_request) |
| 282 |
self.assertEqual(response.test_server_port, "443") |
| 283 |
|
| 284 |
def test_redirect(self): |
| 285 |
"GET a URL that redirects elsewhere" |
| 286 |
response = self.client.get("/redirect_view/") |
| 287 |
self.assertRedirects(response, "/get_view/") |
| 288 |
|
| 289 |
def test_redirect_with_query(self): |
| 290 |
"GET a URL that redirects with given GET parameters" |
| 291 |
response = self.client.get("/redirect_view/", {"var": "value"}) |
| 292 |
self.assertRedirects(response, "/get_view/?var=value") |
| 293 |
|
| 294 |
def test_redirect_with_query_ordering(self): |
| 295 |
"""assertRedirects() ignores the order of query string parameters.""" |
| 296 |
response = self.client.get("/redirect_view/", {"var": "value", "foo": "bar"}) |
| 297 |
self.assertRedirects(response, "/get_view/?var=value&foo=bar") |
| 298 |
self.assertRedirects(response, "/get_view/?foo=bar&var=value") |
| 299 |
|
| 300 |
def test_permanent_redirect(self): |
| 301 |
"GET a URL that redirects permanently elsewhere" |
| 302 |
response = self.client.get("/permanent_redirect_view/") |
| 303 |
self.assertRedirects(response, "/get_view/", status_code=301) |
| 304 |
|
| 305 |
def test_temporary_redirect(self): |
| 306 |
"GET a URL that does a non-permanent redirect" |
| 307 |
response = self.client.get("/temporary_redirect_view/") |
| 308 |
self.assertRedirects(response, "/get_view/", status_code=302) |
| 309 |
|
| 310 |
def test_redirect_to_strange_location(self): |
| 311 |
"GET a URL that redirects to a non-200 page" |
| 312 |
response = self.client.get("/double_redirect_view/") |
| 313 |
# The response was a 302, and that the attempt to get the redirection |
| 314 |
# location returned 301 when retrieved |
| 315 |
self.assertRedirects( |
| 316 |
response, "/permanent_redirect_view/", target_status_code=301 |
| 317 |
) |
| 318 |
|
| 319 |
def test_follow_redirect(self): |
| 320 |
"A URL that redirects can be followed to termination." |
| 321 |
response = self.client.get("/double_redirect_view/", follow=True) |
| 322 |
self.assertRedirects( |
| 323 |
response, "/get_view/", status_code=302, target_status_code=200 |
| 324 |
) |
| 325 |
self.assertEqual(len(response.redirect_chain), 2) |
| 326 |
|
| 327 |
def test_follow_relative_redirect(self): |
| 328 |
"A URL with a relative redirect can be followed." |
| 329 |
response = self.client.get("/accounts/", follow=True) |
| 330 |
self.assertEqual(response.status_code, 200) |
| 331 |
self.assertEqual(response.request["PATH_INFO"], "/accounts/login/") |
| 332 |
|
| 333 |
def test_follow_relative_redirect_no_trailing_slash(self): |
| 334 |
"A URL with a relative redirect with no trailing slash can be followed." |
| 335 |
response = self.client.get("/accounts/no_trailing_slash", follow=True) |
| 336 |
self.assertEqual(response.status_code, 200) |
| 337 |
self.assertEqual(response.request["PATH_INFO"], "/accounts/login/") |
| 338 |
|
| 339 |
def test_redirect_to_querystring_only(self): |
| 340 |
"""A URL that consists of a querystring only can be followed""" |
| 341 |
response = self.client.post("/post_then_get_view/", follow=True) |
| 342 |
self.assertEqual(response.status_code, 200) |
| 343 |
self.assertEqual(response.request["PATH_INFO"], "/post_then_get_view/") |
| 344 |
self.assertEqual(response.content, b"The value of success is true.") |
| 345 |
|
| 346 |
def test_follow_307_and_308_redirect(self): |
| 347 |
""" |
| 348 |
A 307 or 308 redirect preserves the request method after the redirect. |
| 349 |
""" |
| 350 |
methods = ("get", "post", "head", "options", "put", "patch", "delete", "trace") |
| 351 |
codes = (307, 308) |
| 352 |
for method, code in itertools.product(methods, codes): |
| 353 |
with self.subTest(method=method, code=code): |
| 354 |
req_method = getattr(self.client, method) |
| 355 |
response = req_method( |
| 356 |
"/redirect_view_%s/" % code, data={"value": "test"}, follow=True |
| 357 |
) |
| 358 |
self.assertEqual(response.status_code, 200) |
| 359 |
self.assertEqual(response.request["PATH_INFO"], "/post_view/") |
| 360 |
self.assertEqual(response.request["REQUEST_METHOD"], method.upper()) |
| 361 |
|
| 362 |
def test_follow_307_and_308_preserves_query_string(self): |
| 363 |
methods = ("post", "options", "put", "patch", "delete", "trace") |
| 364 |
codes = (307, 308) |
| 365 |
for method, code in itertools.product(methods, codes): |
| 366 |
with self.subTest(method=method, code=code): |
| 367 |
req_method = getattr(self.client, method) |
| 368 |
response = req_method( |
| 369 |
"/redirect_view_%s_query_string/" % code, |
| 370 |
data={"value": "test"}, |
| 371 |
follow=True, |
| 372 |
) |
| 373 |
self.assertRedirects( |
| 374 |
response, "/post_view/?hello=world", status_code=code |
| 375 |
) |
| 376 |
self.assertEqual(response.request["QUERY_STRING"], "hello=world") |
| 377 |
|
| 378 |
def test_follow_307_and_308_get_head_query_string(self): |
| 379 |
methods = ("get", "head") |
| 380 |
codes = (307, 308) |
| 381 |
for method, code in itertools.product(methods, codes): |
| 382 |
with self.subTest(method=method, code=code): |
| 383 |
req_method = getattr(self.client, method) |
| 384 |
response = req_method( |
| 385 |
"/redirect_view_%s_query_string/" % code, |
| 386 |
data={"value": "test"}, |
| 387 |
follow=True, |
| 388 |
) |
| 389 |
self.assertRedirects( |
| 390 |
response, "/post_view/?hello=world", status_code=code |
| 391 |
) |
| 392 |
self.assertEqual(response.request["QUERY_STRING"], "value=test") |
| 393 |
|
| 394 |
def test_follow_307_and_308_preserves_post_data(self): |
| 395 |
for code in (307, 308): |
| 396 |
with self.subTest(code=code): |
| 397 |
response = self.client.post( |
| 398 |
"/redirect_view_%s/" % code, data={"value": "test"}, follow=True |
| 399 |
) |
| 400 |
self.assertContains(response, "test is the value") |
| 401 |
|
| 402 |
def test_follow_307_and_308_preserves_put_body(self): |
| 403 |
for code in (307, 308): |
| 404 |
with self.subTest(code=code): |
| 405 |
response = self.client.put( |
| 406 |
"/redirect_view_%s/?to=/put_view/" % code, data="a=b", follow=True |
| 407 |
) |
| 408 |
self.assertContains(response, "a=b is the body") |
| 409 |
|
| 410 |
def test_follow_307_and_308_preserves_get_params(self): |
| 411 |
data = {"var": 30, "to": "/get_view/"} |
| 412 |
for code in (307, 308): |
| 413 |
with self.subTest(code=code): |
| 414 |
response = self.client.get( |
| 415 |
"/redirect_view_%s/" % code, data=data, follow=True |
| 416 |
) |
| 417 |
self.assertContains(response, "30 is the value") |
| 418 |
|
| 419 |
def test_redirect_http(self): |
| 420 |
"""GET a URL that redirects to an HTTP URI.""" |
| 421 |
response = self.client.get("/http_redirect_view/", follow=True) |
| 422 |
self.assertFalse(response.test_was_secure_request) |
| 423 |
|
| 424 |
def test_redirect_https(self): |
| 425 |
"""GET a URL that redirects to an HTTPS URI.""" |
| 426 |
response = self.client.get("/https_redirect_view/", follow=True) |
| 427 |
self.assertTrue(response.test_was_secure_request) |
| 428 |
|
| 429 |
def test_notfound_response(self): |
| 430 |
"GET a URL that responds as '404:Not Found'" |
| 431 |
response = self.client.get("/bad_view/") |
| 432 |
self.assertContains(response, "MAGIC", status_code=404) |
| 433 |
|
| 434 |
def test_valid_form(self): |
| 435 |
"POST valid data to a form" |
| 436 |
post_data = { |
| 437 |
"text": "Hello World", |
| 438 |
"email": "[email protected]", |
| 439 |
"value": 37, |
| 440 |
"single": "b", |
| 441 |
"multi": ("b", "c", "e"), |
| 442 |
} |
| 443 |
response = self.client.post("/form_view/", post_data) |
| 444 |
self.assertEqual(response.status_code, 200) |
| 445 |
self.assertTemplateUsed(response, "Valid POST Template") |
| 446 |
|
| 447 |
def test_valid_form_with_hints(self): |
| 448 |
"GET a form, providing hints in the GET data" |
| 449 |
hints = {"text": "Hello World", "multi": ("b", "c", "e")} |
| 450 |
response = self.client.get("/form_view/", data=hints) |
| 451 |
# The multi-value data has been rolled out ok |
| 452 |
self.assertContains(response, "Select a valid choice.", 0) |
| 453 |
self.assertTemplateUsed(response, "Form GET Template") |
| 454 |
|
| 455 |
def test_incomplete_data_form(self): |
| 456 |
"POST incomplete data to a form" |
| 457 |
post_data = {"text": "Hello World", "value": 37} |
| 458 |
response = self.client.post("/form_view/", post_data) |
| 459 |
self.assertContains(response, "This field is required.", 3) |
| 460 |
self.assertTemplateUsed(response, "Invalid POST Template") |
| 461 |
form = response.context["form"] |
| 462 |
self.assertFormError(form, "email", "This field is required.") |
| 463 |
self.assertFormError(form, "single", "This field is required.") |
| 464 |
self.assertFormError(form, "multi", "This field is required.") |
| 465 |
|
| 466 |
def test_form_error(self): |
| 467 |
"POST erroneous data to a form" |
| 468 |
post_data = { |
| 469 |
"text": "Hello World", |
| 470 |
"email": "not an email address", |
| 471 |
"value": 37, |
| 472 |
"single": "b", |
| 473 |
"multi": ("b", "c", "e"), |
| 474 |
} |
| 475 |
response = self.client.post("/form_view/", post_data) |
| 476 |
self.assertEqual(response.status_code, 200) |
| 477 |
self.assertTemplateUsed(response, "Invalid POST Template") |
| 478 |
|
| 479 |
self.assertFormError( |
| 480 |
response.context["form"], "email", "Enter a valid email address." |
| 481 |
) |
| 482 |
|
| 483 |
def test_valid_form_with_template(self): |
| 484 |
"POST valid data to a form using multiple templates" |
| 485 |
post_data = { |
| 486 |
"text": "Hello World", |
| 487 |
"email": "[email protected]", |
| 488 |
"value": 37, |
| 489 |
"single": "b", |
| 490 |
"multi": ("b", "c", "e"), |
| 491 |
} |
| 492 |
response = self.client.post("/form_view_with_template/", post_data) |
| 493 |
self.assertContains(response, "POST data OK") |
| 494 |
self.assertTemplateUsed(response, "form_view.html") |
| 495 |
self.assertTemplateUsed(response, "base.html") |
| 496 |
self.assertTemplateNotUsed(response, "Valid POST Template") |
| 497 |
|
| 498 |
def test_incomplete_data_form_with_template(self): |
| 499 |
"POST incomplete data to a form using multiple templates" |
| 500 |
post_data = {"text": "Hello World", "value": 37} |
| 501 |
response = self.client.post("/form_view_with_template/", post_data) |
| 502 |
self.assertContains(response, "POST data has errors") |
| 503 |
self.assertTemplateUsed(response, "form_view.html") |
| 504 |
self.assertTemplateUsed(response, "base.html") |
| 505 |
self.assertTemplateNotUsed(response, "Invalid POST Template") |
| 506 |
form = response.context["form"] |
| 507 |
self.assertFormError(form, "email", "This field is required.") |
| 508 |
self.assertFormError(form, "single", "This field is required.") |
| 509 |
self.assertFormError(form, "multi", "This field is required.") |
| 510 |
|
| 511 |
def test_form_error_with_template(self): |
| 512 |
"POST erroneous data to a form using multiple templates" |
| 513 |
post_data = { |
| 514 |
"text": "Hello World", |
| 515 |
"email": "not an email address", |
| 516 |
"value": 37, |
| 517 |
"single": "b", |
| 518 |
"multi": ("b", "c", "e"), |
| 519 |
} |
| 520 |
response = self.client.post("/form_view_with_template/", post_data) |
| 521 |
self.assertContains(response, "POST data has errors") |
| 522 |
self.assertTemplateUsed(response, "form_view.html") |
| 523 |
self.assertTemplateUsed(response, "base.html") |
| 524 |
self.assertTemplateNotUsed(response, "Invalid POST Template") |
| 525 |
|
| 526 |
self.assertFormError( |
| 527 |
response.context["form"], "email", "Enter a valid email address." |
| 528 |
) |
| 529 |
|
| 530 |
def test_unknown_page(self): |
| 531 |
"GET an invalid URL" |
| 532 |
response = self.client.get("/unknown_view/") |
| 533 |
|
| 534 |
# The response was a 404 |
| 535 |
self.assertEqual(response.status_code, 404) |
| 536 |
|
| 537 |
def test_url_parameters(self): |
| 538 |
"Make sure that URL ;-parameters are not stripped." |
| 539 |
response = self.client.get("/unknown_view/;some-parameter") |
| 540 |
|
| 541 |
# The path in the response includes it (ignore that it's a 404) |
| 542 |
self.assertEqual(response.request["PATH_INFO"], "/unknown_view/;some-parameter") |
| 543 |
|
| 544 |
def test_view_with_login(self): |
| 545 |
"Request a page that is protected with @login_required" |
| 546 |
|
| 547 |
# Get the page without logging in. Should result in 302. |
| 548 |
response = self.client.get("/login_protected_view/") |
| 549 |
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") |
| 550 |
|
| 551 |
# Log in |
| 552 |
login = self.client.login(username="testclient", password="password") |
| 553 |
self.assertTrue(login, "Could not log in") |
| 554 |
|
| 555 |
# Request a page that requires a login |
| 556 |
response = self.client.get("/login_protected_view/") |
| 557 |
self.assertEqual(response.status_code, 200) |
| 558 |
self.assertEqual(response.context["user"].username, "testclient") |
| 559 |
|
| 560 |
@override_settings( |
| 561 |
INSTALLED_APPS=["django.contrib.auth"], |
| 562 |
SESSION_ENGINE="django.contrib.sessions.backends.file", |
| 563 |
) |
| 564 |
def test_view_with_login_when_sessions_app_is_not_installed(self): |
| 565 |
self.test_view_with_login() |
| 566 |
|
| 567 |
def test_view_with_force_login(self): |
| 568 |
"Request a page that is protected with @login_required" |
| 569 |
# Get the page without logging in. Should result in 302. |
| 570 |
response = self.client.get("/login_protected_view/") |
| 571 |
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") |
| 572 |
|
| 573 |
# Log in |
| 574 |
self.client.force_login(self.u1) |
| 575 |
|
| 576 |
# Request a page that requires a login |
| 577 |
response = self.client.get("/login_protected_view/") |
| 578 |
self.assertEqual(response.status_code, 200) |
| 579 |
self.assertEqual(response.context["user"].username, "testclient") |
| 580 |
|
| 581 |
def test_view_with_method_login(self): |
| 582 |
"Request a page that is protected with a @login_required method" |
| 583 |
|
| 584 |
# Get the page without logging in. Should result in 302. |
| 585 |
response = self.client.get("/login_protected_method_view/") |
| 586 |
self.assertRedirects( |
| 587 |
response, "/accounts/login/?next=/login_protected_method_view/" |
| 588 |
) |
| 589 |
|
| 590 |
# Log in |
| 591 |
login = self.client.login(username="testclient", password="password") |
| 592 |
self.assertTrue(login, "Could not log in") |
| 593 |
|
| 594 |
# Request a page that requires a login |
| 595 |
response = self.client.get("/login_protected_method_view/") |
| 596 |
self.assertEqual(response.status_code, 200) |
| 597 |
self.assertEqual(response.context["user"].username, "testclient") |
| 598 |
|
| 599 |
def test_view_with_method_force_login(self): |
| 600 |
"Request a page that is protected with a @login_required method" |
| 601 |
# Get the page without logging in. Should result in 302. |
| 602 |
response = self.client.get("/login_protected_method_view/") |
| 603 |
self.assertRedirects( |
| 604 |
response, "/accounts/login/?next=/login_protected_method_view/" |
| 605 |
) |
| 606 |
|
| 607 |
# Log in |
| 608 |
self.client.force_login(self.u1) |
| 609 |
|
| 610 |
# Request a page that requires a login |
| 611 |
response = self.client.get("/login_protected_method_view/") |
| 612 |
self.assertEqual(response.status_code, 200) |
| 613 |
self.assertEqual(response.context["user"].username, "testclient") |
| 614 |
|
| 615 |
def test_view_with_login_and_custom_redirect(self): |
| 616 |
""" |
| 617 |
Request a page that is protected with |
| 618 |
@login_required(redirect_field_name='redirect_to') |
| 619 |
""" |
| 620 |
|
| 621 |
# Get the page without logging in. Should result in 302. |
| 622 |
response = self.client.get("/login_protected_view_custom_redirect/") |
| 623 |
self.assertRedirects( |
| 624 |
response, |
| 625 |
"/accounts/login/?redirect_to=/login_protected_view_custom_redirect/", |
| 626 |
) |
| 627 |
|
| 628 |
# Log in |
| 629 |
login = self.client.login(username="testclient", password="password") |
| 630 |
self.assertTrue(login, "Could not log in") |
| 631 |
|
| 632 |
# Request a page that requires a login |
| 633 |
response = self.client.get("/login_protected_view_custom_redirect/") |
| 634 |
self.assertEqual(response.status_code, 200) |
| 635 |
self.assertEqual(response.context["user"].username, "testclient") |
| 636 |
|
| 637 |
def test_view_with_force_login_and_custom_redirect(self): |
| 638 |
""" |
| 639 |
Request a page that is protected with |
| 640 |
@login_required(redirect_field_name='redirect_to') |
| 641 |
""" |
| 642 |
# Get the page without logging in. Should result in 302. |
| 643 |
response = self.client.get("/login_protected_view_custom_redirect/") |
| 644 |
self.assertRedirects( |
| 645 |
response, |
| 646 |
"/accounts/login/?redirect_to=/login_protected_view_custom_redirect/", |
| 647 |
) |
| 648 |
|
| 649 |
# Log in |
| 650 |
self.client.force_login(self.u1) |
| 651 |
|
| 652 |
# Request a page that requires a login |
| 653 |
response = self.client.get("/login_protected_view_custom_redirect/") |
| 654 |
self.assertEqual(response.status_code, 200) |
| 655 |
self.assertEqual(response.context["user"].username, "testclient") |
| 656 |
|
| 657 |
def test_view_with_bad_login(self): |
| 658 |
"Request a page that is protected with @login, but use bad credentials" |
| 659 |
|
| 660 |
login = self.client.login(username="otheruser", password="nopassword") |
| 661 |
self.assertFalse(login) |
| 662 |
|
| 663 |
def test_view_with_inactive_login(self): |
| 664 |
""" |
| 665 |
An inactive user may login if the authenticate backend allows it. |
| 666 |
""" |
| 667 |
credentials = {"username": "inactive", "password": "password"} |
| 668 |
self.assertFalse(self.client.login(**credentials)) |
| 669 |
|
| 670 |
with self.settings( |
| 671 |
AUTHENTICATION_BACKENDS=[ |
| 672 |
"django.contrib.auth.backends.AllowAllUsersModelBackend" |
| 673 |
] |
| 674 |
): |
| 675 |
self.assertTrue(self.client.login(**credentials)) |
| 676 |
|
| 677 |
@override_settings( |
| 678 |
AUTHENTICATION_BACKENDS=[ |
| 679 |
"django.contrib.auth.backends.ModelBackend", |
| 680 |
"django.contrib.auth.backends.AllowAllUsersModelBackend", |
| 681 |
] |
| 682 |
) |
| 683 |
def test_view_with_inactive_force_login(self): |
| 684 |
"Request a page that is protected with @login, but use an inactive login" |
| 685 |
|
| 686 |
# Get the page without logging in. Should result in 302. |
| 687 |
response = self.client.get("/login_protected_view/") |
| 688 |
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") |
| 689 |
|
| 690 |
# Log in |
| 691 |
self.client.force_login( |
| 692 |
self.u2, backend="django.contrib.auth.backends.AllowAllUsersModelBackend" |
| 693 |
) |
| 694 |
|
| 695 |
# Request a page that requires a login |
| 696 |
response = self.client.get("/login_protected_view/") |
| 697 |
self.assertEqual(response.status_code, 200) |
| 698 |
self.assertEqual(response.context["user"].username, "inactive") |
| 699 |
|
| 700 |
def test_logout(self): |
| 701 |
"Request a logout after logging in" |
| 702 |
# Log in |
| 703 |
self.client.login(username="testclient", password="password") |
| 704 |
|
| 705 |
# Request a page that requires a login |
| 706 |
response = self.client.get("/login_protected_view/") |
| 707 |
self.assertEqual(response.status_code, 200) |
| 708 |
self.assertEqual(response.context["user"].username, "testclient") |
| 709 |
|
| 710 |
# Log out |
| 711 |
self.client.logout() |
| 712 |
|
| 713 |
# Request a page that requires a login |
| 714 |
response = self.client.get("/login_protected_view/") |
| 715 |
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") |
| 716 |
|
| 717 |
def test_logout_with_force_login(self): |
| 718 |
"Request a logout after logging in" |
| 719 |
# Log in |
| 720 |
self.client.force_login(self.u1) |
| 721 |
|
| 722 |
# Request a page that requires a login |
| 723 |
response = self.client.get("/login_protected_view/") |
| 724 |
self.assertEqual(response.status_code, 200) |
| 725 |
self.assertEqual(response.context["user"].username, "testclient") |
| 726 |
|
| 727 |
# Log out |
| 728 |
self.client.logout() |
| 729 |
|
| 730 |
# Request a page that requires a login |
| 731 |
response = self.client.get("/login_protected_view/") |
| 732 |
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") |
| 733 |
|
| 734 |
@override_settings( |
| 735 |
AUTHENTICATION_BACKENDS=[ |
| 736 |
"django.contrib.auth.backends.ModelBackend", |
| 737 |
"test_client.auth_backends.TestClientBackend", |
| 738 |
], |
| 739 |
) |
| 740 |
def test_force_login_with_backend(self): |
| 741 |
""" |
| 742 |
Request a page that is protected with @login_required when using |
| 743 |
force_login() and passing a backend. |
| 744 |
""" |
| 745 |
# Get the page without logging in. Should result in 302. |
| 746 |
response = self.client.get("/login_protected_view/") |
| 747 |
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") |
| 748 |
|
| 749 |
# Log in |
| 750 |
self.client.force_login( |
| 751 |
self.u1, backend="test_client.auth_backends.TestClientBackend" |
| 752 |
) |
| 753 |
self.assertEqual(self.u1.backend, "test_client.auth_backends.TestClientBackend") |
| 754 |
|
| 755 |
# Request a page that requires a login |
| 756 |
response = self.client.get("/login_protected_view/") |
| 757 |
self.assertEqual(response.status_code, 200) |
| 758 |
self.assertEqual(response.context["user"].username, "testclient") |
| 759 |
|
| 760 |
@override_settings( |
| 761 |
AUTHENTICATION_BACKENDS=[ |
| 762 |
"django.contrib.auth.backends.ModelBackend", |
| 763 |
"test_client.auth_backends.TestClientBackend", |
| 764 |
], |
| 765 |
) |
| 766 |
def test_force_login_without_backend(self): |
| 767 |
""" |
| 768 |
force_login() without passing a backend and with multiple backends |
| 769 |
configured should automatically use the first backend. |
| 770 |
""" |
| 771 |
self.client.force_login(self.u1) |
| 772 |
response = self.client.get("/login_protected_view/") |
| 773 |
self.assertEqual(response.status_code, 200) |
| 774 |
self.assertEqual(response.context["user"].username, "testclient") |
| 775 |
self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend") |
| 776 |
|
| 777 |
@override_settings( |
| 778 |
AUTHENTICATION_BACKENDS=[ |
| 779 |
"test_client.auth_backends.BackendWithoutGetUserMethod", |
| 780 |
"django.contrib.auth.backends.ModelBackend", |
| 781 |
] |
| 782 |
) |
| 783 |
def test_force_login_with_backend_missing_get_user(self): |
| 784 |
""" |
| 785 |
force_login() skips auth backends without a get_user() method. |
| 786 |
""" |
| 787 |
self.client.force_login(self.u1) |
| 788 |
self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend") |
| 789 |
|
| 790 |
@override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies") |
| 791 |
def test_logout_cookie_sessions(self): |
| 792 |
self.test_logout() |
| 793 |
|
| 794 |
def test_view_with_permissions(self): |
| 795 |
"Request a page that is protected with @permission_required" |
| 796 |
|
| 797 |
# Get the page without logging in. Should result in 302. |
| 798 |
response = self.client.get("/permission_protected_view/") |
| 799 |
self.assertRedirects( |
| 800 |
response, "/accounts/login/?next=/permission_protected_view/" |
| 801 |
) |
| 802 |
|
| 803 |
# Log in |
| 804 |
login = self.client.login(username="testclient", password="password") |
| 805 |
self.assertTrue(login, "Could not log in") |
| 806 |
|
| 807 |
# Log in with wrong permissions. Should result in 302. |
| 808 |
response = self.client.get("/permission_protected_view/") |
| 809 |
self.assertRedirects( |
| 810 |
response, "/accounts/login/?next=/permission_protected_view/" |
| 811 |
) |
| 812 |
|
| 813 |
# TODO: Log in with right permissions and request the page again |
| 814 |
|
| 815 |
def test_view_with_permissions_exception(self): |
| 816 |
""" |
| 817 |
Request a page that is protected with @permission_required but raises |
| 818 |
an exception. |
| 819 |
""" |
| 820 |
|
| 821 |
# Get the page without logging in. Should result in 403. |
| 822 |
response = self.client.get("/permission_protected_view_exception/") |
| 823 |
self.assertEqual(response.status_code, 403) |
| 824 |
|
| 825 |
# Log in |
| 826 |
login = self.client.login(username="testclient", password="password") |
| 827 |
self.assertTrue(login, "Could not log in") |
| 828 |
|
| 829 |
# Log in with wrong permissions. Should result in 403. |
| 830 |
response = self.client.get("/permission_protected_view_exception/") |
| 831 |
self.assertEqual(response.status_code, 403) |
| 832 |
|
| 833 |
def test_view_with_method_permissions(self): |
| 834 |
"Request a page that is protected with a @permission_required method" |
| 835 |
|
| 836 |
# Get the page without logging in. Should result in 302. |
| 837 |
response = self.client.get("/permission_protected_method_view/") |
| 838 |
self.assertRedirects( |
| 839 |
response, "/accounts/login/?next=/permission_protected_method_view/" |
| 840 |
) |
| 841 |
|
| 842 |
# Log in |
| 843 |
login = self.client.login(username="testclient", password="password") |
| 844 |
self.assertTrue(login, "Could not log in") |
| 845 |
|
| 846 |
# Log in with wrong permissions. Should result in 302. |
| 847 |
response = self.client.get("/permission_protected_method_view/") |
| 848 |
self.assertRedirects( |
| 849 |
response, "/accounts/login/?next=/permission_protected_method_view/" |
| 850 |
) |
| 851 |
|
| 852 |
# TODO: Log in with right permissions and request the page again |
| 853 |
|
| 854 |
def test_external_redirect(self): |
| 855 |
response = self.client.get("/django_project_redirect/") |
| 856 |
self.assertRedirects( |
| 857 |
response, "https://www.djangoproject.com/", fetch_redirect_response=False |
| 858 |
) |
| 859 |
|
| 860 |
@override_settings(ALLOWED_HOSTS=["hostname1", "hostname2"]) |
| 861 |
def test_redirect_with_http_host(self): |
| 862 |
response = self.client.get( |
| 863 |
"/redirect_to_different_hostname/", follow=True, HTTP_HOST="hostname1" |
| 864 |
) |
| 865 |
self.assertEqual(response.content, b"hostname2") |
| 866 |
|
| 867 |
def test_external_redirect_without_trailing_slash(self): |
| 868 |
""" |
| 869 |
Client._handle_redirects() with an empty path. |
| 870 |
""" |
| 871 |
response = self.client.get("/no_trailing_slash_external_redirect/", follow=True) |
| 872 |
self.assertRedirects(response, "https://testserver") |
| 873 |
|
| 874 |
def test_external_redirect_with_fetch_error_msg(self): |
| 875 |
""" |
| 876 |
assertRedirects without fetch_redirect_response=False raises |
| 877 |
a relevant ValueError rather than a non-descript AssertionError. |
| 878 |
""" |
| 879 |
response = self.client.get("/django_project_redirect/") |
| 880 |
msg = ( |
| 881 |
"The test client is unable to fetch remote URLs (got " |
| 882 |
"https://www.djangoproject.com/). If the host is served by Django, " |
| 883 |
"add 'www.djangoproject.com' to ALLOWED_HOSTS. " |
| 884 |
"Otherwise, use assertRedirects(..., fetch_redirect_response=False)." |
| 885 |
) |
| 886 |
with self.assertRaisesMessage(ValueError, msg): |
| 887 |
self.assertRedirects(response, "https://www.djangoproject.com/") |
| 888 |
|
| 889 |
def test_session_modifying_view(self): |
| 890 |
"Request a page that modifies the session" |
| 891 |
# Session value isn't set initially |
| 892 |
with self.assertRaises(KeyError): |
| 893 |
self.client.session["tobacconist"] |
| 894 |
|
| 895 |
self.client.post("/session_view/") |
| 896 |
# The session was modified |
| 897 |
self.assertEqual(self.client.session["tobacconist"], "hovercraft") |
| 898 |
|
| 899 |
@override_settings( |
| 900 |
INSTALLED_APPS=[], |
| 901 |
SESSION_ENGINE="django.contrib.sessions.backends.file", |
| 902 |
) |
| 903 |
def test_sessions_app_is_not_installed(self): |
| 904 |
self.test_session_modifying_view() |
| 905 |
|
| 906 |
@override_settings( |
| 907 |
INSTALLED_APPS=[], |
| 908 |
SESSION_ENGINE="django.contrib.sessions.backends.nonexistent", |
| 909 |
) |
| 910 |
def test_session_engine_is_invalid(self): |
| 911 |
with self.assertRaisesMessage(ImportError, "nonexistent"): |
| 912 |
self.test_session_modifying_view() |
| 913 |
|
| 914 |
def test_view_with_exception(self): |
| 915 |
"Request a page that is known to throw an error" |
| 916 |
with self.assertRaises(KeyError): |
| 917 |
self.client.get("/broken_view/") |
| 918 |
|
| 919 |
def test_exc_info(self): |
| 920 |
client = Client(raise_request_exception=False) |
| 921 |
response = client.get("/broken_view/") |
| 922 |
self.assertEqual(response.status_code, 500) |
| 923 |
exc_type, exc_value, exc_traceback = response.exc_info |
| 924 |
self.assertIs(exc_type, KeyError) |
| 925 |
self.assertIsInstance(exc_value, KeyError) |
| 926 |
self.assertEqual(str(exc_value), "'Oops! Looks like you wrote some bad code.'") |
| 927 |
self.assertIsNotNone(exc_traceback) |
| 928 |
|
| 929 |
def test_exc_info_none(self): |
| 930 |
response = self.client.get("/get_view/") |
| 931 |
self.assertIsNone(response.exc_info) |
| 932 |
|
| 933 |
def test_mail_sending(self): |
| 934 |
"Mail is redirected to a dummy outbox during test setup" |
| 935 |
response = self.client.get("/mail_sending_view/") |
| 936 |
self.assertEqual(response.status_code, 200) |
| 937 |
|
| 938 |
self.assertEqual(len(mail.outbox), 1) |
| 939 |
self.assertEqual(mail.outbox[0].subject, "Test message") |
| 940 |
self.assertEqual(mail.outbox[0].body, "This is a test email") |
| 941 |
self.assertEqual(mail.outbox[0].from_email, "[email protected]") |
| 942 |
self.assertEqual(mail.outbox[0].to[0], "[email protected]") |
| 943 |
self.assertEqual(mail.outbox[0].to[1], "[email protected]") |
| 944 |
|
| 945 |
def test_reverse_lazy_decodes(self): |
| 946 |
"reverse_lazy() works in the test client" |
| 947 |
data = {"var": "data"} |
| 948 |
response = self.client.get(reverse_lazy("get_view"), data) |
| 949 |
|
| 950 |
# Check some response details |
| 951 |
self.assertContains(response, "This is a test") |
| 952 |
|
| 953 |
def test_relative_redirect(self): |
| 954 |
response = self.client.get("/accounts/") |
| 955 |
self.assertRedirects(response, "/accounts/login/") |
| 956 |
|
| 957 |
def test_relative_redirect_no_trailing_slash(self): |
| 958 |
response = self.client.get("/accounts/no_trailing_slash") |
| 959 |
self.assertRedirects(response, "/accounts/login/") |
| 960 |
|
| 961 |
def test_mass_mail_sending(self): |
| 962 |
"Mass mail is redirected to a dummy outbox during test setup" |
| 963 |
response = self.client.get("/mass_mail_sending_view/") |
| 964 |
self.assertEqual(response.status_code, 200) |
| 965 |
|
| 966 |
self.assertEqual(len(mail.outbox), 2) |
| 967 |
self.assertEqual(mail.outbox[0].subject, "First Test message") |
| 968 |
self.assertEqual(mail.outbox[0].body, "This is the first test email") |
| 969 |
self.assertEqual(mail.outbox[0].from_email, "[email protected]") |
| 970 |
self.assertEqual(mail.outbox[0].to[0], "[email protected]") |
| 971 |
self.assertEqual(mail.outbox[0].to[1], "[email protected]") |
| 972 |
|
| 973 |
self.assertEqual(mail.outbox[1].subject, "Second Test message") |
| 974 |
self.assertEqual(mail.outbox[1].body, "This is the second test email") |
| 975 |
self.assertEqual(mail.outbox[1].from_email, "[email protected]") |
| 976 |
self.assertEqual(mail.outbox[1].to[0], "[email protected]") |
| 977 |
self.assertEqual(mail.outbox[1].to[1], "[email protected]") |
| 978 |
|
| 979 |
def test_exception_following_nested_client_request(self): |
| 980 |
""" |
| 981 |
A nested test client request shouldn't clobber exception signals from |
| 982 |
the outer client request. |
| 983 |
""" |
| 984 |
with self.assertRaisesMessage(Exception, "exception message"): |
| 985 |
self.client.get("/nesting_exception_view/") |
| 986 |
|
| 987 |
def test_response_raises_multi_arg_exception(self): |
| 988 |
"""A request may raise an exception with more than one required arg.""" |
| 989 |
with self.assertRaises(TwoArgException) as cm: |
| 990 |
self.client.get("/two_arg_exception/") |
| 991 |
self.assertEqual(cm.exception.args, ("one", "two")) |
| 992 |
|
| 993 |
def test_uploading_temp_file(self): |
| 994 |
with tempfile.TemporaryFile() as test_file: |
| 995 |
response = self.client.post("/upload_view/", data={"temp_file": test_file}) |
| 996 |
self.assertEqual(response.content, b"temp_file") |
| 997 |
|
| 998 |
def test_uploading_named_temp_file(self): |
| 999 |
with tempfile.NamedTemporaryFile() as test_file: |
| 1000 |
response = self.client.post( |
| 1001 |
"/upload_view/", |
| 1002 |
data={"named_temp_file": test_file}, |
| 1003 |
) |
| 1004 |
self.assertEqual(response.content, b"named_temp_file") |
| 1005 |
|
| 1006 |
def test_query_params(self): |
| 1007 |
tests = ( |
| 1008 |
"get", |
| 1009 |
"post", |
| 1010 |
"put", |
| 1011 |
"patch", |
| 1012 |
"delete", |
| 1013 |
"head", |
| 1014 |
"options", |
| 1015 |
"trace", |
| 1016 |
) |
| 1017 |
for method in tests: |
| 1018 |
with self.subTest(method=method): |
| 1019 |
client_method = getattr(self.client, method) |
| 1020 |
response = client_method("/get_view/", query_params={"example": "data"}) |
| 1021 |
self.assertEqual(response.wsgi_request.GET["example"], "data") |
| 1022 |
|
| 1023 |
def test_cannot_use_data_and_query_params_together(self): |
| 1024 |
tests = ["get", "head"] |
| 1025 |
msg = "query_params and data arguments are mutually exclusive." |
| 1026 |
for method in tests: |
| 1027 |
with self.subTest(method=method): |
| 1028 |
client_method = getattr(self.client, method) |
| 1029 |
with self.assertRaisesMessage(ValueError, msg): |
| 1030 |
client_method( |
| 1031 |
"/get_view/", |
| 1032 |
data={"example": "data"}, |
| 1033 |
query_params={"q": "terms"}, |
| 1034 |
) |
| 1035 |
|
| 1036 |
|
| 1037 |
@override_settings( |
| 1038 |
MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], |
| 1039 |
ROOT_URLCONF="test_client.urls", |
| 1040 |
) |
| 1041 |
class CSRFEnabledClientTests(SimpleTestCase): |
| 1042 |
def test_csrf_enabled_client(self): |
| 1043 |
"A client can be instantiated with CSRF checks enabled" |
| 1044 |
csrf_client = Client(enforce_csrf_checks=True) |
| 1045 |
# The normal client allows the post |
| 1046 |
response = self.client.post("/post_view/", {}) |
| 1047 |
self.assertEqual(response.status_code, 200) |
| 1048 |
# The CSRF-enabled client rejects it |
| 1049 |
response = csrf_client.post("/post_view/", {}) |
| 1050 |
self.assertEqual(response.status_code, 403) |
| 1051 |
|
| 1052 |
|
| 1053 |
class CustomTestClient(Client): |
| 1054 |
i_am_customized = "Yes" |
| 1055 |
|
| 1056 |
|
| 1057 |
class CustomTestClientTest(SimpleTestCase): |
| 1058 |
client_class = CustomTestClient |
| 1059 |
|
| 1060 |
def test_custom_test_client(self): |
| 1061 |
"""A test case can specify a custom class for self.client.""" |
| 1062 |
self.assertIs(hasattr(self.client, "i_am_customized"), True) |
| 1063 |
|
| 1064 |
|
| 1065 |
def _generic_view(request): |
| 1066 |
return HttpResponse(status=200) |
| 1067 |
|
| 1068 |
|
| 1069 |
@override_settings(ROOT_URLCONF="test_client.urls") |
| 1070 |
class RequestFactoryTest(SimpleTestCase): |
| 1071 |
"""Tests for the request factory.""" |
| 1072 |
|
| 1073 |
# A mapping between names of HTTP/1.1 methods and their test views. |
| 1074 |
http_methods_and_views = ( |
| 1075 |
("get", get_view), |
| 1076 |
("post", post_view), |
| 1077 |
("put", _generic_view), |
| 1078 |
("patch", _generic_view), |
| 1079 |
("delete", _generic_view), |
| 1080 |
("head", _generic_view), |
| 1081 |
("options", _generic_view), |
| 1082 |
("trace", trace_view), |
| 1083 |
) |
| 1084 |
request_factory = RequestFactory() |
| 1085 |
|
| 1086 |
def test_request_factory(self): |
| 1087 |
"""The request factory implements all the HTTP/1.1 methods.""" |
| 1088 |
for method_name, view in self.http_methods_and_views: |
| 1089 |
method = getattr(self.request_factory, method_name) |
| 1090 |
request = method("/somewhere/") |
| 1091 |
response = view(request) |
| 1092 |
self.assertEqual(response.status_code, 200) |
| 1093 |
|
| 1094 |
def test_get_request_from_factory(self): |
| 1095 |
""" |
| 1096 |
The request factory returns a templated response for a GET request. |
| 1097 |
""" |
| 1098 |
request = self.request_factory.get("/somewhere/") |
| 1099 |
response = get_view(request) |
| 1100 |
self.assertContains(response, "This is a test") |
| 1101 |
|
| 1102 |
def test_trace_request_from_factory(self): |
| 1103 |
"""The request factory returns an echo response for a TRACE request.""" |
| 1104 |
url_path = "/somewhere/" |
| 1105 |
request = self.request_factory.trace(url_path) |
| 1106 |
response = trace_view(request) |
| 1107 |
protocol = request.META["SERVER_PROTOCOL"] |
| 1108 |
echoed_request_line = "TRACE {} {}".format(url_path, protocol) |
| 1109 |
self.assertContains(response, echoed_request_line) |
| 1110 |
|
| 1111 |
def test_request_factory_default_headers(self): |
| 1112 |
request = RequestFactory( |
| 1113 |
headers={ |
| 1114 |
"authorization": "Bearer faketoken", |
| 1115 |
"x-another-header": "some other value", |
| 1116 |
} |
| 1117 |
).get("/somewhere/") |
| 1118 |
self.assertEqual(request.headers["authorization"], "Bearer faketoken") |
| 1119 |
self.assertIn("HTTP_AUTHORIZATION", request.META) |
| 1120 |
self.assertEqual(request.headers["x-another-header"], "some other value") |
| 1121 |
self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) |
| 1122 |
|
| 1123 |
request = RequestFactory( |
| 1124 |
headers={ |
| 1125 |
"Authorization": "Bearer faketoken", |
| 1126 |
"X-Another-Header": "some other value", |
| 1127 |
} |
| 1128 |
).get("/somewhere/") |
| 1129 |
self.assertEqual(request.headers["authorization"], "Bearer faketoken") |
| 1130 |
self.assertIn("HTTP_AUTHORIZATION", request.META) |
| 1131 |
self.assertEqual(request.headers["x-another-header"], "some other value") |
| 1132 |
self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) |
| 1133 |
|
| 1134 |
def test_request_factory_sets_headers(self): |
| 1135 |
for method_name, view in self.http_methods_and_views: |
| 1136 |
method = getattr(self.request_factory, method_name) |
| 1137 |
request = method( |
| 1138 |
"/somewhere/", |
| 1139 |
headers={ |
| 1140 |
"authorization": "Bearer faketoken", |
| 1141 |
"x-another-header": "some other value", |
| 1142 |
}, |
| 1143 |
) |
| 1144 |
self.assertEqual(request.headers["authorization"], "Bearer faketoken") |
| 1145 |
self.assertIn("HTTP_AUTHORIZATION", request.META) |
| 1146 |
self.assertEqual(request.headers["x-another-header"], "some other value") |
| 1147 |
self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) |
| 1148 |
|
| 1149 |
request = method( |
| 1150 |
"/somewhere/", |
| 1151 |
headers={ |
| 1152 |
"Authorization": "Bearer faketoken", |
| 1153 |
"X-Another-Header": "some other value", |
| 1154 |
}, |
| 1155 |
) |
| 1156 |
self.assertEqual(request.headers["authorization"], "Bearer faketoken") |
| 1157 |
self.assertIn("HTTP_AUTHORIZATION", request.META) |
| 1158 |
self.assertEqual(request.headers["x-another-header"], "some other value") |
| 1159 |
self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) |
| 1160 |
|
| 1161 |
def test_request_factory_query_params(self): |
| 1162 |
tests = ( |
| 1163 |
"get", |
| 1164 |
"post", |
| 1165 |
"put", |
| 1166 |
"patch", |
| 1167 |
"delete", |
| 1168 |
"head", |
| 1169 |
"options", |
| 1170 |
"trace", |
| 1171 |
) |
| 1172 |
for method in tests: |
| 1173 |
with self.subTest(method=method): |
| 1174 |
factory = getattr(self.request_factory, method) |
| 1175 |
request = factory("/somewhere", query_params={"example": "data"}) |
| 1176 |
self.assertEqual(request.GET["example"], "data") |
| 1177 |
|
| 1178 |
|
| 1179 |
@override_settings(ROOT_URLCONF="test_client.urls") |
| 1180 |
class AsyncClientTest(TestCase): |
| 1181 |
async def test_response_resolver_match(self): |
| 1182 |
response = await self.async_client.get("/async_get_view/") |
| 1183 |
self.assertTrue(hasattr(response, "resolver_match")) |
| 1184 |
self.assertEqual(response.resolver_match.url_name, "async_get_view") |
| 1185 |
|
| 1186 |
@modify_settings( |
| 1187 |
MIDDLEWARE={"prepend": "test_client.tests.async_middleware_urlconf"}, |
| 1188 |
) |
| 1189 |
async def test_response_resolver_match_middleware_urlconf(self): |
| 1190 |
response = await self.async_client.get("/middleware_urlconf_view/") |
| 1191 |
self.assertEqual(response.resolver_match.url_name, "middleware_urlconf_view") |
| 1192 |
|
| 1193 |
async def test_redirect(self): |
| 1194 |
response = await self.async_client.get("/redirect_view/") |
| 1195 |
self.assertEqual(response.status_code, 302) |
| 1196 |
|
| 1197 |
async def test_follow_redirect(self): |
| 1198 |
tests = ( |
| 1199 |
"get", |
| 1200 |
"post", |
| 1201 |
"put", |
| 1202 |
"patch", |
| 1203 |
"delete", |
| 1204 |
"head", |
| 1205 |
"options", |
| 1206 |
"trace", |
| 1207 |
) |
| 1208 |
for method_name in tests: |
| 1209 |
with self.subTest(method=method_name): |
| 1210 |
method = getattr(self.async_client, method_name) |
| 1211 |
response = await method("/redirect_view/", follow=True) |
| 1212 |
self.assertEqual(response.status_code, 200) |
| 1213 |
self.assertEqual(response.resolver_match.url_name, "get_view") |
| 1214 |
|
| 1215 |
async def test_follow_double_redirect(self): |
| 1216 |
response = await self.async_client.get("/double_redirect_view/", follow=True) |
| 1217 |
self.assertRedirects( |
| 1218 |
response, "/get_view/", status_code=302, target_status_code=200 |
| 1219 |
) |
| 1220 |
self.assertEqual(len(response.redirect_chain), 2) |
| 1221 |
|
| 1222 |
async def test_get_data(self): |
| 1223 |
response = await self.async_client.get("/get_view/", {"var": "val"}) |
| 1224 |
self.assertContains(response, "This is a test. val is the value.") |
| 1225 |
|
| 1226 |
async def test_post_data(self): |
| 1227 |
response = await self.async_client.post("/post_view/", {"value": 37}) |
| 1228 |
self.assertContains(response, "Data received: 37 is the value.") |
| 1229 |
|
| 1230 |
async def test_body_read_on_get_data(self): |
| 1231 |
response = await self.async_client.get("/post_view/") |
| 1232 |
self.assertContains(response, "Viewing GET page.") |
| 1233 |
|
| 1234 |
async def test_query_params(self): |
| 1235 |
tests = ( |
| 1236 |
"get", |
| 1237 |
"post", |
| 1238 |
"put", |
| 1239 |
"patch", |
| 1240 |
"delete", |
| 1241 |
"head", |
| 1242 |
"options", |
| 1243 |
"trace", |
| 1244 |
) |
| 1245 |
for method in tests: |
| 1246 |
with self.subTest(method=method): |
| 1247 |
client_method = getattr(self.async_client, method) |
| 1248 |
response = await client_method( |
| 1249 |
"/async_get_view/", query_params={"example": "data"} |
| 1250 |
) |
| 1251 |
self.assertEqual(response.asgi_request.GET["example"], "data") |
| 1252 |
|
| 1253 |
|
| 1254 |
@override_settings(ROOT_URLCONF="test_client.urls") |
| 1255 |
class AsyncRequestFactoryTest(SimpleTestCase): |
| 1256 |
request_factory = AsyncRequestFactory() |
| 1257 |
|
| 1258 |
async def test_request_factory(self): |
| 1259 |
tests = ( |
| 1260 |
"get", |
| 1261 |
"post", |
| 1262 |
"put", |
| 1263 |
"patch", |
| 1264 |
"delete", |
| 1265 |
"head", |
| 1266 |
"options", |
| 1267 |
"trace", |
| 1268 |
) |
| 1269 |
for method_name in tests: |
| 1270 |
with self.subTest(method=method_name): |
| 1271 |
|
| 1272 |
async def async_generic_view(request): |
| 1273 |
if request.method.lower() != method_name: |
| 1274 |
return HttpResponseNotAllowed(method_name) |
| 1275 |
return HttpResponse(status=200) |
| 1276 |
|
| 1277 |
method = getattr(self.request_factory, method_name) |
| 1278 |
request = method("/somewhere/") |
| 1279 |
response = await async_generic_view(request) |
| 1280 |
self.assertEqual(response.status_code, 200) |
| 1281 |
|
| 1282 |
async def test_request_factory_data(self): |
| 1283 |
async def async_generic_view(request): |
| 1284 |
return HttpResponse(status=200, content=request.body) |
| 1285 |
|
| 1286 |
request = self.request_factory.post( |
| 1287 |
"/somewhere/", |
| 1288 |
data={"example": "data"}, |
| 1289 |
content_type="application/json", |
| 1290 |
) |
| 1291 |
self.assertEqual(request.headers["content-length"], "19") |
| 1292 |
self.assertEqual(request.headers["content-type"], "application/json") |
| 1293 |
response = await async_generic_view(request) |
| 1294 |
self.assertEqual(response.status_code, 200) |
| 1295 |
self.assertEqual(response.content, b'{"example": "data"}') |
| 1296 |
|
| 1297 |
async def test_request_limited_read(self): |
| 1298 |
tests = ["GET", "POST"] |
| 1299 |
for method in tests: |
| 1300 |
with self.subTest(method=method): |
| 1301 |
request = self.request_factory.generic( |
| 1302 |
method, |
| 1303 |
"/somewhere", |
| 1304 |
) |
| 1305 |
self.assertEqual(request.read(200), b"") |
| 1306 |
|
| 1307 |
def test_request_factory_sets_headers(self): |
| 1308 |
request = self.request_factory.get( |
| 1309 |
"/somewhere/", |
| 1310 |
AUTHORIZATION="Bearer faketoken", |
| 1311 |
X_ANOTHER_HEADER="some other value", |
| 1312 |
) |
| 1313 |
self.assertEqual(request.headers["authorization"], "Bearer faketoken") |
| 1314 |
self.assertIn("HTTP_AUTHORIZATION", request.META) |
| 1315 |
self.assertEqual(request.headers["x-another-header"], "some other value") |
| 1316 |
self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) |
| 1317 |
|
| 1318 |
request = self.request_factory.get( |
| 1319 |
"/somewhere/", |
| 1320 |
headers={ |
| 1321 |
"Authorization": "Bearer faketoken", |
| 1322 |
"X-Another-Header": "some other value", |
| 1323 |
}, |
| 1324 |
) |
| 1325 |
self.assertEqual(request.headers["authorization"], "Bearer faketoken") |
| 1326 |
self.assertIn("HTTP_AUTHORIZATION", request.META) |
| 1327 |
self.assertEqual(request.headers["x-another-header"], "some other value") |
| 1328 |
self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) |
| 1329 |
|
| 1330 |
def test_async_request_factory_default_headers(self): |
| 1331 |
request_factory_with_headers = AsyncRequestFactory( |
| 1332 |
**{ |
| 1333 |
"Authorization": "Bearer faketoken", |
| 1334 |
"X-Another-Header": "some other value", |
| 1335 |
} |
| 1336 |
) |
| 1337 |
request = request_factory_with_headers.get("/somewhere/") |
| 1338 |
self.assertEqual(request.headers["authorization"], "Bearer faketoken") |
| 1339 |
self.assertIn("HTTP_AUTHORIZATION", request.META) |
| 1340 |
self.assertEqual(request.headers["x-another-header"], "some other value") |
| 1341 |
self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) |
| 1342 |
|
| 1343 |
def test_request_factory_query_string(self): |
| 1344 |
request = self.request_factory.get("/somewhere/", {"example": "data"}) |
| 1345 |
self.assertNotIn("Query-String", request.headers) |
| 1346 |
self.assertEqual(request.GET["example"], "data") |
| 1347 |
|
| 1348 |
def test_request_factory_query_params(self): |
| 1349 |
tests = ( |
| 1350 |
"get", |
| 1351 |
"post", |
| 1352 |
"put", |
| 1353 |
"patch", |
| 1354 |
"delete", |
| 1355 |
"head", |
| 1356 |
"options", |
| 1357 |
"trace", |
| 1358 |
) |
| 1359 |
for method in tests: |
| 1360 |
with self.subTest(method=method): |
| 1361 |
factory = getattr(self.request_factory, method) |
| 1362 |
request = factory("/somewhere", query_params={"example": "data"}) |
| 1363 |
self.assertEqual(request.GET["example"], "data") |
| 1364 |
|
| 1365 |
def test_cannot_use_data_and_query_params_together(self): |
| 1366 |
tests = ["get", "head"] |
| 1367 |
msg = "query_params and data arguments are mutually exclusive." |
| 1368 |
for method in tests: |
| 1369 |
with self.subTest(method=method): |
| 1370 |
factory = getattr(self.request_factory, method) |
| 1371 |
with self.assertRaisesMessage(ValueError, msg): |
| 1372 |
factory( |
| 1373 |
"/somewhere", |
| 1374 |
data={"example": "data"}, |
| 1375 |
query_params={"q": "terms"}, |
| 1376 |
) |