Skip to content

Commit

Permalink
Merge pull request #120 from maurerle/double_subscription
Browse files Browse the repository at this point in the history
if subscription for "handle_message" exists, do not execute generic handle_message function
  • Loading branch information
rcschrg authored Oct 22, 2024
2 parents 551426b + f08a76f commit 97c31cf
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
9 changes: 7 additions & 2 deletions mango/agent/role.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,11 +185,16 @@ def handle_message(self, content, meta: dict[str, Any]):
:param content: content
:param meta: meta
"""
for role in self.roles:
role.handle_message(content, meta)
handle_message_found = False
for role, message_condition, method, _ in self._message_subs:
# do not execute handle_message twice if role has subscription as well
if method.__name__ == "handle_message":
handle_message_found = True
if self._is_role_active(role) and message_condition(content, meta):
method(content, meta)
if not handle_message_found:
for role in self.roles:
role.handle_message(content, meta)

def _notify_send_message_subs(self, content, receiver_addr: AgentAddress, **kwargs):
for role in self._send_msg_subs:
Expand Down
22 changes: 21 additions & 1 deletion tests/unit_tests/role_agent_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,20 @@ def setup(self):
class SampleRole(Role):
def __init__(self):
self.setup_called = False
self.messages = 0

def setup(self):
assert self.context is not None
self.setup_called = True

def handle_message(self, content: Any, meta: dict):
self.messages = 1
self.messages += 1


class SampleSubRole(SampleRole):
def setup(self):
super().setup()
self.context.subscribe_message(self, self.handle_message, lambda c, m: True)


@pytest.mark.asyncio
Expand Down Expand Up @@ -246,3 +253,16 @@ async def test_role_register_after_agent_register():
await role.context.send_message("", role.context.addr)

assert role.messages == 1


@pytest.mark.asyncio
async def test_role_with_message_handler():
c = create_tcp_container(addr=("127.0.0.1", 5555))
agent = c.register(RoleAgent())
role = SampleSubRole()
agent.add_role(role)

async with activate(c):
await role.context.send_message("", role.context.addr)

assert role.messages == 1

0 comments on commit 97c31cf

Please sign in to comment.