tests.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """
  2. Tests for django.core.servers.
  3. """
  4. import errno
  5. import os
  6. import socket
  7. from http.client import HTTPConnection
  8. from urllib.error import HTTPError
  9. from urllib.parse import urlencode
  10. from urllib.request import urlopen
  11. from django.core.servers.basehttp import WSGIServer
  12. from django.test import LiveServerTestCase, override_settings
  13. from django.test.testcases import LiveServerThread, QuietWSGIRequestHandler
  14. from .models import Person
  15. TEST_ROOT = os.path.dirname(__file__)
  16. TEST_SETTINGS = {
  17. 'MEDIA_URL': 'media/',
  18. 'MEDIA_ROOT': os.path.join(TEST_ROOT, 'media'),
  19. 'STATIC_URL': 'static/',
  20. 'STATIC_ROOT': os.path.join(TEST_ROOT, 'static'),
  21. }
  22. @override_settings(ROOT_URLCONF='servers.urls', **TEST_SETTINGS)
  23. class LiveServerBase(LiveServerTestCase):
  24. available_apps = [
  25. 'servers',
  26. 'django.contrib.auth',
  27. 'django.contrib.contenttypes',
  28. 'django.contrib.sessions',
  29. ]
  30. fixtures = ['testdata.json']
  31. def urlopen(self, url):
  32. return urlopen(self.live_server_url + url)
  33. class LiveServerAddress(LiveServerBase):
  34. @classmethod
  35. def setUpClass(cls):
  36. super().setUpClass()
  37. # put it in a list to prevent descriptor lookups in test
  38. cls.live_server_url_test = [cls.live_server_url]
  39. def test_live_server_url_is_class_property(self):
  40. self.assertIsInstance(self.live_server_url_test[0], str)
  41. self.assertEqual(self.live_server_url_test[0], self.live_server_url)
  42. class LiveServerSingleThread(LiveServerThread):
  43. def _create_server(self):
  44. return WSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False)
  45. class SingleThreadLiveServerTestCase(LiveServerTestCase):
  46. server_thread_class = LiveServerSingleThread
  47. class LiveServerViews(LiveServerBase):
  48. def test_protocol(self):
  49. """Launched server serves with HTTP 1.1."""
  50. with self.urlopen('/example_view/') as f:
  51. self.assertEqual(f.version, 11)
  52. def test_closes_connection_without_content_length(self):
  53. """
  54. A HTTP 1.1 server is supposed to support keep-alive. Since our
  55. development server is rather simple we support it only in cases where
  56. we can detect a content length from the response. This should be doable
  57. for all simple views and streaming responses where an iterable with
  58. length of one is passed. The latter follows as result of `set_content_length`
  59. from https://github.com/python/cpython/blob/master/Lib/wsgiref/handlers.py.
  60. If we cannot detect a content length we explicitly set the `Connection`
  61. header to `close` to notify the client that we do not actually support
  62. it.
  63. """
  64. conn = HTTPConnection(LiveServerViews.server_thread.host, LiveServerViews.server_thread.port, timeout=1)
  65. try:
  66. conn.request('GET', '/streaming_example_view/', headers={'Connection': 'keep-alive'})
  67. response = conn.getresponse()
  68. self.assertTrue(response.will_close)
  69. self.assertEqual(response.read(), b'Iamastream')
  70. self.assertEqual(response.status, 200)
  71. self.assertEqual(response.getheader('Connection'), 'close')
  72. conn.request('GET', '/streaming_example_view/', headers={'Connection': 'close'})
  73. response = conn.getresponse()
  74. self.assertTrue(response.will_close)
  75. self.assertEqual(response.read(), b'Iamastream')
  76. self.assertEqual(response.status, 200)
  77. self.assertEqual(response.getheader('Connection'), 'close')
  78. finally:
  79. conn.close()
  80. def test_keep_alive_on_connection_with_content_length(self):
  81. """
  82. See `test_closes_connection_without_content_length` for details. This
  83. is a follow up test, which ensure that we do not close the connection
  84. if not needed, hence allowing us to take advantage of keep-alive.
  85. """
  86. conn = HTTPConnection(LiveServerViews.server_thread.host, LiveServerViews.server_thread.port)
  87. try:
  88. conn.request('GET', '/example_view/', headers={"Connection": "keep-alive"})
  89. response = conn.getresponse()
  90. self.assertFalse(response.will_close)
  91. self.assertEqual(response.read(), b'example view')
  92. self.assertEqual(response.status, 200)
  93. self.assertIsNone(response.getheader('Connection'))
  94. conn.request('GET', '/example_view/', headers={"Connection": "close"})
  95. response = conn.getresponse()
  96. self.assertFalse(response.will_close)
  97. self.assertEqual(response.read(), b'example view')
  98. self.assertEqual(response.status, 200)
  99. self.assertIsNone(response.getheader('Connection'))
  100. finally:
  101. conn.close()
  102. def test_keep_alive_connection_clears_previous_request_data(self):
  103. conn = HTTPConnection(LiveServerViews.server_thread.host, LiveServerViews.server_thread.port)
  104. try:
  105. conn.request('POST', '/method_view/', b'{}', headers={"Connection": "keep-alive"})
  106. response = conn.getresponse()
  107. self.assertFalse(response.will_close)
  108. self.assertEqual(response.status, 200)
  109. self.assertEqual(response.read(), b'POST')
  110. conn.request('POST', '/method_view/', b'{}', headers={"Connection": "close"})
  111. response = conn.getresponse()
  112. self.assertFalse(response.will_close)
  113. self.assertEqual(response.status, 200)
  114. self.assertEqual(response.read(), b'POST')
  115. finally:
  116. conn.close()
  117. def test_404(self):
  118. with self.assertRaises(HTTPError) as err:
  119. self.urlopen('/')
  120. err.exception.close()
  121. self.assertEqual(err.exception.code, 404, 'Expected 404 response')
  122. def test_view(self):
  123. with self.urlopen('/example_view/') as f:
  124. self.assertEqual(f.read(), b'example view')
  125. def test_static_files(self):
  126. with self.urlopen('/static/example_static_file.txt') as f:
  127. self.assertEqual(f.read().rstrip(b'\r\n'), b'example static file')
  128. def test_no_collectstatic_emulation(self):
  129. """
  130. LiveServerTestCase reports a 404 status code when HTTP client
  131. tries to access a static file that isn't explicitly put under
  132. STATIC_ROOT.
  133. """
  134. with self.assertRaises(HTTPError) as err:
  135. self.urlopen('/static/another_app/another_app_static_file.txt')
  136. err.exception.close()
  137. self.assertEqual(err.exception.code, 404, 'Expected 404 response')
  138. def test_media_files(self):
  139. with self.urlopen('/media/example_media_file.txt') as f:
  140. self.assertEqual(f.read().rstrip(b'\r\n'), b'example media file')
  141. def test_environ(self):
  142. with self.urlopen('/environ_view/?%s' % urlencode({'q': 'тест'})) as f:
  143. self.assertIn(b"QUERY_STRING: 'q=%D1%82%D0%B5%D1%81%D1%82'", f.read())
  144. @override_settings(ROOT_URLCONF='servers.urls')
  145. class SingleTreadLiveServerViews(SingleThreadLiveServerTestCase):
  146. available_apps = ['servers']
  147. def test_closes_connection_with_content_length(self):
  148. """
  149. Contrast to
  150. LiveServerViews.test_keep_alive_on_connection_with_content_length().
  151. Persistent connections require threading server.
  152. """
  153. conn = HTTPConnection(
  154. SingleTreadLiveServerViews.server_thread.host,
  155. SingleTreadLiveServerViews.server_thread.port,
  156. timeout=1,
  157. )
  158. try:
  159. conn.request('GET', '/example_view/', headers={'Connection': 'keep-alive'})
  160. response = conn.getresponse()
  161. self.assertTrue(response.will_close)
  162. self.assertEqual(response.read(), b'example view')
  163. self.assertEqual(response.status, 200)
  164. self.assertEqual(response.getheader('Connection'), 'close')
  165. finally:
  166. conn.close()
  167. class LiveServerDatabase(LiveServerBase):
  168. def test_fixtures_loaded(self):
  169. """
  170. Fixtures are properly loaded and visible to the live server thread.
  171. """
  172. with self.urlopen('/model_view/') as f:
  173. self.assertEqual(f.read().splitlines(), [b'jane', b'robert'])
  174. def test_database_writes(self):
  175. """
  176. Data written to the database by a view can be read.
  177. """
  178. with self.urlopen('/create_model_instance/'):
  179. pass
  180. self.assertQuerysetEqual(
  181. Person.objects.all().order_by('pk'),
  182. ['jane', 'robert', 'emily'],
  183. lambda b: b.name
  184. )
  185. class LiveServerPort(LiveServerBase):
  186. def test_port_bind(self):
  187. """
  188. Each LiveServerTestCase binds to a unique port or fails to start a
  189. server thread when run concurrently (#26011).
  190. """
  191. TestCase = type("TestCase", (LiveServerBase,), {})
  192. try:
  193. TestCase.setUpClass()
  194. except OSError as e:
  195. if e.errno == errno.EADDRINUSE:
  196. # We're out of ports, LiveServerTestCase correctly fails with
  197. # an OSError.
  198. return
  199. # Unexpected error.
  200. raise
  201. try:
  202. # We've acquired a port, ensure our server threads acquired
  203. # different addresses.
  204. self.assertNotEqual(
  205. self.live_server_url, TestCase.live_server_url,
  206. "Acquired duplicate server addresses for server threads: %s" % self.live_server_url
  207. )
  208. finally:
  209. TestCase.tearDownClass()
  210. def test_specified_port_bind(self):
  211. """LiveServerTestCase.port customizes the server's port."""
  212. TestCase = type('TestCase', (LiveServerBase,), {})
  213. # Find an open port and tell TestCase to use it.
  214. s = socket.socket()
  215. s.bind(('', 0))
  216. TestCase.port = s.getsockname()[1]
  217. s.close()
  218. TestCase.setUpClass()
  219. try:
  220. self.assertEqual(
  221. TestCase.port, TestCase.server_thread.port,
  222. 'Did not use specified port for LiveServerTestCase thread: %s' % TestCase.port
  223. )
  224. finally:
  225. TestCase.tearDownClass()
  226. class LiveServerThreadedTests(LiveServerBase):
  227. """If LiveServerTestCase isn't threaded, these tests will hang."""
  228. def test_view_calls_subview(self):
  229. url = '/subview_calling_view/?%s' % urlencode({'url': self.live_server_url})
  230. with self.urlopen(url) as f:
  231. self.assertEqual(f.read(), b'subview calling view: subview')
  232. def test_check_model_instance_from_subview(self):
  233. url = '/check_model_instance_from_subview/?%s' % urlencode({
  234. 'url': self.live_server_url,
  235. })
  236. with self.urlopen(url) as f:
  237. self.assertIn(b'emily', f.read())