tests.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. # coding: utf-8
  2. """
  3. 39. 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.conf import settings
  20. from django.core import mail
  21. from django.test import Client, TestCase, RequestFactory
  22. from django.test.utils import override_settings
  23. from .views import get_view
  24. @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
  25. class ClientTest(TestCase):
  26. fixtures = ['testdata.json']
  27. def test_get_view(self):
  28. "GET a view"
  29. # The data is ignored, but let's check it doesn't crash the system
  30. # anyway.
  31. data = {'var': '\xf2'}
  32. response = self.client.get('/test_client/get_view/', data)
  33. # Check some response details
  34. self.assertContains(response, 'This is a test')
  35. self.assertEqual(response.context['var'], '\xf2')
  36. self.assertEqual(response.templates[0].name, 'GET Template')
  37. def test_get_post_view(self):
  38. "GET a view that normally expects POSTs"
  39. response = self.client.get('/test_client/post_view/', {})
  40. # Check some response details
  41. self.assertEqual(response.status_code, 200)
  42. self.assertEqual(response.templates[0].name, 'Empty GET Template')
  43. self.assertTemplateUsed(response, 'Empty GET Template')
  44. self.assertTemplateNotUsed(response, 'Empty POST Template')
  45. def test_empty_post(self):
  46. "POST an empty dictionary to a view"
  47. response = self.client.post('/test_client/post_view/', {})
  48. # Check some response details
  49. self.assertEqual(response.status_code, 200)
  50. self.assertEqual(response.templates[0].name, 'Empty POST Template')
  51. self.assertTemplateNotUsed(response, 'Empty GET Template')
  52. self.assertTemplateUsed(response, 'Empty POST Template')
  53. def test_post(self):
  54. "POST some data to a view"
  55. post_data = {
  56. 'value': 37
  57. }
  58. response = self.client.post('/test_client/post_view/', post_data)
  59. # Check some response details
  60. self.assertEqual(response.status_code, 200)
  61. self.assertEqual(response.context['data'], '37')
  62. self.assertEqual(response.templates[0].name, 'POST Template')
  63. self.assertContains(response, 'Data received')
  64. def test_response_headers(self):
  65. "Check the value of HTTP headers returned in a response"
  66. response = self.client.get("/test_client/header_view/")
  67. self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast')
  68. def test_raw_post(self):
  69. "POST raw data (with a content type) to a view"
  70. test_doc = """<?xml version="1.0" encoding="utf-8"?><library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>"""
  71. response = self.client.post("/test_client/raw_post_view/", test_doc,
  72. content_type="text/xml")
  73. self.assertEqual(response.status_code, 200)
  74. self.assertEqual(response.templates[0].name, "Book template")
  75. self.assertEqual(response.content, b"Blink - Malcolm Gladwell")
  76. def test_insecure(self):
  77. "GET a URL through http"
  78. response = self.client.get('/test_client/secure_view/', secure=False)
  79. self.assertFalse(response.test_was_secure_request)
  80. self.assertEqual(response.test_server_port, '80')
  81. def test_secure(self):
  82. "GET a URL through https"
  83. response = self.client.get('/test_client/secure_view/', secure=True)
  84. self.assertTrue(response.test_was_secure_request)
  85. self.assertEqual(response.test_server_port, '443')
  86. def test_redirect(self):
  87. "GET a URL that redirects elsewhere"
  88. response = self.client.get('/test_client/redirect_view/')
  89. # Check that the response was a 302 (redirect) and that
  90. # assertRedirect() understands to put an implicit http://testserver/ in
  91. # front of non-absolute URLs.
  92. self.assertRedirects(response, '/test_client/get_view/')
  93. host = 'django.testserver'
  94. client_providing_host = Client(HTTP_HOST=host)
  95. response = client_providing_host.get('/test_client/redirect_view/')
  96. # Check that the response was a 302 (redirect) with absolute URI
  97. self.assertRedirects(response, '/test_client/get_view/', host=host)
  98. def test_redirect_with_query(self):
  99. "GET a URL that redirects with given GET parameters"
  100. response = self.client.get('/test_client/redirect_view/', {'var': 'value'})
  101. # Check if parameters are intact
  102. self.assertRedirects(response, 'http://testserver/test_client/get_view/?var=value')
  103. def test_permanent_redirect(self):
  104. "GET a URL that redirects permanently elsewhere"
  105. response = self.client.get('/test_client/permanent_redirect_view/')
  106. # Check that the response was a 301 (permanent redirect)
  107. self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=301)
  108. client_providing_host = Client(HTTP_HOST='django.testserver')
  109. response = client_providing_host.get('/test_client/permanent_redirect_view/')
  110. # Check that the response was a 301 (permanent redirect) with absolute URI
  111. self.assertRedirects(response, 'http://django.testserver/test_client/get_view/', status_code=301)
  112. def test_temporary_redirect(self):
  113. "GET a URL that does a non-permanent redirect"
  114. response = self.client.get('/test_client/temporary_redirect_view/')
  115. # Check that the response was a 302 (non-permanent redirect)
  116. self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302)
  117. def test_redirect_to_strange_location(self):
  118. "GET a URL that redirects to a non-200 page"
  119. response = self.client.get('/test_client/double_redirect_view/')
  120. # Check that the response was a 302, and that
  121. # the attempt to get the redirection location returned 301 when retrieved
  122. self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', target_status_code=301)
  123. def test_follow_redirect(self):
  124. "A URL that redirects can be followed to termination."
  125. response = self.client.get('/test_client/double_redirect_view/', follow=True)
  126. self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302, target_status_code=200)
  127. self.assertEqual(len(response.redirect_chain), 2)
  128. def test_redirect_http(self):
  129. "GET a URL that redirects to an http URI"
  130. response = self.client.get('/test_client/http_redirect_view/', follow=True)
  131. self.assertFalse(response.test_was_secure_request)
  132. def test_redirect_https(self):
  133. "GET a URL that redirects to an https URI"
  134. response = self.client.get('/test_client/https_redirect_view/', follow=True)
  135. self.assertTrue(response.test_was_secure_request)
  136. def test_notfound_response(self):
  137. "GET a URL that responds as '404:Not Found'"
  138. response = self.client.get('/test_client/bad_view/')
  139. # Check that the response was a 404, and that the content contains MAGIC
  140. self.assertContains(response, 'MAGIC', status_code=404)
  141. def test_valid_form(self):
  142. "POST valid data to a form"
  143. post_data = {
  144. 'text': 'Hello World',
  145. 'email': 'foo@example.com',
  146. 'value': 37,
  147. 'single': 'b',
  148. 'multi': ('b', 'c', 'e')
  149. }
  150. response = self.client.post('/test_client/form_view/', post_data)
  151. self.assertEqual(response.status_code, 200)
  152. self.assertTemplateUsed(response, "Valid POST Template")
  153. def test_valid_form_with_hints(self):
  154. "GET a form, providing hints in the GET data"
  155. hints = {
  156. 'text': 'Hello World',
  157. 'multi': ('b', 'c', 'e')
  158. }
  159. response = self.client.get('/test_client/form_view/', data=hints)
  160. self.assertEqual(response.status_code, 200)
  161. self.assertTemplateUsed(response, "Form GET Template")
  162. # Check that the multi-value data has been rolled out ok
  163. self.assertContains(response, 'Select a valid choice.', 0)
  164. def test_incomplete_data_form(self):
  165. "POST incomplete data to a form"
  166. post_data = {
  167. 'text': 'Hello World',
  168. 'value': 37
  169. }
  170. response = self.client.post('/test_client/form_view/', post_data)
  171. self.assertContains(response, 'This field is required.', 3)
  172. self.assertEqual(response.status_code, 200)
  173. self.assertTemplateUsed(response, "Invalid POST Template")
  174. self.assertFormError(response, 'form', 'email', 'This field is required.')
  175. self.assertFormError(response, 'form', 'single', 'This field is required.')
  176. self.assertFormError(response, 'form', 'multi', 'This field is required.')
  177. def test_form_error(self):
  178. "POST erroneous data to a form"
  179. post_data = {
  180. 'text': 'Hello World',
  181. 'email': 'not an email address',
  182. 'value': 37,
  183. 'single': 'b',
  184. 'multi': ('b', 'c', 'e')
  185. }
  186. response = self.client.post('/test_client/form_view/', post_data)
  187. self.assertEqual(response.status_code, 200)
  188. self.assertTemplateUsed(response, "Invalid POST Template")
  189. self.assertFormError(response, 'form', 'email', 'Enter a valid email address.')
  190. def test_valid_form_with_template(self):
  191. "POST valid data to a form using multiple templates"
  192. post_data = {
  193. 'text': 'Hello World',
  194. 'email': 'foo@example.com',
  195. 'value': 37,
  196. 'single': 'b',
  197. 'multi': ('b', 'c', 'e')
  198. }
  199. response = self.client.post('/test_client/form_view_with_template/', post_data)
  200. self.assertContains(response, 'POST data OK')
  201. self.assertTemplateUsed(response, "form_view.html")
  202. self.assertTemplateUsed(response, 'base.html')
  203. self.assertTemplateNotUsed(response, "Valid POST Template")
  204. def test_incomplete_data_form_with_template(self):
  205. "POST incomplete data to a form using multiple templates"
  206. post_data = {
  207. 'text': 'Hello World',
  208. 'value': 37
  209. }
  210. response = self.client.post('/test_client/form_view_with_template/', post_data)
  211. self.assertContains(response, 'POST data has errors')
  212. self.assertTemplateUsed(response, 'form_view.html')
  213. self.assertTemplateUsed(response, 'base.html')
  214. self.assertTemplateNotUsed(response, "Invalid POST Template")
  215. self.assertFormError(response, 'form', 'email', 'This field is required.')
  216. self.assertFormError(response, 'form', 'single', 'This field is required.')
  217. self.assertFormError(response, 'form', 'multi', 'This field is required.')
  218. def test_form_error_with_template(self):
  219. "POST erroneous data to a form using multiple templates"
  220. post_data = {
  221. 'text': 'Hello World',
  222. 'email': 'not an email address',
  223. 'value': 37,
  224. 'single': 'b',
  225. 'multi': ('b', 'c', 'e')
  226. }
  227. response = self.client.post('/test_client/form_view_with_template/', post_data)
  228. self.assertContains(response, 'POST data has errors')
  229. self.assertTemplateUsed(response, "form_view.html")
  230. self.assertTemplateUsed(response, 'base.html')
  231. self.assertTemplateNotUsed(response, "Invalid POST Template")
  232. self.assertFormError(response, 'form', 'email', 'Enter a valid email address.')
  233. def test_unknown_page(self):
  234. "GET an invalid URL"
  235. response = self.client.get('/test_client/unknown_view/')
  236. # Check that the response was a 404
  237. self.assertEqual(response.status_code, 404)
  238. def test_url_parameters(self):
  239. "Make sure that URL ;-parameters are not stripped."
  240. response = self.client.get('/test_client/unknown_view/;some-parameter')
  241. # Check that the path in the response includes it (ignore that it's a 404)
  242. self.assertEqual(response.request['PATH_INFO'], '/test_client/unknown_view/;some-parameter')
  243. def test_view_with_login(self):
  244. "Request a page that is protected with @login_required"
  245. # Get the page without logging in. Should result in 302.
  246. response = self.client.get('/test_client/login_protected_view/')
  247. self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/')
  248. # Log in
  249. login = self.client.login(username='testclient', password='password')
  250. self.assertTrue(login, 'Could not log in')
  251. # Request a page that requires a login
  252. response = self.client.get('/test_client/login_protected_view/')
  253. self.assertEqual(response.status_code, 200)
  254. self.assertEqual(response.context['user'].username, 'testclient')
  255. def test_view_with_method_login(self):
  256. "Request a page that is protected with a @login_required method"
  257. # Get the page without logging in. Should result in 302.
  258. response = self.client.get('/test_client/login_protected_method_view/')
  259. self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_method_view/')
  260. # Log in
  261. login = self.client.login(username='testclient', password='password')
  262. self.assertTrue(login, 'Could not log in')
  263. # Request a page that requires a login
  264. response = self.client.get('/test_client/login_protected_method_view/')
  265. self.assertEqual(response.status_code, 200)
  266. self.assertEqual(response.context['user'].username, 'testclient')
  267. def test_view_with_login_and_custom_redirect(self):
  268. "Request a page that is protected with @login_required(redirect_field_name='redirect_to')"
  269. # Get the page without logging in. Should result in 302.
  270. response = self.client.get('/test_client/login_protected_view_custom_redirect/')
  271. self.assertRedirects(response, 'http://testserver/accounts/login/?redirect_to=/test_client/login_protected_view_custom_redirect/')
  272. # Log in
  273. login = self.client.login(username='testclient', password='password')
  274. self.assertTrue(login, 'Could not log in')
  275. # Request a page that requires a login
  276. response = self.client.get('/test_client/login_protected_view_custom_redirect/')
  277. self.assertEqual(response.status_code, 200)
  278. self.assertEqual(response.context['user'].username, 'testclient')
  279. def test_view_with_bad_login(self):
  280. "Request a page that is protected with @login, but use bad credentials"
  281. login = self.client.login(username='otheruser', password='nopassword')
  282. self.assertFalse(login)
  283. def test_view_with_inactive_login(self):
  284. "Request a page that is protected with @login, but use an inactive login"
  285. login = self.client.login(username='inactive', password='password')
  286. self.assertFalse(login)
  287. def test_logout(self):
  288. "Request a logout after logging in"
  289. # Log in
  290. self.client.login(username='testclient', password='password')
  291. # Request a page that requires a login
  292. response = self.client.get('/test_client/login_protected_view/')
  293. self.assertEqual(response.status_code, 200)
  294. self.assertEqual(response.context['user'].username, 'testclient')
  295. # Log out
  296. self.client.logout()
  297. # Request a page that requires a login
  298. response = self.client.get('/test_client/login_protected_view/')
  299. self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/')
  300. def test_view_with_permissions(self):
  301. "Request a page that is protected with @permission_required"
  302. # Get the page without logging in. Should result in 302.
  303. response = self.client.get('/test_client/permission_protected_view/')
  304. self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/')
  305. # Log in
  306. login = self.client.login(username='testclient', password='password')
  307. self.assertTrue(login, 'Could not log in')
  308. # Log in with wrong permissions. Should result in 302.
  309. response = self.client.get('/test_client/permission_protected_view/')
  310. self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/')
  311. # TODO: Log in with right permissions and request the page again
  312. def test_view_with_permissions_exception(self):
  313. "Request a page that is protected with @permission_required but raises a exception"
  314. # Get the page without logging in. Should result in 403.
  315. response = self.client.get('/test_client/permission_protected_view_exception/')
  316. self.assertEqual(response.status_code, 403)
  317. # Log in
  318. login = self.client.login(username='testclient', password='password')
  319. self.assertTrue(login, 'Could not log in')
  320. # Log in with wrong permissions. Should result in 403.
  321. response = self.client.get('/test_client/permission_protected_view_exception/')
  322. self.assertEqual(response.status_code, 403)
  323. def test_view_with_method_permissions(self):
  324. "Request a page that is protected with a @permission_required method"
  325. # Get the page without logging in. Should result in 302.
  326. response = self.client.get('/test_client/permission_protected_method_view/')
  327. self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/')
  328. # Log in
  329. login = self.client.login(username='testclient', password='password')
  330. self.assertTrue(login, 'Could not log in')
  331. # Log in with wrong permissions. Should result in 302.
  332. response = self.client.get('/test_client/permission_protected_method_view/')
  333. self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/')
  334. # TODO: Log in with right permissions and request the page again
  335. def test_external_redirect(self):
  336. response = self.client.get('/test_client/django_project_redirect/')
  337. self.assertRedirects(response, 'https://www.djangoproject.com/', fetch_redirect_response=False)
  338. def test_session_modifying_view(self):
  339. "Request a page that modifies the session"
  340. # Session value isn't set initially
  341. try:
  342. self.client.session['tobacconist']
  343. self.fail("Shouldn't have a session value")
  344. except KeyError:
  345. pass
  346. from django.contrib.sessions.models import Session
  347. self.client.post('/test_client/session_view/')
  348. # Check that the session was modified
  349. self.assertEqual(self.client.session['tobacconist'], 'hovercraft')
  350. def test_view_with_exception(self):
  351. "Request a page that is known to throw an error"
  352. self.assertRaises(KeyError, self.client.get, "/test_client/broken_view/")
  353. #Try the same assertion, a different way
  354. try:
  355. self.client.get('/test_client/broken_view/')
  356. self.fail('Should raise an error')
  357. except KeyError:
  358. pass
  359. def test_mail_sending(self):
  360. "Test that mail is redirected to a dummy outbox during test setup"
  361. response = self.client.get('/test_client/mail_sending_view/')
  362. self.assertEqual(response.status_code, 200)
  363. self.assertEqual(len(mail.outbox), 1)
  364. self.assertEqual(mail.outbox[0].subject, 'Test message')
  365. self.assertEqual(mail.outbox[0].body, 'This is a test email')
  366. self.assertEqual(mail.outbox[0].from_email, 'from@example.com')
  367. self.assertEqual(mail.outbox[0].to[0], 'first@example.com')
  368. self.assertEqual(mail.outbox[0].to[1], 'second@example.com')
  369. def test_mass_mail_sending(self):
  370. "Test that mass mail is redirected to a dummy outbox during test setup"
  371. response = self.client.get('/test_client/mass_mail_sending_view/')
  372. self.assertEqual(response.status_code, 200)
  373. self.assertEqual(len(mail.outbox), 2)
  374. self.assertEqual(mail.outbox[0].subject, 'First Test message')
  375. self.assertEqual(mail.outbox[0].body, 'This is the first test email')
  376. self.assertEqual(mail.outbox[0].from_email, 'from@example.com')
  377. self.assertEqual(mail.outbox[0].to[0], 'first@example.com')
  378. self.assertEqual(mail.outbox[0].to[1], 'second@example.com')
  379. self.assertEqual(mail.outbox[1].subject, 'Second Test message')
  380. self.assertEqual(mail.outbox[1].body, 'This is the second test email')
  381. self.assertEqual(mail.outbox[1].from_email, 'from@example.com')
  382. self.assertEqual(mail.outbox[1].to[0], 'second@example.com')
  383. self.assertEqual(mail.outbox[1].to[1], 'third@example.com')
  384. @override_settings(
  385. MIDDLEWARE_CLASSES = ('django.middleware.csrf.CsrfViewMiddleware',)
  386. )
  387. class CSRFEnabledClientTests(TestCase):
  388. def test_csrf_enabled_client(self):
  389. "A client can be instantiated with CSRF checks enabled"
  390. csrf_client = Client(enforce_csrf_checks=True)
  391. # The normal client allows the post
  392. response = self.client.post('/test_client/post_view/', {})
  393. self.assertEqual(response.status_code, 200)
  394. # The CSRF-enabled client rejects it
  395. response = csrf_client.post('/test_client/post_view/', {})
  396. self.assertEqual(response.status_code, 403)
  397. class CustomTestClient(Client):
  398. i_am_customized = "Yes"
  399. class CustomTestClientTest(TestCase):
  400. client_class = CustomTestClient
  401. def test_custom_test_client(self):
  402. """A test case can specify a custom class for self.client."""
  403. self.assertEqual(hasattr(self.client, "i_am_customized"), True)
  404. class RequestFactoryTest(TestCase):
  405. def test_request_factory(self):
  406. factory = RequestFactory()
  407. request = factory.get('/somewhere/')
  408. response = get_view(request)
  409. self.assertEqual(response.status_code, 200)
  410. self.assertContains(response, 'This is a test')