2
0

tests.py 26 KB

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