tests.py 8.6 KB

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