Skip to content

Commit ece3e67

Browse files
committed
Exit runserver when Daphne startup aborts
1 parent c19f2f4 commit ece3e67

2 files changed

Lines changed: 49 additions & 4 deletions

File tree

daphne/management/commands/runserver.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,16 +136,27 @@ def inner_run(self, *args, **options):
136136

137137
# build the endpoint description string from host/port options
138138
endpoints = build_endpoint_description_strings(host=self.addr, port=self.port)
139+
self.run_daphne(
140+
application=self.get_application(options),
141+
endpoints=endpoints,
142+
options=options,
143+
root_path=getattr(settings, "FORCE_SCRIPT_NAME", "") or "",
144+
)
145+
146+
def run_daphne(self, application, endpoints, options, root_path):
139147
try:
140-
self.server_cls(
141-
application=self.get_application(options),
148+
self.server = self.server_cls(
149+
application=application,
142150
endpoints=endpoints,
143151
signal_handlers=not options["use_reloader"],
144152
action_logger=self.log_action,
145153
http_timeout=self.http_timeout,
146-
root_path=getattr(settings, "FORCE_SCRIPT_NAME", "") or "",
154+
root_path=root_path,
147155
websocket_handshake_timeout=self.websocket_handshake_timeout,
148-
).run()
156+
)
157+
self.server.run()
158+
if self.server.abort_start:
159+
raise CommandError("Daphne failed to start.")
149160
logger.debug("Daphne exited")
150161
except KeyboardInterrupt:
151162
shutdown_message = options.get("shutdown_message", "")

tests/test_runserver_startup.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from unittest import TestCase
2+
3+
from django.core.management import CommandError
4+
5+
from daphne.management.commands.runserver import Command
6+
7+
8+
class TestRunserverCommand(TestCase):
9+
class AbortedServer:
10+
abort_start = True
11+
12+
def __init__(self, **kwargs):
13+
self.init_kwargs = kwargs
14+
self.ran = False
15+
16+
def run(self):
17+
self.ran = True
18+
19+
def test_run_daphne_raises_command_error_when_start_aborts(self):
20+
command = Command()
21+
command.server_cls = self.AbortedServer
22+
command.http_timeout = None
23+
command.websocket_handshake_timeout = 5
24+
25+
with self.assertRaisesRegex(CommandError, "Daphne failed to start."):
26+
command.run_daphne(
27+
application=object(),
28+
endpoints=["tcp:port=8000:interface=127.0.0.1"],
29+
options={"use_reloader": False},
30+
root_path="",
31+
)
32+
33+
self.assertTrue(command.server.ran)
34+
self.assertTrue(command.server.init_kwargs["signal_handlers"])

0 commit comments

Comments
 (0)