From ee1140cf1effb7e5903e2cfad820fba4e5c5e412 Mon Sep 17 00:00:00 2001 From: cherith <315844584+Cherith1222@users.noreply.github.com> Date: Tue, 6 Oct 2026 21:01:33 +0800 Subject: [PATCH] Compile channel_capacity patterns in BaseChannelLayer (#1423) BaseChannelLayer stored channel_capacity as the raw dict, but get_capacity() iterates it as (compiled pattern, capacity) pairs. Passing channel_capacity to InMemoryChannelLayer therefore raised ValueError on the first send(). Compile the patterns in __init__, as channels_redis already does, so glob strings and precompiled regexes both work. AI-assisted (Cursor); not yet reviewed by a human. --- channels/layers.py | 2 +- tests/test_inmemorychannel.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/channels/layers.py b/channels/layers.py index 2ff331eae..5756dffff 100644 --- a/channels/layers.py +++ b/channels/layers.py @@ -108,7 +108,7 @@ class BaseChannelLayer: def __init__(self, expiry=60, capacity=100, channel_capacity=None): self.expiry = expiry self.capacity = capacity - self.channel_capacity = channel_capacity or {} + self.channel_capacity = self.compile_capacities(channel_capacity or {}) def compile_capacities(self, channel_capacity): """ diff --git a/tests/test_inmemorychannel.py b/tests/test_inmemorychannel.py index 4ba4bfabe..7750e705d 100644 --- a/tests/test_inmemorychannel.py +++ b/tests/test_inmemorychannel.py @@ -1,4 +1,5 @@ import asyncio +import re import async_timeout import pytest @@ -70,6 +71,24 @@ async def test_send_capacity(channel_layer): await channel_layer.send("test-channel-1", {"type": "test.message"}) +@pytest.mark.asyncio +async def test_send_channel_capacity(): + """ + Makes sure channel_capacity patterns override the default capacity + """ + channel_layer = InMemoryChannelLayer( + capacity=3, channel_capacity={"small-*": 1, re.compile(r"^big-"): 5} + ) + assert channel_layer.get_capacity("small-channel") == 1 + assert channel_layer.get_capacity("big-channel") == 5 + assert channel_layer.get_capacity("other-channel") == 3 + await channel_layer.send("small-channel", {"type": "test.message"}) + with pytest.raises(ChannelFull): + await channel_layer.send("small-channel", {"type": "test.message"}) + await channel_layer.flush() + await channel_layer.close() + + @pytest.mark.asyncio async def test_process_local_send_receive(channel_layer): """