test_liveserverthread.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from django.db import DEFAULT_DB_ALIAS, connections
  2. from django.test import LiveServerTestCase, TransactionTestCase
  3. from django.test.testcases import LiveServerThread
  4. # Use TransactionTestCase instead of TestCase to run outside of a transaction,
  5. # otherwise closing the connection would implicitly rollback and not set the
  6. # connection to None.
  7. class LiveServerThreadTest(TransactionTestCase):
  8. available_apps = []
  9. def run_live_server_thread(self, connections_override=None):
  10. thread = LiveServerTestCase._create_server_thread(connections_override)
  11. thread.daemon = True
  12. thread.start()
  13. thread.is_ready.wait()
  14. thread.terminate()
  15. def test_closes_connections(self):
  16. conn = connections[DEFAULT_DB_ALIAS]
  17. # Pass a connection to the thread to check they are being closed.
  18. connections_override = {DEFAULT_DB_ALIAS: conn}
  19. # Open a connection to the database.
  20. conn.connect()
  21. conn.inc_thread_sharing()
  22. try:
  23. self.assertIsNotNone(conn.connection)
  24. self.run_live_server_thread(connections_override)
  25. self.assertIsNone(conn.connection)
  26. finally:
  27. conn.dec_thread_sharing()
  28. def test_server_class(self):
  29. class FakeServer:
  30. def __init__(*args, **kwargs):
  31. pass
  32. class MyServerThread(LiveServerThread):
  33. server_class = FakeServer
  34. class MyServerTestCase(LiveServerTestCase):
  35. server_thread_class = MyServerThread
  36. thread = MyServerTestCase._create_server_thread(None)
  37. server = thread._create_server()
  38. self.assertIs(type(server), FakeServer)