forked from python-zeroconf/python-zeroconf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_services.py
More file actions
255 lines (195 loc) · 9.23 KB
/
test_services.py
File metadata and controls
255 lines (195 loc) · 9.23 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
#!/usr/bin/env python
""" Unit tests for zeroconf._services. """
import logging
import socket
import time
import os
import unittest
from threading import Event
from unittest.mock import patch
import pytest
import zeroconf as r
from zeroconf import Zeroconf
from zeroconf._services.info import ServiceInfo
from . import has_working_ipv6, _clear_cache
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)
class ListenerTest(unittest.TestCase):
def test_integration_with_listener_class(self):
sub_service_added = Event()
service_added = Event()
service_removed = Event()
sub_service_updated = Event()
duplicate_service_added = Event()
subtype_name = "_printer"
type_ = "_http._tcp.local."
subtype = subtype_name + "._sub." + type_
name = "UPPERxxxyyyæøå"
registration_name = f"{name}.{subtype}"
class MyListener(r.ServiceListener):
def add_service(self, zeroconf, type, name):
zeroconf.get_service_info(type, name)
service_added.set()
def remove_service(self, zeroconf, type, name):
service_removed.set()
def update_service(self, zeroconf, type, name):
pass
class DuplicateListener(r.ServiceListener):
def add_service(self, zeroconf, type, name):
duplicate_service_added.set()
def remove_service(self, zeroconf, type, name):
pass
def update_service(self, zeroconf, type, name):
pass
class MySubListener(r.ServiceListener):
def add_service(self, zeroconf, type, name):
sub_service_added.set()
pass
def remove_service(self, zeroconf, type, name):
pass
def update_service(self, zeroconf, type, name):
sub_service_updated.set()
listener = MyListener()
zeroconf_browser = Zeroconf(interfaces=['127.0.0.1'])
zeroconf_browser.add_service_listener(type_, listener)
properties = dict(
prop_none=None,
prop_string=b'a_prop',
prop_float=1.0,
prop_blank=b'a blanked string',
prop_true=1,
prop_false=0,
)
zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
desc = {'path': '/~paulsm/'} # type: Dict
desc.update(properties)
addresses = [socket.inet_aton("10.0.1.2")]
if has_working_ipv6() and not os.environ.get('SKIP_IPV6'):
addresses.append(socket.inet_pton(socket.AF_INET6, "6001:db8::1"))
addresses.append(socket.inet_pton(socket.AF_INET6, "2001:db8::1"))
info_service = ServiceInfo(
subtype, registration_name, port=80, properties=desc, server="ash-2.local.", addresses=addresses
)
zeroconf_registrar.register_service(info_service)
with patch.object(
zeroconf_registrar.engine.protocols[0], "suppress_duplicate_packet", return_value=False
), patch.object(
zeroconf_registrar.engine.protocols[1], "suppress_duplicate_packet", return_value=False
):
try:
service_added.wait(1)
assert service_added.is_set()
# short pause to allow multicast timers to expire
time.sleep(3)
zeroconf_browser.add_service_listener(type_, DuplicateListener())
duplicate_service_added.wait(
1
) # Ensure a listener for the same type calls back right away from cache
# clear the answer cache to force query
_clear_cache(zeroconf_browser)
cached_info = ServiceInfo(type_, registration_name)
cached_info.load_from_cache(zeroconf_browser)
assert cached_info.properties == {}
# get service info without answer cache
info = zeroconf_browser.get_service_info(type_, registration_name)
assert info is not None
assert info.properties[b'prop_none'] is None
assert info.properties[b'prop_string'] == properties['prop_string']
assert info.properties[b'prop_float'] == b'1.0'
assert info.properties[b'prop_blank'] == properties['prop_blank']
assert info.properties[b'prop_true'] == b'1'
assert info.properties[b'prop_false'] == b'0'
assert info.addresses == addresses[:1] # no V6 by default
assert set(info.addresses_by_version(r.IPVersion.All)) == set(addresses)
cached_info = ServiceInfo(type_, registration_name)
cached_info.load_from_cache(zeroconf_browser)
assert cached_info.properties is not None
# Populate the cache
zeroconf_browser.get_service_info(subtype, registration_name)
# get service info with only the cache
cached_info = ServiceInfo(subtype, registration_name)
cached_info.load_from_cache(zeroconf_browser)
assert cached_info.properties is not None
assert cached_info.properties[b'prop_float'] == b'1.0'
# get service info with only the cache with the lowercase name
cached_info = ServiceInfo(subtype, registration_name.lower())
cached_info.load_from_cache(zeroconf_browser)
# Ensure uppercase output is preserved
assert cached_info.name == registration_name
assert cached_info.key == registration_name.lower()
assert cached_info.properties is not None
assert cached_info.properties[b'prop_float'] == b'1.0'
info = zeroconf_browser.get_service_info(subtype, registration_name)
assert info is not None
assert info.properties is not None
assert info.properties[b'prop_none'] is None
cached_info = ServiceInfo(subtype, registration_name.lower())
cached_info.load_from_cache(zeroconf_browser)
assert cached_info.properties is not None
assert cached_info.properties[b'prop_none'] is None
# test TXT record update
sublistener = MySubListener()
zeroconf_browser.add_service_listener(subtype, sublistener)
properties['prop_blank'] = b'an updated string'
desc.update(properties)
info_service = ServiceInfo(
subtype,
registration_name,
80,
0,
0,
desc,
"ash-2.local.",
addresses=[socket.inet_aton("10.0.1.2")],
)
zeroconf_registrar.update_service(info_service)
sub_service_added.wait(1) # we cleared the cache above
assert sub_service_added.is_set()
info = zeroconf_browser.get_service_info(type_, registration_name)
assert info is not None
assert info.properties[b'prop_blank'] == properties['prop_blank']
cached_info = ServiceInfo(subtype, registration_name)
cached_info.load_from_cache(zeroconf_browser)
assert cached_info.properties is not None
assert cached_info.properties[b'prop_blank'] == properties['prop_blank']
zeroconf_registrar.unregister_service(info_service)
service_removed.wait(1)
assert service_removed.is_set()
finally:
zeroconf_registrar.close()
zeroconf_browser.remove_service_listener(listener)
zeroconf_browser.close()
def test_servicelisteners_raise_not_implemented():
"""Verify service listeners raise when one of the methods is not implemented."""
class MyPartialListener(r.ServiceListener):
"""A listener that does not implement anything."""
zc = r.Zeroconf(interfaces=['127.0.0.1'])
with pytest.raises(NotImplementedError):
MyPartialListener().add_service(
zc, "_tivo-videostream._tcp.local.", "Tivo1._tivo-videostream._tcp.local."
)
with pytest.raises(NotImplementedError):
MyPartialListener().remove_service(
zc, "_tivo-videostream._tcp.local.", "Tivo1._tivo-videostream._tcp.local."
)
with pytest.raises(NotImplementedError):
MyPartialListener().update_service(
zc, "_tivo-videostream._tcp.local.", "Tivo1._tivo-videostream._tcp.local."
)
zc.close()
def test_signal_registration_interface():
"""Test adding and removing from the SignalRegistrationInterface."""
interface = r.SignalRegistrationInterface([])
def dummy():
pass
interface.register_handler(dummy)
interface.unregister_handler(dummy)
with pytest.raises(ValueError):
interface.unregister_handler(dummy)