tests.py 53 KB

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