forked from jeffsf/pyDE1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_managed_bleak_client.py
1217 lines (1015 loc) · 37.7 KB
/
test_managed_bleak_client.py
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Copyright © 2021-2023 Jeff Kletsky. All Rights Reserved.
License for this software, part of the pyDE1 package, is granted under
GNU General Public License v3.0 only
SPDX-License-Identifier: GPL-3.0-only
"""
import asyncio
import logging
import time
from typing import Optional
import bleak
import pytest
from unittest.mock import MagicMock, AsyncMock, PropertyMock, patch
from bleak.backends.client import BaseBleakClient, \
get_platform_client_backend_type
from pyDE1.bledev.managed_bleak_client import (
CaptureRequest, ManagedBleakClient, cq_from_code, cq_to_code
)
from pyDE1.exceptions import DE1NoAddressError
def print_all_codes():
for c in 'CRN':
for t in 'CR':
for p in 'NCRX':
print(f" '{c+p+t}': '',")
print(" #")
for c in 'CRN':
for t in 'N':
for p in 'NCRX':
# print(f" '{c+p+t}': '',")
print(f" '{c+p+t}': '{c+p+t}',")
vectors_maybe_initiate_action_normalize = {
# key: present queue, value: resulting queue
# action_taken = key[1] != value[1]
#
'CNC': 'CNC',
'CCC': 'CXC',
'CRC': 'CXC',
'CXC': 'CXC',
#
'CNR': 'CRR',
'CCR': 'CXR',
'CRR': 'CRR',
'CXR': 'CXR',
#
'RNC': 'RCC',
'RCC': 'RCC',
'RRC': 'RXC',
'RXC': 'RXC',
#
'RNR': 'RNR',
'RCR': 'RXR',
'RRR': 'RXR',
'RXR': 'RXR',
#
'NNC': 'NCC',
'NCC': 'NCC',
'NRC': 'NXC',
'NXC': 'NXC',
#
'NNR': 'NRR',
'NCR': 'NXR',
'NRR': 'NRR',
'NXR': 'NXR',
#
'CNN': 'CNN',
'CCN': 'CCN',
'CRN': 'CRN',
'CXN': 'CXN',
'RNN': 'RNN',
'RCN': 'RCN',
'RRN': 'RRN',
'RXN': 'RXN',
'NNN': 'NNN',
'NCN': 'NCN',
'NRN': 'NRN',
'NXN': 'NXN',
}
@pytest.mark.asyncio
async def test_maybe_initiate_action_normalize():
with patch('pyDE1.bledev.managed_bleak_client.ManagedBleakClient'
'._start_request_with_lock',
new_callable=MagicMock) as mock_start_request:
for iq, eq in vectors_maybe_initiate_action_normalize.items():
initial_queue = cq_from_code(iq)
expected_queue = cq_from_code(eq)
mbc = ManagedBleakClient('')
assert mbc.address == ''
mbc._capture_queue = initial_queue
req = mbc._capture_queue.target
async with mbc._capture_queue_lock:
mbc._maybe_initiate_action_have_lock(request=req)
assert mbc._capture_queue == expected_queue, \
f"Unexpected resulting queue from {initial_queue} with {req}"
@pytest.mark.asyncio
async def test_maybe_initiate_action_with_no_arg():
with patch('pyDE1.bledev.managed_bleak_client.ManagedBleakClient'
'._start_request_with_lock',
new_callable=MagicMock) as mock_start_request:
for iq, eq in vectors_maybe_initiate_action_normalize.items():
initial_queue = cq_from_code(iq)
expected_queue = cq_from_code(eq)
mbc = ManagedBleakClient(None)
assert mbc.address == '', "Using None as address should return ''"
mbc._capture_queue = initial_queue
async with mbc._capture_queue_lock:
mbc._maybe_initiate_action_have_lock()
assert mbc._capture_queue == expected_queue, \
f"Unexpected resulting queue from {initial_queue} with {'()'}"
@pytest.mark.asyncio
async def test_maybe_initiate_action_with_none_arg():
with patch('pyDE1.bledev.managed_bleak_client.ManagedBleakClient'
'._start_request_with_lock',
new_callable=MagicMock) as mock_start_request:
for iq, eq in vectors_maybe_initiate_action_normalize.items():
initial_queue = cq_from_code(iq)
expected_queue = cq_from_code(eq)
mbc = ManagedBleakClient('No address')
mbc._capture_queue = initial_queue
async with mbc._capture_queue_lock:
mbc._maybe_initiate_action_have_lock(request=None)
assert mbc._capture_queue == expected_queue, \
f"Unexpected resulting queue from {initial_queue} with {None}"
vectors_maybe_initiate_action_capture = {
# key: present queue, value: resulting queue
# action_taken = key[1] != value[1]
#
'CNC': 'CNC',
'CCC': 'CXC',
'CRC': 'CXC',
'CXC': 'CXC',
#
'CNR': 'CNC',
'CCR': 'CXC',
'CRR': 'CXC',
'CXR': 'CXC',
#
'RNC': 'RCC',
'RCC': 'RCC',
'RRC': 'RXC',
'RXC': 'RXC',
#
'RNR': 'RCC',
'RCR': 'RCC',
'RRR': 'RXC',
'RXR': 'RXC',
#
'NNC': 'NCC',
'NCC': 'NCC',
'NRC': 'NXC',
'NXC': 'NXC',
#
'NNR': 'NCC',
'NCR': 'NCC',
'NRR': 'NXC',
'NXR': 'NXC',
#
'CNN': 'CNC',
'CCN': 'CXC',
'CRN': 'CXC',
'CXN': 'CXC',
'RNN': 'RCC',
'RCN': 'RCC',
'RRN': 'RXC',
'RXN': 'RXC',
'NNN': 'NCC',
'NCN': 'NCC',
'NRN': 'NXC',
'NXN': 'NXC',
}
@pytest.mark.asyncio
async def test_maybe_initiate_action_capture():
with patch('pyDE1.bledev.managed_bleak_client.ManagedBleakClient'
'._start_request_with_lock',
new_callable=MagicMock) as mock_start_request:
for iq, eq in vectors_maybe_initiate_action_capture.items():
initial_queue = cq_from_code(iq)
expected_queue = cq_from_code(eq)
mbc = ManagedBleakClient('No address')
mbc._capture_queue = initial_queue
req = CaptureRequest.CAPTURE
async with mbc._capture_queue_lock:
mbc._maybe_initiate_action_have_lock(request=req)
assert mbc._capture_queue == expected_queue, \
f"Unexpected resulting queue from {initial_queue} with {req}"
vectors_maybe_initiate_action_release = {
# key: present queue, value: resulting queue
# action_taken = key[1] != value[1]
#
'CNC': 'CRR',
'CCC': 'CXR',
'CRC': 'CRR',
'CXC': 'CXR',
#
'CNR': 'CRR',
'CCR': 'CXR',
'CRR': 'CRR',
'CXR': 'CXR',
#
'RNC': 'RNR',
'RCC': 'RXR',
'RRC': 'RXR',
'RXC': 'RXR',
#
'RNR': 'RNR',
'RCR': 'RXR',
'RRR': 'RXR',
'RXR': 'RXR',
#
'NNC': 'NRR',
'NCC': 'NXR',
'NRC': 'NRR',
'NXC': 'NXR',
#
'NNR': 'NRR',
'NCR': 'NXR',
'NRR': 'NRR',
'NXR': 'NXR',
#
'CNN': 'CRR',
'CCN': 'CXR',
'CRN': 'CRR',
'CXN': 'CXR',
'RNN': 'RNR',
'RCN': 'RXR',
'RRN': 'RXR',
'RXN': 'RXR',
'NNN': 'NRR',
'NCN': 'NXR',
'NRN': 'NRR',
'NXN': 'NXR',
}
@pytest.mark.asyncio
async def test_maybe_initiate_action_release():
with patch('pyDE1.bledev.managed_bleak_client.ManagedBleakClient'
'._start_request_with_lock',
new_callable=MagicMock) as mock_start_request:
for iq, eq in vectors_maybe_initiate_action_release.items():
initial_queue = cq_from_code(iq)
expected_queue = cq_from_code(eq)
mbc = ManagedBleakClient('No address')
mbc._capture_queue = initial_queue
req = CaptureRequest.RELEASE
async with mbc._capture_queue_lock:
mbc._maybe_initiate_action_have_lock(request=req)
assert mbc._capture_queue == expected_queue, \
f"Unexpected resulting queue from {initial_queue} with {req}"
@pytest.mark.asyncio
async def test_confirm_capture_then_release_requests():
mbc = ManagedBleakClient('No address')
await mbc.request_capture()
assert mbc._capture_queue == cq_from_code('NCC')
await mbc.request_release()
assert mbc._capture_queue == cq_from_code('NXR')
@pytest.mark.asyncio
async def test_done_callback_call_sequence():
mbc = ManagedBleakClient('No address')
event = asyncio.Event()
async def sleepy():
await event.wait()
t = asyncio.create_task(sleepy())
t.add_done_callback(mbc._capture_release_done_callback)
mbc._pending_task = t
assert mbc._pending_task is not None, f"Before event: {mbc._pending_task}"
event.set()
await asyncio.sleep(0.100)
assert mbc._pending_task is None
@pytest.mark.asyncio
async def test_property_mock():
with patch(f"{backend_class_str}.is_connected",
new_callable=PropertyMock) as mock_is_connected:
rv = True # Simple value passed by value
mock_is_connected.return_value = rv
mbc = ManagedBleakClient('No address')
assert mbc.is_connected is True
rv = 'New'
assert mbc.is_connected != 'New'
mock_is_connected.return_value = "Modified"
assert mbc.is_connected == 'Modified'
mbcic = mbc.is_connected
assert (
(isinstance(mbcic, BaseBleakClient._DeprecatedIsConnectedReturn)
and not mbcic)
or mbcic is False
), "Returns wrapper _DeprecatedIsConnectedReturn at least through v0.18.1"
def test_retry_delay():
"""
Checks internal logic, does not check assigned parameters
"""
mbc = ManagedBleakClient('No address')
mbc._retry_start_initial_delay = 10
mbc._retry_initial_delay = 11
mbc._retry_start_long_delay = 20
mbc._retry_long_delay = 22
mbc._retry_since = None
assert mbc._retry_delay() == 0
mbc._retry_since = time.time()
assert mbc._retry_delay() == 0
mbc._retry_since = time.time() - 1
assert mbc._retry_delay() == 0
mbc._retry_since = time.time() - 12
assert mbc._retry_delay() == 11
mbc._retry_since = time.time() - 21
assert mbc._retry_delay() == 22
async def check_retry_delay(client: ManagedBleakClient,
retry_delay: Optional[float]):
two_minutes = 120 # A somewhat arbitrary amount of time
an_hour = 7200 # An even more arbitrary amount of time
async with client._capture_queue_lock:
cq = client._capture_queue
assert not (
retry_delay is None
and client._capture_queue.pending
is CaptureRequest.CAPTURE), \
"None is not a valid retry_delay for CAPTURE"
if (p := client._capture_queue.pending) is not CaptureRequest.CAPTURE:
assert not client._retry_wait_event.is_set(), \
f"{p}: Expected wait event not set {cq}"
assert client._retry_wait_task is None, \
f"{p}: Expected no wait task {cq}"
assert client._retry_since is None, \
f"{p}: Expected _retry_since is None {cq}"
assert not client._retry_is_active, \
f"{p}: Expected _retry_is_active to be False {cq}"
else: # CaptureRequest.CAPTURE pending from here on
assert client._retry_since is not None, \
f"Active: Expected there is started time {cq}"
assert client._retry_is_active, \
f"Active: Expected _retry_is_active {cq}"
if retry_delay == 0:
ds = 'Zero delay'
assert client._retry_wait_event.is_set(), \
f"{ds}: Expected wait event is set {cq}"
assert client._retry_wait_task is None, \
f"{ds}: Expected no wait task {cq}"
else:
ds = f"Delay of {retry_delay}"
assert not client._retry_wait_event.is_set(), \
f"{ds}: Expected wait event is not set {cq}"
assert client._retry_wait_task is not None, \
f"{ds}: Expected there is a wait task {cq}"
# Will need to mock the backend, but it is dynamically determined
# Remember to patch the disconnected_callback call
PBC = get_platform_client_backend_type()
backend_class_str = f"{PBC.__module__}.{PBC.__qualname__}"
@pytest.mark.asyncio
async def test_connect_sequence():
with \
patch(f"{backend_class_str}.is_connected",
new_callable=PropertyMock) as mock_is_connected, \
patch(f"{backend_class_str}.connect",
new_callable=AsyncMock) as mock_connect, \
patch(f"{backend_class_str}.disconnect",
new_callable=AsyncMock) as mock_disconnect:
mock_is_connected.return_value = False
turnstile_connect = asyncio.Event()
turnstile_disconnect = asyncio.Event()
logger=logging.getLogger('test_connect_sequence')
async def mock_connect_side_effect(**kwargs):
try:
await turnstile_connect.wait()
turnstile_connect.clear()
except Exception:
turnstile_connect.clear()
raise
logger.warning('Setting is_connected = True')
mock_is_connected.return_value = True
return True # As with the original backend implementation
async def mock_disconnect_side_effect():
try:
await turnstile_disconnect.wait()
turnstile_disconnect.clear()
except Exception:
turnstile_disconnect.clear()
raise
# TODO: Is this backend agnostic?
if mbc._backend._disconnected_callback is not None:
mbc._backend._disconnected_callback(mbc)
logger.warning('Setting is_connected = False')
mock_is_connected.return_value = False
return True # As with the original backend implementation
mock_connect.side_effect = mock_connect_side_effect
mock_disconnect.side_effect = mock_disconnect_side_effect
loop = asyncio.get_running_loop()
mbc = ManagedBleakClient('No address')
mbc.test_underway = 'Fresh'
assert not mbc.is_connected
assert not mbc.is_captured
assert not mbc.is_released, 'Before first capture, not is_released'
assert mbc._capture_queue == cq_from_code('NNN')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
# Release from fresh
mbc.test_underway = 'Release from fresh'
assert mbc._retry_wait_task is None
loop.call_later(0.1, turnstile_disconnect.set)
await asyncio.wait_for(mbc.release(), 10)
assert not mbc.is_connected
assert not mbc.is_captured
assert mbc.is_released
assert mbc._capture_queue == cq_from_code('RNR')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
assert mock_is_connected.return_value is False
# Capture from release
mbc.test_underway = 'Capture'
loop.call_later(0.1, turnstile_connect.set)
await asyncio.wait_for(mbc.capture(), 10)
assert mbc.is_connected
assert mbc.is_captured
assert not mbc.is_released
assert mbc._capture_queue == cq_from_code('CNC')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
# Now cause a disconnect and confirm that it reconnects
mbc.test_underway = 'Disconnect "forced" from captured'
assert mbc._retry_wait_task is None
turnstile_disconnect.set()
# turnstile_connect.set()
await mbc._backend.disconnect()
await asyncio.sleep(0.100)
assert not mbc.is_connected
assert not mbc.is_captured
# As pending, not "released" yet
assert not mbc.is_released
assert mbc._capture_queue == cq_from_code('RCC')
assert not mbc.event_no_pending.is_set()
assert mbc.connectivity_task_pending
await check_retry_delay(mbc, 0)
# wait for reconnect
mbc.test_underway = 'Expect capture after disconnect'
turnstile_connect.set()
await asyncio.sleep(0.100)
assert mbc.is_connected
assert mbc.is_captured
assert not mbc.is_released
assert mbc._capture_queue == cq_from_code('CNC')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
# Now release from captured
mbc.test_underway = 'Release'
turnstile_connect.set()
turnstile_disconnect.set()
await mbc.release()
await asyncio.sleep(0.100)
assert not mbc.is_connected
assert not mbc.is_captured
assert mbc.is_released
assert mbc._capture_queue == cq_from_code('RNR')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
turnstile_connect.set()
turnstile_disconnect.set()
await asyncio.sleep(0.100)
assert not mbc.is_connected
assert not mbc.is_captured
assert mbc.is_released
assert mbc._capture_queue == cq_from_code('RNR')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
@pytest.mark.asyncio
async def test_connect_sequence_with_retry(monkeypatch):
target_class = bleak.get_platform_client_backend_type()
mock_is_connected = None
turnstile_connect = asyncio.Event()
do_connect = True
turnstile_disconnect = asyncio.Event()
task_completed_event = asyncio.Event()
async def mock_connect(*args, **kwargs):
nonlocal mock_is_connected
try:
await turnstile_connect.wait()
turnstile_connect.clear()
if do_connect:
mock_is_connected = True
except asyncio.CancelledError:
turnstile_connect.clear()
return True # As with the original backend implementation
monkeypatch.setattr(target_class,'connect',
mock_connect)
async def mock_disconnect(*args, **kwargs):
nonlocal mock_is_connected
try:
await turnstile_disconnect.wait()
turnstile_disconnect.clear()
if mbc._backend._disconnected_callback is not None:
mbc._backend._disconnected_callback(mbc)
mock_is_connected = False
except asyncio.CancelledError:
turnstile_disconnect.clear()
return True # As with the original backend implementation
monkeypatch.setattr(target_class,'disconnect',
mock_disconnect)
def mock_is_connected_getter(*args, **kwargs):
nonlocal mock_is_connected
return mock_is_connected
monkeypatch.setattr(target_class, 'is_connected',
property(fget=mock_is_connected_getter))
# Done patching
loop = asyncio.get_running_loop()
mbc = ManagedBleakClient('No address')
# Wrap the generated done callback
_original_cr_done_cb = mbc._capture_release_done_callback
def _cr_done_cb_wrapper(*args, **kwargs):
task_completed_event.set()
_original_cr_done_cb(*args, **kwargs)
mbc._capture_release_done_callback = _cr_done_cb_wrapper
test_underway = 'Fresh'
assert not mbc.is_connected
assert not mbc.is_captured
assert not mbc.is_released, 'Before first capture, not is_released'
assert mbc._capture_queue == cq_from_code('NNN')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
# Release from fresh
test_underway = 'Release from fresh'
assert mbc._retry_wait_task is None
loop.call_later(0.1, turnstile_disconnect.set)
await mbc.request_release()
try:
await asyncio.wait_for(task_completed_event.wait(), 2)
except TimeoutError:
raise
task_completed_event.clear()
assert not mbc.is_connected
assert not mbc.is_captured
assert mbc.is_released
assert mbc._capture_queue == cq_from_code('RNR')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
assert mock_is_connected is False
# Capture from release
test_underway = 'Capture fail'
do_connect = False
await mbc.request_capture()
for cnt in range(0, 5):
loop.call_later(0.1, turnstile_connect.set)
try:
await asyncio.wait_for(task_completed_event.wait(), 2)
except TimeoutError:
raise
task_completed_event.clear()
assert not mbc.is_connected
assert not mbc.is_captured
# As pending, not "released" yet
assert not mbc.is_released
assert mbc._capture_queue == cq_from_code('RCC')
assert not mbc.event_no_pending.is_set()
assert mbc.connectivity_task_pending
await check_retry_delay(mbc, 0)
do_connect = True
loop.call_later(0.1, turnstile_connect.set)
try:
await asyncio.wait_for(task_completed_event.wait(), 2)
except TimeoutError:
raise
task_completed_event.clear()
assert mbc.is_connected
assert mbc.is_captured
assert not mbc.is_released
assert mbc._capture_queue == cq_from_code('CNC')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
@pytest.mark.asyncio
async def test_retry_fallback(monkeypatch):
target_class = bleak.get_platform_client_backend_type()
mock_is_connected = None
turnstile_connect = asyncio.Event()
do_connect = True
turnstile_disconnect = asyncio.Event()
task_completed_event = asyncio.Event()
async def mock_connect(*args, **kwargs):
nonlocal mock_is_connected
try:
await turnstile_connect.wait()
turnstile_connect.clear()
if do_connect:
mock_is_connected = True
except asyncio.CancelledError:
turnstile_connect.clear()
return True # As with the original backend implementation
monkeypatch.setattr(target_class,
'connect',
mock_connect)
async def mock_disconnect(*args, **kwargs):
nonlocal mock_is_connected
try:
await turnstile_disconnect.wait()
turnstile_disconnect.clear()
if mbc._backend._disconnected_callback is not None:
mbc._backend._disconnected_callback(mbc)
mock_is_connected = False
except asyncio.CancelledError:
turnstile_disconnect.clear()
return True # As with the original backend implementation
monkeypatch.setattr(target_class, 'disconnect',
mock_disconnect)
def mock_is_connected_getter(*args, **kwargs):
nonlocal mock_is_connected
return mock_is_connected
monkeypatch.setattr(target_class, 'is_connected',
property(fget=mock_is_connected_getter))
# Done patching
mock_cb = MagicMock()
mock_cb.__name__ = 'mock_cb'
loop = asyncio.get_running_loop()
mbc = ManagedBleakClient('No address',
on_change_callback=mock_cb)
# Wrap the generated done callback
_original_cr_done_cb = mbc._capture_release_done_callback
def _cr_done_cb_wrapper(*args, **kwargs):
task_completed_event.set()
_original_cr_done_cb(*args, **kwargs)
mbc._capture_release_done_callback = _cr_done_cb_wrapper
# Adjust the fall-back times
initial_delay = 0.3
long_delay = 0.4
mbc._retry_initial_delay = initial_delay
mbc._retry_long_delay = long_delay
test_underway = 'Fresh'
assert not mbc.is_connected
assert not mbc.is_captured
assert not mbc.is_released, 'Before first capture, not is_released'
assert mbc._capture_queue == cq_from_code('NNN')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
# Release from fresh
test_underway = 'Release from fresh'
assert mbc._retry_wait_task is None
loop.call_later(0.1, turnstile_disconnect.set)
await mbc.request_release()
try:
await asyncio.wait_for(task_completed_event.wait(), 2)
except TimeoutError:
raise
task_completed_event.clear()
assert not mbc.is_connected
assert not mbc.is_captured
assert mbc.is_released
assert mbc._capture_queue == cq_from_code('RNR')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
assert mock_is_connected is False
# Capture from release
test_underway = 'Capture fail'
do_connect = False
t0 = time.time()
await mbc.request_capture()
await asyncio.sleep(0.100)
assert mbc._pending_task is not None
assert mbc._retry_since is not None
t_since = mbc._retry_since
assert mbc._retry_since > t0
test_underway = 'Capture fail: no delay'
for cnt in range(0, 2):
assert mbc._retry_since == t_since
assert not mbc._retry_delay()
loop.call_later(0.1, turnstile_connect.set)
try:
await asyncio.wait_for(task_completed_event.wait(), 2)
except TimeoutError:
raise
task_completed_event.clear()
assert not mbc.is_connected
assert not mbc.is_captured
# As pending, not "released" yet
assert not mbc.is_released
assert mbc._capture_queue == cq_from_code('RCC')
assert not mbc.event_no_pending.is_set()
assert mbc.connectivity_task_pending
await check_retry_delay(mbc, 0)
test_underway = 'Capture fail: initial delay'
mbc._retry_since = time.time() - mbc._retry_start_initial_delay
for cnt in range(0, 2):
assert mbc._retry_delay() == initial_delay
loop.call_later(0.1, turnstile_connect.set)
try:
await asyncio.wait_for(task_completed_event.wait(), 2)
except TimeoutError:
pass
task_completed_event.clear()
assert not mbc.is_connected
assert not mbc.is_captured
# As pending, not "released" yet
assert not mbc.is_released
assert mbc._capture_queue == cq_from_code('RCC')
assert not mbc.event_no_pending.is_set()
assert mbc.connectivity_task_pending
await check_retry_delay(mbc, mbc._retry_initial_delay)
test_underway = 'Capture fail: long delay'
mbc._retry_since = time.time() - mbc._retry_start_long_delay
for cnt in range(0, 2):
assert mbc._retry_delay() == long_delay
loop.call_later(0.1, turnstile_connect.set)
try:
await asyncio.wait_for(task_completed_event.wait(), 2)
except TimeoutError:
pass
task_completed_event.clear()
assert not mbc.is_connected
assert not mbc.is_captured
# As pending, not "released" yet
assert not mbc.is_released
assert mbc._capture_queue == cq_from_code('RCC')
assert not mbc.event_no_pending.is_set()
assert mbc.connectivity_task_pending
await check_retry_delay(
mbc, mbc._retry_long_delay if cnt else mbc._retry_initial_delay)
test_underway = 'Capture fail: allow connect'
do_connect = True
loop.call_later(0.1, turnstile_connect.set)
try:
await asyncio.wait_for(task_completed_event.wait(), 2)
except TimeoutError:
raise
task_completed_event.clear()
assert mbc.is_connected
assert mbc.is_captured
assert not mbc.is_released
assert mbc._capture_queue == cq_from_code('CNC')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
# This is completely bogus
# assert mock_cb.call_count == 18
check_against = ['NNN',
'NNN', 'NRR', 'RRR', 'RXR', 'RNR',
'RCC', 'RNC', 'RCC', 'RNC', 'RCC',
'RNC', 'RCC', 'RNC', 'RCC', 'RNC',
'RCC', 'RNC', 'RCC', 'CNC']
assert mock_cb_to_checklist(mock_cb) == check_against
def mock_cb_to_checklist(mcb: MagicMock) -> list:
"""
For a mock called with (any, previous: CaptureQueue, new: CaptureQueue)
returns a list of the CaptureQueue "codes"
including the original value and then each new value
"""
retval = [cq_to_code(mcb.call_args_list[0].args[1])]
for ca in mcb.call_args_list:
retval.append(cq_to_code(ca.args[2]))
return retval
def assert_captured(client: ManagedBleakClient):
assert client._backend.is_connected
assert client.is_connected
assert client.is_captured
assert not client.is_released
assert client._capture_queue == cq_from_code('CNC')
assert client.event_no_pending.is_set()
assert not client.connectivity_task_pending
def assert_released(client: ManagedBleakClient):
assert not client._backend.is_connected
assert not client.is_connected
assert not client.is_captured
assert client.is_released
assert client._capture_queue == cq_from_code('RNR')
assert client.event_no_pending.is_set()
assert not client.connectivity_task_pending
def assert_initial(client: ManagedBleakClient):
assert not client._backend.is_connected
assert not client.is_connected
assert not client.is_captured
assert not client.is_released
assert client._capture_queue == cq_from_code('NNN')
assert client.event_no_pending.is_set()
assert not client.connectivity_task_pending
assert client._retry_since is None
assert not client._retry_wait_event.is_set()
@pytest.mark.asyncio
async def test_legacy_disconnected_callback(monkeypatch):
target_class = bleak.get_platform_client_backend_type()
mock_is_connected = None
turnstile_connect = asyncio.Event()
do_connect = True
turnstile_disconnect = asyncio.Event()
task_completed_event = asyncio.Event()
async def mock_connect(*args, **kwargs):
nonlocal mock_is_connected
try:
await turnstile_connect.wait()
turnstile_connect.clear()
if do_connect:
mock_is_connected = True
except asyncio.CancelledError:
turnstile_connect.clear()
return True # As with the original backend implementation
monkeypatch.setattr(target_class, 'connect',
mock_connect)
async def mock_disconnect(*args, **kwargs):
nonlocal mock_is_connected
try:
await turnstile_disconnect.wait()
turnstile_disconnect.clear()
if mbc._backend._disconnected_callback is not None:
mbc._backend._disconnected_callback(mbc)
mock_is_connected = False
except asyncio.CancelledError:
turnstile_disconnect.clear()
return True # As with the original backend implementation
monkeypatch.setattr(target_class, 'disconnect',
mock_disconnect)
def mock_is_connected_getter(*args, **kwargs):
nonlocal mock_is_connected
return mock_is_connected
monkeypatch.setattr(target_class, 'is_connected',
property(fget=mock_is_connected_getter))
dcb_mock0 = MagicMock()
dcb_mock1 = MagicMock()
# Done patching
loop = asyncio.get_running_loop()
mbc = ManagedBleakClient('No address',
disconnected_callback=dcb_mock0)
test_underway = 'Fresh'
dcb_mock0.assert_not_called()
assert not mbc.is_connected
assert not mbc.is_captured
assert not mbc.is_released, 'Before first capture, not is_released'
assert mbc._capture_queue == cq_from_code('NNN')
assert mbc.event_no_pending.is_set()
assert not mbc.connectivity_task_pending
await check_retry_delay(mbc, None)
dcb_mock0.assert_not_called()
# Release from fresh
test_underway = 'Release from fresh'
assert not mbc._backend.is_connected
assert mbc._retry_wait_task is None
turnstile_disconnect.set()
turnstile_connect.set()
await mbc.request_release()
try:
await asyncio.wait_for(mbc.event_released.wait(), 2)