Skip to content

Commit

Permalink
Add additional_payload to Message.
Browse files Browse the repository at this point in the history
  • Loading branch information
BenediktBurger committed May 22, 2024
1 parent 4a49863 commit 055d0fa
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
8 changes: 5 additions & 3 deletions pyleco/core/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from __future__ import annotations
from json import JSONDecodeError
from typing import Any, Optional, Union
from typing import Any, Iterable, Optional, Union


from . import VERSION_B
Expand Down Expand Up @@ -64,6 +64,7 @@ def __init__(self,
conversation_id: Optional[bytes] = None,
message_id: Optional[bytes] = None,
message_type: Union[MessageTypes, int] = MessageTypes.NOT_DEFINED,
additional_payload: Optional[Iterable[bytes]] = None,
) -> None:
self.receiver = receiver.encode() if isinstance(receiver, str) else receiver
self.sender = sender.encode() if isinstance(sender, str) else sender
Expand All @@ -81,6 +82,8 @@ def __init__(self,
self.payload = []
else:
self.payload = [serialize_data(data)]
if additional_payload is not None:
self.payload.extend(additional_payload)

@classmethod
def from_frames(cls, version: bytes, receiver: bytes, sender: bytes, header: bytes,
Expand All @@ -92,9 +95,8 @@ def from_frames(cls, version: bytes, receiver: bytes, sender: bytes, header: byt
frames = socket.recv_multipart()
message = Message.from_frames(*frames)
"""
inst = cls(receiver, sender, header=header)
inst = cls(receiver, sender, header=header, additional_payload=payload)
inst.version = version
inst.payload = list(payload)
return inst

def to_frames(self) -> list[bytes]:
Expand Down
8 changes: 8 additions & 0 deletions tests/core/test_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ def test_message_data_str_to_binary_data(self):
message = Message(b"rec", data="some string")
assert message.payload[0] == b"some string"

def test_additional_binary_data(self):
message = Message(b"rec", data=b"0", additional_payload=[b"1", b"2"])
assert message.payload == [b"0", b"1", b"2"]

def test_additional_payload_without_data(self):
message = Message(b"rec", additional_payload=[b"1", b"2"])
assert message.payload == [b"1", b"2"]

@pytest.mark.parametrize("key, value", (("conversation_id", b"content"),
("message_id", b"mid"),
("message_type", 7),
Expand Down

0 comments on commit 055d0fa

Please sign in to comment.