tests.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. """
  2. Tests for django.core.servers.
  3. """
  4. import errno
  5. import os
  6. import socket
  7. import threading
  8. import unittest
  9. from http.client import HTTPConnection
  10. from urllib.error import HTTPError
  11. from urllib.parse import urlencode
  12. from urllib.request import urlopen
  13. from django.conf import settings
  14. from django.core.servers.basehttp import ThreadedWSGIServer, WSGIServer
  15. from django.db import DEFAULT_DB_ALIAS, connection, connections
  16. from django.test import LiveServerTestCase, override_settings
  17. from django.test.testcases import LiveServerThread, QuietWSGIRequestHandler
  18. from .models import Person
  19. TEST_ROOT = os.path.dirname(__file__)
  20. TEST_SETTINGS = {
  21. "MEDIA_URL": "media/",
  22. "MEDIA_ROOT": os.path.join(TEST_ROOT, "media"),
  23. "STATIC_URL": "static/",
  24. "STATIC_ROOT": os.path.join(TEST_ROOT, "static"),
  25. }
  26. @override_settings(ROOT_URLCONF="servers.urls", **TEST_SETTINGS)
  27. class LiveServerBase(LiveServerTestCase):
  28. available_apps = [
  29. "servers",
  30. "django.contrib.auth",
  31. "django.contrib.contenttypes",
  32. "django.contrib.sessions",
  33. ]
  34. fixtures = ["testdata.json"]
  35. def urlopen(self, url):
  36. return urlopen(self.live_server_url + url)
  37. class CloseConnectionTestServer(ThreadedWSGIServer):
  38. def __init__(self, *args, **kwargs):
  39. super().__init__(*args, **kwargs)
  40. # This event is set right after the first time a request closes its
  41. # database connections.
  42. self._connections_closed = threading.Event()
  43. def _close_connections(self):
  44. super()._close_connections()
  45. self._connections_closed.set()
  46. class CloseConnectionTestLiveServerThread(LiveServerThread):
  47. server_class = CloseConnectionTestServer
  48. def _create_server(self, connections_override=None):
  49. return super()._create_server(connections_override=self.connections_override)
  50. class LiveServerTestCloseConnectionTest(LiveServerBase):
  51. server_thread_class = CloseConnectionTestLiveServerThread
  52. @classmethod
  53. def _make_connections_override(cls):
  54. conn = connections[DEFAULT_DB_ALIAS]
  55. cls.conn = conn
  56. cls.old_conn_max_age = conn.settings_dict["CONN_MAX_AGE"]
  57. # Set the connection's CONN_MAX_AGE to None to simulate the
  58. # CONN_MAX_AGE setting being set to None on the server. This prevents
  59. # Django from closing the connection and allows testing that
  60. # ThreadedWSGIServer closes connections.
  61. conn.settings_dict["CONN_MAX_AGE"] = None
  62. # Pass a database connection through to the server to check it is being
  63. # closed by ThreadedWSGIServer.
  64. return {DEFAULT_DB_ALIAS: conn}
  65. @classmethod
  66. def tearDownConnectionTest(cls):
  67. cls.conn.settings_dict["CONN_MAX_AGE"] = cls.old_conn_max_age
  68. @classmethod
  69. def tearDownClass(cls):
  70. cls.tearDownConnectionTest()
  71. super().tearDownClass()
  72. def test_closes_connections(self):
  73. # The server's request thread sets this event after closing
  74. # its database connections.
  75. closed_event = self.server_thread.httpd._connections_closed
  76. conn = self.conn
  77. # Open a connection to the database.
  78. conn.connect()
  79. self.assertIsNotNone(conn.connection)
  80. with self.urlopen("/model_view/") as f:
  81. # The server can access the database.
  82. self.assertCountEqual(f.read().splitlines(), [b"jane", b"robert"])
  83. # Wait for the server's request thread to close the connection.
  84. # A timeout of 0.1 seconds should be more than enough. If the wait
  85. # times out, the assertion after should fail.
  86. closed_event.wait(timeout=0.1)
  87. self.assertIsNone(conn.connection)
  88. @unittest.skipUnless(connection.vendor == "sqlite", "SQLite specific test.")
  89. class LiveServerInMemoryDatabaseLockTest(LiveServerBase):
  90. def test_in_memory_database_lock(self):
  91. """
  92. With a threaded LiveServer and an in-memory database, an error can
  93. occur when 2 requests reach the server and try to lock the database
  94. at the same time, if the requests do not share the same database
  95. connection.
  96. """
  97. conn = self.server_thread.connections_override[DEFAULT_DB_ALIAS]
  98. # Open a connection to the database.
  99. conn.connect()
  100. # Create a transaction to lock the database.
  101. cursor = conn.cursor()
  102. cursor.execute("BEGIN IMMEDIATE TRANSACTION")
  103. try:
  104. with self.urlopen("/create_model_instance/") as f:
  105. self.assertEqual(f.status, 200)
  106. except HTTPError:
  107. self.fail("Unexpected error due to a database lock.")
  108. finally:
  109. # Release the transaction.
  110. cursor.execute("ROLLBACK")
  111. class FailingLiveServerThread(LiveServerThread):
  112. def _create_server(self, connections_override=None):
  113. raise RuntimeError("Error creating server.")
  114. class LiveServerTestCaseSetupTest(LiveServerBase):
  115. server_thread_class = FailingLiveServerThread
  116. @classmethod
  117. def check_allowed_hosts(cls, expected):
  118. if settings.ALLOWED_HOSTS != expected:
  119. raise RuntimeError(f"{settings.ALLOWED_HOSTS} != {expected}")
  120. @classmethod
  121. def setUpClass(cls):
  122. cls.check_allowed_hosts(["testserver"])
  123. try:
  124. super().setUpClass()
  125. except RuntimeError:
  126. # LiveServerTestCase's change to ALLOWED_HOSTS should be reverted.
  127. cls.doClassCleanups()
  128. cls.check_allowed_hosts(["testserver"])
  129. else:
  130. raise RuntimeError("Server did not fail.")
  131. cls.set_up_called = True
  132. def test_set_up_class(self):
  133. self.assertIs(self.set_up_called, True)
  134. class LiveServerAddress(LiveServerBase):
  135. @classmethod
  136. def setUpClass(cls):
  137. super().setUpClass()
  138. # put it in a list to prevent descriptor lookups in test
  139. cls.live_server_url_test = [cls.live_server_url]
  140. def test_live_server_url_is_class_property(self):
  141. self.assertIsInstance(self.live_server_url_test[0], str)
  142. self.assertEqual(self.live_server_url_test[0], self.live_server_url)
  143. class LiveServerSingleThread(LiveServerThread):
  144. def _create_server(self, connections_override=None):
  145. return WSGIServer(
  146. (self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False
  147. )
  148. class SingleThreadLiveServerTestCase(LiveServerTestCase):
  149. server_thread_class = LiveServerSingleThread
  150. class LiveServerViews(LiveServerBase):
  151. def test_protocol(self):
  152. """Launched server serves with HTTP 1.1."""
  153. with self.urlopen("/example_view/") as f:
  154. self.assertEqual(f.version, 11)
  155. def test_closes_connection_without_content_length(self):
  156. """
  157. An HTTP 1.1 server is supposed to support keep-alive. Since our
  158. development server is rather simple we support it only in cases where
  159. we can detect a content length from the response. This should be doable
  160. for all simple views and streaming responses where an iterable with
  161. length of one is passed. The latter follows as result of `set_content_length`
  162. from https://github.com/python/cpython/blob/main/Lib/wsgiref/handlers.py.
  163. If we cannot detect a content length we explicitly set the `Connection`
  164. header to `close` to notify the client that we do not actually support
  165. it.
  166. """
  167. conn = HTTPConnection(
  168. LiveServerViews.server_thread.host,
  169. LiveServerViews.server_thread.port,
  170. timeout=1,
  171. )
  172. try:
  173. conn.request(
  174. "GET", "/streaming_example_view/", headers={"Connection": "keep-alive"}
  175. )
  176. response = conn.getresponse()
  177. self.assertTrue(response.will_close)
  178. self.assertEqual(response.read(), b"Iamastream")
  179. self.assertEqual(response.status, 200)
  180. self.assertEqual(response.getheader("Connection"), "close")
  181. conn.request(
  182. "GET", "/streaming_example_view/", headers={"Connection": "close"}
  183. )
  184. response = conn.getresponse()
  185. self.assertTrue(response.will_close)
  186. self.assertEqual(response.read(), b"Iamastream")
  187. self.assertEqual(response.status, 200)
  188. self.assertEqual(response.getheader("Connection"), "close")
  189. finally:
  190. conn.close()
  191. def test_keep_alive_on_connection_with_content_length(self):
  192. """
  193. See `test_closes_connection_without_content_length` for details. This
  194. is a follow up test, which ensure that we do not close the connection
  195. if not needed, hence allowing us to take advantage of keep-alive.
  196. """
  197. conn = HTTPConnection(
  198. LiveServerViews.server_thread.host, LiveServerViews.server_thread.port
  199. )
  200. try:
  201. conn.request("GET", "/example_view/", headers={"Connection": "keep-alive"})
  202. response = conn.getresponse()
  203. self.assertFalse(response.will_close)
  204. self.assertEqual(response.read(), b"example view")
  205. self.assertEqual(response.status, 200)
  206. self.assertIsNone(response.getheader("Connection"))
  207. conn.request("GET", "/example_view/", headers={"Connection": "close"})
  208. response = conn.getresponse()
  209. self.assertFalse(response.will_close)
  210. self.assertEqual(response.read(), b"example view")
  211. self.assertEqual(response.status, 200)
  212. self.assertIsNone(response.getheader("Connection"))
  213. finally:
  214. conn.close()
  215. def test_keep_alive_connection_clears_previous_request_data(self):
  216. conn = HTTPConnection(
  217. LiveServerViews.server_thread.host, LiveServerViews.server_thread.port
  218. )
  219. try:
  220. conn.request(
  221. "POST", "/method_view/", b"{}", headers={"Connection": "keep-alive"}
  222. )
  223. response = conn.getresponse()
  224. self.assertFalse(response.will_close)
  225. self.assertEqual(response.status, 200)
  226. self.assertEqual(response.read(), b"POST")
  227. conn.request(
  228. "POST", "/method_view/", b"{}", headers={"Connection": "close"}
  229. )
  230. response = conn.getresponse()
  231. self.assertFalse(response.will_close)
  232. self.assertEqual(response.status, 200)
  233. self.assertEqual(response.read(), b"POST")
  234. finally:
  235. conn.close()
  236. def test_404(self):
  237. with self.assertRaises(HTTPError) as err:
  238. self.urlopen("/")
  239. err.exception.close()
  240. self.assertEqual(err.exception.code, 404, "Expected 404 response")
  241. def test_view(self):
  242. with self.urlopen("/example_view/") as f:
  243. self.assertEqual(f.read(), b"example view")
  244. def test_static_files(self):
  245. with self.urlopen("/static/example_static_file.txt") as f:
  246. self.assertEqual(f.read().rstrip(b"\r\n"), b"example static file")
  247. def test_no_collectstatic_emulation(self):
  248. """
  249. LiveServerTestCase reports a 404 status code when HTTP client
  250. tries to access a static file that isn't explicitly put under
  251. STATIC_ROOT.
  252. """
  253. with self.assertRaises(HTTPError) as err:
  254. self.urlopen("/static/another_app/another_app_static_file.txt")
  255. err.exception.close()
  256. self.assertEqual(err.exception.code, 404, "Expected 404 response")
  257. def test_media_files(self):
  258. with self.urlopen("/media/example_media_file.txt") as f:
  259. self.assertEqual(f.read().rstrip(b"\r\n"), b"example media file")
  260. def test_environ(self):
  261. with self.urlopen("/environ_view/?%s" % urlencode({"q": "тест"})) as f:
  262. self.assertIn(b"QUERY_STRING: 'q=%D1%82%D0%B5%D1%81%D1%82'", f.read())
  263. @override_settings(ROOT_URLCONF="servers.urls")
  264. class SingleThreadLiveServerViews(SingleThreadLiveServerTestCase):
  265. available_apps = ["servers"]
  266. def test_closes_connection_with_content_length(self):
  267. """
  268. Contrast to
  269. LiveServerViews.test_keep_alive_on_connection_with_content_length().
  270. Persistent connections require threading server.
  271. """
  272. conn = HTTPConnection(
  273. SingleThreadLiveServerViews.server_thread.host,
  274. SingleThreadLiveServerViews.server_thread.port,
  275. timeout=1,
  276. )
  277. try:
  278. conn.request("GET", "/example_view/", headers={"Connection": "keep-alive"})
  279. response = conn.getresponse()
  280. self.assertTrue(response.will_close)
  281. self.assertEqual(response.read(), b"example view")
  282. self.assertEqual(response.status, 200)
  283. self.assertEqual(response.getheader("Connection"), "close")
  284. finally:
  285. conn.close()
  286. class LiveServerDatabase(LiveServerBase):
  287. def test_fixtures_loaded(self):
  288. """
  289. Fixtures are properly loaded and visible to the live server thread.
  290. """
  291. with self.urlopen("/model_view/") as f:
  292. self.assertCountEqual(f.read().splitlines(), [b"jane", b"robert"])
  293. def test_database_writes(self):
  294. """
  295. Data written to the database by a view can be read.
  296. """
  297. with self.urlopen("/create_model_instance/"):
  298. pass
  299. self.assertQuerySetEqual(
  300. Person.objects.order_by("pk"),
  301. ["jane", "robert", "emily"],
  302. lambda b: b.name,
  303. )
  304. class LiveServerPort(LiveServerBase):
  305. def test_port_bind(self):
  306. """
  307. Each LiveServerTestCase binds to a unique port or fails to start a
  308. server thread when run concurrently (#26011).
  309. """
  310. TestCase = type("TestCase", (LiveServerBase,), {})
  311. try:
  312. TestCase._start_server_thread()
  313. except OSError as e:
  314. if e.errno == errno.EADDRINUSE:
  315. # We're out of ports, LiveServerTestCase correctly fails with
  316. # an OSError.
  317. return
  318. # Unexpected error.
  319. raise
  320. try:
  321. self.assertNotEqual(
  322. self.live_server_url,
  323. TestCase.live_server_url,
  324. f"Acquired duplicate server addresses for server threads: "
  325. f"{self.live_server_url}",
  326. )
  327. finally:
  328. TestCase.doClassCleanups()
  329. def test_specified_port_bind(self):
  330. """LiveServerTestCase.port customizes the server's port."""
  331. TestCase = type("TestCase", (LiveServerBase,), {})
  332. # Find an open port and tell TestCase to use it.
  333. s = socket.socket()
  334. s.bind(("", 0))
  335. TestCase.port = s.getsockname()[1]
  336. s.close()
  337. TestCase._start_server_thread()
  338. try:
  339. self.assertEqual(
  340. TestCase.port,
  341. TestCase.server_thread.port,
  342. f"Did not use specified port for LiveServerTestCase thread: "
  343. f"{TestCase.port}",
  344. )
  345. finally:
  346. TestCase.doClassCleanups()
  347. class LiveServerThreadedTests(LiveServerBase):
  348. """If LiveServerTestCase isn't threaded, these tests will hang."""
  349. def test_view_calls_subview(self):
  350. url = "/subview_calling_view/?%s" % urlencode({"url": self.live_server_url})
  351. with self.urlopen(url) as f:
  352. self.assertEqual(f.read(), b"subview calling view: subview")
  353. def test_check_model_instance_from_subview(self):
  354. url = "/check_model_instance_from_subview/?%s" % urlencode(
  355. {
  356. "url": self.live_server_url,
  357. }
  358. )
  359. with self.urlopen(url) as f:
  360. self.assertIn(b"emily", f.read())