You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

live.py 2.3KB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from django.core.exceptions import ImproperlyConfigured
  2. from django.db import connections
  3. from django.test.testcases import TransactionTestCase
  4. from django.test.utils import modify_settings
  5. from channels.routing import get_default_application
  6. from channels.staticfiles import StaticFilesWrapper
  7. from daphne.testing import DaphneProcess
  8. class ChannelsLiveServerTestCase(TransactionTestCase):
  9. """
  10. Does basically the same as TransactionTestCase but also launches a
  11. live Daphne server in a separate process, so
  12. that the tests may use another test framework, such as Selenium,
  13. instead of the built-in dummy client.
  14. """
  15. host = "localhost"
  16. ProtocolServerProcess = DaphneProcess
  17. static_wrapper = StaticFilesWrapper
  18. serve_static = True
  19. @property
  20. def live_server_url(self):
  21. return "http://%s:%s" % (self.host, self._port)
  22. @property
  23. def live_server_ws_url(self):
  24. return "ws://%s:%s" % (self.host, self._port)
  25. def _pre_setup(self):
  26. for connection in connections.all():
  27. if self._is_in_memory_db(connection):
  28. raise ImproperlyConfigured(
  29. "ChannelLiveServerTestCase can not be used with in memory databases"
  30. )
  31. super(ChannelsLiveServerTestCase, self)._pre_setup()
  32. self._live_server_modified_settings = modify_settings(
  33. ALLOWED_HOSTS={"append": self.host}
  34. )
  35. self._live_server_modified_settings.enable()
  36. if self.serve_static:
  37. application = self.static_wrapper(get_default_application())
  38. else:
  39. application = get_default_application()
  40. self._server_process = self.ProtocolServerProcess(self.host, application)
  41. self._server_process.start()
  42. self._server_process.ready.wait()
  43. self._port = self._server_process.port.value
  44. def _post_teardown(self):
  45. self._server_process.terminate()
  46. self._server_process.join()
  47. self._live_server_modified_settings.disable()
  48. super(ChannelsLiveServerTestCase, self)._post_teardown()
  49. def _is_in_memory_db(self, connection):
  50. """
  51. Check if DatabaseWrapper holds in memory database.
  52. """
  53. if connection.vendor == "sqlite":
  54. return connection.is_in_memory_db()