Skip to content

Commit 1290f60

Browse files
authored
Restructured layer manager so exceptions within the backend are not hidden (#2146)
* Restructured exceptions so exceptions within the backend are not hidden * Add regression test and fix linting issue
1 parent fffced5 commit 1290f60

File tree

2 files changed

+34
-6
lines changed

2 files changed

+34
-6
lines changed

channels/layers.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,18 @@ def _make_backend(self, name, config):
6363
)
6464
# Load the backend class
6565
try:
66-
backend_class = import_string(self.configs[name]["BACKEND"])
66+
backend_module = self.configs[name]["BACKEND"]
6767
except KeyError:
6868
raise InvalidChannelLayerError("No BACKEND specified for %s" % name)
69-
except ImportError:
70-
raise InvalidChannelLayerError(
71-
"Cannot import BACKEND %r specified for %s"
72-
% (self.configs[name]["BACKEND"], name)
73-
)
69+
else:
70+
try:
71+
backend_class = import_string(backend_module)
72+
except ImportError:
73+
raise InvalidChannelLayerError(
74+
"Cannot import BACKEND %r specified for %s"
75+
% (self.configs[name]["BACKEND"], name)
76+
)
77+
7478
# Initialise and pass config
7579
return backend_class(**config)
7680

tests/test_layers.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,30 @@ def test_override_settings(self):
5858
self.assertNotEqual(channel_layers.backends, {})
5959
self.assertEqual(channel_layers.backends, {})
6060

61+
@override_settings(
62+
CHANNEL_LAYERS={
63+
"default": {
64+
"BACKEND": "tests.test_layers.BrokenBackend",
65+
}
66+
}
67+
)
68+
def test_backend_import_error_not_hidden(self):
69+
"""
70+
Test that KeyError exceptions within the backend import are not hidden.
71+
This test ensures that the PR #2146 fix works correctly.
72+
"""
73+
# This should raise a KeyError from the backend, not an InvalidChannelLayerError
74+
with self.assertRaises(KeyError):
75+
channel_layers.make_backend(DEFAULT_CHANNEL_LAYER)
76+
77+
78+
# Mock backend that raises KeyError during import
79+
class BrokenBackend:
80+
def __init__(self, **kwargs):
81+
# This will be called during backend initialization
82+
# and should raise a KeyError that should not be caught
83+
raise KeyError("This is a deliberate KeyError from the backend")
84+
6185

6286
# In-memory layer tests
6387

0 commit comments

Comments
 (0)