2016-08-20 00:47:41 +08:00
|
|
|
from django.db import DEFAULT_DB_ALIAS, connections
|
2021-02-21 11:23:56 +08:00
|
|
|
from django.test import LiveServerTestCase, TransactionTestCase
|
2021-02-12 10:32:09 +08:00
|
|
|
from django.test.testcases import LiveServerThread
|
2016-08-20 00:47:41 +08:00
|
|
|
|
|
|
|
|
2021-02-21 11:23:56 +08:00
|
|
|
# Use TransactionTestCase instead of TestCase to run outside of a transaction,
|
|
|
|
# otherwise closing the connection would implicitly rollback and not set the
|
|
|
|
# connection to None.
|
|
|
|
class LiveServerThreadTest(TransactionTestCase):
|
|
|
|
|
|
|
|
available_apps = []
|
2016-08-20 00:47:41 +08:00
|
|
|
|
|
|
|
def run_live_server_thread(self, connections_override=None):
|
|
|
|
thread = LiveServerTestCase._create_server_thread(connections_override)
|
|
|
|
thread.daemon = True
|
|
|
|
thread.start()
|
|
|
|
thread.is_ready.wait()
|
|
|
|
thread.terminate()
|
|
|
|
|
|
|
|
def test_closes_connections(self):
|
|
|
|
conn = connections[DEFAULT_DB_ALIAS]
|
|
|
|
# Pass a connection to the thread to check they are being closed.
|
|
|
|
connections_override = {DEFAULT_DB_ALIAS: conn}
|
2021-02-21 11:23:56 +08:00
|
|
|
# Open a connection to the database.
|
|
|
|
conn.connect()
|
2019-02-14 23:04:55 +08:00
|
|
|
conn.inc_thread_sharing()
|
2016-08-20 00:47:41 +08:00
|
|
|
try:
|
2021-02-21 11:23:56 +08:00
|
|
|
self.assertIsNotNone(conn.connection)
|
2016-08-20 00:47:41 +08:00
|
|
|
self.run_live_server_thread(connections_override)
|
2021-02-21 11:23:56 +08:00
|
|
|
self.assertIsNone(conn.connection)
|
2016-08-20 00:47:41 +08:00
|
|
|
finally:
|
2019-02-14 23:04:55 +08:00
|
|
|
conn.dec_thread_sharing()
|
2021-02-12 10:32:09 +08:00
|
|
|
|
|
|
|
def test_server_class(self):
|
|
|
|
class FakeServer:
|
|
|
|
def __init__(*args, **kwargs):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class MyServerThread(LiveServerThread):
|
|
|
|
server_class = FakeServer
|
|
|
|
|
|
|
|
class MyServerTestCase(LiveServerTestCase):
|
|
|
|
server_thread_class = MyServerThread
|
|
|
|
|
|
|
|
thread = MyServerTestCase._create_server_thread(None)
|
|
|
|
server = thread._create_server()
|
|
|
|
self.assertIs(type(server), FakeServer)
|