forked from apache/pulsar-client-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncio_test.py
More file actions
324 lines (275 loc) · 12.3 KB
/
asyncio_test.py
File metadata and controls
324 lines (275 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#!/usr/bin/env python3
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
"""
Unit tests for asyncio Pulsar client API.
"""
# pylint: disable=missing-function-docstring
import asyncio
import time
from typing import List
from unittest import (
main,
IsolatedAsyncioTestCase,
)
import pulsar # pylint: disable=import-error
from pulsar.asyncio import ( # pylint: disable=import-error
Client,
Consumer,
Producer,
PulsarException,
)
from pulsar.schema import ( # pylint: disable=import-error
AvroSchema,
Integer,
Record,
String,
)
SERVICE_URL = 'pulsar://localhost:6650'
class AsyncioTest(IsolatedAsyncioTestCase):
"""Test cases for asyncio Pulsar client."""
async def asyncSetUp(self) -> None:
self._client = Client(SERVICE_URL,
operation_timeout_seconds=5)
async def asyncTearDown(self) -> None:
await self._client.close()
async def test_batch_end_to_end(self):
topic = f'asyncio-test-batch-e2e-{time.time()}'
producer = await self._client.create_producer(topic,
producer_name="my-producer")
self.assertEqual(producer.topic(), f'persistent://public/default/{topic}')
self.assertEqual(producer.producer_name(), "my-producer")
tasks = []
for i in range(5):
tasks.append(asyncio.create_task(producer.send(f'msg-{i}'.encode())))
msg_ids = await asyncio.gather(*tasks)
self.assertEqual(len(msg_ids), 5)
# pylint: disable=fixme
# TODO: the result is wrong due to https://github.com/apache/pulsar-client-cpp/issues/531
self.assertEqual(producer.last_sequence_id(), 8)
ledger_id = msg_ids[0].ledger_id()
entry_id = msg_ids[0].entry_id()
# These messages should be in the same entry
for i in range(5):
msg_id = msg_ids[i]
print(f'{i} was sent to {msg_id}')
self.assertIsInstance(msg_id, pulsar.MessageId)
self.assertEqual(msg_ids[i].ledger_id(), ledger_id)
self.assertEqual(msg_ids[i].entry_id(), entry_id)
self.assertEqual(msg_ids[i].batch_index(), i)
consumer = await self._client.subscribe(topic, 'sub',
initial_position=pulsar.InitialPosition.Earliest)
for i in range(5):
msg = await consumer.receive()
self.assertEqual(msg.data(), f'msg-{i}'.encode())
await consumer.close()
# create a different subscription to verify initial position is latest by default
consumer = await self._client.subscribe(topic, 'sub2')
await producer.send(b'final-message')
msg = await consumer.receive()
self.assertEqual(msg.data(), b'final-message')
async def test_send_keyed_message(self):
topic = f'asyncio-test-send-keyed-message-{time.time()}'
producer = await self._client.create_producer(topic)
consumer = await self._client.subscribe(topic, 'sub')
await producer.send(b'msg', partition_key='key0',
ordering_key="key1", properties={'my-prop': 'my-value'})
msg = await consumer.receive()
self.assertEqual(msg.data(), b'msg')
self.assertEqual(msg.partition_key(), 'key0')
self.assertEqual(msg.ordering_key(), 'key1')
self.assertEqual(msg.properties(), {'my-prop': 'my-value'})
async def test_flush(self):
topic = f'asyncio-test-flush-{time.time()}'
producer = await self._client.create_producer(topic, batching_max_messages=3,
batching_max_publish_delay_ms=60000)
tasks = []
tasks.append(asyncio.create_task(producer.send(b'msg-0')))
tasks.append(asyncio.create_task(producer.send(b'msg-1')))
done, pending = await asyncio.wait(tasks, timeout=1, return_when=asyncio.FIRST_COMPLETED)
self.assertEqual(len(done), 0)
self.assertEqual(len(pending), 2)
# flush will trigger sending the batched messages
await producer.flush()
for task in pending:
self.assertTrue(task.done())
msg_id0 = tasks[0].result()
msg_id1 = tasks[1].result()
self.assertEqual(msg_id0.ledger_id(), msg_id1.ledger_id())
self.assertEqual(msg_id0.entry_id(), msg_id1.entry_id())
self.assertEqual(msg_id0.batch_index(), 0)
self.assertEqual(msg_id1.batch_index(), 1)
async def test_create_producer_failure(self):
try:
await self._client.create_producer('tenant/ns/asyncio-test-send-failure')
self.fail()
except PulsarException as e:
self.assertEqual(e.error(), pulsar.Result.Timeout)
async def test_send_failure(self):
producer = await self._client.create_producer('asyncio-test-send-failure')
try:
await producer.send(('x' * 1024 * 1024 * 10).encode())
self.fail()
except PulsarException as e:
self.assertEqual(e.error(), pulsar.Result.MessageTooBig)
async def test_close_producer(self):
producer = await self._client.create_producer('asyncio-test-close-producer')
await producer.close()
try:
await producer.close()
self.fail()
except PulsarException as e:
self.assertEqual(e.error(), pulsar.Result.AlreadyClosed)
async def _prepare_messages(self, producer: Producer) -> List[pulsar.MessageId]:
msg_ids = []
for i in range(5):
msg_ids.append(await producer.send(f'msg-{i}'.encode()))
return msg_ids
async def test_consumer_cumulative_acknowledge(self):
topic = f'asyncio-test-consumer-cumulative-ack-{time.time()}'
sub = 'sub'
consumer = await self._client.subscribe(topic, sub)
producer = await self._client.create_producer(topic)
await self._prepare_messages(producer)
last_msg = None
for _ in range(5):
last_msg = await consumer.receive()
await consumer.acknowledge_cumulative(last_msg)
await consumer.close()
consumer = await self._client.subscribe(topic, sub)
await producer.send(b'final-message')
msg = await consumer.receive()
self.assertEqual(msg.data(), b'final-message')
async def test_consumer_individual_acknowledge(self):
topic = f'asyncio-test-consumer-individual-ack-{time.time()}'
sub = 'sub'
consumer = await self._client.subscribe(topic, sub,
consumer_type=pulsar.ConsumerType.Shared)
producer = await self._client.create_producer(topic)
await self._prepare_messages(producer)
msgs = []
for _ in range(5):
msg = await consumer.receive()
msgs.append(msg)
await consumer.acknowledge(msgs[0])
await consumer.acknowledge(msgs[2])
await consumer.acknowledge(msgs[4])
await consumer.close()
consumer = await self._client.subscribe(topic, sub,
consumer_type=pulsar.ConsumerType.Shared)
msg = await consumer.receive()
self.assertEqual(msg.data(), b'msg-1')
msg = await consumer.receive()
self.assertEqual(msg.data(), b'msg-3')
async def test_multi_topic_consumer(self):
topics = ['asyncio-test-multi-topic-1', 'asyncio-test-multi-topic-2']
producers = []
for topic in topics:
producer = await self._client.create_producer(topic)
producers.append(producer)
consumer = await self._client.subscribe(topics, 'test-multi-subscription')
await producers[0].send(b'message-from-topic-1')
await producers[1].send(b'message-from-topic-2')
async def verify_receive(consumer: Consumer):
received_messages = {}
for _ in range(2):
msg = await consumer.receive()
received_messages[msg.data()] = None
await consumer.acknowledge(msg.message_id())
self.assertEqual(received_messages, {
b'message-from-topic-1': None,
b'message-from-topic-2': None
})
await verify_receive(consumer)
await consumer.close()
consumer = await self._client.subscribe('public/default/asyncio-test-multi-topic-.*',
'test-multi-subscription-2',
is_pattern_topic=True,
initial_position=pulsar.InitialPosition.Earliest)
await verify_receive(consumer)
await consumer.close()
async def test_unsubscribe(self):
topic = f'asyncio-test-unsubscribe-{time.time()}'
sub = 'sub'
consumer = await self._client.subscribe(topic, sub)
await consumer.unsubscribe()
# Verify the consumer can be created successfully with the same subscription name
consumer = await self._client.subscribe(topic, sub)
await consumer.close()
async def test_seek_message_id(self):
topic = f'asyncio-test-seek-message-id-{time.time()}'
sub = 'sub'
producer = await self._client.create_producer(topic)
msg_ids = await self._prepare_messages(producer)
consumer = await self._client.subscribe(
topic, sub, initial_position=pulsar.InitialPosition.Earliest
)
await consumer.seek(msg_ids[2])
msg = await consumer.receive()
self.assertEqual(msg.data(), b'msg-3')
await consumer.close()
consumer = await self._client.subscribe(
topic, sub, initial_position=pulsar.InitialPosition.Earliest,
start_message_id_inclusive=True
)
await consumer.seek(msg_ids[2])
msg = await consumer.receive()
self.assertEqual(msg.data(), b'msg-2')
await consumer.close()
async def test_seek_timestamp(self):
topic = f'asyncio-test-seek-timestamp-{time.time()}'
sub = 'sub'
consumer = await self._client.subscribe(
topic, sub, initial_position=pulsar.InitialPosition.Earliest
)
producer = await self._client.create_producer(topic)
# Send first 3 messages
for i in range(3):
await producer.send(f'msg-{i}'.encode())
seek_time = int(time.time() * 1000)
# Send 2 more messages
for i in range(3, 5):
await producer.send(f'msg-{i}'.encode())
# Consume all messages first
for i in range(5):
msg = await consumer.receive()
self.assertEqual(msg.data(), f'msg-{i}'.encode())
# Seek to the timestamp (should start from msg-3)
await consumer.seek(seek_time)
msg = await consumer.receive()
self.assertEqual(msg.data(), b'msg-3')
async def test_schema(self):
class ExampleRecord(Record): # pylint: disable=too-few-public-methods
"""Example record schema for testing."""
str_field = String()
int_field = Integer()
topic = f'asyncio-test-schema-{time.time()}'
producer = await self._client.create_producer(
topic, schema=AvroSchema(ExampleRecord)
)
consumer = await self._client.subscribe(
topic, 'sub', schema=AvroSchema(ExampleRecord)
)
await producer.send(ExampleRecord(str_field='test', int_field=42))
msg = await consumer.receive()
self.assertIsInstance(msg.value(), ExampleRecord)
self.assertEqual(msg.value().str_field, 'test')
self.assertEqual(msg.value().int_field, 42)
if __name__ == '__main__':
main()