tests.py 30 KB

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