Skip to content

Commit 3cab0c1

Browse files
fix(fcm): String representation in Message class (#350)
* String representation in Message class * PR fixes and add test cases * Fix pylint errors
1 parent f889dff commit 3cab0c1

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

firebase_admin/_messaging_utils.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ def __init__(self, data=None, notification=None, android=None, webpush=None, apn
5757
self.topic = topic
5858
self.condition = condition
5959

60+
def __str__(self):
61+
return json.dumps(self, cls=MessageEncoder, sort_keys=True)
62+
6063

6164
class MulticastMessage(object):
6265
"""A message that can be sent to multiple tokens via Firebase Cloud Messaging.

tests/test_messaging.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,34 @@ def check_exception(exception, message, status):
6161
assert exception.http_response.status_code == status
6262

6363

64+
class TestMessageStr(object):
65+
66+
@pytest.mark.parametrize('msg', [
67+
messaging.Message(),
68+
messaging.Message(topic='topic', token='token'),
69+
messaging.Message(topic='topic', condition='condition'),
70+
messaging.Message(condition='condition', token='token'),
71+
messaging.Message(topic='topic', token='token', condition='condition'),
72+
])
73+
def test_invalid_target_message(self, msg):
74+
with pytest.raises(ValueError) as excinfo:
75+
str(msg)
76+
assert str(
77+
excinfo.value) == 'Exactly one of token, topic or condition must be specified.'
78+
79+
def test_empty_message(self):
80+
assert str(messaging.Message(token='value')) == '{"token": "value"}'
81+
assert str(messaging.Message(topic='value')) == '{"topic": "value"}'
82+
assert str(messaging.Message(condition='value')
83+
) == '{"condition": "value"}'
84+
85+
def test_data_message(self):
86+
assert str(messaging.Message(topic='topic', data={})
87+
) == '{"topic": "topic"}'
88+
assert str(messaging.Message(topic='topic', data={
89+
'k1': 'v1', 'k2': 'v2'})) == '{"data": {"k1": "v1", "k2": "v2"}, "topic": "topic"}'
90+
91+
6492
class TestMulticastMessage(object):
6593

6694
@pytest.mark.parametrize('tokens', NON_LIST_ARGS)

0 commit comments

Comments
 (0)