tests.py 62 KB

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