tests.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. # -*- coding: utf-8 -*-
  2. """
  3. Testing using the Test Client
  4. The test client is a class that can act like a simple
  5. browser for testing purposes.
  6. It allows the user to compose GET and POST requests, and
  7. obtain the response that the server gave to those requests.
  8. The server Response objects are annotated with the details
  9. of the contexts and templates that were rendered during the
  10. process of serving the request.
  11. ``Client`` objects are stateful - they will retain cookie (and
  12. thus session) details for the lifetime of the ``Client`` instance.
  13. This is not intended as a replacement for Twill, Selenium, or
  14. other browser automation frameworks - it is here to allow
  15. testing against the contexts and templates produced by a view,
  16. rather than the HTML rendered to the end-user.
  17. """
  18. from __future__ import unicode_literals
  19. from django.contrib.auth.models import User
  20. from django.core import mail
  21. from django.http import HttpResponse
  22. from django.test import (
  23. Client, RequestFactory, SimpleTestCase, TestCase, override_settings,
  24. )
  25. from django.urls import reverse_lazy
  26. from .views import get_view, post_view, trace_view
  27. @override_settings(ROOT_URLCONF='test_client.urls')
  28. class ClientTest(TestCase):
  29. @classmethod
  30. def setUpTestData(cls):
  31. cls.u1 = User.objects.create_user(username='testclient', password='password')
  32. cls.u2 = User.objects.create_user(username='inactive', password='password', is_active=False)
  33. def test_get_view(self):
  34. "GET a view"
  35. # The data is ignored, but let's check it doesn't crash the system
  36. # anyway.
  37. data = {'var': '\xf2'}
  38. response = self.client.get('/get_view/', data)
  39. # Check some response details
  40. self.assertContains(response, 'This is a test')
  41. self.assertEqual(response.context['var'], '\xf2')
  42. self.assertEqual(response.templates[0].name, 'GET Template')
  43. def test_get_post_view(self):
  44. "GET a view that normally expects POSTs"
  45. response = self.client.get('/post_view/', {})
  46. # Check some response details
  47. self.assertEqual(response.status_code, 200)
  48. self.assertEqual(response.templates[0].name, 'Empty GET Template')
  49. self.assertTemplateUsed(response, 'Empty GET Template')
  50. self.assertTemplateNotUsed(response, 'Empty POST Template')
  51. def test_empty_post(self):
  52. "POST an empty dictionary to a view"
  53. response = self.client.post('/post_view/', {})
  54. # Check some response details
  55. self.assertEqual(response.status_code, 200)
  56. self.assertEqual(response.templates[0].name, 'Empty POST Template')
  57. self.assertTemplateNotUsed(response, 'Empty GET Template')
  58. self.assertTemplateUsed(response, 'Empty POST Template')
  59. def test_post(self):
  60. "POST some data to a view"
  61. post_data = {
  62. 'value': 37
  63. }
  64. response = self.client.post('/post_view/', post_data)
  65. # Check some response details
  66. self.assertEqual(response.status_code, 200)
  67. self.assertEqual(response.context['data'], '37')
  68. self.assertEqual(response.templates[0].name, 'POST Template')
  69. self.assertContains(response, 'Data received')
  70. def test_trace(self):
  71. """TRACE a view"""
  72. response = self.client.trace('/trace_view/')
  73. self.assertEqual(response.status_code, 200)
  74. self.assertEqual(response.context['method'], 'TRACE')
  75. self.assertEqual(response.templates[0].name, 'TRACE Template')
  76. def test_response_headers(self):
  77. "Check the value of HTTP headers returned in a response"
  78. response = self.client.get("/header_view/")
  79. self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast')
  80. def test_response_attached_request(self):
  81. """
  82. Check that the returned response has a ``request`` attribute with the
  83. originating environ dict and a ``wsgi_request`` with the originating
  84. ``WSGIRequest`` instance.
  85. """
  86. response = self.client.get("/header_view/")
  87. self.assertTrue(hasattr(response, 'request'))
  88. self.assertTrue(hasattr(response, 'wsgi_request'))
  89. for key, value in response.request.items():
  90. self.assertIn(key, response.wsgi_request.environ)
  91. self.assertEqual(response.wsgi_request.environ[key], value)
  92. def test_response_resolver_match(self):
  93. """
  94. The response contains a ResolverMatch instance.
  95. """
  96. response = self.client.get('/header_view/')
  97. self.assertTrue(hasattr(response, 'resolver_match'))
  98. def test_response_resolver_match_redirect_follow(self):
  99. """
  100. The response ResolverMatch instance contains the correct
  101. information when following redirects.
  102. """
  103. response = self.client.get('/redirect_view/', follow=True)
  104. self.assertEqual(response.resolver_match.url_name, 'get_view')
  105. def test_response_resolver_match_regular_view(self):
  106. """
  107. The response ResolverMatch instance contains the correct
  108. information when accessing a regular view.
  109. """
  110. response = self.client.get('/get_view/')
  111. self.assertEqual(response.resolver_match.url_name, 'get_view')
  112. def test_raw_post(self):
  113. "POST raw data (with a content type) to a view"
  114. test_doc = """<?xml version="1.0" encoding="utf-8"?>
  115. <library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>
  116. """
  117. response = self.client.post("/raw_post_view/", test_doc,
  118. content_type="text/xml")
  119. self.assertEqual(response.status_code, 200)
  120. self.assertEqual(response.templates[0].name, "Book template")
  121. self.assertEqual(response.content, b"Blink - Malcolm Gladwell")
  122. def test_insecure(self):
  123. "GET a URL through http"
  124. response = self.client.get('/secure_view/', secure=False)
  125. self.assertFalse(response.test_was_secure_request)
  126. self.assertEqual(response.test_server_port, '80')
  127. def test_secure(self):
  128. "GET a URL through https"
  129. response = self.client.get('/secure_view/', secure=True)
  130. self.assertTrue(response.test_was_secure_request)
  131. self.assertEqual(response.test_server_port, '443')
  132. def test_redirect(self):
  133. "GET a URL that redirects elsewhere"
  134. response = self.client.get('/redirect_view/')
  135. # Check that the response was a 302 (redirect)
  136. self.assertRedirects(response, '/get_view/')
  137. def test_redirect_with_query(self):
  138. "GET a URL that redirects with given GET parameters"
  139. response = self.client.get('/redirect_view/', {'var': 'value'})
  140. # Check if parameters are intact
  141. self.assertRedirects(response, '/get_view/?var=value')
  142. def test_permanent_redirect(self):
  143. "GET a URL that redirects permanently elsewhere"
  144. response = self.client.get('/permanent_redirect_view/')
  145. # Check that the response was a 301 (permanent redirect)
  146. self.assertRedirects(response, '/get_view/', status_code=301)
  147. def test_temporary_redirect(self):
  148. "GET a URL that does a non-permanent redirect"
  149. response = self.client.get('/temporary_redirect_view/')
  150. # Check that the response was a 302 (non-permanent redirect)
  151. self.assertRedirects(response, '/get_view/', status_code=302)
  152. def test_redirect_to_strange_location(self):
  153. "GET a URL that redirects to a non-200 page"
  154. response = self.client.get('/double_redirect_view/')
  155. # Check that the response was a 302, and that
  156. # the attempt to get the redirection location returned 301 when retrieved
  157. self.assertRedirects(response, '/permanent_redirect_view/', target_status_code=301)
  158. def test_follow_redirect(self):
  159. "A URL that redirects can be followed to termination."
  160. response = self.client.get('/double_redirect_view/', follow=True)
  161. self.assertRedirects(response, '/get_view/', status_code=302, target_status_code=200)
  162. self.assertEqual(len(response.redirect_chain), 2)
  163. def test_follow_relative_redirect(self):
  164. "A URL with a relative redirect can be followed."
  165. response = self.client.get('/accounts/', follow=True)
  166. self.assertEqual(response.status_code, 200)
  167. self.assertEqual(response.request['PATH_INFO'], '/accounts/login/')
  168. def test_follow_relative_redirect_no_trailing_slash(self):
  169. "A URL with a relative redirect with no trailing slash can be followed."
  170. response = self.client.get('/accounts/no_trailing_slash', follow=True)
  171. self.assertEqual(response.status_code, 200)
  172. self.assertEqual(response.request['PATH_INFO'], '/accounts/login/')
  173. def test_redirect_http(self):
  174. "GET a URL that redirects to an http URI"
  175. response = self.client.get('/http_redirect_view/', follow=True)
  176. self.assertFalse(response.test_was_secure_request)
  177. def test_redirect_https(self):
  178. "GET a URL that redirects to an https URI"
  179. response = self.client.get('/https_redirect_view/', follow=True)
  180. self.assertTrue(response.test_was_secure_request)
  181. def test_notfound_response(self):
  182. "GET a URL that responds as '404:Not Found'"
  183. response = self.client.get('/bad_view/')
  184. # Check that the response was a 404, and that the content contains MAGIC
  185. self.assertContains(response, 'MAGIC', status_code=404)
  186. def test_valid_form(self):
  187. "POST valid data to a form"
  188. post_data = {
  189. 'text': 'Hello World',
  190. 'email': 'foo@example.com',
  191. 'value': 37,
  192. 'single': 'b',
  193. 'multi': ('b', 'c', 'e')
  194. }
  195. response = self.client.post('/form_view/', post_data)
  196. self.assertEqual(response.status_code, 200)
  197. self.assertTemplateUsed(response, "Valid POST Template")
  198. def test_valid_form_with_hints(self):
  199. "GET a form, providing hints in the GET data"
  200. hints = {
  201. 'text': 'Hello World',
  202. 'multi': ('b', 'c', 'e')
  203. }
  204. response = self.client.get('/form_view/', data=hints)
  205. self.assertEqual(response.status_code, 200)
  206. self.assertTemplateUsed(response, "Form GET Template")
  207. # Check that the multi-value data has been rolled out ok
  208. self.assertContains(response, 'Select a valid choice.', 0)
  209. def test_incomplete_data_form(self):
  210. "POST incomplete data to a form"
  211. post_data = {
  212. 'text': 'Hello World',
  213. 'value': 37
  214. }
  215. response = self.client.post('/form_view/', post_data)
  216. self.assertContains(response, 'This field is required.', 3)
  217. self.assertEqual(response.status_code, 200)
  218. self.assertTemplateUsed(response, "Invalid POST Template")
  219. self.assertFormError(response, 'form', 'email', 'This field is required.')
  220. self.assertFormError(response, 'form', 'single', 'This field is required.')
  221. self.assertFormError(response, 'form', 'multi', 'This field is required.')
  222. def test_form_error(self):
  223. "POST erroneous data to a form"
  224. post_data = {
  225. 'text': 'Hello World',
  226. 'email': 'not an email address',
  227. 'value': 37,
  228. 'single': 'b',
  229. 'multi': ('b', 'c', 'e')
  230. }
  231. response = self.client.post('/form_view/', post_data)
  232. self.assertEqual(response.status_code, 200)
  233. self.assertTemplateUsed(response, "Invalid POST Template")
  234. self.assertFormError(response, 'form', 'email', 'Enter a valid email address.')
  235. def test_valid_form_with_template(self):
  236. "POST valid data to a form using multiple templates"
  237. post_data = {
  238. 'text': 'Hello World',
  239. 'email': 'foo@example.com',
  240. 'value': 37,
  241. 'single': 'b',
  242. 'multi': ('b', 'c', 'e')
  243. }
  244. response = self.client.post('/form_view_with_template/', post_data)
  245. self.assertContains(response, 'POST data OK')
  246. self.assertTemplateUsed(response, "form_view.html")
  247. self.assertTemplateUsed(response, 'base.html')
  248. self.assertTemplateNotUsed(response, "Valid POST Template")
  249. def test_incomplete_data_form_with_template(self):
  250. "POST incomplete data to a form using multiple templates"
  251. post_data = {
  252. 'text': 'Hello World',
  253. 'value': 37
  254. }
  255. response = self.client.post('/form_view_with_template/', post_data)
  256. self.assertContains(response, 'POST data has errors')
  257. self.assertTemplateUsed(response, 'form_view.html')
  258. self.assertTemplateUsed(response, 'base.html')
  259. self.assertTemplateNotUsed(response, "Invalid POST Template")
  260. self.assertFormError(response, 'form', 'email', 'This field is required.')
  261. self.assertFormError(response, 'form', 'single', 'This field is required.')
  262. self.assertFormError(response, 'form', 'multi', 'This field is required.')
  263. def test_form_error_with_template(self):
  264. "POST erroneous data to a form using multiple templates"
  265. post_data = {
  266. 'text': 'Hello World',
  267. 'email': 'not an email address',
  268. 'value': 37,
  269. 'single': 'b',
  270. 'multi': ('b', 'c', 'e')
  271. }
  272. response = self.client.post('/form_view_with_template/', post_data)
  273. self.assertContains(response, 'POST data has errors')
  274. self.assertTemplateUsed(response, "form_view.html")
  275. self.assertTemplateUsed(response, 'base.html')
  276. self.assertTemplateNotUsed(response, "Invalid POST Template")
  277. self.assertFormError(response, 'form', 'email', 'Enter a valid email address.')
  278. def test_unknown_page(self):
  279. "GET an invalid URL"
  280. response = self.client.get('/unknown_view/')
  281. # Check that the response was a 404
  282. self.assertEqual(response.status_code, 404)
  283. def test_url_parameters(self):
  284. "Make sure that URL ;-parameters are not stripped."
  285. response = self.client.get('/unknown_view/;some-parameter')
  286. # Check that the path in the response includes it (ignore that it's a 404)
  287. self.assertEqual(response.request['PATH_INFO'], '/unknown_view/;some-parameter')
  288. def test_view_with_login(self):
  289. "Request a page that is protected with @login_required"
  290. # Get the page without logging in. Should result in 302.
  291. response = self.client.get('/login_protected_view/')
  292. self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')
  293. # Log in
  294. login = self.client.login(username='testclient', password='password')
  295. self.assertTrue(login, 'Could not log in')
  296. # Request a page that requires a login
  297. response = self.client.get('/login_protected_view/')
  298. self.assertEqual(response.status_code, 200)
  299. self.assertEqual(response.context['user'].username, 'testclient')
  300. @override_settings(
  301. INSTALLED_APPS=['django.contrib.auth'],
  302. SESSION_ENGINE='django.contrib.sessions.backends.file',
  303. )
  304. def test_view_with_login_when_sessions_app_is_not_installed(self):
  305. self.test_view_with_login()
  306. def test_view_with_force_login(self):
  307. "Request a page that is protected with @login_required"
  308. # Get the page without logging in. Should result in 302.
  309. response = self.client.get('/login_protected_view/')
  310. self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')
  311. # Log in
  312. self.client.force_login(self.u1)
  313. # Request a page that requires a login
  314. response = self.client.get('/login_protected_view/')
  315. self.assertEqual(response.status_code, 200)
  316. self.assertEqual(response.context['user'].username, 'testclient')
  317. def test_view_with_method_login(self):
  318. "Request a page that is protected with a @login_required method"
  319. # Get the page without logging in. Should result in 302.
  320. response = self.client.get('/login_protected_method_view/')
  321. self.assertRedirects(response, '/accounts/login/?next=/login_protected_method_view/')
  322. # Log in
  323. login = self.client.login(username='testclient', password='password')
  324. self.assertTrue(login, 'Could not log in')
  325. # Request a page that requires a login
  326. response = self.client.get('/login_protected_method_view/')
  327. self.assertEqual(response.status_code, 200)
  328. self.assertEqual(response.context['user'].username, 'testclient')
  329. def test_view_with_method_force_login(self):
  330. "Request a page that is protected with a @login_required method"
  331. # Get the page without logging in. Should result in 302.
  332. response = self.client.get('/login_protected_method_view/')
  333. self.assertRedirects(response, '/accounts/login/?next=/login_protected_method_view/')
  334. # Log in
  335. self.client.force_login(self.u1)
  336. # Request a page that requires a login
  337. response = self.client.get('/login_protected_method_view/')
  338. self.assertEqual(response.status_code, 200)
  339. self.assertEqual(response.context['user'].username, 'testclient')
  340. def test_view_with_login_and_custom_redirect(self):
  341. "Request a page that is protected with @login_required(redirect_field_name='redirect_to')"
  342. # Get the page without logging in. Should result in 302.
  343. response = self.client.get('/login_protected_view_custom_redirect/')
  344. self.assertRedirects(response, '/accounts/login/?redirect_to=/login_protected_view_custom_redirect/')
  345. # Log in
  346. login = self.client.login(username='testclient', password='password')
  347. self.assertTrue(login, 'Could not log in')
  348. # Request a page that requires a login
  349. response = self.client.get('/login_protected_view_custom_redirect/')
  350. self.assertEqual(response.status_code, 200)
  351. self.assertEqual(response.context['user'].username, 'testclient')
  352. def test_view_with_force_login_and_custom_redirect(self):
  353. """
  354. Request a page that is protected with
  355. @login_required(redirect_field_name='redirect_to')
  356. """
  357. # Get the page without logging in. Should result in 302.
  358. response = self.client.get('/login_protected_view_custom_redirect/')
  359. self.assertRedirects(response, '/accounts/login/?redirect_to=/login_protected_view_custom_redirect/')
  360. # Log in
  361. self.client.force_login(self.u1)
  362. # Request a page that requires a login
  363. response = self.client.get('/login_protected_view_custom_redirect/')
  364. self.assertEqual(response.status_code, 200)
  365. self.assertEqual(response.context['user'].username, 'testclient')
  366. def test_view_with_bad_login(self):
  367. "Request a page that is protected with @login, but use bad credentials"
  368. login = self.client.login(username='otheruser', password='nopassword')
  369. self.assertFalse(login)
  370. def test_view_with_inactive_login(self):
  371. """
  372. An inactive user may login if the authenticate backend allows it.
  373. """
  374. credentials = {'username': 'inactive', 'password': 'password'}
  375. self.assertFalse(self.client.login(**credentials))
  376. with self.settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBackend']):
  377. self.assertTrue(self.client.login(**credentials))
  378. @override_settings(
  379. AUTHENTICATION_BACKENDS=[
  380. 'django.contrib.auth.backends.ModelBackend',
  381. 'django.contrib.auth.backends.AllowAllUsersModelBackend',
  382. ]
  383. )
  384. def test_view_with_inactive_force_login(self):
  385. "Request a page that is protected with @login, but use an inactive login"
  386. # Get the page without logging in. Should result in 302.
  387. response = self.client.get('/login_protected_view/')
  388. self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')
  389. # Log in
  390. self.client.force_login(self.u2, backend='django.contrib.auth.backends.AllowAllUsersModelBackend')
  391. # Request a page that requires a login
  392. response = self.client.get('/login_protected_view/')
  393. self.assertEqual(response.status_code, 200)
  394. self.assertEqual(response.context['user'].username, 'inactive')
  395. def test_logout(self):
  396. "Request a logout after logging in"
  397. # Log in
  398. self.client.login(username='testclient', password='password')
  399. # Request a page that requires a login
  400. response = self.client.get('/login_protected_view/')
  401. self.assertEqual(response.status_code, 200)
  402. self.assertEqual(response.context['user'].username, 'testclient')
  403. # Log out
  404. self.client.logout()
  405. # Request a page that requires a login
  406. response = self.client.get('/login_protected_view/')
  407. self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')
  408. def test_logout_with_force_login(self):
  409. "Request a logout after logging in"
  410. # Log in
  411. self.client.force_login(self.u1)
  412. # Request a page that requires a login
  413. response = self.client.get('/login_protected_view/')
  414. self.assertEqual(response.status_code, 200)
  415. self.assertEqual(response.context['user'].username, 'testclient')
  416. # Log out
  417. self.client.logout()
  418. # Request a page that requires a login
  419. response = self.client.get('/login_protected_view/')
  420. self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')
  421. @override_settings(
  422. AUTHENTICATION_BACKENDS=[
  423. 'django.contrib.auth.backends.ModelBackend',
  424. 'test_client.auth_backends.TestClientBackend',
  425. ],
  426. )
  427. def test_force_login_with_backend(self):
  428. """
  429. Request a page that is protected with @login_required when using
  430. force_login() and passing a backend.
  431. """
  432. # Get the page without logging in. Should result in 302.
  433. response = self.client.get('/login_protected_view/')
  434. self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')
  435. # Log in
  436. self.client.force_login(self.u1, backend='test_client.auth_backends.TestClientBackend')
  437. # Request a page that requires a login
  438. response = self.client.get('/login_protected_view/')
  439. self.assertEqual(response.status_code, 200)
  440. self.assertEqual(response.context['user'].username, 'testclient')
  441. @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies")
  442. def test_logout_cookie_sessions(self):
  443. self.test_logout()
  444. def test_view_with_permissions(self):
  445. "Request a page that is protected with @permission_required"
  446. # Get the page without logging in. Should result in 302.
  447. response = self.client.get('/permission_protected_view/')
  448. self.assertRedirects(response, '/accounts/login/?next=/permission_protected_view/')
  449. # Log in
  450. login = self.client.login(username='testclient', password='password')
  451. self.assertTrue(login, 'Could not log in')
  452. # Log in with wrong permissions. Should result in 302.
  453. response = self.client.get('/permission_protected_view/')
  454. self.assertRedirects(response, '/accounts/login/?next=/permission_protected_view/')
  455. # TODO: Log in with right permissions and request the page again
  456. def test_view_with_permissions_exception(self):
  457. "Request a page that is protected with @permission_required but raises an exception"
  458. # Get the page without logging in. Should result in 403.
  459. response = self.client.get('/permission_protected_view_exception/')
  460. self.assertEqual(response.status_code, 403)
  461. # Log in
  462. login = self.client.login(username='testclient', password='password')
  463. self.assertTrue(login, 'Could not log in')
  464. # Log in with wrong permissions. Should result in 403.
  465. response = self.client.get('/permission_protected_view_exception/')
  466. self.assertEqual(response.status_code, 403)
  467. def test_view_with_method_permissions(self):
  468. "Request a page that is protected with a @permission_required method"
  469. # Get the page without logging in. Should result in 302.
  470. response = self.client.get('/permission_protected_method_view/')
  471. self.assertRedirects(response, '/accounts/login/?next=/permission_protected_method_view/')
  472. # Log in
  473. login = self.client.login(username='testclient', password='password')
  474. self.assertTrue(login, 'Could not log in')
  475. # Log in with wrong permissions. Should result in 302.
  476. response = self.client.get('/permission_protected_method_view/')
  477. self.assertRedirects(response, '/accounts/login/?next=/permission_protected_method_view/')
  478. # TODO: Log in with right permissions and request the page again
  479. def test_external_redirect(self):
  480. response = self.client.get('/django_project_redirect/')
  481. self.assertRedirects(response, 'https://www.djangoproject.com/', fetch_redirect_response=False)
  482. def test_external_redirect_with_fetch_error_msg(self):
  483. """
  484. Check that assertRedirects without fetch_redirect_response=False raises
  485. a relevant ValueError rather than a non-descript AssertionError.
  486. """
  487. response = self.client.get('/django_project_redirect/')
  488. msg = (
  489. "The test client is unable to fetch remote URLs (got "
  490. "https://www.djangoproject.com/). If the host is served by Django, "
  491. "add 'www.djangoproject.com' to ALLOWED_HOSTS. "
  492. "Otherwise, use assertRedirects(..., fetch_redirect_response=False)."
  493. )
  494. with self.assertRaisesMessage(ValueError, msg):
  495. self.assertRedirects(response, 'https://www.djangoproject.com/')
  496. def test_session_modifying_view(self):
  497. "Request a page that modifies the session"
  498. # Session value isn't set initially
  499. try:
  500. self.client.session['tobacconist']
  501. self.fail("Shouldn't have a session value")
  502. except KeyError:
  503. pass
  504. self.client.post('/session_view/')
  505. # Check that the session was modified
  506. self.assertEqual(self.client.session['tobacconist'], 'hovercraft')
  507. @override_settings(
  508. INSTALLED_APPS=[],
  509. SESSION_ENGINE='django.contrib.sessions.backends.file',
  510. )
  511. def test_sessions_app_is_not_installed(self):
  512. self.test_session_modifying_view()
  513. @override_settings(
  514. INSTALLED_APPS=[],
  515. SESSION_ENGINE='django.contrib.sessions.backends.nonexistent',
  516. )
  517. def test_session_engine_is_invalid(self):
  518. with self.assertRaisesMessage(ImportError, 'nonexistent'):
  519. self.test_session_modifying_view()
  520. def test_view_with_exception(self):
  521. "Request a page that is known to throw an error"
  522. with self.assertRaises(KeyError):
  523. self.client.get("/broken_view/")
  524. # Try the same assertion, a different way
  525. try:
  526. self.client.get('/broken_view/')
  527. self.fail('Should raise an error')
  528. except KeyError:
  529. pass
  530. def test_mail_sending(self):
  531. "Test that mail is redirected to a dummy outbox during test setup"
  532. response = self.client.get('/mail_sending_view/')
  533. self.assertEqual(response.status_code, 200)
  534. self.assertEqual(len(mail.outbox), 1)
  535. self.assertEqual(mail.outbox[0].subject, 'Test message')
  536. self.assertEqual(mail.outbox[0].body, 'This is a test email')
  537. self.assertEqual(mail.outbox[0].from_email, 'from@example.com')
  538. self.assertEqual(mail.outbox[0].to[0], 'first@example.com')
  539. self.assertEqual(mail.outbox[0].to[1], 'second@example.com')
  540. def test_reverse_lazy_decodes(self):
  541. "Ensure reverse_lazy works in the test client"
  542. data = {'var': 'data'}
  543. response = self.client.get(reverse_lazy('get_view'), data)
  544. # Check some response details
  545. self.assertContains(response, 'This is a test')
  546. def test_relative_redirect(self):
  547. response = self.client.get('/accounts/')
  548. self.assertRedirects(response, '/accounts/login/')
  549. def test_relative_redirect_no_trailing_slash(self):
  550. response = self.client.get('/accounts/no_trailing_slash')
  551. self.assertRedirects(response, '/accounts/login/')
  552. def test_mass_mail_sending(self):
  553. "Test that mass mail is redirected to a dummy outbox during test setup"
  554. response = self.client.get('/mass_mail_sending_view/')
  555. self.assertEqual(response.status_code, 200)
  556. self.assertEqual(len(mail.outbox), 2)
  557. self.assertEqual(mail.outbox[0].subject, 'First Test message')
  558. self.assertEqual(mail.outbox[0].body, 'This is the first test email')
  559. self.assertEqual(mail.outbox[0].from_email, 'from@example.com')
  560. self.assertEqual(mail.outbox[0].to[0], 'first@example.com')
  561. self.assertEqual(mail.outbox[0].to[1], 'second@example.com')
  562. self.assertEqual(mail.outbox[1].subject, 'Second Test message')
  563. self.assertEqual(mail.outbox[1].body, 'This is the second test email')
  564. self.assertEqual(mail.outbox[1].from_email, 'from@example.com')
  565. self.assertEqual(mail.outbox[1].to[0], 'second@example.com')
  566. self.assertEqual(mail.outbox[1].to[1], 'third@example.com')
  567. def test_exception_following_nested_client_request(self):
  568. """
  569. A nested test client request shouldn't clobber exception signals from
  570. the outer client request.
  571. """
  572. with self.assertRaisesMessage(Exception, 'exception message'):
  573. self.client.get('/nesting_exception_view/')
  574. @override_settings(
  575. MIDDLEWARE=['django.middleware.csrf.CsrfViewMiddleware'],
  576. ROOT_URLCONF='test_client.urls',
  577. )
  578. class CSRFEnabledClientTests(SimpleTestCase):
  579. def test_csrf_enabled_client(self):
  580. "A client can be instantiated with CSRF checks enabled"
  581. csrf_client = Client(enforce_csrf_checks=True)
  582. # The normal client allows the post
  583. response = self.client.post('/post_view/', {})
  584. self.assertEqual(response.status_code, 200)
  585. # The CSRF-enabled client rejects it
  586. response = csrf_client.post('/post_view/', {})
  587. self.assertEqual(response.status_code, 403)
  588. class CustomTestClient(Client):
  589. i_am_customized = "Yes"
  590. class CustomTestClientTest(SimpleTestCase):
  591. client_class = CustomTestClient
  592. def test_custom_test_client(self):
  593. """A test case can specify a custom class for self.client."""
  594. self.assertIs(hasattr(self.client, "i_am_customized"), True)
  595. def _generic_view(request):
  596. return HttpResponse(status=200)
  597. @override_settings(ROOT_URLCONF='test_client.urls')
  598. class RequestFactoryTest(SimpleTestCase):
  599. """Tests for the request factory."""
  600. # A mapping between names of HTTP/1.1 methods and their test views.
  601. http_methods_and_views = (
  602. ('get', get_view),
  603. ('post', post_view),
  604. ('put', _generic_view),
  605. ('patch', _generic_view),
  606. ('delete', _generic_view),
  607. ('head', _generic_view),
  608. ('options', _generic_view),
  609. ('trace', trace_view),
  610. )
  611. def setUp(self):
  612. self.request_factory = RequestFactory()
  613. def test_request_factory(self):
  614. """The request factory implements all the HTTP/1.1 methods."""
  615. for method_name, view in self.http_methods_and_views:
  616. method = getattr(self.request_factory, method_name)
  617. request = method('/somewhere/')
  618. response = view(request)
  619. self.assertEqual(response.status_code, 200)
  620. def test_get_request_from_factory(self):
  621. """
  622. The request factory returns a templated response for a GET request.
  623. """
  624. request = self.request_factory.get('/somewhere/')
  625. response = get_view(request)
  626. self.assertContains(response, 'This is a test')
  627. def test_trace_request_from_factory(self):
  628. """The request factory returns an echo response for a TRACE request."""
  629. url_path = '/somewhere/'
  630. request = self.request_factory.trace(url_path)
  631. response = trace_view(request)
  632. protocol = request.META["SERVER_PROTOCOL"]
  633. echoed_request_line = "TRACE {} {}".format(url_path, protocol)
  634. self.assertContains(response, echoed_request_line)