File: test_eventprocessor_async.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (769 lines) | stat: -rw-r--r-- 26,448 bytes parent folder | download
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

import pytest
import asyncio
import time

from azure.eventhub import EventData, LoadBalancingStrategy
from azure.eventhub.aio import EventHubConsumerClient
from azure.eventhub.aio._eventprocessor.event_processor import (
    EventProcessor,
    CloseReason,
)
from azure.eventhub.aio._eventprocessor.in_memory_checkpoint_store import (
    InMemoryCheckpointStore,
)
from azure.eventhub.aio._eventprocessor._ownership_manager import OwnershipManager
from azure.eventhub.exceptions import OwnershipLostError, EventHubError
from azure.eventhub._client_base import _Address


TEST_NAMESPACE = "test_namespace"
TEST_EVENTHUB = "test_eventhub"
TEST_CONSUMER_GROUP = "test_consumer_group"
TEST_OWNER = "test_owner_id"


async def event_handler(partition_context, event):
    pass


@pytest.mark.asyncio
async def test_loadbalancer_balance():

    class MockEventHubClient:
        eventhub_name = "test_eventhub_name"

        def __init__(self):
            self._address = _Address(hostname="test", path=MockEventHubClient.eventhub_name)

        def _create_consumer(self, consumer_group, partition_id, event_position, on_event_received, **kwargs):
            consumer = MockEventhubConsumer(on_event_received=on_event_received, **kwargs)
            return consumer

        async def get_partition_ids(self):
            return ["0", "1"]

        async def close(self):
            pass

    class MockEventhubConsumer:
        def __init__(self, **kwargs):
            self.stop = False
            self._on_event_received = kwargs.get("on_event_received")

        async def receive(self, *args, **kwargs):
            await asyncio.sleep(0.1)
            await self._on_event_received(EventData("mock events"))

        async def close(self):
            pass

    eventhub_client = MockEventHubClient()
    checkpoint_store = InMemoryCheckpointStore()
    tasks = []

    event_processor1 = EventProcessor(
        eventhub_client=eventhub_client,
        consumer_group="$default",
        checkpoint_store=checkpoint_store,
        event_handler=event_handler,
        error_handler=None,
        partition_initialize_handler=None,
        partition_close_handler=None,
        load_balancing_interval=1.3,
    )

    tasks.append(asyncio.ensure_future(event_processor1.start()))
    await asyncio.sleep(3)
    assert len(event_processor1._tasks) == 2  # event_processor1 claims two partitions

    event_processor2 = EventProcessor(
        eventhub_client=eventhub_client,
        consumer_group="$default",
        checkpoint_store=checkpoint_store,
        event_handler=event_handler,
        error_handler=None,
        partition_initialize_handler=None,
        partition_close_handler=None,
        load_balancing_interval=1.3,
    )

    tasks.append(asyncio.ensure_future(event_processor2.start()))
    await asyncio.sleep(3)
    assert len(event_processor1._tasks) == 1  # two event processors balance. So each has 1 task
    assert len(event_processor2._tasks) == 1

    event_processor3 = EventProcessor(
        eventhub_client=eventhub_client,
        consumer_group="$default",
        checkpoint_store=checkpoint_store,
        event_handler=event_handler,
        error_handler=None,
        partition_initialize_handler=None,
        partition_close_handler=None,
        load_balancing_interval=1.3,
    )
    tasks.append(asyncio.ensure_future(event_processor3.start()))
    await asyncio.sleep(3)
    assert len(event_processor3._tasks) == 0
    await event_processor3.stop()

    await event_processor1.stop()
    await asyncio.sleep(3)
    assert len(event_processor2._tasks) == 2  # event_procesor2 takes another one after event_processor1 stops
    await event_processor2.stop()

    await eventhub_client.close()


@pytest.mark.asyncio
async def test_loadbalancer_list_ownership_error():
    class MockEventHubClient:
        eventhub_name = "test_eventhub_name"

        def __init__(self):
            self._address = _Address(hostname="test", path=MockEventHubClient.eventhub_name)

        def _create_consumer(self, consumer_group, partition_id, event_position, on_event_received, **kwargs):
            consumer = MockEventhubConsumer(on_event_received=on_event_received, **kwargs)
            return consumer

        async def get_partition_ids(self):
            return ["0", "1"]

        async def close(self):
            pass

    class MockEventhubConsumer:
        def __init__(self, **kwargs):
            self.stop = False
            self._on_event_received = kwargs.get("on_event_received")

        async def receive(self):
            await asyncio.sleep(0.1)
            await self._on_event_received(EventData("mock events"))

        async def close(self):
            pass

    class ErrorCheckpointStore(InMemoryCheckpointStore):
        async def list_ownership(self, fully_qualified_namespace, eventhub_name, consumer_group):
            raise RuntimeError("Test runtime error")

    async def on_error(partition_context, error):
        assert partition_context is None
        assert isinstance(error, RuntimeError)
        on_error.called = True

    on_error.called = False
    eventhub_client = MockEventHubClient()
    checkpoint_store = ErrorCheckpointStore()

    event_processor = EventProcessor(
        eventhub_client=eventhub_client,
        consumer_group="$default",
        checkpoint_store=checkpoint_store,
        event_handler=event_handler,
        error_handler=on_error,
        partition_initialize_handler=None,
        partition_close_handler=None,
        load_balancing_interval=1.3,
    )
    task = asyncio.ensure_future(event_processor.start())
    await asyncio.sleep(5)
    try:
        assert event_processor._running is True
        assert len(event_processor._tasks) == 0
        assert on_error.called is True
    finally:
        await event_processor.stop()
        await task
        await eventhub_client.close()


@pytest.mark.asyncio
async def test_partition_processor():

    class MockEventHubClient:
        eventhub_name = "test_eventhub_name"

        def __init__(self):
            self._address = _Address(hostname="test", path=MockEventHubClient.eventhub_name)

        def _create_consumer(self, consumer_group, partition_id, event_position, on_event_received, **kwargs):
            consumer = MockEventhubConsumer(on_event_received=on_event_received, **kwargs)
            return consumer

        async def get_partition_ids(self):
            return ["0", "1"]

        async def close(self):
            pass

    class MockEventhubConsumer:
        def __init__(self, **kwargs):
            self.stop = False
            self._on_event_received = kwargs.get("on_event_received")

        async def receive(self, *args, **kwargs):
            await asyncio.sleep(0.1)
            await self._on_event_received(EventData("mock events"))

        async def close(self):
            pass

    lock = asyncio.Lock()
    event_map = {}
    checkpoint = None
    close_reason = None
    error = None

    async def partition_initialize_handler(partition_context):
        partition_initialize_handler.partition_context = partition_context

    async def event_handler(partition_context, event):
        async with lock:
            if event:
                nonlocal checkpoint, event_map
                event_map[partition_context.partition_id] = event_map.get(partition_context.partition_id, 0) + 1
                offset, sn = event.offset, event.sequence_number
                checkpoint = (offset, sn)
                await partition_context.update_checkpoint(event)

    async def partition_close_handler(partition_context, reason):
        assert partition_context and reason
        nonlocal close_reason
        close_reason = reason

    async def error_handler(partition_context, err):
        assert partition_context and err
        nonlocal error
        error = err

    eventhub_client = MockEventHubClient()
    checkpoint_store = InMemoryCheckpointStore()

    event_processor = EventProcessor(
        eventhub_client=eventhub_client,
        consumer_group="$default",
        checkpoint_store=checkpoint_store,
        event_handler=event_handler,
        error_handler=error_handler,
        partition_initialize_handler=partition_initialize_handler,
        partition_close_handler=partition_close_handler,
        load_balancing_interval=1.3,
    )

    task = asyncio.ensure_future(event_processor.start())

    await asyncio.sleep(2)
    assert len(event_processor._tasks) == 2
    await event_processor.stop()
    await task
    await eventhub_client.close()
    assert event_map["0"] >= 1 and event_map["1"] >= 1
    assert checkpoint is not None
    assert close_reason == CloseReason.SHUTDOWN
    assert error is None
    assert partition_initialize_handler.partition_context


@pytest.mark.asyncio
async def test_partition_processor_process_events_error():

    class MockEventHubClient:
        eventhub_name = "test_eventhub_name"

        def __init__(self):
            self._address = _Address(hostname="test", path=MockEventHubClient.eventhub_name)

        def _create_consumer(self, consumer_group, partition_id, event_position, on_event_received, **kwargs):
            consumer = MockEventhubConsumer(on_event_received=on_event_received, **kwargs)
            return consumer

        async def get_partition_ids(self):
            return ["0", "1"]

        async def close(self):
            pass

    class MockEventhubConsumer:
        def __init__(self, **kwargs):
            self.stop = False
            self._on_event_received = kwargs.get("on_event_received")

        async def receive(self, *args, **kwargs):
            await asyncio.sleep(0.1)
            await self._on_event_received(EventData("mock events"))

        async def close(self):
            pass

    async def event_handler(partition_context, event):
        if partition_context.partition_id == "1":
            raise RuntimeError("processing events error")
        else:
            pass

    async def error_handler(partition_context, error):
        if partition_context.partition_id == "1":
            error_handler.error = error
        else:
            raise RuntimeError("There shouldn't be an error for partition other than 1")

    eventhub_client = MockEventHubClient()
    checkpoint_store = InMemoryCheckpointStore()

    event_processor = EventProcessor(
        eventhub_client=eventhub_client,
        consumer_group="$default",
        checkpoint_store=checkpoint_store,
        event_handler=event_handler,
        error_handler=error_handler,
        initial_event_position="-1",
        partition_initialize_handler=None,
        load_balancing_interval=1.3,
    )
    task = asyncio.ensure_future(event_processor.start())
    await asyncio.sleep(10)
    await event_processor.stop()
    await task
    await asyncio.sleep(1)
    await eventhub_client.close()
    assert isinstance(error_handler.error, RuntimeError)


@pytest.mark.asyncio
async def test_partition_processor_process_eventhub_consumer_error():
    async def event_handler(partition_context, event):
        pass

    async def error_handler(partition_context, error):
        error_handler.error = error

    async def partition_close_handler(partition_context, reason):
        partition_close_handler.reason = reason

    class MockEventHubClient:
        eventhub_name = "test_eh_name"

        def __init__(self):
            self._address = _Address(hostname="test", path=MockEventHubClient.eventhub_name)

        def _create_consumer(self, consumer_group, partition_id, event_position, on_event_received, **kwargs):
            return MockEventhubConsumer(on_event_received=on_event_received, **kwargs)

        async def get_partition_ids(self):
            return ["0", "1"]

    class MockEventhubConsumer:
        def __init__(self, **kwargs):
            self.stop = False
            self._on_event_received = kwargs.get("on_event_received")

        async def receive(self, *args, **kwargs):
            raise EventHubError("Mock EventHubConsumer EventHubError")

        async def close(self):
            pass

    eventhub_client = MockEventHubClient()
    checkpoint_store = InMemoryCheckpointStore()

    event_processor = EventProcessor(
        eventhub_client=eventhub_client,
        consumer_group="$default",
        checkpoint_store=checkpoint_store,
        event_handler=event_handler,
        error_handler=error_handler,
        partition_initialize_handler=None,
        partition_close_handler=partition_close_handler,
        load_balancing_interval=1.3,
    )
    task = asyncio.ensure_future(event_processor.start())
    await asyncio.sleep(5)
    await event_processor.stop()
    await task
    assert isinstance(error_handler.error, EventHubError)
    assert partition_close_handler.reason == CloseReason.OWNERSHIP_LOST


@pytest.mark.asyncio
async def test_partition_processor_process_error_close_error():
    async def partition_initialize_handler(partition_context):
        partition_initialize_handler.called = True
        raise RuntimeError("initialize error")

    async def event_handler(partition_context, event):
        event_handler.called = True
        raise RuntimeError("process_events error")

    async def error_handler(partition_context, error):
        assert isinstance(error, RuntimeError)
        error_handler.called = True
        raise RuntimeError("process_error error")

    async def partition_close_handler(partition_context, reason):
        assert reason == CloseReason.OWNERSHIP_LOST
        partition_close_handler.called = True
        raise RuntimeError("close error")

    class MockEventHubClient:
        eventhub_name = "test_eh_name"

        def __init__(self):
            self._address = _Address(hostname="test", path=MockEventHubClient.eventhub_name)

        def _create_consumer(self, consumer_group, partition_id, event_position, on_event_received, **kwargs):
            return MockEventhubConsumer(on_event_received=on_event_received, **kwargs)

        async def get_partition_ids(self):
            return ["0", "1"]

    class MockEventhubConsumer:
        def __init__(self, **kwargs):
            self.stop = False
            self._on_event_received = kwargs.get("on_event_received")

        async def receive(self, *args, **kwargs):
            await asyncio.sleep(0.1)
            await self._on_event_received(EventData("mock events"))

        async def close(self):
            pass

    class MockOwnershipManager(OwnershipManager):

        called = False

        async def release_ownership(self, partition_id):
            self.called = True

    eventhub_client = MockEventHubClient()
    checkpoint_store = InMemoryCheckpointStore()
    ownership_manager = MockOwnershipManager(
        eventhub_client,
        "$Default",
        "owner",
        checkpoint_store,
        10.0,
        LoadBalancingStrategy.GREEDY,
        "0",
    )
    event_processor = EventProcessor(
        eventhub_client=eventhub_client,
        consumer_group="$default",
        checkpoint_store=checkpoint_store,
        event_handler=event_handler,
        error_handler=error_handler,
        partition_initialize_handler=partition_initialize_handler,
        partition_close_handler=partition_close_handler,
        load_balancing_strategy=LoadBalancingStrategy.GREEDY,
        load_balancing_interval=1.3,
    )
    event_processor._ownership_manager = ownership_manager
    task = asyncio.ensure_future(event_processor.start())
    await asyncio.sleep(5)
    await event_processor.stop()
    await task
    assert partition_initialize_handler.called
    assert event_handler.called
    assert error_handler.called
    assert ownership_manager.called
    assert partition_close_handler.called


@pytest.mark.asyncio
async def test_ownership_manager_release_partition():
    class MockEventHubClient:
        eventhub_name = "test_eh_name"

        def __init__(self):
            self._address = _Address(hostname="test", path=MockEventHubClient.eventhub_name)

        async def get_partition_ids(self):
            return ["0", "1"]

    class MockCheckpointStore(InMemoryCheckpointStore):

        released = None

        async def claim_ownership(self, ownsership):
            self.released = ownsership

    checkpoint_store = MockCheckpointStore()
    ownership_manager = OwnershipManager(
        MockEventHubClient(),
        "$Default",
        "owner",
        checkpoint_store,
        10.0,
        LoadBalancingStrategy.GREEDY,
        "0",
    )
    ownership_manager.cached_parition_ids = ["0", "1"]
    ownership_manager.owned_partitions = []
    await ownership_manager.release_ownership("1")
    assert checkpoint_store.released is None

    ownership_manager.owned_partitions = [
        {"partition_id": "0", "owner_id": "foo", "last_modified_time": time.time() + 31}
    ]
    await ownership_manager.release_ownership("0")
    assert checkpoint_store.released is None

    ownership_manager.owned_partitions = [{"partition_id": "0", "owner_id": "", "last_modified_time": time.time()}]
    await ownership_manager.release_ownership("0")
    assert checkpoint_store.released is None

    ownership_manager.owned_partitions = [{"partition_id": "0", "owner_id": "foo", "last_modified_time": time.time()}]
    await ownership_manager.release_ownership("0")
    assert checkpoint_store.released is None

    ownership_manager.owned_partitions = [{"partition_id": "0", "owner_id": "owner", "last_modified_time": time.time()}]
    await ownership_manager.release_ownership("0")
    assert checkpoint_store.released[0]["owner_id"] == ""


@pytest.mark.parametrize(
    "ownerships, partitions, expected_result",
    [
        ([], ["0", "1", "2"], 3),
        (["ownership_active0", "ownership_active1"], ["0", "1", "2"], 1),
        (["ownership_active0", "ownership_expired"], ["0", "1", "2"], 2),
        (
            ["ownership_active0", "ownership_expired", "ownership_released"],
            ["0", "1", "2", "3"],
            2,
        ),
        (["ownership_active0"], ["0", "1", "2", "3"], 2),
        (["ownership_expired", "ownership_released"], ["0", "1", "2", "3"], 4),
        (["ownership_active0", "ownership_active1"], ["0", "1"], 0),
        (["ownership_active0", "ownership_self_owned"], ["0", "1"], 1),
    ],
)
def test_balance_ownership_greedy(ownerships, partitions, expected_result):
    ownership_ref = {
        "ownership_active0": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "0",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": "owner_0",
            "last_modified_time": time.time(),
        },
        "ownership_active1": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "1",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": "owner_1",
            "last_modified_time": time.time(),
        },
        "ownership_self_owned": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "1",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": TEST_OWNER,
            "last_modified_time": time.time(),
        },
        "ownership_expired": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "2",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": "owner_1",
            "last_modified_time": time.time() - 100000,
        },
        "ownership_released": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "3",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": "",
            "last_modified_time": time.time(),
        },
    }

    class MockEventHubClient:
        eventhub_name = TEST_EVENTHUB

        def __init__(self):
            self._address = _Address(hostname=TEST_NAMESPACE, path=MockEventHubClient.eventhub_name)

        def get_partition_ids(self):
            return ["0", "1"]

    mock_client = MockEventHubClient()
    current_ownerships = [ownership_ref[o] for o in ownerships]
    om = OwnershipManager(
        mock_client,
        TEST_CONSUMER_GROUP,
        TEST_OWNER,
        None,
        10,
        LoadBalancingStrategy.GREEDY,
        None,
    )
    to_claim_ownership = om._balance_ownership(current_ownerships, partitions)
    assert len(to_claim_ownership) == expected_result


@pytest.mark.parametrize(
    "ownerships, partitions, expected_result",
    [
        ([], ["0", "1", "2"], 1),
        (["ownership_active0", "ownership_active1"], ["0", "1", "2"], 1),
        (["ownership_active0", "ownership_expired"], ["0", "1", "2"], 1),
        (
            ["ownership_active0", "ownership_expired", "ownership_released"],
            ["0", "1", "2", "3"],
            1,
        ),
        (["ownership_active0"], ["0", "1", "2", "3"], 1),
        (["ownership_expired", "ownership_released"], ["0", "1", "2", "3"], 1),
        (["ownership_active0", "ownership_active1"], ["0", "1"], 0),
        (["ownership_active0", "ownership_self_owned"], ["0", "1"], 1),
    ],
)
def test_balance_ownership_balanced(ownerships, partitions, expected_result):
    ownership_ref = {
        "ownership_active0": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "0",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": "owner_0",
            "last_modified_time": time.time(),
        },
        "ownership_active1": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "1",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": "owner_1",
            "last_modified_time": time.time(),
        },
        "ownership_self_owned": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "1",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": TEST_OWNER,
            "last_modified_time": time.time(),
        },
        "ownership_expired": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "2",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": "owner_1",
            "last_modified_time": time.time() - 100000,
        },
        "ownership_released": {
            "fully_qualified_namespace": TEST_NAMESPACE,
            "partition_id": "3",
            "eventhub_name": TEST_EVENTHUB,
            "consumer_group": TEST_CONSUMER_GROUP,
            "owner_id": "",
            "last_modified_time": time.time(),
        },
    }

    class MockEventHubClient:
        eventhub_name = TEST_EVENTHUB

        def __init__(self):
            self._address = _Address(hostname=TEST_NAMESPACE, path=MockEventHubClient.eventhub_name)

        def get_partition_ids(self):
            return ["0", "1"]

    mock_client = MockEventHubClient()
    current_ownerships = [ownership_ref[o] for o in ownerships]
    om = OwnershipManager(
        mock_client,
        TEST_CONSUMER_GROUP,
        TEST_OWNER,
        None,
        10,
        LoadBalancingStrategy.BALANCED,
        None,
    )
    to_claim_ownership = om._balance_ownership(current_ownerships, partitions)
    assert len(to_claim_ownership) == expected_result


@pytest.mark.asyncio
async def test_partition_processor_process_update_checkpoint_error():

    class MockEventHubClient:
        eventhub_name = "test_eventhub_name"

        def __init__(self):
            self._address = _Address(hostname="test", path=MockEventHubClient.eventhub_name)

        def _create_consumer(self, consumer_group, partition_id, event_position, on_event_received, **kwargs):
            consumer = MockEventhubConsumer(on_event_received=on_event_received, **kwargs)
            return consumer

        async def get_partition_ids(self):
            return ["0", "1"]

        async def close(self):
            pass

    class MockEventhubConsumer:
        def __init__(self, **kwargs):
            self.stop = False
            self._on_event_received = kwargs.get("on_event_received")

        async def receive(self):
            await asyncio.sleep(0.1)
            await self._on_event_received(EventData("mock events"))

        async def close(self):
            pass

    class ErrorCheckpointStore(InMemoryCheckpointStore):
        async def update_checkpoint(self, checkpoint):
            if checkpoint["partition_id"] == "1":
                raise OwnershipLostError("Mocked ownership lost")

    async def event_handler(partition_context, event):
        await partition_context.update_checkpoint(event)

    async def error_handler(partition_context, error):
        assert isinstance(error, OwnershipLostError)

    async def partition_close_handler(partition_context, reason):
        if partition_context.partition_id == "1":
            assert reason == CloseReason.OWNERSHIP_LOST
            partition_close_handler.called = True

    eventhub_client = MockEventHubClient()
    checkpoint_store = ErrorCheckpointStore()

    event_processor = EventProcessor(
        eventhub_client=eventhub_client,
        consumer_group="$default",
        checkpoint_store=checkpoint_store,
        event_handler=event_handler,
        error_handler=error_handler,
        partition_initialize_handler=None,
        partition_close_handler=partition_close_handler,
        load_balancing_interval=1.3,
    )
    task = asyncio.ensure_future(event_processor.start())
    await asyncio.sleep(10)
    await event_processor.stop()
    await task
    await asyncio.sleep(1)
    await eventhub_client.close()
    assert partition_close_handler.called