Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change Message body argument to support str type like in pika module.… #416

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions aio_pika/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ class Message:

def __init__(
self,
body: bytes,
body: Union[bytes, str],
*,
headers: dict = None,
content_type: str = None,
Expand Down Expand Up @@ -279,7 +279,8 @@ def __init__(
"""

self.__lock = False
self.body = body if isinstance(body, bytes) else bytes(body)

self.body = Message._prepare_msg_body(body)
self.body_size = len(self.body) if self.body else 0
self.headers_raw = format_headers(headers)
self._headers = HeaderProxy(self.headers_raw)
Expand Down Expand Up @@ -308,6 +309,20 @@ def headers(self):
def headers(self, value: dict):
self.headers_raw = format_headers(value)

@staticmethod
def _prepare_msg_body(body: Union[str, bytes]) -> bytes:
"""
If body type is bytes returns body with no changes
If body type is str converts it to bytes ith encoding = 'utf8'
If body type is not either str or bytes raises TypeError
"""
if isinstance(body, bytes):
return body
elif isinstance(body, str):
return bytes(body, 'utf8')
else:
raise TypeError("body argument should be str or bytes, {} was provided instead".format(type(body)))

@staticmethod
def _as_bytes(value):
if isinstance(value, bytes):
Expand Down
15 changes: 15 additions & 0 deletions tests/test_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@
import shortuuid

from aio_pika import DeliveryMode, Message
import pytest


def test_init_message_body():
# test body is string
msg = Message(body="test")
assert msg.body == b"test"

# test body is bytes
msg = Message(body=b"test")
assert msg.body == b"test"

# net not str or bytes body
with pytest.raises(TypeError):
Message(body=1)


def test_message_copy():
Expand Down