-
Notifications
You must be signed in to change notification settings - Fork 219
/
test_asyncio.py
1337 lines (1104 loc) · 44.6 KB
/
test_asyncio.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
#!/usr/bin/env python
"""Unit tests for aio.py."""
import asyncio
import logging
import os
import socket
import threading
import time
from unittest.mock import ANY, call, patch
import pytest
import zeroconf._services.browser as _services_browser
from zeroconf import (
DNSAddress,
DNSIncoming,
DNSOutgoing,
DNSPointer,
DNSQuestion,
DNSService,
DNSText,
NotRunningException,
ServiceStateChange,
Zeroconf,
const,
)
from zeroconf._exceptions import (
BadTypeInNameException,
NonUniqueNameException,
ServiceNameAlreadyRegistered,
)
from zeroconf._services import ServiceListener
from zeroconf._services.info import ServiceInfo
from zeroconf._utils.time import current_time_millis
from zeroconf.asyncio import (
AsyncServiceBrowser,
AsyncServiceInfo,
AsyncZeroconf,
AsyncZeroconfServiceTypes,
)
from zeroconf.const import _LISTENER_TIME
from . import _clear_cache, has_working_ipv6
log = logging.getLogger('zeroconf')
original_logging_level = logging.NOTSET
def setup_module():
global original_logging_level
original_logging_level = log.level
log.setLevel(logging.DEBUG)
def teardown_module():
if original_logging_level != logging.NOTSET:
log.setLevel(original_logging_level)
@pytest.fixture(autouse=True)
def verify_threads_ended():
"""Verify that the threads are not running after the test."""
threads_before = frozenset(threading.enumerate())
yield
threads_after = frozenset(threading.enumerate())
non_executor_threads = frozenset(
thread
for thread in threads_after
if "asyncio" not in thread.name and "ThreadPoolExecutor" not in thread.name
)
threads = non_executor_threads - threads_before
assert not threads
@pytest.mark.asyncio
async def test_async_basic_usage() -> None:
"""Test we can create and close the instance."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
await aiozc.async_close()
@pytest.mark.asyncio
async def test_async_close_twice() -> None:
"""Test we can close twice."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
await aiozc.async_close()
await aiozc.async_close()
@pytest.mark.asyncio
async def test_async_with_sync_passed_in() -> None:
"""Test we can create and close the instance when passing in a sync Zeroconf."""
zc = Zeroconf(interfaces=['127.0.0.1'])
aiozc = AsyncZeroconf(zc=zc)
assert aiozc.zeroconf is zc
await aiozc.async_close()
@pytest.mark.asyncio
async def test_async_with_sync_passed_in_closed_in_async() -> None:
"""Test caller closes the sync version in async."""
zc = Zeroconf(interfaces=['127.0.0.1'])
aiozc = AsyncZeroconf(zc=zc)
assert aiozc.zeroconf is zc
zc.close()
await aiozc.async_close()
@pytest.mark.asyncio
async def test_sync_within_event_loop_executor() -> None:
"""Test sync version still works from an executor within an event loop."""
def sync_code():
zc = Zeroconf(interfaces=['127.0.0.1'])
assert zc.get_service_info("_neverused._tcp.local.", "xneverused._neverused._tcp.local.", 10) is None
zc.close()
await asyncio.get_event_loop().run_in_executor(None, sync_code)
@pytest.mark.asyncio
async def test_async_service_registration() -> None:
"""Test registering services broadcasts the registration by default."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test1-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = f"{name}.{type_}"
calls = []
class MyListener(ServiceListener):
def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("add", type, name))
def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("remove", type, name))
def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("update", type, name))
listener = MyListener()
aiozc.zeroconf.add_service_listener(type_, listener)
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
task = await aiozc.async_register_service(info)
await task
new_info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.3")],
)
task = await aiozc.async_update_service(new_info)
await task
task = await aiozc.async_unregister_service(new_info)
await task
await aiozc.async_close()
assert calls == [
('add', type_, registration_name),
('update', type_, registration_name),
('remove', type_, registration_name),
]
@pytest.mark.asyncio
async def test_async_service_registration_with_server_missing() -> None:
"""Test registering a service with the server not specified.
For backwards compatibility, the server should be set to the
name that was passed in.
"""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test1-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = f"{name}.{type_}"
calls = []
class MyListener(ServiceListener):
def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("add", type, name))
def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("remove", type, name))
def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("update", type, name))
listener = MyListener()
aiozc.zeroconf.add_service_listener(type_, listener)
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
addresses=[socket.inet_aton("10.0.1.2")],
)
task = await aiozc.async_register_service(info)
await task
assert info.server == registration_name
assert info.server_key == registration_name
new_info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.3")],
)
task = await aiozc.async_update_service(new_info)
await task
task = await aiozc.async_unregister_service(new_info)
await task
await aiozc.async_close()
assert calls == [
('add', type_, registration_name),
('update', type_, registration_name),
('remove', type_, registration_name),
]
@pytest.mark.asyncio
async def test_async_service_registration_same_server_different_ports() -> None:
"""Test registering services with the same server with different srv records."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test1-srvc-type._tcp.local."
name = "xxxyyy"
name2 = "xxxyyy2"
registration_name = f"{name}.{type_}"
registration_name2 = f"{name2}.{type_}"
calls = []
class MyListener(ServiceListener):
def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("add", type, name))
def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("remove", type, name))
def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("update", type, name))
listener = MyListener()
aiozc.zeroconf.add_service_listener(type_, listener)
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
info2 = ServiceInfo(
type_,
registration_name2,
81,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
tasks = []
tasks.append(await aiozc.async_register_service(info))
tasks.append(await aiozc.async_register_service(info2))
await asyncio.gather(*tasks)
task = await aiozc.async_unregister_service(info)
await task
entries = aiozc.zeroconf.cache.async_entries_with_server("ash-2.local.")
assert len(entries) == 1
assert info2.dns_service() in entries
await aiozc.async_close()
assert calls == [
('add', type_, registration_name),
('add', type_, registration_name2),
('remove', type_, registration_name),
('remove', type_, registration_name2),
]
@pytest.mark.asyncio
async def test_async_service_registration_same_server_same_ports() -> None:
"""Test registering services with the same server with the exact same srv record."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test1-srvc-type._tcp.local."
name = "xxxyyy"
name2 = "xxxyyy2"
registration_name = f"{name}.{type_}"
registration_name2 = f"{name2}.{type_}"
calls = []
class MyListener(ServiceListener):
def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("add", type, name))
def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("remove", type, name))
def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("update", type, name))
listener = MyListener()
aiozc.zeroconf.add_service_listener(type_, listener)
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
info2 = ServiceInfo(
type_,
registration_name2,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
tasks = []
tasks.append(await aiozc.async_register_service(info))
tasks.append(await aiozc.async_register_service(info2))
await asyncio.gather(*tasks)
task = await aiozc.async_unregister_service(info)
await task
entries = aiozc.zeroconf.cache.async_entries_with_server("ash-2.local.")
assert len(entries) == 1
assert info2.dns_service() in entries
await aiozc.async_close()
assert calls == [
('add', type_, registration_name),
('add', type_, registration_name2),
('remove', type_, registration_name),
('remove', type_, registration_name2),
]
@pytest.mark.asyncio
async def test_async_service_registration_name_conflict() -> None:
"""Test registering services throws on name conflict."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test-srvc2-type._tcp.local."
name = "xxxyyy"
registration_name = f"{name}.{type_}"
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
task = await aiozc.async_register_service(info)
await task
with pytest.raises(NonUniqueNameException):
task = await aiozc.async_register_service(info)
await task
with pytest.raises(ServiceNameAlreadyRegistered):
task = await aiozc.async_register_service(info, cooperating_responders=True)
await task
conflicting_info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-3.local.",
addresses=[socket.inet_aton("10.0.1.3")],
)
with pytest.raises(NonUniqueNameException):
task = await aiozc.async_register_service(conflicting_info)
await task
await aiozc.async_close()
@pytest.mark.asyncio
async def test_async_service_registration_name_does_not_match_type() -> None:
"""Test registering services throws when the name does not match the type."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test-srvc3-type._tcp.local."
name = "xxxyyy"
registration_name = f"{name}.{type_}"
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
info.type = "_wrong._tcp.local."
with pytest.raises(BadTypeInNameException):
task = await aiozc.async_register_service(info)
await task
await aiozc.async_close()
@pytest.mark.asyncio
async def test_async_service_registration_name_strict_check() -> None:
"""Test registering services throws when the name does not comply."""
zc = Zeroconf(interfaces=['127.0.0.1'])
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_ibisip_http._tcp.local."
name = "CustomerInformationService-F4D4895E9EEB"
registration_name = f"{name}.{type_}"
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
with pytest.raises(BadTypeInNameException):
await zc.async_check_service(info, allow_name_change=False)
with pytest.raises(BadTypeInNameException):
task = await aiozc.async_register_service(info)
await task
await zc.async_check_service(info, allow_name_change=False, strict=False)
task = await aiozc.async_register_service(info, strict=False)
await task
await aiozc.async_unregister_service(info)
await aiozc.async_close()
@pytest.mark.asyncio
async def test_async_tasks() -> None:
"""Test awaiting broadcast tasks"""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test-srvc4-type._tcp.local."
name = "xxxyyy"
registration_name = f"{name}.{type_}"
calls = []
class MyListener(ServiceListener):
def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("add", type, name))
def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("remove", type, name))
def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
calls.append(("update", type, name))
listener = MyListener()
aiozc.zeroconf.add_service_listener(type_, listener)
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
task = await aiozc.async_register_service(info)
assert isinstance(task, asyncio.Task)
await task
new_info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.3")],
)
task = await aiozc.async_update_service(new_info)
assert isinstance(task, asyncio.Task)
await task
task = await aiozc.async_unregister_service(new_info)
assert isinstance(task, asyncio.Task)
await task
await aiozc.async_close()
assert calls == [
('add', type_, registration_name),
('update', type_, registration_name),
('remove', type_, registration_name),
]
@pytest.mark.asyncio
async def test_async_wait_unblocks_on_update() -> None:
"""Test async_wait will unblock on update."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test-srvc4-type._tcp.local."
name = "xxxyyy"
registration_name = f"{name}.{type_}"
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
task = await aiozc.async_register_service(info)
# Should unblock due to update from the
# registration
now = current_time_millis()
await aiozc.zeroconf.async_wait(50000)
assert current_time_millis() - now < 3000
await task
now = current_time_millis()
await aiozc.zeroconf.async_wait(50)
assert current_time_millis() - now < 1000
await aiozc.async_close()
@pytest.mark.asyncio
async def test_service_info_async_request() -> None:
"""Test registering services broadcasts and query with AsyncServceInfo.async_request."""
if not has_working_ipv6() or os.environ.get('SKIP_IPV6'):
pytest.skip('Requires IPv6')
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test1-srvc-type._tcp.local."
name = "xxxyyy"
name2 = "abc"
registration_name = f"{name}.{type_}"
registration_name2 = f"{name2}.{type_}"
# Start a tasks BEFORE the registration that will keep trying
# and see the registration a bit later
get_service_info_task1 = asyncio.ensure_future(aiozc.async_get_service_info(type_, registration_name))
await asyncio.sleep(_LISTENER_TIME / 1000 / 2)
get_service_info_task2 = asyncio.ensure_future(aiozc.async_get_service_info(type_, registration_name))
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-1.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
info2 = ServiceInfo(
type_,
registration_name2,
80,
0,
0,
desc,
"ash-5.local.",
addresses=[socket.inet_aton("10.0.1.5")],
)
tasks = []
tasks.append(await aiozc.async_register_service(info))
tasks.append(await aiozc.async_register_service(info2))
await asyncio.gather(*tasks)
aiosinfo = await get_service_info_task1
assert aiosinfo is not None
assert aiosinfo.addresses == [socket.inet_aton("10.0.1.2")]
aiosinfo = await get_service_info_task2
assert aiosinfo is not None
assert aiosinfo.addresses == [socket.inet_aton("10.0.1.2")]
aiosinfo = await aiozc.async_get_service_info(type_, registration_name)
assert aiosinfo is not None
assert aiosinfo.addresses == [socket.inet_aton("10.0.1.2")]
new_info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.3"), socket.inet_pton(socket.AF_INET6, "6001:db8::1")],
)
task = await aiozc.async_update_service(new_info)
await task
aiosinfo = await aiozc.async_get_service_info(type_, registration_name)
assert aiosinfo is not None
assert aiosinfo.addresses == [socket.inet_aton("10.0.1.3")]
aiosinfos = await asyncio.gather(
aiozc.async_get_service_info(type_, registration_name),
aiozc.async_get_service_info(type_, registration_name2),
)
assert aiosinfos[0] is not None
assert aiosinfos[0].addresses == [socket.inet_aton("10.0.1.3")]
assert aiosinfos[1] is not None
assert aiosinfos[1].addresses == [socket.inet_aton("10.0.1.5")]
aiosinfo = AsyncServiceInfo(type_, registration_name)
_clear_cache(aiozc.zeroconf)
# Generating the race condition is almost impossible
# without patching since its a TOCTOU race
with patch("zeroconf.asyncio.AsyncServiceInfo._is_complete", False):
await aiosinfo.async_request(aiozc.zeroconf, 3000)
assert aiosinfo is not None
assert aiosinfo.addresses == [socket.inet_aton("10.0.1.3")]
task = await aiozc.async_unregister_service(new_info)
await task
aiosinfo = await aiozc.async_get_service_info(type_, registration_name)
assert aiosinfo is None
await aiozc.async_close()
@pytest.mark.asyncio
async def test_async_service_browser() -> None:
"""Test AsyncServiceBrowser."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test9-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = f"{name}.{type_}"
calls = []
class MyListener(ServiceListener):
def add_service(self, aiozc: Zeroconf, type: str, name: str) -> None:
calls.append(("add", type, name))
def remove_service(self, aiozc: Zeroconf, type: str, name: str) -> None:
calls.append(("remove", type, name))
def update_service(self, aiozc: Zeroconf, type: str, name: str) -> None:
calls.append(("update", type, name))
listener = MyListener()
await aiozc.async_add_service_listener(type_, listener)
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
task = await aiozc.async_register_service(info)
await task
new_info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.3")],
)
task = await aiozc.async_update_service(new_info)
await task
task = await aiozc.async_unregister_service(new_info)
await task
await aiozc.zeroconf.async_wait(1)
await aiozc.async_close()
assert calls == [
('add', type_, registration_name),
('update', type_, registration_name),
('remove', type_, registration_name),
]
@pytest.mark.asyncio
async def test_async_context_manager() -> None:
"""Test using an async context manager."""
type_ = "_test10-sr-type._tcp.local."
name = "xxxyyy"
registration_name = f"{name}.{type_}"
async with AsyncZeroconf(interfaces=['127.0.0.1']) as aiozc:
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
{'path': '/~paulsm/'},
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
task = await aiozc.async_register_service(info)
await task
aiosinfo = await aiozc.async_get_service_info(type_, registration_name)
assert aiosinfo is not None
@pytest.mark.asyncio
async def test_async_unregister_all_services() -> None:
"""Test unregistering all services."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
type_ = "_test1-srvc-type._tcp.local."
name = "xxxyyy"
name2 = "abc"
registration_name = f"{name}.{type_}"
registration_name2 = f"{name2}.{type_}"
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-1.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
info2 = ServiceInfo(
type_,
registration_name2,
80,
0,
0,
desc,
"ash-5.local.",
addresses=[socket.inet_aton("10.0.1.5")],
)
tasks = []
tasks.append(await aiozc.async_register_service(info))
tasks.append(await aiozc.async_register_service(info2))
await asyncio.gather(*tasks)
tasks = []
tasks.append(aiozc.async_get_service_info(type_, registration_name))
tasks.append(aiozc.async_get_service_info(type_, registration_name2))
results = await asyncio.gather(*tasks)
assert results[0] is not None
assert results[1] is not None
await aiozc.async_unregister_all_services()
_clear_cache(aiozc.zeroconf)
tasks = []
tasks.append(aiozc.async_get_service_info(type_, registration_name))
tasks.append(aiozc.async_get_service_info(type_, registration_name2))
results = await asyncio.gather(*tasks)
assert results[0] is None
assert results[1] is None
# Verify we can call again
await aiozc.async_unregister_all_services()
await aiozc.async_close()
@pytest.mark.asyncio
async def test_async_zeroconf_service_types():
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = f"{name}.{type_}"
zeroconf_registrar = AsyncZeroconf(interfaces=['127.0.0.1'])
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
task = await zeroconf_registrar.async_register_service(info)
await task
# Ensure we do not clear the cache until after the last broadcast is processed
await asyncio.sleep(0.2)
_clear_cache(zeroconf_registrar.zeroconf)
try:
service_types = await AsyncZeroconfServiceTypes.async_find(interfaces=['127.0.0.1'], timeout=2)
assert type_ in service_types
_clear_cache(zeroconf_registrar.zeroconf)
service_types = await AsyncZeroconfServiceTypes.async_find(aiozc=zeroconf_registrar, timeout=2)
assert type_ in service_types
finally:
await zeroconf_registrar.async_close()
@pytest.mark.asyncio
async def test_guard_against_running_serviceinfo_request_event_loop() -> None:
"""Test that running ServiceInfo.request from the event loop throws."""
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
service_info = AsyncServiceInfo("_hap._tcp.local.", "doesnotmatter._hap._tcp.local.")
with pytest.raises(RuntimeError):
service_info.request(aiozc.zeroconf, 3000)
await aiozc.async_close()
@pytest.mark.asyncio
async def test_service_browser_instantiation_generates_add_events_from_cache():
"""Test that the ServiceBrowser will generate Add events with the existing cache when starting."""
# instantiate a zeroconf instance
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
zc = aiozc.zeroconf
type_ = "_hap._tcp.local."
registration_name = "xxxyyy.%s" % type_
callbacks = []
class MyServiceListener(ServiceListener):
def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def]
nonlocal callbacks
if name == registration_name:
callbacks.append(("add", type_, name))
def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def]
nonlocal callbacks
if name == registration_name:
callbacks.append(("remove", type_, name))
def update_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def]
nonlocal callbacks
if name == registration_name:
callbacks.append(("update", type_, name))
listener = MyServiceListener()
desc = {'path': '/~paulsm/'}
address_parsed = "10.0.1.2"
address = socket.inet_aton(address_parsed)
info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address])
zc.cache.async_add_records(
[info.dns_pointer(), info.dns_service(), *info.dns_addresses(), info.dns_text()]
)
browser = AsyncServiceBrowser(zc, type_, None, listener)
await asyncio.sleep(0)
assert callbacks == [
('add', type_, registration_name),
]
await browser.async_cancel()
await aiozc.async_close()
@pytest.mark.asyncio
async def test_integration():
service_added = asyncio.Event()
service_removed = asyncio.Event()
unexpected_ttl = asyncio.Event()
got_query = asyncio.Event()
type_ = "_http._tcp.local."
registration_name = "xxxyyy.%s" % type_
def on_service_state_change(zeroconf, service_type, state_change, name):
if name == registration_name:
if state_change is ServiceStateChange.Added:
service_added.set()
elif state_change is ServiceStateChange.Removed:
service_removed.set()
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
zeroconf_browser = aiozc.zeroconf
await zeroconf_browser.async_wait_for_start()
# we are going to patch the zeroconf send to check packet sizes
old_send = zeroconf_browser.async_send
time_offset = 0.0
def _new_current_time_millis():
"""Current system time in milliseconds"""
return (time.monotonic() * 1000) + (time_offset * 1000)
expected_ttl = const._DNS_HOST_TTL
nbr_answers = 0
def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()):
"""Sends an outgoing packet."""
pout = DNSIncoming(out.packets()[0])
nonlocal nbr_answers
for answer in pout.answers:
nbr_answers += 1
if not answer.ttl > expected_ttl / 2:
unexpected_ttl.set()
got_query.set()
old_send(out, addr=addr, port=port, v6_flow_scope=v6_flow_scope)
assert len(zeroconf_browser.engine.protocols) == 2
aio_zeroconf_registrar = AsyncZeroconf(interfaces=['127.0.0.1'])
zeroconf_registrar = aio_zeroconf_registrar.zeroconf
await aio_zeroconf_registrar.zeroconf.async_wait_for_start()
assert len(zeroconf_registrar.engine.protocols) == 2
# patch the zeroconf send
# patch the zeroconf current_time_millis
# patch the backoff limit to ensure we always get one query every 1/4 of the DNS TTL
# Disable duplicate question suppression and duplicate packet suppression for this test as it works
# by asking the same question over and over
with patch.object(zeroconf_browser.question_history, "suppresses", return_value=False), patch.object(
zeroconf_browser, "async_send", send
), patch("zeroconf._services.browser.current_time_millis", _new_current_time_millis), patch.object(
_services_browser, "_BROWSER_BACKOFF_LIMIT", int(expected_ttl / 4)
):
service_added = asyncio.Event()
service_removed = asyncio.Event()