1515
1616def fake_service_info (
1717 cached : bool , answers : bool , id_ : bytes = b'aabbccddeeff' ,
18+ gate : asyncio .Event | None = None ,
1819) -> type [Any ]:
19- """A stand-in for AsyncServiceInfo with a controllable cache and plug response."""
20+ """A stand-in for AsyncServiceInfo with a controllable cache and plug response.
21+
22+ If gate is given, the plug only answers once the gate is set.
23+ """
2024
2125 class FakeServiceInfo :
2226 requested = False
27+ requests = 0
2328
2429 def __init__ (self , type_ : str , name : str ) -> None :
2530 self .port = 49476
@@ -30,6 +35,9 @@ def load_from_cache(self, zc: Any) -> bool:
3035
3136 async def async_request (self , zc : Any , timeout : float ) -> bool :
3237 FakeServiceInfo .requested = True
38+ FakeServiceInfo .requests += 1
39+ if gate is not None :
40+ await gate .wait ()
3341 return answers
3442
3543 def parsed_addresses (self ) -> list [str ]:
@@ -44,7 +52,13 @@ async def settle(devices: PowersensorZeroconfDevices) -> None:
4452 await asyncio .sleep (0 )
4553 if not devices ._internal_callbacks :
4654 return
47- await asyncio .gather (* list (devices ._internal_callbacks ))
55+ await asyncio .gather (* list (devices ._internal_callbacks ), return_exceptions = True )
56+
57+
58+ async def let_run () -> None :
59+ """Let scheduled tasks run up to their next wait, without waiting for them."""
60+ for _ in range (5 ):
61+ await asyncio .sleep (0 )
4862
4963
5064@pytest .mark .asyncio
@@ -92,6 +106,63 @@ async def test_unanswered_request_is_logged(caplog: pytest.LogCaptureFixture) ->
92106 assert f'No response from { NAME } ' in caplog .text
93107
94108
109+ @pytest .mark .asyncio
110+ async def test_removal_before_answer_cancels_lookup (caplog : pytest .LogCaptureFixture ) -> None :
111+ devices = PowersensorZeroconfDevices (
112+ zeroconf_instance = MagicMock (), logger = logging .getLogger ('test' ),
113+ )
114+ gate = asyncio .Event ()
115+ info = fake_service_info (cached = False , answers = True , gate = gate )
116+ with caplog .at_level (logging .WARNING ), \
117+ patch .object (zd , 'AsyncServiceInfo' , info ), \
118+ patch .object (devices , '_on_zc_add' , AsyncMock ()) as on_add , \
119+ patch .object (devices , '_on_zc_remove' , AsyncMock ()) as on_remove :
120+ listener = zd ._Listener (devices )
121+ listener .add_service (MagicMock (), TYPE , NAME )
122+ await let_run ()
123+ listener .remove_service (MagicMock (), TYPE , NAME )
124+ gate .set ()
125+ await settle (devices )
126+ # The plug was never dispatched, so there is nothing to remove either.
127+ on_add .assert_not_awaited ()
128+ on_remove .assert_not_awaited ()
129+ assert 'removal ignored' not in caplog .text
130+
131+
132+ @pytest .mark .asyncio
133+ async def test_one_lookup_per_plug_at_a_time () -> None :
134+ devices = PowersensorZeroconfDevices (zeroconf_instance = MagicMock ())
135+ gate = asyncio .Event ()
136+ info = fake_service_info (cached = False , answers = True , gate = gate )
137+ with patch .object (zd , 'AsyncServiceInfo' , info ), \
138+ patch .object (devices , '_on_zc_add' , AsyncMock ()) as on_add , \
139+ patch .object (devices , '_on_zc_update' , AsyncMock ()) as on_update :
140+ listener = zd ._Listener (devices )
141+ listener .add_service (MagicMock (), TYPE , NAME )
142+ await let_run ()
143+ listener .update_service (MagicMock (), TYPE , NAME )
144+ gate .set ()
145+ await settle (devices )
146+ assert info .requests == 1
147+ on_add .assert_awaited_once_with ('aabbccddeeff' , '192.0.2.10' , 49476 )
148+ on_update .assert_not_awaited ()
149+
150+
151+ @pytest .mark .asyncio
152+ async def test_removal_after_answer_is_debounced () -> None :
153+ devices = PowersensorZeroconfDevices (zeroconf_instance = MagicMock ())
154+ info = fake_service_info (cached = False , answers = True )
155+ with patch .object (zd , 'AsyncServiceInfo' , info ), \
156+ patch .object (devices , '_on_zc_add' , AsyncMock ()), \
157+ patch .object (devices , '_on_zc_remove' , AsyncMock ()) as on_remove :
158+ listener = zd ._Listener (devices )
159+ listener .add_service (MagicMock (), TYPE , NAME )
160+ await settle (devices )
161+ listener .remove_service (MagicMock (), TYPE , NAME )
162+ await settle (devices )
163+ on_remove .assert_awaited_once_with ('aabbccddeeff' )
164+
165+
95166# Browser callbacks must never raise (see _Listener): zeroconf does not catch
96167# their exceptions, which would disrupt other listeners on a shared instance.
97168
0 commit comments