| 1 |
""" |
| 2 |
Regression tests for the Test Client, especially the customized assertions. |
| 3 |
""" |
| 4 |
|
| 5 |
import itertools |
| 6 |
import os |
| 7 |
|
| 8 |
from django.contrib.auth.models import User |
| 9 |
from django.contrib.auth.signals import user_logged_in, user_logged_out |
| 10 |
from django.http import HttpResponse |
| 11 |
from django.template import Context, RequestContext, TemplateSyntaxError, engines |
| 12 |
from django.template.response import SimpleTemplateResponse |
| 13 |
from django.test import ( |
| 14 |
Client, |
| 15 |
SimpleTestCase, |
| 16 |
TestCase, |
| 17 |
modify_settings, |
| 18 |
override_settings, |
| 19 |
) |
| 20 |
from django.test.client import RedirectCycleError, RequestFactory, encode_file |
| 21 |
from django.test.utils import ContextList |
| 22 |
from django.urls import NoReverseMatch, reverse |
| 23 |
from django.utils.translation import gettext_lazy |
| 24 |
|
| 25 |
from .models import CustomUser |
| 26 |
from .views import CustomTestException |
| 27 |
|
| 28 |
|
| 29 |
class TestDataMixin: |
| 30 |
@classmethod |
| 31 |
def setUpTestData(cls): |
| 32 |
cls.u1 = User.objects.create_user(username="testclient", password="password") |
| 33 |
cls.staff = User.objects.create_user( |
| 34 |
username="staff", password="password", is_staff=True |
| 35 |
) |
| 36 |
|
| 37 |
|
| 38 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 39 |
class AssertContainsTests(SimpleTestCase): |
| 40 |
def test_contains(self): |
| 41 |
"Responses can be inspected for content, including counting repeated substrings" |
| 42 |
response = self.client.get("/no_template_view/") |
| 43 |
|
| 44 |
self.assertNotContains(response, "never") |
| 45 |
self.assertContains(response, "never", 0) |
| 46 |
self.assertContains(response, "once") |
| 47 |
self.assertContains(response, "once", 1) |
| 48 |
self.assertContains(response, "twice") |
| 49 |
self.assertContains(response, "twice", 2) |
| 50 |
|
| 51 |
try: |
| 52 |
self.assertContains(response, "text", status_code=999) |
| 53 |
except AssertionError as e: |
| 54 |
self.assertIn( |
| 55 |
"Couldn't retrieve content: Response code was 200 (expected 999)", |
| 56 |
str(e), |
| 57 |
) |
| 58 |
try: |
| 59 |
self.assertContains(response, "text", status_code=999, msg_prefix="abc") |
| 60 |
except AssertionError as e: |
| 61 |
self.assertIn( |
| 62 |
"abc: Couldn't retrieve content: Response code was 200 (expected 999)", |
| 63 |
str(e), |
| 64 |
) |
| 65 |
|
| 66 |
try: |
| 67 |
self.assertNotContains(response, "text", status_code=999) |
| 68 |
except AssertionError as e: |
| 69 |
self.assertIn( |
| 70 |
"Couldn't retrieve content: Response code was 200 (expected 999)", |
| 71 |
str(e), |
| 72 |
) |
| 73 |
try: |
| 74 |
self.assertNotContains(response, "text", status_code=999, msg_prefix="abc") |
| 75 |
except AssertionError as e: |
| 76 |
self.assertIn( |
| 77 |
"abc: Couldn't retrieve content: Response code was 200 (expected 999)", |
| 78 |
str(e), |
| 79 |
) |
| 80 |
|
| 81 |
try: |
| 82 |
self.assertNotContains(response, "once") |
| 83 |
except AssertionError as e: |
| 84 |
self.assertIn( |
| 85 |
"'once' unexpectedly found in the following response\n" |
| 86 |
f"{response.content}", |
| 87 |
str(e), |
| 88 |
) |
| 89 |
try: |
| 90 |
self.assertNotContains(response, "once", msg_prefix="abc") |
| 91 |
except AssertionError as e: |
| 92 |
self.assertIn( |
| 93 |
"abc: 'once' unexpectedly found in the following response\n" |
| 94 |
f"{response.content}", |
| 95 |
str(e), |
| 96 |
) |
| 97 |
|
| 98 |
try: |
| 99 |
self.assertContains(response, "never", 1) |
| 100 |
except AssertionError as e: |
| 101 |
self.assertIn( |
| 102 |
"Found 0 instances of 'never' (expected 1) in the following response\n" |
| 103 |
f"{response.content}", |
| 104 |
str(e), |
| 105 |
) |
| 106 |
try: |
| 107 |
self.assertContains(response, "never", 1, msg_prefix="abc") |
| 108 |
except AssertionError as e: |
| 109 |
self.assertIn( |
| 110 |
"abc: Found 0 instances of 'never' (expected 1) in the following " |
| 111 |
f"response\n{response.content}", |
| 112 |
str(e), |
| 113 |
) |
| 114 |
|
| 115 |
try: |
| 116 |
self.assertContains(response, "once", 0) |
| 117 |
except AssertionError as e: |
| 118 |
self.assertIn( |
| 119 |
"Found 1 instances of 'once' (expected 0) in the following response\n" |
| 120 |
f"{response.content}", |
| 121 |
str(e), |
| 122 |
) |
| 123 |
try: |
| 124 |
self.assertContains(response, "once", 0, msg_prefix="abc") |
| 125 |
except AssertionError as e: |
| 126 |
self.assertIn( |
| 127 |
"abc: Found 1 instances of 'once' (expected 0) in the following " |
| 128 |
f"response\n{response.content}", |
| 129 |
str(e), |
| 130 |
) |
| 131 |
|
| 132 |
try: |
| 133 |
self.assertContains(response, "once", 2) |
| 134 |
except AssertionError as e: |
| 135 |
self.assertIn( |
| 136 |
"Found 1 instances of 'once' (expected 2) in the following response\n" |
| 137 |
f"{response.content}", |
| 138 |
str(e), |
| 139 |
) |
| 140 |
try: |
| 141 |
self.assertContains(response, "once", 2, msg_prefix="abc") |
| 142 |
except AssertionError as e: |
| 143 |
self.assertIn( |
| 144 |
"abc: Found 1 instances of 'once' (expected 2) in the following " |
| 145 |
f"response\n{response.content}", |
| 146 |
str(e), |
| 147 |
) |
| 148 |
|
| 149 |
try: |
| 150 |
self.assertContains(response, "twice", 1) |
| 151 |
except AssertionError as e: |
| 152 |
self.assertIn( |
| 153 |
"Found 2 instances of 'twice' (expected 1) in the following response\n" |
| 154 |
f"{response.content}", |
| 155 |
str(e), |
| 156 |
) |
| 157 |
try: |
| 158 |
self.assertContains(response, "twice", 1, msg_prefix="abc") |
| 159 |
except AssertionError as e: |
| 160 |
self.assertIn( |
| 161 |
"abc: Found 2 instances of 'twice' (expected 1) in the following " |
| 162 |
f"response\n{response.content}", |
| 163 |
str(e), |
| 164 |
) |
| 165 |
|
| 166 |
try: |
| 167 |
self.assertContains(response, "thrice") |
| 168 |
except AssertionError as e: |
| 169 |
self.assertIn( |
| 170 |
f"Couldn't find 'thrice' in the following response\n{response.content}", |
| 171 |
str(e), |
| 172 |
) |
| 173 |
try: |
| 174 |
self.assertContains(response, "thrice", msg_prefix="abc") |
| 175 |
except AssertionError as e: |
| 176 |
self.assertIn( |
| 177 |
"abc: Couldn't find 'thrice' in the following response\n" |
| 178 |
f"{response.content}", |
| 179 |
str(e), |
| 180 |
) |
| 181 |
|
| 182 |
try: |
| 183 |
self.assertContains(response, "thrice", 3) |
| 184 |
except AssertionError as e: |
| 185 |
self.assertIn( |
| 186 |
"Found 0 instances of 'thrice' (expected 3) in the following response\n" |
| 187 |
f"{response.content}", |
| 188 |
str(e), |
| 189 |
) |
| 190 |
try: |
| 191 |
self.assertContains(response, "thrice", 3, msg_prefix="abc") |
| 192 |
except AssertionError as e: |
| 193 |
self.assertIn( |
| 194 |
"abc: Found 0 instances of 'thrice' (expected 3) in the following " |
| 195 |
f"response\n{response.content}", |
| 196 |
str(e), |
| 197 |
) |
| 198 |
|
| 199 |
long_content = ( |
| 200 |
b"This is a very very very very very very very very long message which " |
| 201 |
b"exceeds the max limit of truncation." |
| 202 |
) |
| 203 |
response = HttpResponse(long_content) |
| 204 |
msg = f"Couldn't find 'thrice' in the following response\n{long_content}" |
| 205 |
with self.assertRaisesMessage(AssertionError, msg): |
| 206 |
self.assertContains(response, "thrice") |
| 207 |
|
| 208 |
msg = ( |
| 209 |
"Found 1 instances of 'This' (expected 3) in the following response\n" |
| 210 |
f"{long_content}" |
| 211 |
) |
| 212 |
with self.assertRaisesMessage(AssertionError, msg): |
| 213 |
self.assertContains(response, "This", 3) |
| 214 |
|
| 215 |
msg = f"'very' unexpectedly found in the following response\n{long_content}" |
| 216 |
with self.assertRaisesMessage(AssertionError, msg): |
| 217 |
self.assertNotContains(response, "very") |
| 218 |
|
| 219 |
def test_unicode_contains(self): |
| 220 |
"Unicode characters can be found in template context" |
| 221 |
# Regression test for #10183 |
| 222 |
r = self.client.get("/check_unicode/") |
| 223 |
self.assertContains(r, "さかき") |
| 224 |
self.assertContains(r, b"\xe5\xb3\xa0".decode()) |
| 225 |
|
| 226 |
def test_unicode_not_contains(self): |
| 227 |
"Unicode characters can be searched for, and not found in template context" |
| 228 |
# Regression test for #10183 |
| 229 |
r = self.client.get("/check_unicode/") |
| 230 |
self.assertNotContains(r, "はたけ") |
| 231 |
self.assertNotContains(r, b"\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91".decode()) |
| 232 |
|
| 233 |
def test_binary_contains(self): |
| 234 |
r = self.client.get("/check_binary/") |
| 235 |
self.assertContains(r, b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e") |
| 236 |
with self.assertRaises(AssertionError): |
| 237 |
self.assertContains(r, b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e", count=2) |
| 238 |
|
| 239 |
def test_binary_not_contains(self): |
| 240 |
r = self.client.get("/check_binary/") |
| 241 |
self.assertNotContains(r, b"%ODF-1.4\r\n%\x93\x8c\x8b\x9e") |
| 242 |
with self.assertRaises(AssertionError): |
| 243 |
self.assertNotContains(r, b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e") |
| 244 |
|
| 245 |
def test_nontext_contains(self): |
| 246 |
r = self.client.get("/no_template_view/") |
| 247 |
self.assertContains(r, gettext_lazy("once")) |
| 248 |
|
| 249 |
def test_nontext_not_contains(self): |
| 250 |
r = self.client.get("/no_template_view/") |
| 251 |
self.assertNotContains(r, gettext_lazy("never")) |
| 252 |
|
| 253 |
def test_assert_contains_renders_template_response(self): |
| 254 |
""" |
| 255 |
An unrendered SimpleTemplateResponse may be used in assertContains(). |
| 256 |
""" |
| 257 |
template = engines["django"].from_string("Hello") |
| 258 |
response = SimpleTemplateResponse(template) |
| 259 |
self.assertContains(response, "Hello") |
| 260 |
|
| 261 |
def test_assert_contains_using_non_template_response(self): |
| 262 |
"""auto-rendering does not affect responses that aren't |
| 263 |
instances (or subclasses) of SimpleTemplateResponse. |
| 264 |
Refs #15826. |
| 265 |
""" |
| 266 |
response = HttpResponse("Hello") |
| 267 |
self.assertContains(response, "Hello") |
| 268 |
|
| 269 |
def test_assert_not_contains_renders_template_response(self): |
| 270 |
""" |
| 271 |
An unrendered SimpleTemplateResponse may be used in assertNotContains(). |
| 272 |
""" |
| 273 |
template = engines["django"].from_string("Hello") |
| 274 |
response = SimpleTemplateResponse(template) |
| 275 |
self.assertNotContains(response, "Bye") |
| 276 |
|
| 277 |
def test_assert_not_contains_using_non_template_response(self): |
| 278 |
""" |
| 279 |
auto-rendering does not affect responses that aren't instances (or |
| 280 |
subclasses) of SimpleTemplateResponse. |
| 281 |
""" |
| 282 |
response = HttpResponse("Hello") |
| 283 |
self.assertNotContains(response, "Bye") |
| 284 |
|
| 285 |
|
| 286 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 287 |
class AssertTemplateUsedTests(TestDataMixin, TestCase): |
| 288 |
def test_no_context(self): |
| 289 |
"Template usage assertions work then templates aren't in use" |
| 290 |
response = self.client.get("/no_template_view/") |
| 291 |
|
| 292 |
# The no template case doesn't mess with the template assertions |
| 293 |
self.assertTemplateNotUsed(response, "GET Template") |
| 294 |
|
| 295 |
try: |
| 296 |
self.assertTemplateUsed(response, "GET Template") |
| 297 |
except AssertionError as e: |
| 298 |
self.assertIn("No templates used to render the response", str(e)) |
| 299 |
|
| 300 |
try: |
| 301 |
self.assertTemplateUsed(response, "GET Template", msg_prefix="abc") |
| 302 |
except AssertionError as e: |
| 303 |
self.assertIn("abc: No templates used to render the response", str(e)) |
| 304 |
|
| 305 |
msg = "No templates used to render the response" |
| 306 |
with self.assertRaisesMessage(AssertionError, msg): |
| 307 |
self.assertTemplateUsed(response, "GET Template", count=2) |
| 308 |
|
| 309 |
def test_single_context(self): |
| 310 |
"Template assertions work when there is a single context" |
| 311 |
response = self.client.get("/post_view/", {}) |
| 312 |
msg = ( |
| 313 |
": Template 'Empty GET Template' was used unexpectedly in " |
| 314 |
"rendering the response" |
| 315 |
) |
| 316 |
with self.assertRaisesMessage(AssertionError, msg): |
| 317 |
self.assertTemplateNotUsed(response, "Empty GET Template") |
| 318 |
with self.assertRaisesMessage(AssertionError, "abc" + msg): |
| 319 |
self.assertTemplateNotUsed(response, "Empty GET Template", msg_prefix="abc") |
| 320 |
msg = ( |
| 321 |
": Template 'Empty POST Template' was not a template used to " |
| 322 |
"render the response. Actual template(s) used: Empty GET Template" |
| 323 |
) |
| 324 |
with self.assertRaisesMessage(AssertionError, msg): |
| 325 |
self.assertTemplateUsed(response, "Empty POST Template") |
| 326 |
with self.assertRaisesMessage(AssertionError, "abc" + msg): |
| 327 |
self.assertTemplateUsed(response, "Empty POST Template", msg_prefix="abc") |
| 328 |
msg = ( |
| 329 |
": Template 'Empty GET Template' was expected to be rendered 2 " |
| 330 |
"time(s) but was actually rendered 1 time(s)." |
| 331 |
) |
| 332 |
with self.assertRaisesMessage(AssertionError, msg): |
| 333 |
self.assertTemplateUsed(response, "Empty GET Template", count=2) |
| 334 |
with self.assertRaisesMessage(AssertionError, "abc" + msg): |
| 335 |
self.assertTemplateUsed( |
| 336 |
response, "Empty GET Template", msg_prefix="abc", count=2 |
| 337 |
) |
| 338 |
|
| 339 |
def test_multiple_context(self): |
| 340 |
"Template assertions work when there are multiple contexts" |
| 341 |
post_data = { |
| 342 |
"text": "Hello World", |
| 343 |
"email": "[email protected]", |
| 344 |
"value": 37, |
| 345 |
"single": "b", |
| 346 |
"multi": ("b", "c", "e"), |
| 347 |
} |
| 348 |
response = self.client.post("/form_view_with_template/", post_data) |
| 349 |
self.assertContains(response, "POST data OK") |
| 350 |
msg = "Template '%s' was used unexpectedly in rendering the response" |
| 351 |
with self.assertRaisesMessage(AssertionError, msg % "form_view.html"): |
| 352 |
self.assertTemplateNotUsed(response, "form_view.html") |
| 353 |
with self.assertRaisesMessage(AssertionError, msg % "base.html"): |
| 354 |
self.assertTemplateNotUsed(response, "base.html") |
| 355 |
msg = ( |
| 356 |
"Template 'Valid POST Template' was not a template used to render " |
| 357 |
"the response. Actual template(s) used: form_view.html, base.html" |
| 358 |
) |
| 359 |
with self.assertRaisesMessage(AssertionError, msg): |
| 360 |
self.assertTemplateUsed(response, "Valid POST Template") |
| 361 |
msg = ( |
| 362 |
"Template 'base.html' was expected to be rendered 2 time(s) but " |
| 363 |
"was actually rendered 1 time(s)." |
| 364 |
) |
| 365 |
with self.assertRaisesMessage(AssertionError, msg): |
| 366 |
self.assertTemplateUsed(response, "base.html", count=2) |
| 367 |
|
| 368 |
def test_template_rendered_multiple_times(self): |
| 369 |
"""Template assertions work when a template is rendered multiple times.""" |
| 370 |
response = self.client.get("/render_template_multiple_times/") |
| 371 |
|
| 372 |
self.assertTemplateUsed(response, "base.html", count=2) |
| 373 |
|
| 374 |
|
| 375 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 376 |
class AssertRedirectsTests(SimpleTestCase): |
| 377 |
def test_redirect_page(self): |
| 378 |
"An assertion is raised if the original page couldn't be retrieved as expected" |
| 379 |
# This page will redirect with code 301, not 302 |
| 380 |
response = self.client.get("/permanent_redirect_view/") |
| 381 |
try: |
| 382 |
self.assertRedirects(response, "/get_view/") |
| 383 |
except AssertionError as e: |
| 384 |
self.assertIn( |
| 385 |
"Response didn't redirect as expected: Response code was 301 " |
| 386 |
"(expected 302)", |
| 387 |
str(e), |
| 388 |
) |
| 389 |
|
| 390 |
try: |
| 391 |
self.assertRedirects(response, "/get_view/", msg_prefix="abc") |
| 392 |
except AssertionError as e: |
| 393 |
self.assertIn( |
| 394 |
"abc: Response didn't redirect as expected: Response code was 301 " |
| 395 |
"(expected 302)", |
| 396 |
str(e), |
| 397 |
) |
| 398 |
|
| 399 |
def test_lost_query(self): |
| 400 |
""" |
| 401 |
An assertion is raised if the redirect location doesn't preserve GET |
| 402 |
parameters. |
| 403 |
""" |
| 404 |
response = self.client.get("/redirect_view/", {"var": "value"}) |
| 405 |
try: |
| 406 |
self.assertRedirects(response, "/get_view/") |
| 407 |
except AssertionError as e: |
| 408 |
self.assertIn( |
| 409 |
"Response redirected to '/get_view/?var=value', expected '/get_view/'", |
| 410 |
str(e), |
| 411 |
) |
| 412 |
|
| 413 |
try: |
| 414 |
self.assertRedirects(response, "/get_view/", msg_prefix="abc") |
| 415 |
except AssertionError as e: |
| 416 |
self.assertIn( |
| 417 |
"abc: Response redirected to '/get_view/?var=value', expected " |
| 418 |
"'/get_view/'", |
| 419 |
str(e), |
| 420 |
) |
| 421 |
|
| 422 |
def test_incorrect_target(self): |
| 423 |
"An assertion is raised if the response redirects to another target" |
| 424 |
response = self.client.get("/permanent_redirect_view/") |
| 425 |
try: |
| 426 |
# Should redirect to get_view |
| 427 |
self.assertRedirects(response, "/some_view/") |
| 428 |
except AssertionError as e: |
| 429 |
self.assertIn( |
| 430 |
"Response didn't redirect as expected: Response code was 301 " |
| 431 |
"(expected 302)", |
| 432 |
str(e), |
| 433 |
) |
| 434 |
|
| 435 |
def test_target_page(self): |
| 436 |
""" |
| 437 |
An assertion is raised if the response redirect target cannot be |
| 438 |
retrieved as expected. |
| 439 |
""" |
| 440 |
response = self.client.get("/double_redirect_view/") |
| 441 |
try: |
| 442 |
# The redirect target responds with a 301 code, not 200 |
| 443 |
self.assertRedirects(response, "http://testserver/permanent_redirect_view/") |
| 444 |
except AssertionError as e: |
| 445 |
self.assertIn( |
| 446 |
"Couldn't retrieve redirection page '/permanent_redirect_view/': " |
| 447 |
"response code was 301 (expected 200)", |
| 448 |
str(e), |
| 449 |
) |
| 450 |
|
| 451 |
try: |
| 452 |
# The redirect target responds with a 301 code, not 200 |
| 453 |
self.assertRedirects( |
| 454 |
response, "http://testserver/permanent_redirect_view/", msg_prefix="abc" |
| 455 |
) |
| 456 |
except AssertionError as e: |
| 457 |
self.assertIn( |
| 458 |
"abc: Couldn't retrieve redirection page '/permanent_redirect_view/': " |
| 459 |
"response code was 301 (expected 200)", |
| 460 |
str(e), |
| 461 |
) |
| 462 |
|
| 463 |
def test_redirect_chain(self): |
| 464 |
"You can follow a redirect chain of multiple redirects" |
| 465 |
response = self.client.get("/redirects/further/more/", {}, follow=True) |
| 466 |
self.assertRedirects( |
| 467 |
response, "/no_template_view/", status_code=302, target_status_code=200 |
| 468 |
) |
| 469 |
|
| 470 |
self.assertEqual(len(response.redirect_chain), 1) |
| 471 |
self.assertEqual(response.redirect_chain[0], ("/no_template_view/", 302)) |
| 472 |
|
| 473 |
def test_multiple_redirect_chain(self): |
| 474 |
"You can follow a redirect chain of multiple redirects" |
| 475 |
response = self.client.get("/redirects/", {}, follow=True) |
| 476 |
self.assertRedirects( |
| 477 |
response, "/no_template_view/", status_code=302, target_status_code=200 |
| 478 |
) |
| 479 |
|
| 480 |
self.assertEqual(len(response.redirect_chain), 3) |
| 481 |
self.assertEqual(response.redirect_chain[0], ("/redirects/further/", 302)) |
| 482 |
self.assertEqual(response.redirect_chain[1], ("/redirects/further/more/", 302)) |
| 483 |
self.assertEqual(response.redirect_chain[2], ("/no_template_view/", 302)) |
| 484 |
|
| 485 |
def test_redirect_chain_to_non_existent(self): |
| 486 |
"You can follow a chain to a nonexistent view." |
| 487 |
response = self.client.get("/redirect_to_non_existent_view2/", {}, follow=True) |
| 488 |
self.assertRedirects( |
| 489 |
response, "/non_existent_view/", status_code=302, target_status_code=404 |
| 490 |
) |
| 491 |
|
| 492 |
def test_redirect_chain_to_self(self): |
| 493 |
"Redirections to self are caught and escaped" |
| 494 |
with self.assertRaises(RedirectCycleError) as context: |
| 495 |
self.client.get("/redirect_to_self/", {}, follow=True) |
| 496 |
response = context.exception.last_response |
| 497 |
# The chain of redirects stops once the cycle is detected. |
| 498 |
self.assertRedirects( |
| 499 |
response, "/redirect_to_self/", status_code=302, target_status_code=302 |
| 500 |
) |
| 501 |
self.assertEqual(len(response.redirect_chain), 2) |
| 502 |
|
| 503 |
def test_redirect_to_self_with_changing_query(self): |
| 504 |
"Redirections don't loop forever even if query is changing" |
| 505 |
with self.assertRaises(RedirectCycleError): |
| 506 |
self.client.get( |
| 507 |
"/redirect_to_self_with_changing_query_view/", |
| 508 |
{"counter": "0"}, |
| 509 |
follow=True, |
| 510 |
) |
| 511 |
|
| 512 |
def test_circular_redirect(self): |
| 513 |
"Circular redirect chains are caught and escaped" |
| 514 |
with self.assertRaises(RedirectCycleError) as context: |
| 515 |
self.client.get("/circular_redirect_1/", {}, follow=True) |
| 516 |
response = context.exception.last_response |
| 517 |
# The chain of redirects will get back to the starting point, but stop there. |
| 518 |
self.assertRedirects( |
| 519 |
response, "/circular_redirect_2/", status_code=302, target_status_code=302 |
| 520 |
) |
| 521 |
self.assertEqual(len(response.redirect_chain), 4) |
| 522 |
|
| 523 |
def test_redirect_chain_post(self): |
| 524 |
"A redirect chain will be followed from an initial POST post" |
| 525 |
response = self.client.post("/redirects/", {"nothing": "to_send"}, follow=True) |
| 526 |
self.assertRedirects(response, "/no_template_view/", 302, 200) |
| 527 |
self.assertEqual(len(response.redirect_chain), 3) |
| 528 |
|
| 529 |
def test_redirect_chain_head(self): |
| 530 |
"A redirect chain will be followed from an initial HEAD request" |
| 531 |
response = self.client.head("/redirects/", {"nothing": "to_send"}, follow=True) |
| 532 |
self.assertRedirects(response, "/no_template_view/", 302, 200) |
| 533 |
self.assertEqual(len(response.redirect_chain), 3) |
| 534 |
|
| 535 |
def test_redirect_chain_options(self): |
| 536 |
"A redirect chain will be followed from an initial OPTIONS request" |
| 537 |
response = self.client.options("/redirects/", follow=True) |
| 538 |
self.assertRedirects(response, "/no_template_view/", 302, 200) |
| 539 |
self.assertEqual(len(response.redirect_chain), 3) |
| 540 |
|
| 541 |
def test_redirect_chain_put(self): |
| 542 |
"A redirect chain will be followed from an initial PUT request" |
| 543 |
response = self.client.put("/redirects/", follow=True) |
| 544 |
self.assertRedirects(response, "/no_template_view/", 302, 200) |
| 545 |
self.assertEqual(len(response.redirect_chain), 3) |
| 546 |
|
| 547 |
def test_redirect_chain_delete(self): |
| 548 |
"A redirect chain will be followed from an initial DELETE request" |
| 549 |
response = self.client.delete("/redirects/", follow=True) |
| 550 |
self.assertRedirects(response, "/no_template_view/", 302, 200) |
| 551 |
self.assertEqual(len(response.redirect_chain), 3) |
| 552 |
|
| 553 |
@modify_settings(ALLOWED_HOSTS={"append": "otherserver"}) |
| 554 |
def test_redirect_to_different_host(self): |
| 555 |
"The test client will preserve scheme, host and port changes" |
| 556 |
response = self.client.get("/redirect_other_host/", follow=True) |
| 557 |
self.assertRedirects( |
| 558 |
response, |
| 559 |
"https://otherserver:8443/no_template_view/", |
| 560 |
status_code=302, |
| 561 |
target_status_code=200, |
| 562 |
) |
| 563 |
# We can't use is_secure() or get_host() |
| 564 |
# because response.request is a dictionary, not an HttpRequest |
| 565 |
self.assertEqual(response.request.get("wsgi.url_scheme"), "https") |
| 566 |
self.assertEqual(response.request.get("SERVER_NAME"), "otherserver") |
| 567 |
self.assertEqual(response.request.get("SERVER_PORT"), "8443") |
| 568 |
# assertRedirects() can follow redirect to 'otherserver' too. |
| 569 |
response = self.client.get("/redirect_other_host/", follow=False) |
| 570 |
self.assertRedirects( |
| 571 |
response, |
| 572 |
"https://otherserver:8443/no_template_view/", |
| 573 |
status_code=302, |
| 574 |
target_status_code=200, |
| 575 |
) |
| 576 |
|
| 577 |
def test_redirect_chain_on_non_redirect_page(self): |
| 578 |
""" |
| 579 |
An assertion is raised if the original page couldn't be retrieved as |
| 580 |
expected. |
| 581 |
""" |
| 582 |
# This page will redirect with code 301, not 302 |
| 583 |
response = self.client.get("/get_view/", follow=True) |
| 584 |
try: |
| 585 |
self.assertRedirects(response, "/get_view/") |
| 586 |
except AssertionError as e: |
| 587 |
self.assertIn( |
| 588 |
"Response didn't redirect as expected: Response code was 200 " |
| 589 |
"(expected 302)", |
| 590 |
str(e), |
| 591 |
) |
| 592 |
|
| 593 |
try: |
| 594 |
self.assertRedirects(response, "/get_view/", msg_prefix="abc") |
| 595 |
except AssertionError as e: |
| 596 |
self.assertIn( |
| 597 |
"abc: Response didn't redirect as expected: Response code was 200 " |
| 598 |
"(expected 302)", |
| 599 |
str(e), |
| 600 |
) |
| 601 |
|
| 602 |
def test_redirect_on_non_redirect_page(self): |
| 603 |
"An assertion is raised if the original page couldn't be retrieved as expected" |
| 604 |
# This page will redirect with code 301, not 302 |
| 605 |
response = self.client.get("/get_view/") |
| 606 |
try: |
| 607 |
self.assertRedirects(response, "/get_view/") |
| 608 |
except AssertionError as e: |
| 609 |
self.assertIn( |
| 610 |
"Response didn't redirect as expected: Response code was 200 " |
| 611 |
"(expected 302)", |
| 612 |
str(e), |
| 613 |
) |
| 614 |
|
| 615 |
try: |
| 616 |
self.assertRedirects(response, "/get_view/", msg_prefix="abc") |
| 617 |
except AssertionError as e: |
| 618 |
self.assertIn( |
| 619 |
"abc: Response didn't redirect as expected: Response code was 200 " |
| 620 |
"(expected 302)", |
| 621 |
str(e), |
| 622 |
) |
| 623 |
|
| 624 |
def test_redirect_scheme(self): |
| 625 |
""" |
| 626 |
An assertion is raised if the response doesn't have the scheme |
| 627 |
specified in expected_url. |
| 628 |
""" |
| 629 |
|
| 630 |
# For all possible True/False combinations of follow and secure |
| 631 |
for follow, secure in itertools.product([True, False], repeat=2): |
| 632 |
# always redirects to https |
| 633 |
response = self.client.get( |
| 634 |
"/https_redirect_view/", follow=follow, secure=secure |
| 635 |
) |
| 636 |
# the goal scheme is https |
| 637 |
self.assertRedirects( |
| 638 |
response, "https://testserver/secure_view/", status_code=302 |
| 639 |
) |
| 640 |
with self.assertRaises(AssertionError): |
| 641 |
self.assertRedirects( |
| 642 |
response, "http://testserver/secure_view/", status_code=302 |
| 643 |
) |
| 644 |
|
| 645 |
def test_redirect_fetch_redirect_response(self): |
| 646 |
"""Preserve extra headers of requests made with django.test.Client.""" |
| 647 |
methods = ( |
| 648 |
"get", |
| 649 |
"post", |
| 650 |
"head", |
| 651 |
"options", |
| 652 |
"put", |
| 653 |
"patch", |
| 654 |
"delete", |
| 655 |
"trace", |
| 656 |
) |
| 657 |
for method in methods: |
| 658 |
with self.subTest(method=method): |
| 659 |
req_method = getattr(self.client, method) |
| 660 |
# HTTP_REDIRECT in "extra". |
| 661 |
response = req_method( |
| 662 |
"/redirect_based_on_extra_headers_1/", |
| 663 |
follow=False, |
| 664 |
HTTP_REDIRECT="val", |
| 665 |
) |
| 666 |
self.assertRedirects( |
| 667 |
response, |
| 668 |
"/redirect_based_on_extra_headers_2/", |
| 669 |
fetch_redirect_response=True, |
| 670 |
status_code=302, |
| 671 |
target_status_code=302, |
| 672 |
) |
| 673 |
# HTTP_REDIRECT in "headers". |
| 674 |
response = req_method( |
| 675 |
"/redirect_based_on_extra_headers_1/", |
| 676 |
follow=False, |
| 677 |
headers={"redirect": "val"}, |
| 678 |
) |
| 679 |
self.assertRedirects( |
| 680 |
response, |
| 681 |
"/redirect_based_on_extra_headers_2/", |
| 682 |
fetch_redirect_response=True, |
| 683 |
status_code=302, |
| 684 |
target_status_code=302, |
| 685 |
) |
| 686 |
|
| 687 |
|
| 688 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 689 |
class LoginTests(TestDataMixin, TestCase): |
| 690 |
def test_login_different_client(self): |
| 691 |
"Using a different test client doesn't violate authentication" |
| 692 |
|
| 693 |
# Create a second client, and log in. |
| 694 |
c = Client() |
| 695 |
login = c.login(username="testclient", password="password") |
| 696 |
self.assertTrue(login, "Could not log in") |
| 697 |
|
| 698 |
# Get a redirection page with the second client. |
| 699 |
response = c.get("/login_protected_redirect_view/") |
| 700 |
|
| 701 |
# At this points, the self.client isn't logged in. |
| 702 |
# assertRedirects uses the original client, not the default client. |
| 703 |
self.assertRedirects(response, "/get_view/") |
| 704 |
|
| 705 |
|
| 706 |
@override_settings( |
| 707 |
SESSION_ENGINE="test_client_regress.session", |
| 708 |
ROOT_URLCONF="test_client_regress.urls", |
| 709 |
) |
| 710 |
class SessionEngineTests(TestDataMixin, TestCase): |
| 711 |
def test_login(self): |
| 712 |
"A session engine that modifies the session key can be used to log in" |
| 713 |
login = self.client.login(username="testclient", password="password") |
| 714 |
self.assertTrue(login, "Could not log in") |
| 715 |
|
| 716 |
# Try to access a login protected page. |
| 717 |
response = self.client.get("/login_protected_view/") |
| 718 |
self.assertEqual(response.status_code, 200) |
| 719 |
self.assertEqual(response.context["user"].username, "testclient") |
| 720 |
|
| 721 |
|
| 722 |
@override_settings( |
| 723 |
ROOT_URLCONF="test_client_regress.urls", |
| 724 |
) |
| 725 |
class URLEscapingTests(SimpleTestCase): |
| 726 |
def test_simple_argument_get(self): |
| 727 |
"Get a view that has a simple string argument" |
| 728 |
response = self.client.get(reverse("arg_view", args=["Slartibartfast"])) |
| 729 |
self.assertEqual(response.status_code, 200) |
| 730 |
self.assertEqual(response.content, b"Howdy, Slartibartfast") |
| 731 |
|
| 732 |
def test_argument_with_space_get(self): |
| 733 |
"Get a view that has a string argument that requires escaping" |
| 734 |
response = self.client.get(reverse("arg_view", args=["Arthur Dent"])) |
| 735 |
self.assertEqual(response.status_code, 200) |
| 736 |
self.assertEqual(response.content, b"Hi, Arthur") |
| 737 |
|
| 738 |
def test_simple_argument_post(self): |
| 739 |
"Post for a view that has a simple string argument" |
| 740 |
response = self.client.post(reverse("arg_view", args=["Slartibartfast"])) |
| 741 |
self.assertEqual(response.status_code, 200) |
| 742 |
self.assertEqual(response.content, b"Howdy, Slartibartfast") |
| 743 |
|
| 744 |
def test_argument_with_space_post(self): |
| 745 |
"Post for a view that has a string argument that requires escaping" |
| 746 |
response = self.client.post(reverse("arg_view", args=["Arthur Dent"])) |
| 747 |
self.assertEqual(response.status_code, 200) |
| 748 |
self.assertEqual(response.content, b"Hi, Arthur") |
| 749 |
|
| 750 |
|
| 751 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 752 |
class ExceptionTests(TestDataMixin, TestCase): |
| 753 |
def test_exception_cleared(self): |
| 754 |
"#5836 - A stale user exception isn't re-raised by the test client." |
| 755 |
|
| 756 |
login = self.client.login(username="testclient", password="password") |
| 757 |
self.assertTrue(login, "Could not log in") |
| 758 |
with self.assertRaises(CustomTestException): |
| 759 |
self.client.get("/staff_only/") |
| 760 |
|
| 761 |
# At this point, an exception has been raised, and should be cleared. |
| 762 |
|
| 763 |
# This next operation should be successful; if it isn't we have a problem. |
| 764 |
login = self.client.login(username="staff", password="password") |
| 765 |
self.assertTrue(login, "Could not log in") |
| 766 |
self.client.get("/staff_only/") |
| 767 |
|
| 768 |
|
| 769 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 770 |
class TemplateExceptionTests(SimpleTestCase): |
| 771 |
@override_settings( |
| 772 |
TEMPLATES=[ |
| 773 |
{ |
| 774 |
"BACKEND": "django.template.backends.django.DjangoTemplates", |
| 775 |
"DIRS": [os.path.join(os.path.dirname(__file__), "bad_templates")], |
| 776 |
} |
| 777 |
] |
| 778 |
) |
| 779 |
def test_bad_404_template(self): |
| 780 |
"Errors found when rendering 404 error templates are re-raised" |
| 781 |
with self.assertRaises(TemplateSyntaxError): |
| 782 |
self.client.get("/no_such_view/") |
| 783 |
|
| 784 |
|
| 785 |
# We need two different tests to check URLconf substitution - one to check |
| 786 |
# it was changed, and another one (without self.urls) to check it was reverted on |
| 787 |
# teardown. This pair of tests relies upon the alphabetical ordering of test execution. |
| 788 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 789 |
class UrlconfSubstitutionTests(SimpleTestCase): |
| 790 |
def test_urlconf_was_changed(self): |
| 791 |
"TestCase can enforce a custom URLconf on a per-test basis" |
| 792 |
url = reverse("arg_view", args=["somename"]) |
| 793 |
self.assertEqual(url, "/arg_view/somename/") |
| 794 |
|
| 795 |
|
| 796 |
# This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in the |
| 797 |
# name is to ensure alphabetical ordering. |
| 798 |
class zzUrlconfSubstitutionTests(SimpleTestCase): |
| 799 |
def test_urlconf_was_reverted(self): |
| 800 |
"""URLconf is reverted to original value after modification in a TestCase |
| 801 |
|
| 802 |
This will not find a match as the default ROOT_URLCONF is empty. |
| 803 |
""" |
| 804 |
with self.assertRaises(NoReverseMatch): |
| 805 |
reverse("arg_view", args=["somename"]) |
| 806 |
|
| 807 |
|
| 808 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 809 |
class ContextTests(TestDataMixin, TestCase): |
| 810 |
def test_single_context(self): |
| 811 |
"Context variables can be retrieved from a single context" |
| 812 |
response = self.client.get("/request_data/", data={"foo": "whiz"}) |
| 813 |
self.assertIsInstance(response.context, RequestContext) |
| 814 |
self.assertIn("get-foo", response.context) |
| 815 |
self.assertEqual(response.context["get-foo"], "whiz") |
| 816 |
self.assertEqual(response.context["data"], "sausage") |
| 817 |
|
| 818 |
with self.assertRaisesMessage(KeyError, "does-not-exist"): |
| 819 |
response.context["does-not-exist"] |
| 820 |
|
| 821 |
def test_inherited_context(self): |
| 822 |
"Context variables can be retrieved from a list of contexts" |
| 823 |
response = self.client.get("/request_data_extended/", data={"foo": "whiz"}) |
| 824 |
self.assertEqual(response.context.__class__, ContextList) |
| 825 |
self.assertEqual(len(response.context), 2) |
| 826 |
self.assertIn("get-foo", response.context) |
| 827 |
self.assertEqual(response.context["get-foo"], "whiz") |
| 828 |
self.assertEqual(response.context["data"], "bacon") |
| 829 |
|
| 830 |
with self.assertRaisesMessage(KeyError, "does-not-exist"): |
| 831 |
response.context["does-not-exist"] |
| 832 |
|
| 833 |
def test_contextlist_keys(self): |
| 834 |
c1 = Context() |
| 835 |
c1.update({"hello": "world", "goodbye": "john"}) |
| 836 |
c1.update({"hello": "dolly", "dolly": "parton"}) |
| 837 |
c2 = Context() |
| 838 |
c2.update({"goodbye": "world", "python": "rocks"}) |
| 839 |
c2.update({"goodbye": "dolly"}) |
| 840 |
|
| 841 |
k = ContextList([c1, c2]) |
| 842 |
# None, True and False are builtins of BaseContext, and present |
| 843 |
# in every Context without needing to be added. |
| 844 |
self.assertEqual( |
| 845 |
{"None", "True", "False", "hello", "goodbye", "python", "dolly"}, k.keys() |
| 846 |
) |
| 847 |
|
| 848 |
def test_contextlist_get(self): |
| 849 |
c1 = Context({"hello": "world", "goodbye": "john"}) |
| 850 |
c2 = Context({"goodbye": "world", "python": "rocks"}) |
| 851 |
k = ContextList([c1, c2]) |
| 852 |
self.assertEqual(k.get("hello"), "world") |
| 853 |
self.assertEqual(k.get("goodbye"), "john") |
| 854 |
self.assertEqual(k.get("python"), "rocks") |
| 855 |
self.assertEqual(k.get("nonexistent", "default"), "default") |
| 856 |
|
| 857 |
def test_15368(self): |
| 858 |
# Need to insert a context processor that assumes certain things about |
| 859 |
# the request instance. This triggers a bug caused by some ways of |
| 860 |
# copying RequestContext. |
| 861 |
with self.settings( |
| 862 |
TEMPLATES=[ |
| 863 |
{ |
| 864 |
"BACKEND": "django.template.backends.django.DjangoTemplates", |
| 865 |
"APP_DIRS": True, |
| 866 |
"OPTIONS": { |
| 867 |
"context_processors": [ |
| 868 |
"test_client_regress.context_processors.special", |
| 869 |
], |
| 870 |
}, |
| 871 |
} |
| 872 |
] |
| 873 |
): |
| 874 |
response = self.client.get("/request_context_view/") |
| 875 |
self.assertContains(response, "Path: /request_context_view/") |
| 876 |
|
| 877 |
def test_nested_requests(self): |
| 878 |
""" |
| 879 |
response.context is not lost when view call another view. |
| 880 |
""" |
| 881 |
response = self.client.get("/nested_view/") |
| 882 |
self.assertIsInstance(response.context, RequestContext) |
| 883 |
self.assertEqual(response.context["nested"], "yes") |
| 884 |
|
| 885 |
|
| 886 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 887 |
class SessionTests(TestDataMixin, TestCase): |
| 888 |
def test_session(self): |
| 889 |
"The session isn't lost if a user logs in" |
| 890 |
# The session doesn't exist to start. |
| 891 |
response = self.client.get("/check_session/") |
| 892 |
self.assertEqual(response.status_code, 200) |
| 893 |
self.assertEqual(response.content, b"NO") |
| 894 |
|
| 895 |
# This request sets a session variable. |
| 896 |
response = self.client.get("/set_session/") |
| 897 |
self.assertEqual(response.status_code, 200) |
| 898 |
self.assertEqual(response.content, b"set_session") |
| 899 |
|
| 900 |
# The session has been modified |
| 901 |
response = self.client.get("/check_session/") |
| 902 |
self.assertEqual(response.status_code, 200) |
| 903 |
self.assertEqual(response.content, b"YES") |
| 904 |
|
| 905 |
# Log in |
| 906 |
login = self.client.login(username="testclient", password="password") |
| 907 |
self.assertTrue(login, "Could not log in") |
| 908 |
|
| 909 |
# Session should still contain the modified value |
| 910 |
response = self.client.get("/check_session/") |
| 911 |
self.assertEqual(response.status_code, 200) |
| 912 |
self.assertEqual(response.content, b"YES") |
| 913 |
|
| 914 |
def test_session_initiated(self): |
| 915 |
session = self.client.session |
| 916 |
session["session_var"] = "foo" |
| 917 |
session.save() |
| 918 |
|
| 919 |
response = self.client.get("/check_session/") |
| 920 |
self.assertEqual(response.content, b"foo") |
| 921 |
|
| 922 |
def test_logout(self): |
| 923 |
"""Logout should work whether the user is logged in or not (#9978).""" |
| 924 |
self.client.logout() |
| 925 |
login = self.client.login(username="testclient", password="password") |
| 926 |
self.assertTrue(login, "Could not log in") |
| 927 |
self.client.logout() |
| 928 |
self.client.logout() |
| 929 |
|
| 930 |
def test_logout_with_user(self): |
| 931 |
"""Logout should send user_logged_out signal if user was logged in.""" |
| 932 |
|
| 933 |
def listener(*args, **kwargs): |
| 934 |
listener.executed = True |
| 935 |
self.assertEqual(kwargs["sender"], User) |
| 936 |
|
| 937 |
listener.executed = False |
| 938 |
|
| 939 |
user_logged_out.connect(listener) |
| 940 |
self.client.login(username="testclient", password="password") |
| 941 |
self.client.logout() |
| 942 |
user_logged_out.disconnect(listener) |
| 943 |
self.assertTrue(listener.executed) |
| 944 |
|
| 945 |
@override_settings(AUTH_USER_MODEL="test_client_regress.CustomUser") |
| 946 |
def test_logout_with_custom_user(self): |
| 947 |
"""Logout should send user_logged_out signal if custom user was logged in.""" |
| 948 |
|
| 949 |
def listener(*args, **kwargs): |
| 950 |
self.assertEqual(kwargs["sender"], CustomUser) |
| 951 |
listener.executed = True |
| 952 |
|
| 953 |
listener.executed = False |
| 954 |
u = CustomUser.custom_objects.create(email="[email protected]") |
| 955 |
u.set_password("password") |
| 956 |
u.save() |
| 957 |
|
| 958 |
user_logged_out.connect(listener) |
| 959 |
self.client.login(username="[email protected]", password="password") |
| 960 |
self.client.logout() |
| 961 |
user_logged_out.disconnect(listener) |
| 962 |
self.assertTrue(listener.executed) |
| 963 |
|
| 964 |
@override_settings( |
| 965 |
AUTHENTICATION_BACKENDS=( |
| 966 |
"django.contrib.auth.backends.ModelBackend", |
| 967 |
"test_client_regress.auth_backends.CustomUserBackend", |
| 968 |
) |
| 969 |
) |
| 970 |
def test_logout_with_custom_auth_backend(self): |
| 971 |
"Request a logout after logging in with custom authentication backend" |
| 972 |
|
| 973 |
def listener(*args, **kwargs): |
| 974 |
self.assertEqual(kwargs["sender"], CustomUser) |
| 975 |
listener.executed = True |
| 976 |
|
| 977 |
listener.executed = False |
| 978 |
u = CustomUser.custom_objects.create(email="[email protected]") |
| 979 |
u.set_password("password") |
| 980 |
u.save() |
| 981 |
|
| 982 |
user_logged_out.connect(listener) |
| 983 |
self.client.login(username="[email protected]", password="password") |
| 984 |
self.client.logout() |
| 985 |
user_logged_out.disconnect(listener) |
| 986 |
self.assertTrue(listener.executed) |
| 987 |
|
| 988 |
def test_logout_without_user(self): |
| 989 |
"""Logout should send signal even if user not authenticated.""" |
| 990 |
|
| 991 |
def listener(user, *args, **kwargs): |
| 992 |
listener.user = user |
| 993 |
listener.executed = True |
| 994 |
|
| 995 |
listener.executed = False |
| 996 |
|
| 997 |
user_logged_out.connect(listener) |
| 998 |
self.client.login(username="incorrect", password="password") |
| 999 |
self.client.logout() |
| 1000 |
user_logged_out.disconnect(listener) |
| 1001 |
|
| 1002 |
self.assertTrue(listener.executed) |
| 1003 |
self.assertIsNone(listener.user) |
| 1004 |
|
| 1005 |
def test_login_with_user(self): |
| 1006 |
"""Login should send user_logged_in signal on successful login.""" |
| 1007 |
|
| 1008 |
def listener(*args, **kwargs): |
| 1009 |
listener.executed = True |
| 1010 |
|
| 1011 |
listener.executed = False |
| 1012 |
|
| 1013 |
user_logged_in.connect(listener) |
| 1014 |
self.client.login(username="testclient", password="password") |
| 1015 |
user_logged_out.disconnect(listener) |
| 1016 |
|
| 1017 |
self.assertTrue(listener.executed) |
| 1018 |
|
| 1019 |
def test_login_without_signal(self): |
| 1020 |
"""Login shouldn't send signal if user wasn't logged in""" |
| 1021 |
|
| 1022 |
def listener(*args, **kwargs): |
| 1023 |
listener.executed = True |
| 1024 |
|
| 1025 |
listener.executed = False |
| 1026 |
|
| 1027 |
user_logged_in.connect(listener) |
| 1028 |
self.client.login(username="incorrect", password="password") |
| 1029 |
user_logged_in.disconnect(listener) |
| 1030 |
|
| 1031 |
self.assertFalse(listener.executed) |
| 1032 |
|
| 1033 |
|
| 1034 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 1035 |
class RequestMethodTests(SimpleTestCase): |
| 1036 |
def test_get(self): |
| 1037 |
"Request a view via request method GET" |
| 1038 |
response = self.client.get("/request_methods/") |
| 1039 |
self.assertEqual(response.status_code, 200) |
| 1040 |
self.assertEqual(response.content, b"request method: GET") |
| 1041 |
|
| 1042 |
def test_post(self): |
| 1043 |
"Request a view via request method POST" |
| 1044 |
response = self.client.post("/request_methods/") |
| 1045 |
self.assertEqual(response.status_code, 200) |
| 1046 |
self.assertEqual(response.content, b"request method: POST") |
| 1047 |
|
| 1048 |
def test_head(self): |
| 1049 |
"Request a view via request method HEAD" |
| 1050 |
response = self.client.head("/request_methods/") |
| 1051 |
self.assertEqual(response.status_code, 200) |
| 1052 |
# A HEAD request doesn't return any content. |
| 1053 |
self.assertNotEqual(response.content, b"request method: HEAD") |
| 1054 |
self.assertEqual(response.content, b"") |
| 1055 |
|
| 1056 |
def test_options(self): |
| 1057 |
"Request a view via request method OPTIONS" |
| 1058 |
response = self.client.options("/request_methods/") |
| 1059 |
self.assertEqual(response.status_code, 200) |
| 1060 |
self.assertEqual(response.content, b"request method: OPTIONS") |
| 1061 |
|
| 1062 |
def test_put(self): |
| 1063 |
"Request a view via request method PUT" |
| 1064 |
response = self.client.put("/request_methods/") |
| 1065 |
self.assertEqual(response.status_code, 200) |
| 1066 |
self.assertEqual(response.content, b"request method: PUT") |
| 1067 |
|
| 1068 |
def test_delete(self): |
| 1069 |
"Request a view via request method DELETE" |
| 1070 |
response = self.client.delete("/request_methods/") |
| 1071 |
self.assertEqual(response.status_code, 200) |
| 1072 |
self.assertEqual(response.content, b"request method: DELETE") |
| 1073 |
|
| 1074 |
def test_patch(self): |
| 1075 |
"Request a view via request method PATCH" |
| 1076 |
response = self.client.patch("/request_methods/") |
| 1077 |
self.assertEqual(response.status_code, 200) |
| 1078 |
self.assertEqual(response.content, b"request method: PATCH") |
| 1079 |
|
| 1080 |
|
| 1081 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 1082 |
class RequestMethodStringDataTests(SimpleTestCase): |
| 1083 |
def test_post(self): |
| 1084 |
"Request a view with string data via request method POST" |
| 1085 |
# Regression test for #11371 |
| 1086 |
data = '{"test": "json"}' |
| 1087 |
response = self.client.post( |
| 1088 |
"/request_methods/", data=data, content_type="application/json" |
| 1089 |
) |
| 1090 |
self.assertEqual(response.status_code, 200) |
| 1091 |
self.assertEqual(response.content, b"request method: POST") |
| 1092 |
|
| 1093 |
def test_put(self): |
| 1094 |
"Request a view with string data via request method PUT" |
| 1095 |
# Regression test for #11371 |
| 1096 |
data = '{"test": "json"}' |
| 1097 |
response = self.client.put( |
| 1098 |
"/request_methods/", data=data, content_type="application/json" |
| 1099 |
) |
| 1100 |
self.assertEqual(response.status_code, 200) |
| 1101 |
self.assertEqual(response.content, b"request method: PUT") |
| 1102 |
|
| 1103 |
def test_patch(self): |
| 1104 |
"Request a view with string data via request method PATCH" |
| 1105 |
# Regression test for #17797 |
| 1106 |
data = '{"test": "json"}' |
| 1107 |
response = self.client.patch( |
| 1108 |
"/request_methods/", data=data, content_type="application/json" |
| 1109 |
) |
| 1110 |
self.assertEqual(response.status_code, 200) |
| 1111 |
self.assertEqual(response.content, b"request method: PATCH") |
| 1112 |
|
| 1113 |
def test_empty_string_data(self): |
| 1114 |
"Request a view with empty string data via request method GET/POST/HEAD" |
| 1115 |
# Regression test for #21740 |
| 1116 |
response = self.client.get("/body/", data="", content_type="application/json") |
| 1117 |
self.assertEqual(response.content, b"") |
| 1118 |
response = self.client.post("/body/", data="", content_type="application/json") |
| 1119 |
self.assertEqual(response.content, b"") |
| 1120 |
response = self.client.head("/body/", data="", content_type="application/json") |
| 1121 |
self.assertEqual(response.content, b"") |
| 1122 |
|
| 1123 |
def test_json_bytes(self): |
| 1124 |
response = self.client.post( |
| 1125 |
"/body/", data=b"{'value': 37}", content_type="application/json" |
| 1126 |
) |
| 1127 |
self.assertEqual(response.content, b"{'value': 37}") |
| 1128 |
|
| 1129 |
def test_json(self): |
| 1130 |
response = self.client.get("/json_response/") |
| 1131 |
self.assertEqual(response.json(), {"key": "value"}) |
| 1132 |
|
| 1133 |
def test_json_charset(self): |
| 1134 |
response = self.client.get("/json_response_latin1/") |
| 1135 |
self.assertEqual(response.charset, "latin1") |
| 1136 |
self.assertEqual(response.json(), {"a": "Å"}) |
| 1137 |
|
| 1138 |
def test_json_structured_suffixes(self): |
| 1139 |
valid_types = ( |
| 1140 |
"application/vnd.api+json", |
| 1141 |
"application/vnd.api.foo+json", |
| 1142 |
"application/json; charset=utf-8", |
| 1143 |
"application/activity+json", |
| 1144 |
"application/activity+json; charset=utf-8", |
| 1145 |
) |
| 1146 |
for content_type in valid_types: |
| 1147 |
response = self.client.get( |
| 1148 |
"/json_response/", {"content_type": content_type} |
| 1149 |
) |
| 1150 |
self.assertEqual(response.headers["Content-Type"], content_type) |
| 1151 |
self.assertEqual(response.json(), {"key": "value"}) |
| 1152 |
|
| 1153 |
def test_json_multiple_access(self): |
| 1154 |
response = self.client.get("/json_response/") |
| 1155 |
self.assertIs(response.json(), response.json()) |
| 1156 |
|
| 1157 |
def test_json_wrong_header(self): |
| 1158 |
response = self.client.get("/body/") |
| 1159 |
msg = ( |
| 1160 |
'Content-Type header is "text/html; charset=utf-8", not "application/json"' |
| 1161 |
) |
| 1162 |
with self.assertRaisesMessage(ValueError, msg): |
| 1163 |
self.assertEqual(response.json(), {"key": "value"}) |
| 1164 |
|
| 1165 |
|
| 1166 |
@override_settings( |
| 1167 |
ROOT_URLCONF="test_client_regress.urls", |
| 1168 |
) |
| 1169 |
class QueryStringTests(SimpleTestCase): |
| 1170 |
def test_get_like_requests(self): |
| 1171 |
for method_name in ("get", "head"): |
| 1172 |
# A GET-like request can pass a query string as data (#10571) |
| 1173 |
method = getattr(self.client, method_name) |
| 1174 |
response = method("/request_data/", data={"foo": "whiz"}) |
| 1175 |
self.assertEqual(response.context["get-foo"], "whiz") |
| 1176 |
|
| 1177 |
# A GET-like request can pass a query string as part of the URL |
| 1178 |
response = method("/request_data/?foo=whiz") |
| 1179 |
self.assertEqual(response.context["get-foo"], "whiz") |
| 1180 |
|
| 1181 |
# Data provided in the URL to a GET-like request is overridden by |
| 1182 |
# actual form data. |
| 1183 |
response = method("/request_data/?foo=whiz", data={"foo": "bang"}) |
| 1184 |
self.assertEqual(response.context["get-foo"], "bang") |
| 1185 |
|
| 1186 |
response = method("/request_data/?foo=whiz", data={"bar": "bang"}) |
| 1187 |
self.assertIsNone(response.context["get-foo"]) |
| 1188 |
self.assertEqual(response.context["get-bar"], "bang") |
| 1189 |
|
| 1190 |
def test_post_like_requests(self): |
| 1191 |
# A POST-like request can pass a query string as data |
| 1192 |
response = self.client.post("/request_data/", data={"foo": "whiz"}) |
| 1193 |
self.assertIsNone(response.context["get-foo"]) |
| 1194 |
self.assertEqual(response.context["post-foo"], "whiz") |
| 1195 |
|
| 1196 |
# A POST-like request can pass a query string as part of the URL |
| 1197 |
response = self.client.post("/request_data/?foo=whiz") |
| 1198 |
self.assertEqual(response.context["get-foo"], "whiz") |
| 1199 |
self.assertIsNone(response.context["post-foo"]) |
| 1200 |
|
| 1201 |
response = self.client.post("/request_data/", query_params={"foo": "whiz"}) |
| 1202 |
self.assertEqual(response.context["get-foo"], "whiz") |
| 1203 |
self.assertIsNone(response.context["post-foo"]) |
| 1204 |
|
| 1205 |
# POST data provided in the URL augments actual form data |
| 1206 |
response = self.client.post("/request_data/?foo=whiz", data={"foo": "bang"}) |
| 1207 |
self.assertEqual(response.context["get-foo"], "whiz") |
| 1208 |
self.assertEqual(response.context["post-foo"], "bang") |
| 1209 |
|
| 1210 |
response = self.client.post("/request_data/?foo=whiz", data={"bar": "bang"}) |
| 1211 |
self.assertEqual(response.context["get-foo"], "whiz") |
| 1212 |
self.assertIsNone(response.context["get-bar"]) |
| 1213 |
self.assertIsNone(response.context["post-foo"]) |
| 1214 |
self.assertEqual(response.context["post-bar"], "bang") |
| 1215 |
|
| 1216 |
|
| 1217 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 1218 |
class PayloadEncodingTests(SimpleTestCase): |
| 1219 |
"""Regression tests for #10571.""" |
| 1220 |
|
| 1221 |
def test_simple_payload(self): |
| 1222 |
"""A simple ASCII-only text can be POSTed.""" |
| 1223 |
text = "English: mountain pass" |
| 1224 |
response = self.client.post( |
| 1225 |
"/parse_encoded_text/", text, content_type="text/plain" |
| 1226 |
) |
| 1227 |
self.assertEqual(response.content, text.encode()) |
| 1228 |
|
| 1229 |
def test_utf8_payload(self): |
| 1230 |
"""Non-ASCII data encoded as UTF-8 can be POSTed.""" |
| 1231 |
text = "dog: собака" |
| 1232 |
response = self.client.post( |
| 1233 |
"/parse_encoded_text/", text, content_type="text/plain; charset=utf-8" |
| 1234 |
) |
| 1235 |
self.assertEqual(response.content, text.encode()) |
| 1236 |
|
| 1237 |
def test_utf16_payload(self): |
| 1238 |
"""Non-ASCII data encoded as UTF-16 can be POSTed.""" |
| 1239 |
text = "dog: собака" |
| 1240 |
response = self.client.post( |
| 1241 |
"/parse_encoded_text/", text, content_type="text/plain; charset=utf-16" |
| 1242 |
) |
| 1243 |
self.assertEqual(response.content, text.encode("utf-16")) |
| 1244 |
|
| 1245 |
def test_non_utf_payload(self): |
| 1246 |
"""Non-ASCII data as a non-UTF based encoding can be POSTed.""" |
| 1247 |
text = "dog: собака" |
| 1248 |
response = self.client.post( |
| 1249 |
"/parse_encoded_text/", text, content_type="text/plain; charset=koi8-r" |
| 1250 |
) |
| 1251 |
self.assertEqual(response.content, text.encode("koi8-r")) |
| 1252 |
|
| 1253 |
|
| 1254 |
class DummyFile: |
| 1255 |
def __init__(self, filename): |
| 1256 |
self.name = filename |
| 1257 |
|
| 1258 |
def read(self): |
| 1259 |
return b"TEST_FILE_CONTENT" |
| 1260 |
|
| 1261 |
|
| 1262 |
class UploadedFileEncodingTest(SimpleTestCase): |
| 1263 |
def test_file_encoding(self): |
| 1264 |
encoded_file = encode_file( |
| 1265 |
"TEST_BOUNDARY", "TEST_KEY", DummyFile("test_name.bin") |
| 1266 |
) |
| 1267 |
self.assertEqual(b"--TEST_BOUNDARY", encoded_file[0]) |
| 1268 |
self.assertEqual( |
| 1269 |
b'Content-Disposition: form-data; name="TEST_KEY"; ' |
| 1270 |
b'filename="test_name.bin"', |
| 1271 |
encoded_file[1], |
| 1272 |
) |
| 1273 |
self.assertEqual(b"TEST_FILE_CONTENT", encoded_file[-1]) |
| 1274 |
|
| 1275 |
def test_guesses_content_type_on_file_encoding(self): |
| 1276 |
self.assertEqual( |
| 1277 |
b"Content-Type: application/octet-stream", |
| 1278 |
encode_file("IGNORE", "IGNORE", DummyFile("file.bin"))[2], |
| 1279 |
) |
| 1280 |
self.assertEqual( |
| 1281 |
b"Content-Type: text/plain", |
| 1282 |
encode_file("IGNORE", "IGNORE", DummyFile("file.txt"))[2], |
| 1283 |
) |
| 1284 |
self.assertIn( |
| 1285 |
encode_file("IGNORE", "IGNORE", DummyFile("file.zip"))[2], |
| 1286 |
( |
| 1287 |
b"Content-Type: application/x-compress", |
| 1288 |
b"Content-Type: application/x-zip", |
| 1289 |
b"Content-Type: application/x-zip-compressed", |
| 1290 |
b"Content-Type: application/zip", |
| 1291 |
), |
| 1292 |
) |
| 1293 |
self.assertEqual( |
| 1294 |
b"Content-Type: application/octet-stream", |
| 1295 |
encode_file("IGNORE", "IGNORE", DummyFile("file.unknown"))[2], |
| 1296 |
) |
| 1297 |
|
| 1298 |
|
| 1299 |
@override_settings( |
| 1300 |
ROOT_URLCONF="test_client_regress.urls", |
| 1301 |
) |
| 1302 |
class RequestHeadersTest(SimpleTestCase): |
| 1303 |
def test_client_headers(self): |
| 1304 |
"A test client can receive custom headers" |
| 1305 |
response = self.client.get( |
| 1306 |
"/check_headers/", headers={"x-arg-check": "Testing 123"} |
| 1307 |
) |
| 1308 |
self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123") |
| 1309 |
self.assertEqual(response.status_code, 200) |
| 1310 |
|
| 1311 |
def test_client_headers_redirect(self): |
| 1312 |
"Test client headers are preserved through redirects" |
| 1313 |
response = self.client.get( |
| 1314 |
"/check_headers_redirect/", |
| 1315 |
follow=True, |
| 1316 |
headers={"x-arg-check": "Testing 123"}, |
| 1317 |
) |
| 1318 |
self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123") |
| 1319 |
self.assertRedirects( |
| 1320 |
response, "/check_headers/", status_code=302, target_status_code=200 |
| 1321 |
) |
| 1322 |
|
| 1323 |
|
| 1324 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 1325 |
class ReadLimitedStreamTest(SimpleTestCase): |
| 1326 |
""" |
| 1327 |
HttpRequest.body, HttpRequest.read(), and HttpRequest.read(BUFFER) have |
| 1328 |
proper LimitedStream behavior. |
| 1329 |
|
| 1330 |
Refs #14753, #15785 |
| 1331 |
""" |
| 1332 |
|
| 1333 |
def test_body_from_empty_request(self): |
| 1334 |
"""HttpRequest.body on a test client GET request should return |
| 1335 |
the empty string.""" |
| 1336 |
self.assertEqual(self.client.get("/body/").content, b"") |
| 1337 |
|
| 1338 |
def test_read_from_empty_request(self): |
| 1339 |
"""HttpRequest.read() on a test client GET request should return the |
| 1340 |
empty string.""" |
| 1341 |
self.assertEqual(self.client.get("/read_all/").content, b"") |
| 1342 |
|
| 1343 |
def test_read_numbytes_from_empty_request(self): |
| 1344 |
"""HttpRequest.read(LARGE_BUFFER) on a test client GET request should |
| 1345 |
return the empty string.""" |
| 1346 |
self.assertEqual(self.client.get("/read_buffer/").content, b"") |
| 1347 |
|
| 1348 |
def test_read_from_nonempty_request(self): |
| 1349 |
"""HttpRequest.read() on a test client PUT request with some payload |
| 1350 |
should return that payload.""" |
| 1351 |
payload = b"foobar" |
| 1352 |
self.assertEqual( |
| 1353 |
self.client.put( |
| 1354 |
"/read_all/", data=payload, content_type="text/plain" |
| 1355 |
).content, |
| 1356 |
payload, |
| 1357 |
) |
| 1358 |
|
| 1359 |
def test_read_numbytes_from_nonempty_request(self): |
| 1360 |
"""HttpRequest.read(LARGE_BUFFER) on a test client PUT request with |
| 1361 |
some payload should return that payload.""" |
| 1362 |
payload = b"foobar" |
| 1363 |
self.assertEqual( |
| 1364 |
self.client.put( |
| 1365 |
"/read_buffer/", data=payload, content_type="text/plain" |
| 1366 |
).content, |
| 1367 |
payload, |
| 1368 |
) |
| 1369 |
|
| 1370 |
|
| 1371 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 1372 |
class RequestFactoryStateTest(SimpleTestCase): |
| 1373 |
"""Regression tests for #15929.""" |
| 1374 |
|
| 1375 |
# These tests are checking that certain middleware don't change certain |
| 1376 |
# global state. Alternatively, from the point of view of a test, they are |
| 1377 |
# ensuring test isolation behavior. So, unusually, it doesn't make sense to |
| 1378 |
# run the tests individually, and if any are failing it is confusing to run |
| 1379 |
# them with any other set of tests. |
| 1380 |
|
| 1381 |
def common_test_that_should_always_pass(self): |
| 1382 |
request = RequestFactory().get("/") |
| 1383 |
request.session = {} |
| 1384 |
self.assertFalse(hasattr(request, "user")) |
| 1385 |
|
| 1386 |
def test_request(self): |
| 1387 |
self.common_test_that_should_always_pass() |
| 1388 |
|
| 1389 |
def test_request_after_client(self): |
| 1390 |
# apart from the next line the three tests are identical |
| 1391 |
self.client.get("/") |
| 1392 |
self.common_test_that_should_always_pass() |
| 1393 |
|
| 1394 |
def test_request_after_client_2(self): |
| 1395 |
# This test is executed after the previous one |
| 1396 |
self.common_test_that_should_always_pass() |
| 1397 |
|
| 1398 |
|
| 1399 |
@override_settings(ROOT_URLCONF="test_client_regress.urls") |
| 1400 |
class RequestFactoryEnvironmentTests(SimpleTestCase): |
| 1401 |
""" |
| 1402 |
Regression tests for #8551 and #17067: ensure that environment variables |
| 1403 |
are set correctly in RequestFactory. |
| 1404 |
""" |
| 1405 |
|
| 1406 |
def test_should_set_correct_env_variables(self): |
| 1407 |
request = RequestFactory().get("/path/") |
| 1408 |
|
| 1409 |
self.assertEqual(request.META.get("REMOTE_ADDR"), "127.0.0.1") |
| 1410 |
self.assertEqual(request.META.get("SERVER_NAME"), "testserver") |
| 1411 |
self.assertEqual(request.META.get("SERVER_PORT"), "80") |
| 1412 |
self.assertEqual(request.META.get("SERVER_PROTOCOL"), "HTTP/1.1") |
| 1413 |
self.assertEqual( |
| 1414 |
request.META.get("SCRIPT_NAME") + request.META.get("PATH_INFO"), "/path/" |
| 1415 |
) |
| 1416 |
|
| 1417 |
def test_cookies(self): |
| 1418 |
factory = RequestFactory() |
| 1419 |
factory.cookies.load('A="B"; C="D"; Path=/; Version=1') |
| 1420 |
request = factory.get("/") |
| 1421 |
self.assertEqual(request.META["HTTP_COOKIE"], 'A="B"; C="D"') |