Debian Codegraph @

tests/test_plugin_xmpp.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 """
29 Unit Tests for the XMPP plugin.
30
31 """
32
33 from __future__ import annotations
34
35 import asyncio
36 import contextlib
37 import gc
38 import logging
39 import ssl
40 import threading
41 import time
42 from types import SimpleNamespace
43 from typing import Any, Optional
44
45 import pytest
46
47 from apprise import LOGGER_NAME, Apprise, NotifyType
48 from apprise.exception import AppriseException, AppriseImproperlyConfigured
49 from apprise.plugins.xmpp import adapter as xmpp_adapter, base as xmpp_base
50 from apprise.plugins.xmpp.base import NotifyXMPP
51
52
53 def test_plugin_xmpp_channel_binding_exception() -> None:
54 """Channel-binding failures use the common Apprise exception."""
55 exc = xmpp_adapter.XMPPChannelBindingError()
56 assert isinstance(exc, AppriseException)
57 assert str(exc) == "SASL SCRAM-PLUS channel-binding authentication failed."
58
59
60 def run_on_loop(loop: asyncio.AbstractEventLoop, coro: Any) -> Any:
61 """Run a coroutine on a specific event loop."""
62 asyncio.set_event_loop(loop)
63 return loop.run_until_complete(coro)
64
65
66 # ---------------------------------------------------------------------------
67 # Slixmpp Availability Handling
68 # ---------------------------------------------------------------------------
69
70 try:
71 # Enforce slixmpp >= Minimum Supported Version
72 SLIXMPP_AVAILABLE = xmpp_adapter.SlixmppAdapter.supported_version()
73
74 except Exception:
75 SLIXMPP_AVAILABLE = False
76
77 # Seconds to sleep before forcing the timeout branch in _FakeDoneEvent.wait().
78 # This gives the worker thread enough time to progress to a known checkpoint
79 # (e.g. event loop created, client instantiated) without relying on a longer
80 # wall-clock timeout that would slow tests down.
81 WORKER_THREAD_STARTUP_DELAY: float = 0.02
82
83
84 # ---------------------------------------------------------------------------
85 # Fake Slixmpp Client
86 # ---------------------------------------------------------------------------
87
88
89 class FakeClientXMPP:
90 def __init__(self, jid: str, password: str) -> None:
91 self.jid = jid
92 self.password = password
93 # Loop is assigned by adapter via `client.loop = loop`, but we default
94 # to the current event loop for safety in tests.
95 self.loop: Optional[asyncio.AbstractEventLoop] = None
96 self.handlers: dict[str, Any] = {}
97 self.auto_reconnect = True
98
99 # Slixmpp >= 1.16.0: adapter waits on this Future
100 self.disconnected: Optional[asyncio.Future[bool]] = None
101
102 # Slixmpp toggles used by adapter
103 self.enable_plaintext = True
104 self.enable_starttls = True
105 self.enable_direct_tls = False
106 self.ssl_context = None
107
108 # Track plugins registered by the adapter (keepalive path)
109 self.registered_plugins: dict[str, Any] = {}
110
111 def add_event_handler(self, name: str, handler: Any) -> None:
112 self.handlers[name] = handler
113
114 def send_presence(self) -> None:
115 return None
116
117 async def get_roster(self) -> None:
118 return None
119
120 def send_message(self, **kwargs: Any) -> None:
121 return None
122
123 def register_plugin(self, name: str, config: Optional[Any] = None) -> None:
124 self.registered_plugins[name] = config
125 return None
126
127 def disconnect(self) -> None:
128 # Complete the disconnected Future if it is not already done.
129 if self.disconnected is not None and not self.disconnected.done():
130 self.disconnected.set_result(True)
131
132 def connect(self, **kwargs: Any) -> asyncio.Future[bool]:
133 """
134 Slixmpp >= 1.16.0 connect() returns a Future. Our adapter awaits it.
135
136 This fake schedules session_start on the assigned loop so the adapter's
137 loop.run_until_complete() drives it, and ensures disconnected resolves.
138 """
139 loop = self.loop or asyncio.get_running_loop()
140
141 # Ensure disconnected future exists on the correct loop
142 if self.disconnected is None:
143 self.disconnected = loop.create_future()
144
145 fut: asyncio.Future[bool] = loop.create_future()
146 fut.set_result(True)
147
148 handler = self.handlers.get("session_start")
149 if handler:
150
151 def _fire_session_start() -> None:
152 rv = handler()
153 if asyncio.iscoroutine(rv):
154 task = loop.create_task(rv)
155 # Ensure we always disconnect after session_start
156 task.add_done_callback(lambda _: self.disconnect())
157 else:
158 # sync handler, just disconnect
159 self.disconnect()
160
161 # Schedule for when the adapter starts running the loop
162 loop.call_soon(_fire_session_start)
163
164 return fut
165
166
167 # ---------------------------------------------------------------------------
168 # Helpers
169 # ---------------------------------------------------------------------------
170
171
172 def install_fake_slixmpp(monkeypatch: pytest.MonkeyPatch) -> None:
173 monkeypatch.setattr(xmpp_adapter, "asyncio", asyncio, raising=False)
174 monkeypatch.setattr(
175 xmpp_adapter,
176 "slixmpp",
177 SimpleNamespace(ClientXMPP=FakeClientXMPP),
178 raising=False,
179 )
180 monkeypatch.setattr(
181 xmpp_adapter, "SLIXMPP_SUPPORT_AVAILABLE", True, raising=False
182 )
183 monkeypatch.setattr(
184 xmpp_adapter.SlixmppAdapter,
185 "_enabled",
186 True,
187 raising=False,
188 )
189
190
191 def _patch_threading(
192 monkeypatch: pytest.MonkeyPatch, *, done_event_cls: type
193 ) -> None:
194 """Patch adapter threading to use a custom done-event class."""
195 import threading as _real_threading
196
197 class _ThreadingProxy:
198 Event = done_event_cls
199 Thread = _real_threading.Thread
200
201 def __getattr__(self, name: str) -> Any:
202 return getattr(_real_threading, name)
203
204 monkeypatch.setattr(
205 xmpp_adapter, "threading", _ThreadingProxy(), raising=True
206 )
207
208
209 # ---------------------------------------------------------------------------
210 # NotifyXMPP Tests
211 # ---------------------------------------------------------------------------
212
213
214 def _make_fake_done_event_cls(
215 signal_evt: Optional[threading.Event] = None,
216 ) -> type:
217 """Return a deterministic threading.Event replacement for timeout tests.
218
219 The adapter under test uses ``threading.Event()`` for *done*, then calls
220 ``done.wait(timeout=...)`` and later ``done.set()`` from the worker thread.
221
222 These tests want ``wait()`` to return ``False`` deterministically (forcing
223 the timeout branch), while still giving the worker thread a chance to
224 reach a known checkpoint first (e.g. event loop created, client created).
225
226 Capturing *signal_evt* in a closure rather than as a class-level attribute
227 ensures that each test's event class is fully independent — parallel test
228 runs cannot interfere with one another through shared mutable class state.
229
230 Parameters
231 ----------
232 signal_evt:
233 Optional ``threading.Event`` that the worker thread sets when it
234 reaches a stable checkpoint. If provided, ``wait()`` pauses until
235 that event is set before forcing the timeout branch.
236 """
237
238 class _FakeDoneEvent:
239 def __init__(self) -> None:
240 self._set = False
241 self._wait_calls = 0
242
243 def is_set(self) -> bool:
244 return self._set
245
246 def set(self) -> None:
247 self._set = True
248
249 def clear(self) -> None:
250 self._set = False
251
252 def wait(self, timeout: Optional[float] = None) -> bool:
253 self._wait_calls += 1
254 if self._wait_calls == 1:
255 if signal_evt is not None:
256 # The specific timeout value isn't important; we just
257 # don't want this to hang if the checkpoint is never
258 # reached.
259 signal_evt.wait(timeout=1.0)
260
261 # Give the worker thread a brief chance to run before we
262 # force the timeout condition in the code under test.
263 time.sleep(WORKER_THREAD_STARTUP_DELAY)
264 return False
265 return self._set
266
267 return _FakeDoneEvent
268
269
270 @pytest.mark.skipif(SLIXMPP_AVAILABLE, reason="Requires slixmpp NOT installed")
271 def test_slixmpp_unavailable() -> None:
272 obj = NotifyXMPP(host="example.com", user="[email protected]", password="x")
273 assert obj.send("will fail") is False
274
275
276 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
277 def test_xmpp_invalid_jid() -> None:
278 with pytest.raises(AppriseImproperlyConfigured):
279 NotifyXMPP(host="example.com", user="bad jid", password="x")
280
281
282 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
283 def test_xmpp_targets_filtered() -> None:
284 n = NotifyXMPP(
285 host="example.com",
286 user="[email protected]",
287 password="x",
288 targets=["[email protected]", " user1 user2 ", "", "[email protected]"],
289 )
290
291 # parse_list() tokenises on whitespace, so "bad jid" becomes two targets.
292 # Empty values are dropped before they reach the validation loop, so no
293 # warning is guaranteed for the empty string.
294 assert sorted(n.targets) == [
295 ("chat", "[email protected]"),
296 ("chat", "[email protected]"),
297 ("chat", "[email protected]"),
298 ("chat", "[email protected]"),
299 ]
300
301
302 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
303 def test_xmpp_len() -> None:
304 n1 = NotifyXMPP(host="example.com", user="[email protected]", password="x")
305 assert len(n1) == 1
306
307 n2 = NotifyXMPP(
308 host="example.com",
309 user="[email protected]",
310 password="x",
311 targets=["[email protected]", "[email protected]"],
312 )
313 # still just one upstream message
314 assert len(n2) == 1
315
316
317 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
318 def test_xmpp_url_privacy() -> None:
319 n = NotifyXMPP(
320 host="example.com",
321 user="[email protected]",
322 password="secret",
323 targets=["[email protected]"],
324 verify=False,
325 )
326 u = n.url(privacy=True)
327 assert "secret" not in u
328 assert "verify=" in u
329
330
331 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
332 def test_xmpp_parse_url() -> None:
333 r = NotifyXMPP.parse_url(
334 "xmpps://me:[email protected]/[email protected]?verify=no"
335 )
336 assert r["verify"] is False
337 assert r["targets"] == ["[email protected]"]
338
339
340 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
341 def test_xmpp_parse_url_to() -> None:
342 r = NotifyXMPP.parse_url(
343 "xmpp://me:[email protected][email protected],[email protected]"
344 )
345 assert sorted(r["targets"]) == ["[email protected]", "[email protected]"]
346
347
348 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
349 def test_xmpp_invalid_targets_logged(
350 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
351 ) -> None:
352 """Invalid XMPP targets are dropped with a warning."""
353
354 # Some test modules disable logging globally at import time
355 # This ensures we're correctly configured for this test.
356 logging.disable(logging.NOTSET)
357 caplog.set_level(logging.WARNING, logger=LOGGER_NAME)
358 caplog.set_level(logging.WARNING, logger=xmpp_base.__name__)
359
360 try:
361 # parse_list() tokenises on whitespace, so it is difficult to
362 # naturally feed a whitespace-containing value through. Patch
363 # parse_list() to return a value that will fail IS_JID validation.
364 monkeypatch.setattr(
365 xmpp_base,
366 "parse_list",
367 lambda _v: ["bad jid", "[email protected]"],
368 raising=True,
369 )
370
371 n = NotifyXMPP(
372 host="example.com",
373 user="[email protected]",
374 password="x",
375 targets=["ignored"],
376 )
377
378 assert n.targets == [("chat", "[email protected]")]
379 assert "Dropped invalid XMPP target" in caplog.text
380
381 finally:
382 logging.disable(logging.CRITICAL)
383
384
385 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
386 def test_xmpp_url_identifier_is_accessible() -> None:
387 """url_identifier property should be accessible and stable."""
388 n = NotifyXMPP(
389 host="example.com", user="[email protected]", password="secret"
390 )
391 schema, host, xmpp_host, user, password, port = n.url_identifier
392 assert schema == "xmpp"
393 assert host == "example.com"
394 assert xmpp_host == ""
395 assert user == "[email protected]"
396 assert password == "secret"
397 assert port is None
398
399
400 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
401 def test_xmpp_server_override_parse_url() -> None:
402 """?xmpp= is extracted into xmpp_host by parse_url()."""
403 r = NotifyXMPP.parse_url(
404 "xmpps://[email protected]/joe?xmpp=xmpp.example.com"
405 )
406 assert r is not None
407 assert r["xmpp_host"] == "xmpp.example.com"
408 # host stays as the JID domain
409 assert r["host"] == "example.com"
410
411
412 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
413 def test_xmpp_server_override_constructor_and_url() -> None:
414 """xmpp_host is stored and round-trips through url()."""
415 n = NotifyXMPP(
416 host="example.com",
417 user="user",
418 password="pass",
419 xmpp_host="xmpp.example.com",
420 )
421
422 # Stored correctly
423 assert n.xmpp_host == "xmpp.example.com"
424
425 # JIDs are built from host, not xmpp_host
426 assert n.jid == "[email protected]"
427
428 # url() emits xmpp= when it differs from host
429 u = n.url(privacy=False)
430 assert "xmpp=xmpp.example.com" in u
431 assert "example.com" in u
432
433 # url() omits xmpp= when xmpp_host matches host (redundant)
434 n2 = NotifyXMPP(
435 host="example.com",
436 user="user",
437 password="pass",
438 xmpp_host="example.com",
439 )
440 u2 = n2.url(privacy=False)
441 assert "xmpp=" not in u2
442
443 # url() omits xmpp= when xmpp_host is empty
444 n3 = NotifyXMPP(
445 host="example.com",
446 user="user",
447 password="pass",
448 )
449 u3 = n3.url(privacy=False)
450 assert "xmpp=" not in u3
451
452
453 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
454 def test_xmpp_server_override_target_jids_use_host() -> None:
455 """Target JIDs are built from host, not xmpp_host."""
456 n = NotifyXMPP(
457 host="example.com",
458 user="user",
459 password="pass",
460 targets=["joe"],
461 xmpp_host="xmpp.example.com",
462 )
463 # Target 'joe' gets host domain appended, not xmpp_host
464 assert n.targets == [("chat", "[email protected]")]
465
466
467 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
468 def test_xmpp_server_override_url_identifier() -> None:
469 """url_identifier carries xmpp_host so deduplication is xmpp_host-aware."""
470 n = NotifyXMPP(
471 host="example.com",
472 user="user",
473 password="pass",
474 xmpp_host="xmpp.example.com",
475 )
476 _schema, host, xmpp_host, _user, _password, _port = n.url_identifier
477 assert host == "example.com"
478 assert xmpp_host == "xmpp.example.com"
479
480
481 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
482 def test_xmpp_server_override_config_host(
483 monkeypatch: pytest.MonkeyPatch,
484 ) -> None:
485 """send() passes xmpp_host (not host) to XMPPConfig when set."""
486 captured: dict = {}
487
488 class _Adapter:
489 def __init__(self, config: Any, **kwargs: Any) -> None:
490 captured["config_host"] = config.host
491
492 def process(self) -> bool:
493 return True
494
495 monkeypatch.setattr(xmpp_base, "SlixmppAdapter", _Adapter, raising=True)
496
497 apobj = Apprise()
498 apobj.add("xmpps://[email protected]/joe?xmpp=xmpp.example.com")
499 apobj.notify("hello")
500
501 assert captured["config_host"] == "xmpp.example.com"
502
503
504 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
505 def test_xmpp_server_override_config_host_defaults_to_host(
506 monkeypatch: pytest.MonkeyPatch,
507 ) -> None:
508 """send() passes host to XMPPConfig when xmpp_host is not set."""
509 captured: dict = {}
510
511 class _Adapter:
512 def __init__(self, config: Any, **kwargs: Any) -> None:
513 captured["config_host"] = config.host
514
515 def process(self) -> bool:
516 return True
517
518 monkeypatch.setattr(xmpp_base, "SlixmppAdapter", _Adapter, raising=True)
519
520 apobj = Apprise()
521 apobj.add("xmpps://[email protected]/joe")
522 apobj.notify("hello")
523
524 assert captured["config_host"] == "example.com"
525
526
527 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
528 def test_xmpp_url_handling() -> None:
529 """url() must not append a path when there are no targets."""
530 apobj = Apprise()
531 assert apobj.add("xmpp://me:[email protected]?verify=no") is True
532
533 assert len(apobj) == 1
534 plugin = apobj[0]
535
536 u = plugin.url(privacy=False)
537 assert "example.com/?" in u
538 assert "mode=none" in u
539
540 apobj = Apprise()
541 assert apobj.add("xmpps://me:[email protected]?mode=tls") is True
542
543 assert len(apobj) == 1
544 plugin = apobj[0]
545
546 u = plugin.url(privacy=False)
547 assert "mode=tls" in u
548
549 # invalid Mode
550 apobj = Apprise()
551 assert apobj.add("xmpps://me:[email protected]?mode=invalid") is False
552
553 # Ambiguous secure=true (xmpps://) and mode = none
554 apobj = Apprise()
555 assert apobj.add("xmpps://me:[email protected]?mode=none") is True
556
557 assert len(apobj) == 1
558 plugin = apobj[0]
559
560 u = plugin.url(privacy=False)
561 # starttls (upgraded from none - most secure path)
562 assert "mode=starttls" in u
563
564 # Ambiguous secure=False (xmpp://) and mode != none
565 apobj = Apprise()
566 assert apobj.add("xmpp://me:[email protected]?mode=tls") is True
567
568 assert len(apobj) == 1
569 plugin = apobj[0]
570
571 u = plugin.url(privacy=False)
572 # most secure path prevails
573 assert "mode=tls" in u
574
575 apobj = Apprise()
576 assert (
577 apobj.add("xmpp://me:[email protected]?subject=yes&roster=yes")
578 is True
579 )
580
581 assert len(apobj) == 1
582 plugin = apobj[0]
583
584 u = plugin.url(privacy=False)
585 # most secure path prevails
586 assert "mode=none" in u
587 assert "roster=yes" in u
588 assert "subject=yes" in u
589
590
591 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
592 def test_xmpp_parse_url_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:
593 """parse_url() returns None when NotifyBase.parse_url() fails."""
594
595 monkeypatch.setattr(
596 xmpp_base.NotifyBase,
597 "parse_url",
598 lambda *_args, **_kwargs: None,
599 raising=True,
600 )
601 assert NotifyXMPP.parse_url("xmpp://bad") is None
602
603
604 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
605 def test_xmpp_finalize_loop_when_already_closed_does_not_close_again() -> None:
606 loop = asyncio.new_event_loop()
607 loop.close()
608
609 # If _finalize_loop tried to close again, this would still be harmless,
610 # but this test specifically forces the "if not loop.is_closed()" branch
611 # to be False for coverage.
612 xmpp_adapter.SlixmppAdapter._finalize_loop(loop)
613
614 assert loop.is_closed()
615
616
617 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
618 def test_xmpp_apprise_notify_invokes_adapter(
619 monkeypatch: pytest.MonkeyPatch,
620 ) -> None:
621 """Exercise the Apprise.notify() workflow while mocking network I/O."""
622
623 captured: dict[str, Any] = {}
624
625 class _Adapter:
626 def __init__(
627 self,
628 config: xmpp_adapter.XMPPConfig,
629 targets: list[str],
630 subject: str,
631 body: str,
632 timeout: float = 0.0,
633 roster: bool = False,
634 before_message: Any = None,
635 logger: Optional[logging.Logger] = None,
636 **kwargs: Any,
637 ) -> None:
638 captured["targets"] = targets
639 captured["body"] = body
640 captured["subject"] = subject
641 captured["roster"] = roster
642
643 def process(self) -> bool:
644 return True
645
646 monkeypatch.setattr(xmpp_base, "SlixmppAdapter", _Adapter, raising=True)
647
648 apobj = Apprise()
649 apobj.add("xmpp://me:[email protected]/[email protected]")
650
651 assert (
652 bool(
653 apobj.notify("hello", title="subject", notify_type=NotifyType.INFO)
654 )
655 is True
656 )
657 assert captured["targets"] == [("chat", "[email protected]")]
658 assert captured["subject"] == ""
659 assert "subject\r\nhello" in captured["body"]
660
661 apobj = Apprise()
662 apobj.add("xmpp://me:[email protected]/[email protected]?subject=yes")
663
664 assert (
665 bool(
666 apobj.notify("hello", title="subject", notify_type=NotifyType.INFO)
667 )
668 is True
669 )
670 assert captured["targets"] == [("chat", "[email protected]")]
671 assert captured["subject"] == "subject"
672 assert "hello" in captured["body"]
673
674
675 # ---------------------------------------------------------------------------
676 # Adapter Tests
677 # ---------------------------------------------------------------------------
678
679
680 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
681 def test_xmpp_ssl_context() -> None:
682 ctx = xmpp_adapter.SlixmppAdapter._ssl_context(True)
683 assert ctx.verify_mode != ssl.CERT_NONE
684
685 ctx2 = xmpp_adapter.SlixmppAdapter._ssl_context(False)
686 assert ctx2.verify_mode == ssl.CERT_NONE
687 assert ctx2.check_hostname is False
688
689
690 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
691 def test_xmpp_cancel_pending_empty(monkeypatch: pytest.MonkeyPatch) -> None:
692 loop = asyncio.new_event_loop()
693 try:
694 monkeypatch.setattr(
695 asyncio, "all_tasks", lambda _: set(), raising=True
696 )
697 xmpp_adapter.SlixmppAdapter._finalize_loop(loop)
698
699 finally:
700 with contextlib.suppress(Exception):
701 asyncio.set_event_loop(None)
702
703 loop.close()
704
705
706 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
707 def test_xmpp_cancel_pending_tasks(monkeypatch: pytest.MonkeyPatch) -> None:
708 loop = asyncio.new_event_loop()
709 try:
710 asyncio.set_event_loop(loop)
711
712 async def _noop() -> None:
713 await asyncio.sleep(0)
714
715 t1 = loop.create_task(_noop())
716 t2 = loop.create_task(_noop())
717
718 monkeypatch.setattr(
719 asyncio, "all_tasks", lambda _: {t1, t2}, raising=True
720 )
721
722 xmpp_adapter.SlixmppAdapter._finalize_loop(loop)
723 assert t1.cancelled()
724 assert t2.cancelled()
725
726 finally:
727 # Avoid asyncio.get_event_loop() here to prevent DeprecationWarning on
728 # newer Python versions. Setting to None is sufficient for isolation.
729 with contextlib.suppress(Exception):
730 asyncio.set_event_loop(None)
731
732 loop.close()
733
734
735 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
736 def test_xmpp_process_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
737 install_fake_slixmpp(monkeypatch)
738 config = xmpp_adapter.XMPPConfig(
739 jid="[email protected]",
740 password="x",
741 host="example.com",
742 port=5223,
743 secure=xmpp_adapter.SecureXMPPMode.TLS,
744 verify_certificate=True,
745 )
746 a = xmpp_adapter.SlixmppAdapter(
747 config=config,
748 targets=[],
749 subject="s",
750 body="b",
751 timeout=1,
752 )
753 monkeypatch.setattr(a, "_enabled", False, raising=True)
754 assert a.process() is False
755
756
757 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
758 def test_xmpp_process_fail(
759 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
760 ) -> None:
761 install_fake_slixmpp(monkeypatch)
762 caplog.set_level(logging.WARNING)
763
764 def bad_connect(self: FakeClientXMPP, **kw: Any) -> asyncio.Future[bool]:
765 fut: asyncio.Future[bool] = self.loop.create_future()
766 fut.set_result(False)
767 return fut
768
769 monkeypatch.setattr(FakeClientXMPP, "connect", bad_connect, raising=True)
770
771 config = xmpp_adapter.XMPPConfig(
772 jid="[email protected]",
773 password="x",
774 host="example.com",
775 port=5223,
776 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
777 verify_certificate=True,
778 )
779 a = xmpp_adapter.SlixmppAdapter(
780 config=config,
781 targets=[("chat", "[email protected]")],
782 subject="s",
783 body="b",
784 timeout=1,
785 )
786 assert a.process() is False
787
788
789 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
790 def test_xmpp_process_success(monkeypatch: pytest.MonkeyPatch) -> None:
791 install_fake_slixmpp(monkeypatch)
792 config = xmpp_adapter.XMPPConfig(
793 jid="[email protected]",
794 password="x",
795 host="example.com",
796 port=5223,
797 secure=xmpp_adapter.SecureXMPPMode.TLS,
798 verify_certificate=False,
799 )
800
801 a = xmpp_adapter.SlixmppAdapter(
802 config=config,
803 targets=[("chat", "[email protected]")],
804 subject="s",
805 body="b",
806 timeout=1.0,
807 )
808 assert a.process() is True
809
810 # Test with roster=True
811 a = xmpp_adapter.SlixmppAdapter(
812 config=config,
813 targets=[("chat", "[email protected]")],
814 subject="s",
815 body="b",
816 timeout=1.0,
817 roster=True,
818 )
819 assert a.process() is True
820
821
822 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
823 def test_xmpp_process_default_target(monkeypatch: pytest.MonkeyPatch) -> None:
824 install_fake_slixmpp(monkeypatch)
825 config = xmpp_adapter.XMPPConfig(
826 jid="[email protected]",
827 password="x",
828 host="example.com",
829 port=5223,
830 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
831 verify_certificate=False,
832 )
833
834 a = xmpp_adapter.SlixmppAdapter(
835 config=config,
836 targets=[],
837 subject="s",
838 body="b",
839 timeout=1.0,
840 )
841 assert a.process() is True
842
843
844 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
845 def test_xmpp_process_exception(
846 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
847 ) -> None:
848 install_fake_slixmpp(monkeypatch)
849 caplog.set_level(logging.DEBUG)
850
851 def explode(self: FakeClientXMPP, **kw: Any) -> bool:
852 raise RuntimeError("boom")
853
854 monkeypatch.setattr(FakeClientXMPP, "connect", explode, raising=True)
855
856 config = xmpp_adapter.XMPPConfig(
857 jid="[email protected]",
858 password="x",
859 host="example.com",
860 port=5223,
861 secure=xmpp_adapter.SecureXMPPMode.TLS,
862 verify_certificate=True,
863 )
864 a = xmpp_adapter.SlixmppAdapter(
865 config=config,
866 targets=[("chat", "[email protected]")],
867 subject="s",
868 body="b",
869 timeout=1,
870 )
871 assert a.process() is False
872
873
874 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
875 def test_xmpp_process_before_message(monkeypatch: pytest.MonkeyPatch) -> None:
876 """Ensure before_message callback is invoked for each target."""
877 install_fake_slixmpp(monkeypatch)
878
879 called: list[int] = []
880
881 def before_message() -> None:
882 called.append(1)
883
884 config = xmpp_adapter.XMPPConfig(
885 jid="[email protected]",
886 password="x",
887 host="example.com",
888 port=5223,
889 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
890 verify_certificate=False,
891 )
892 a = xmpp_adapter.SlixmppAdapter(
893 config=config,
894 targets=[("chat", "[email protected]"), ("chat", "[email protected]")],
895 subject="s",
896 body="b",
897 timeout=1,
898 before_message=before_message,
899 )
900 assert a.process() is True
901 assert len(called) == 2
902
903
904 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
905 def test_xmpp_process_failed_auth_disconnect(
906 monkeypatch: pytest.MonkeyPatch,
907 ) -> None:
908 """Authentication failure path must still call disconnect()."""
909 install_fake_slixmpp(monkeypatch)
910
911 # Force the connect() path to trigger the failed_auth handler.
912 def connect_failed_auth(
913 self: FakeClientXMPP, **kw: Any
914 ) -> asyncio.Future[bool]:
915 loop = self.loop or asyncio.get_running_loop()
916 if self.disconnected is None:
917 self.disconnected = loop.create_future()
918
919 fut: asyncio.Future[bool] = loop.create_future()
920 fut.set_result(True)
921
922 handler = self.handlers.get("failed_auth")
923 if handler:
924 loop.call_soon(handler)
925 loop.call_soon(self.disconnect)
926
927 return fut
928
929 monkeypatch.setattr(
930 FakeClientXMPP, "connect", connect_failed_auth, raising=True
931 )
932
933 disconnected = {"called": False}
934
935 def disconnect(self: FakeClientXMPP) -> None:
936 disconnected["called"] = True
937 if not self.disconnected.done():
938 self.disconnected.set_result(True)
939
940 monkeypatch.setattr(FakeClientXMPP, "disconnect", disconnect, raising=True)
941
942 config = xmpp_adapter.XMPPConfig(
943 jid="[email protected]",
944 password="x",
945 host="example.com",
946 port=5223,
947 secure=xmpp_adapter.SecureXMPPMode.TLS,
948 verify_certificate=False,
949 )
950 a = xmpp_adapter.SlixmppAdapter(
951 config=config,
952 targets=[("chat", "[email protected]")],
953 subject="s",
954 body="b",
955 timeout=1,
956 )
957 assert a.process() is False
958 assert disconnected["called"] is True
959
960
961 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
962 def test_xmpp_normalize_jid() -> None:
963 """Tests normalize_jid()"""
964 assert NotifyXMPP.normalize_jid("user", "example.ca") == (
965 "[email protected]",
966 False,
967 )
968 assert NotifyXMPP.normalize_jid("user/resource", "example.ca") == (
969 "[email protected]/resource",
970 False,
971 )
972 assert NotifyXMPP.normalize_jid(
973 "user/resource/extra/crap", "example.ca"
974 ) == ("[email protected]/resource", False)
975 assert NotifyXMPP.normalize_jid("[email protected]/r1", "example.ca") == (
976 "[email protected]/r1",
977 False,
978 )
979 assert NotifyXMPP.normalize_jid(
980 "#[email protected]", "example.ca"
981 ) == ("[email protected]", True)
982
983 with pytest.raises(AppriseImproperlyConfigured):
984 # Bad entry
985 NotifyXMPP.normalize_jid("", "example.ca")
986
987
988 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
989 def test_xmpp_bridge_logging_safe_lock(
990 monkeypatch: pytest.MonkeyPatch,
991 ) -> None:
992 """tests bridge logging on multiple attempts"""
993 # Reset module globals
994 monkeypatch.setattr(xmpp_adapter, "_LOG_BRIDGED", False, raising=True)
995
996 # Acquire the lock so the worker blocks inside bridge_slixmpp_logging()
997 xmpp_adapter._LOG_BRIDGE_LOCK.acquire()
998
999 done = {"ok": False}
1000
1001 def worker() -> None:
1002 xmpp_adapter.bridge_slixmpp_logging()
1003 done["ok"] = True
1004
1005 t = threading.Thread(target=worker, daemon=True)
1006 t.start()
1007
1008 # Allow enough time for the worker to reach the lock, even on busy hosts.
1009 time.sleep(0.1)
1010
1011 # Now flip the flag while the lock is still held; when released, worker
1012 # will acquire the lock and hit the *inner* early-return.
1013 monkeypatch.setattr(xmpp_adapter, "_LOG_BRIDGED", True, raising=True)
1014
1015 xmpp_adapter._LOG_BRIDGE_LOCK.release()
1016 t.join(timeout=1.0)
1017
1018 assert done["ok"] is True
1019
1020
1021 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1022 def test_xmpp_multi_logging_bridge_handling(
1023 monkeypatch: pytest.MonkeyPatch,
1024 ) -> None:
1025 """Handles multiple logging attempts made by multiple xmpp instances"""
1026
1027 # Reset module globals
1028 monkeypatch.setattr(xmpp_adapter, "_LOG_BRIDGED", False, raising=True)
1029
1030 apprise_logger = logging.getLogger("apprise")
1031 slix_logger = logging.getLogger("slixmpp")
1032
1033 # Preserve existing handlers
1034 old_apprise = list(apprise_logger.handlers)
1035 old_slix = list(slix_logger.handlers)
1036
1037 try:
1038 handler = logging.NullHandler()
1039
1040 # Arrange for slix to already have the handler
1041 apprise_logger.handlers = [handler]
1042 slix_logger.handlers = [handler]
1043
1044 xmpp_adapter.bridge_slixmpp_logging()
1045
1046 # Handler should not be duplicated
1047 assert slix_logger.handlers.count(handler) == 1
1048
1049 finally:
1050 apprise_logger.handlers = old_apprise
1051 slix_logger.handlers = old_slix
1052
1053
1054 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1055 def test_xmpp_process_failure_cleanup(monkeypatch: pytest.MonkeyPatch) -> None:
1056 """Tests edge cases for failures that require cleanup"""
1057
1058 install_fake_slixmpp(monkeypatch)
1059
1060 # Ensure adapter is enabled
1061 monkeypatch.setattr(
1062 xmpp_adapter.SlixmppAdapter, "_enabled", True, raising=True
1063 )
1064
1065 # Make new_event_loop fail before shared['loop'] is assigned
1066 def raise_new_event_loop() -> Any:
1067 raise RuntimeError("poof")
1068
1069 monkeypatch.setattr(
1070 xmpp_adapter.asyncio,
1071 "new_event_loop",
1072 raise_new_event_loop,
1073 raising=True,
1074 )
1075
1076 config = xmpp_adapter.XMPPConfig(
1077 jid="[email protected]",
1078 password="x",
1079 host="example.com",
1080 port=5223,
1081 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
1082 verify_certificate=False,
1083 )
1084
1085 a = xmpp_adapter.SlixmppAdapter(
1086 config=config,
1087 targets=[("chat", "[email protected]")],
1088 subject="s",
1089 body="b",
1090 timeout=5.0,
1091 )
1092
1093 # Should return False
1094 assert a.process() is False
1095
1096
1097 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1098 def test_xmpp_timeout_cleanup_disconnect_exception_suppressed(
1099 monkeypatch: pytest.MonkeyPatch,
1100 ) -> None:
1101 """Cover timeout cleanup: loop_obj != None"""
1102 install_fake_slixmpp(monkeypatch)
1103
1104 # Ensure adapter is enabled
1105 monkeypatch.setattr(
1106 xmpp_adapter.SlixmppAdapter, "_enabled", True, raising=True
1107 )
1108
1109 client_created = threading.Event()
1110
1111 # Let us know when _Client() has been constructed (super().__init__ call)
1112 orig_init = FakeClientXMPP.__init__
1113
1114 def init_signal(
1115 self: FakeClientXMPP,
1116 jid: str,
1117 password: str,
1118 *args: Any,
1119 **kwargs: Any,
1120 ) -> None:
1121 orig_init(self, jid, password, *args, **kwargs)
1122 client_created.set()
1123
1124 monkeypatch.setattr(FakeClientXMPP, "__init__", init_signal, raising=True)
1125
1126 # Block connect so runner cannot complete before the timeout branch.
1127 def connect_blocks(
1128 self: FakeClientXMPP, **kw: Any
1129 ) -> asyncio.Future[bool]:
1130 fut: asyncio.Future[bool] = self.loop.create_future()
1131 # Never resolve.
1132 return fut
1133
1134 monkeypatch.setattr(
1135 FakeClientXMPP, "connect", connect_blocks, raising=True
1136 )
1137
1138 # Make done.wait deterministic without touching real threading.Event used
1139 # by Thread internals
1140 _patch_threading(
1141 monkeypatch,
1142 done_event_cls=_make_fake_done_event_cls(client_created),
1143 )
1144
1145 # Capture and control loop.call_soon_threadsafe behaviour
1146 import asyncio as _real_asyncio
1147
1148 orig_new_event_loop = _real_asyncio.new_event_loop
1149
1150 calls: list[str] = []
1151
1152 def new_event_loop_wrapped() -> _real_asyncio.AbstractEventLoop:
1153 loop = orig_new_event_loop()
1154 orig_csts = loop.call_soon_threadsafe
1155
1156 def csts(cb: Any, *a: Any) -> Any:
1157 # Identify which callback is being scheduled
1158 name = getattr(cb, "__name__", repr(cb))
1159 calls.append(name)
1160
1161 # Raise only for disconnect callback to hit try/except
1162 if name == "disconnect":
1163 raise RuntimeError("boom")
1164
1165 return orig_csts(cb, *a)
1166
1167 monkeypatch.setattr(loop, "call_soon_threadsafe", csts, raising=True)
1168 return loop
1169
1170 monkeypatch.setattr(
1171 xmpp_adapter.asyncio,
1172 "new_event_loop",
1173 new_event_loop_wrapped,
1174 raising=True,
1175 )
1176
1177 config = xmpp_adapter.XMPPConfig(
1178 jid="[email protected]",
1179 password="x",
1180 host="example.com",
1181 port=5223,
1182 secure=xmpp_adapter.SecureXMPPMode.TLS,
1183 verify_certificate=False,
1184 )
1185
1186 a = xmpp_adapter.SlixmppAdapter(
1187 config=config,
1188 targets=[("chat", "[email protected]")],
1189 subject="s",
1190 body="b",
1191 timeout=5.0,
1192 )
1193
1194 assert a.process() is False
1195
1196 # We should have attempted both disconnect and loop.stop scheduling
1197 assert "disconnect" in calls
1198 assert "stop" in calls
1199
1200
1201 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1202 def test_xmpp_timeout_cleanup_no_client_stop_exception_suppressed(
1203 monkeypatch: pytest.MonkeyPatch,
1204 ) -> None:
1205 """Cover timeout cleanup: loop_obj != None"""
1206 install_fake_slixmpp(monkeypatch)
1207
1208 monkeypatch.setattr(
1209 xmpp_adapter.SlixmppAdapter, "_enabled", True, raising=True
1210 )
1211
1212 loop_created = threading.Event()
1213 allow_client_create = threading.Event()
1214
1215 # Block FakeClientXMPP.__init__ so shared['client'] never gets set before
1216 # timeout
1217 orig_init = FakeClientXMPP.__init__
1218
1219 def init_block(
1220 self: FakeClientXMPP,
1221 jid: str,
1222 password: str,
1223 *args: Any,
1224 **kwargs: Any,
1225 ) -> None:
1226 # Wait until main thread has already taken the timeout path
1227 allow_client_create.wait(timeout=1.0)
1228 orig_init(self, jid, password, *args, **kwargs)
1229
1230 monkeypatch.setattr(FakeClientXMPP, "__init__", init_block, raising=True)
1231
1232 # Deterministic done.wait: wait until loop exists, then force timeout
1233 _patch_threading(
1234 monkeypatch,
1235 done_event_cls=_make_fake_done_event_cls(loop_created),
1236 )
1237
1238 # Wrap new_event_loop so we can (a) signal loop exists and (b) make stop
1239 # raise
1240 import asyncio as _real_asyncio
1241
1242 orig_new_event_loop = _real_asyncio.new_event_loop
1243
1244 calls: list[str] = []
1245
1246 def new_event_loop_wrapped() -> _real_asyncio.AbstractEventLoop:
1247 loop = orig_new_event_loop()
1248 loop_created.set()
1249
1250 def csts(cb: Any, *a: Any) -> Any:
1251 name = getattr(cb, "__name__", repr(cb))
1252 calls.append(name)
1253 if name == "stop":
1254 raise RuntimeError("boom-stop")
1255 return None
1256
1257 monkeypatch.setattr(loop, "call_soon_threadsafe", csts, raising=True)
1258 return loop
1259
1260 monkeypatch.setattr(
1261 xmpp_adapter.asyncio,
1262 "new_event_loop",
1263 new_event_loop_wrapped,
1264 raising=True,
1265 )
1266
1267 config = xmpp_adapter.XMPPConfig(
1268 jid="[email protected]",
1269 password="x",
1270 host="example.com",
1271 port=5223,
1272 secure=xmpp_adapter.SecureXMPPMode.NONE,
1273 verify_certificate=False,
1274 )
1275
1276 a = xmpp_adapter.SlixmppAdapter(
1277 config=config,
1278 targets=[("chat", "[email protected]")],
1279 subject="s",
1280 body="b",
1281 timeout=5.0,
1282 )
1283
1284 try:
1285 assert a.process() is False
1286 # client_obj is None, so no disconnect scheduling attempt should occur
1287 assert "disconnect" not in calls
1288 # stop scheduling attempted and exception suppressed
1289 assert "stop" in calls
1290 finally:
1291 # Unblock the runner thread so it does not linger
1292 allow_client_create.set()
1293
1294
1295 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1296 def test_xmpp_timeout_cleanup_loop_none_skips_disconnect_and_stop(
1297 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
1298 ) -> None:
1299 """Cover timeout clean-up branch where shared['loop'] is still None."""
1300 install_fake_slixmpp(monkeypatch)
1301
1302 # Some test modules disable logging globally at import time (see
1303 # "Disable logging for a cleaner testing output" elsewhere in the
1304 # suite). caplog.set_level() only relies on newer pytest versions to
1305 # un-suppress that global disable -- older pytest releases (as
1306 # packaged for some RPM builds) do not, leaving caplog.text empty
1307 # regardless of the level requested. Force logging on explicitly so
1308 # this assertion holds under any pytest version or collection order.
1309 logging.disable(logging.NOTSET)
1310 caplog.set_level(logging.WARNING, logger="apprise.xmpp")
1311
1312 # Ensure adapter is enabled
1313 monkeypatch.setattr(
1314 xmpp_adapter.SlixmppAdapter, "_enabled", True, raising=True
1315 )
1316
1317 # Gate used to block runner before it can assign shared["loop"].
1318 gate = threading.Event()
1319
1320 # Raised by new_event_loop_blocking as soon as the worker enters it --
1321 # before any loop object is created and before shared["loop"] is set.
1322 # This lets done.wait() synchronize on this checkpoint so we have a
1323 # deterministic guarantee that shared["loop"] is still None when the
1324 # main-thread timeout cleanup runs.
1325 worker_entered_gate = threading.Event()
1326
1327 # Patch asyncio.new_event_loop to block until we allow it, so
1328 # shared["loop"] remains None when the timeout clean-up executes.
1329 import asyncio as _real_asyncio
1330
1331 orig_new_event_loop = _real_asyncio.new_event_loop
1332
1333 def new_event_loop_blocking() -> _real_asyncio.AbstractEventLoop:
1334 # Signal the main thread: we are inside new_event_loop_blocking and
1335 # shared["loop"] has not been set yet.
1336 worker_entered_gate.set()
1337 gate.wait(timeout=2.0)
1338 return orig_new_event_loop()
1339
1340 monkeypatch.setattr(
1341 xmpp_adapter.asyncio,
1342 "new_event_loop",
1343 new_event_loop_blocking,
1344 raising=True,
1345 )
1346
1347 # Make done.wait deterministic: wait until the worker has entered
1348 # new_event_loop_blocking (guaranteeing shared["loop"] is still None)
1349 # before forcing the timeout branch.
1350 _patch_threading(
1351 monkeypatch,
1352 done_event_cls=_make_fake_done_event_cls(worker_entered_gate),
1353 )
1354
1355 # Track whether any loop clean-up scheduling occurs.
1356 # It must NOT when loop_obj is None.
1357 called = {"disconnect": 0, "stop": 0}
1358
1359 # Block connect so runner cannot complete before the timeout branch.
1360 def connect_blocks(
1361 self: FakeClientXMPP, **kw: Any
1362 ) -> asyncio.Future[bool]:
1363 fut: asyncio.Future[bool] = self.loop.create_future()
1364 # Never resolve.
1365 return fut
1366
1367 monkeypatch.setattr(
1368 FakeClientXMPP, "connect", connect_blocks, raising=True
1369 )
1370
1371 # As an extra guard, if loop.call_soon_threadsafe were somehow reached,
1372 # we'd see it via this patch. Since loop_obj is None, it must not.
1373 def fake_disconnect(self: FakeClientXMPP) -> None:
1374 called["disconnect"] += 1
1375
1376 monkeypatch.setattr(
1377 FakeClientXMPP, "disconnect", fake_disconnect, raising=True
1378 )
1379
1380 config = xmpp_adapter.XMPPConfig(
1381 jid="[email protected]",
1382 password="x",
1383 host="example.com",
1384 port=5223,
1385 secure=xmpp_adapter.SecureXMPPMode.TLS,
1386 verify_certificate=False,
1387 )
1388
1389 a = xmpp_adapter.SlixmppAdapter(
1390 config=config,
1391 targets=[("chat", "[email protected]")],
1392 subject="s",
1393 body="b",
1394 timeout=5.0,
1395 )
1396
1397 try:
1398 # done.wait blocks until the worker signals worker_entered_gate
1399 # (guaranteeing shared["loop"] is None), then returns False
1400 # immediately, so the timeout clean-up sees loop_obj=None.
1401 assert a.process() is False
1402 assert "XMPP send timed out" in caplog.text
1403
1404 # No disconnect should have been scheduled because loop_obj was None.
1405 assert called["disconnect"] == 0
1406
1407 finally:
1408 # Let the runner proceed and exit
1409 gate.set()
1410 logging.disable(logging.CRITICAL)
1411
1412
1413 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1414 def test_xmpp_process_unsupported_secure_mode(
1415 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
1416 ) -> None:
1417 """The process runner handles an unsupported secure mode."""
1418 install_fake_slixmpp(monkeypatch)
1419 # See test_xmpp_invalid_targets_logged for why this is needed: older
1420 # pytest releases don't un-suppress a prior logging.disable(CRITICAL)
1421 # left by another test module's import-time call.
1422 logging.disable(logging.NOTSET)
1423 caplog.set_level(logging.WARNING, logger="apprise.xmpp")
1424
1425 try:
1426 config = xmpp_adapter.XMPPConfig(
1427 jid="[email protected]",
1428 password="x",
1429 host="example.com",
1430 port=5222,
1431 secure="invalid",
1432 verify_certificate=False,
1433 )
1434
1435 a = xmpp_adapter.SlixmppAdapter(
1436 config=config,
1437 targets=[("chat", "[email protected]")],
1438 subject="s",
1439 body="b",
1440 timeout=5.0,
1441 )
1442
1443 assert a.process() is False
1444 assert "XMPP send failed" in caplog.text
1445
1446 finally:
1447 logging.disable(logging.CRITICAL)
1448
1449
1450 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1451 def test_xmpp_process_connect_timeout(
1452 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
1453 ) -> None:
1454 """Cover connect timeout branch (asyncio.TimeoutError)."""
1455 install_fake_slixmpp(monkeypatch)
1456 # See test_xmpp_invalid_targets_logged for why this is needed: older
1457 # pytest releases don't un-suppress a prior logging.disable(CRITICAL)
1458 # left by another test module's import-time call.
1459 logging.disable(logging.NOTSET)
1460 caplog.set_level(logging.WARNING, logger="apprise.xmpp")
1461
1462 try:
1463 # Return a Future that never resolves.
1464 connect_future: dict[str, Any] = {"fut": None}
1465
1466 def connect_never(
1467 self: FakeClientXMPP, **kw: Any
1468 ) -> asyncio.Future[bool]:
1469 fut: asyncio.Future[bool] = self.loop.create_future()
1470 connect_future["fut"] = fut
1471 return fut
1472
1473 monkeypatch.setattr(
1474 FakeClientXMPP, "connect", connect_never, raising=True
1475 )
1476
1477 # Force wait_for() to raise TimeoutError immediately for this
1478 # connect future.
1479 real_wait_for = xmpp_adapter.asyncio.wait_for
1480
1481 async def wait_for_patched(
1482 aw: Any, timeout: Optional[float] = None
1483 ) -> Any:
1484 if aw is connect_future["fut"]:
1485 raise asyncio.TimeoutError()
1486 return await real_wait_for(aw, timeout=timeout)
1487
1488 monkeypatch.setattr(
1489 xmpp_adapter.asyncio, "wait_for", wait_for_patched, raising=True
1490 )
1491
1492 config = xmpp_adapter.XMPPConfig(
1493 jid="[email protected]",
1494 password="x",
1495 host="example.com",
1496 port=5222,
1497 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
1498 verify_certificate=False,
1499 )
1500
1501 a = xmpp_adapter.SlixmppAdapter(
1502 config=config,
1503 targets=[("chat", "[email protected]")],
1504 subject="s",
1505 body="b",
1506 timeout=5.0,
1507 )
1508
1509 assert a.process() is False
1510 assert "XMPP connect timed out" in caplog.text
1511
1512 finally:
1513 logging.disable(logging.CRITICAL)
1514
1515
1516 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1517 def test_xmpp_process_session_timeout(
1518 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
1519 ) -> None:
1520 """Cover session timeout branch when waiting on client.disconnected."""
1521 install_fake_slixmpp(monkeypatch)
1522 # See test_xmpp_invalid_targets_logged for why this is needed: older
1523 # pytest releases don't un-suppress a prior logging.disable(CRITICAL)
1524 # left by another test module's import-time call.
1525 logging.disable(logging.NOTSET)
1526 caplog.set_level(logging.WARNING, logger="apprise.xmpp")
1527
1528 try:
1529 # Ensure disconnect does not complete the disconnected Future.
1530 def disconnect_no_complete(self: FakeClientXMPP) -> None:
1531 return None
1532
1533 monkeypatch.setattr(
1534 FakeClientXMPP, "disconnect", disconnect_no_complete, raising=True
1535 )
1536
1537 # Capture the disconnected future once connect() creates it. It
1538 # does not exist yet at __init__ time (see FakeClientXMPP.__init__),
1539 # so it must be captured here instead.
1540 real_connect = FakeClientXMPP.connect
1541 disconnected_future: dict[str, Any] = {"fut": None}
1542
1543 def connect_capture(self: FakeClientXMPP, **kwargs: Any) -> Any:
1544 fut = real_connect(self, **kwargs)
1545 disconnected_future["fut"] = self.disconnected
1546 return fut
1547
1548 monkeypatch.setattr(
1549 FakeClientXMPP, "connect", connect_capture, raising=True
1550 )
1551
1552 # Force wait_for() to raise TimeoutError immediately, but only for
1553 # the disconnected future -- matching by identity rather than call
1554 # order keeps this deterministic even if session_start's own
1555 # concurrently-scheduled task (MUC join, etc.) happens to call
1556 # wait_for() of its own accord first.
1557 real_wait_for = xmpp_adapter.asyncio.wait_for
1558
1559 def wait_for_patched(aw: Any, timeout: Optional[float] = None) -> Any:
1560 if aw is disconnected_future["fut"]:
1561 # If aw is a coroutine, close it to avoid warnings
1562 with contextlib.suppress(Exception):
1563 if hasattr(aw, "close"):
1564 aw.close()
1565 raise asyncio.TimeoutError()
1566 return real_wait_for(aw, timeout=timeout)
1567
1568 monkeypatch.setattr(
1569 xmpp_adapter.asyncio, "wait_for", wait_for_patched, raising=True
1570 )
1571
1572 config = xmpp_adapter.XMPPConfig(
1573 jid="[email protected]",
1574 password="x",
1575 host="example.com",
1576 port=5222,
1577 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
1578 verify_certificate=False,
1579 )
1580
1581 a = xmpp_adapter.SlixmppAdapter(
1582 config=config,
1583 targets=[("chat", "[email protected]")],
1584 subject="s",
1585 body="b",
1586 timeout=5.0,
1587 )
1588
1589 assert a.process() is False
1590 assert "XMPP session timed out" in caplog.text
1591
1592 finally:
1593 logging.disable(logging.CRITICAL)
1594
1595
1596 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1597 def test_xmpp_slixmpp_versioning(monkeypatch: pytest.MonkeyPatch) -> None:
1598 """
1599 Simple checks to verify versioning works correctly
1600 """
1601 # Garbage in... garbage out
1602 assert xmpp_adapter.SlixmppAdapter.supported_version("garbage") is False
1603 # These versions are too old
1604 assert xmpp_adapter.SlixmppAdapter.supported_version("1.0.0") is False
1605 assert xmpp_adapter.SlixmppAdapter.supported_version("1.10.0") is False
1606 assert xmpp_adapter.SlixmppAdapter.supported_version("1.14.1") is False
1607 assert xmpp_adapter.SlixmppAdapter.supported_version("1.15.0") is False
1608 assert xmpp_adapter.SlixmppAdapter.supported_version("1.15.1") is False
1609
1610 # Good version checks
1611 assert xmpp_adapter.SlixmppAdapter.supported_version("1.16.0") is True
1612 assert xmpp_adapter.SlixmppAdapter.supported_version("1.16") is True
1613 assert xmpp_adapter.SlixmppAdapter.supported_version("1.16.1") is True
1614 assert xmpp_adapter.SlixmppAdapter.supported_version("1.16.100") is True
1615 assert xmpp_adapter.SlixmppAdapter.supported_version("1.17.0") is True
1616
1617 # This version is too old
1618 assert xmpp_adapter.SlixmppAdapter.supported_version("1") is False
1619
1620 # This version is good
1621 assert xmpp_adapter.SlixmppAdapter.supported_version("3") is True
1622 assert xmpp_adapter.SlixmppAdapter.supported_version("3.2") is True
1623
1624 monkeypatch.setattr(
1625 xmpp_adapter, "SLIXMPP_SUPPORT_AVAILABLE", False, raising=False
1626 )
1627 monkeypatch.setattr(
1628 xmpp_adapter.SlixmppAdapter,
1629 "_enabled",
1630 False,
1631 raising=False,
1632 )
1633 assert xmpp_adapter.SlixmppAdapter.supported_version("3.2") is False
1634
1635
1636 # ---------------------------------------------------------------------------
1637 # Keepalive Tests
1638 # ---------------------------------------------------------------------------
1639
1640
1641 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1642 def test_xmpp_keepalive_url_and_parse() -> None:
1643 n = NotifyXMPP(
1644 host="example.com",
1645 user="[email protected]",
1646 password="x",
1647 targets=["[email protected]"],
1648 keepalive=True,
1649 )
1650 u = n.url(privacy=False)
1651 assert "keepalive=yes" in u
1652
1653 r = NotifyXMPP.parse_url(
1654 "xmpp://me:[email protected]/[email protected]?keepalive=yes"
1655 )
1656 assert r["keepalive"] is True
1657
1658
1659 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1660 def test_xmpp_keepalive_reuses_adapter_instance(
1661 monkeypatch: pytest.MonkeyPatch,
1662 ) -> None:
1663 created = {"count": 0}
1664 calls = {"send_message": 0, "process": 0}
1665
1666 class _Adapter:
1667 def __init__(self, *args: Any, **kwargs: Any) -> None:
1668 created["count"] += 1
1669 self.keepalive = kwargs.get("keepalive", False)
1670
1671 def process(self) -> bool:
1672 calls["process"] += 1
1673 return True
1674
1675 def send_message(self, **kwargs: Any) -> bool:
1676 calls["send_message"] += 1
1677 return True
1678
1679 def close(self) -> None:
1680 return None
1681
1682 monkeypatch.setattr(xmpp_base, "SlixmppAdapter", _Adapter, raising=True)
1683
1684 # keepalive=yes should create adapter once, then reuse it
1685 n = NotifyXMPP(
1686 host="example.com",
1687 user="[email protected]",
1688 password="x",
1689 targets=["[email protected]"],
1690 keepalive=True,
1691 )
1692 assert n.send("body1", title="t1") is True
1693 assert n.send("body2", title="t2") is True
1694
1695 assert created["count"] == 1
1696 assert calls["send_message"] == 2
1697 assert calls["process"] == 0
1698
1699 # keepalive=no should not reuse adapter, it uses process() one-shot
1700 created["count"] = 0
1701 calls["send_message"] = 0
1702 calls["process"] = 0
1703
1704 n = NotifyXMPP(
1705 host="example.com",
1706 user="[email protected]",
1707 password="x",
1708 targets=["[email protected]"],
1709 keepalive=False,
1710 )
1711 assert n.send("body", title="t") is True
1712 assert created["count"] == 1
1713 assert calls["process"] == 1
1714 assert calls["send_message"] == 0
1715
1716
1717 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1718 def test_adapter_send_message_keepalive_false_calls_process(
1719 monkeypatch: pytest.MonkeyPatch,
1720 ) -> None:
1721 install_fake_slixmpp(monkeypatch)
1722 config = xmpp_adapter.XMPPConfig(
1723 jid="[email protected]",
1724 password="x",
1725 host="example.com",
1726 port=5222,
1727 secure=xmpp_adapter.SecureXMPPMode.NONE,
1728 verify_certificate=False,
1729 )
1730 a = xmpp_adapter.SlixmppAdapter(
1731 config=config,
1732 targets=[("chat", "[email protected]")],
1733 subject="s",
1734 body="b",
1735 timeout=5.0,
1736 keepalive=False,
1737 )
1738
1739 called = {"process": 0}
1740
1741 def process() -> bool:
1742 called["process"] += 1
1743 return True
1744
1745 monkeypatch.setattr(a, "process", process, raising=True)
1746
1747 assert a.send_message(targets=["x"], subject="y", body="z") is True
1748 assert called["process"] == 1
1749 assert a.targets == ["x"]
1750 assert a.subject == "y"
1751 assert a.body == "z"
1752
1753
1754 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1755 def test_adapter_ensure_keepalive_worker_edge_cases(
1756 monkeypatch: pytest.MonkeyPatch,
1757 ) -> None:
1758 install_fake_slixmpp(monkeypatch)
1759 config = xmpp_adapter.XMPPConfig(
1760 jid="[email protected]",
1761 password="x",
1762 host="example.com",
1763 port=5222,
1764 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
1765 verify_certificate=False,
1766 )
1767
1768 # keepalive False => False
1769 a = xmpp_adapter.SlixmppAdapter(
1770 config=config,
1771 targets=[],
1772 subject="s",
1773 body="b",
1774 keepalive=False,
1775 )
1776 assert a._ensure_keepalive_worker() is False
1777
1778 # keepalive True but closing => False
1779 a = xmpp_adapter.SlixmppAdapter(
1780 config=config,
1781 targets=[],
1782 subject="s",
1783 body="b",
1784 keepalive=True,
1785 )
1786 a._closing = True
1787 assert a._ensure_keepalive_worker() is False
1788
1789 # keepalive True but disabled => False
1790 a = xmpp_adapter.SlixmppAdapter(
1791 config=config,
1792 targets=[],
1793 subject="s",
1794 body="b",
1795 keepalive=True,
1796 )
1797 monkeypatch.setattr(a, "_enabled", False, raising=True)
1798 assert a._ensure_keepalive_worker() is False
1799
1800 # thread already alive => True
1801 a = xmpp_adapter.SlixmppAdapter(
1802 config=config,
1803 targets=[],
1804 subject="s",
1805 body="b",
1806 keepalive=True,
1807 )
1808
1809 class _AliveThread:
1810 def is_alive(self) -> bool:
1811 return True
1812
1813 a._thread = _AliveThread()
1814 assert a._ensure_keepalive_worker() is True
1815
1816
1817 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1818 def test_adapter_ensure_keepalive_worker_wait_timeout(
1819 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
1820 ) -> None:
1821 install_fake_slixmpp(monkeypatch)
1822 # See test_xmpp_invalid_targets_logged for why this is needed: older
1823 # pytest releases don't un-suppress a prior logging.disable(CRITICAL)
1824 # left by another test module's import-time call.
1825 logging.disable(logging.NOTSET)
1826 caplog.set_level(logging.WARNING, logger="apprise.xmpp")
1827
1828 try:
1829 config = xmpp_adapter.XMPPConfig(
1830 jid="[email protected]",
1831 password="x",
1832 host="example.com",
1833 port=5222,
1834 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
1835 verify_certificate=False,
1836 )
1837 a = xmpp_adapter.SlixmppAdapter(
1838 config=config,
1839 targets=[],
1840 subject="s",
1841 body="b",
1842 timeout=0.1,
1843 keepalive=True,
1844 )
1845
1846 # Prevent starting a real loop thread
1847 monkeypatch.setattr(a, "_keepalive_runner", lambda: None, raising=True)
1848
1849 # Force wait() to fail
1850 monkeypatch.setattr(
1851 a._loop_ready, "wait", lambda timeout=None: False, raising=True
1852 )
1853
1854 assert a._ensure_keepalive_worker() is False
1855 assert "keepalive worker failed to start" in caplog.text
1856
1857 finally:
1858 logging.disable(logging.CRITICAL)
1859
1860
1861 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1862 def test_adapter_connect_if_required_early_returns(
1863 monkeypatch: pytest.MonkeyPatch,
1864 ) -> None:
1865 install_fake_slixmpp(monkeypatch)
1866 config = xmpp_adapter.XMPPConfig(
1867 jid="[email protected]",
1868 password="x",
1869 host="example.com",
1870 port=5222,
1871 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
1872 verify_certificate=False,
1873 )
1874 a = xmpp_adapter.SlixmppAdapter(
1875 config=config, targets=[], subject="s", body="b", keepalive=True
1876 )
1877
1878 assert asyncio.run(a._connect_if_required()) is False
1879
1880 loop = asyncio.new_event_loop()
1881 try:
1882 asyncio.set_event_loop(loop)
1883 a._loop = loop
1884
1885 assert run_on_loop(loop, a._connect_if_required()) is False
1886 a._client = SimpleNamespace()
1887 assert run_on_loop(loop, a._connect_if_required()) is False
1888 a._connect_lock = asyncio.Lock()
1889 assert run_on_loop(loop, a._connect_if_required()) is False
1890 a._session_started = asyncio.Event()
1891 assert run_on_loop(loop, a._connect_if_required()) is False
1892
1893 finally:
1894 with contextlib.suppress(Exception):
1895 asyncio.set_event_loop(None)
1896
1897 loop.close()
1898
1899
1900 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1901 def test_adapter_connect_if_required_already_connected(
1902 monkeypatch: pytest.MonkeyPatch,
1903 ) -> None:
1904 install_fake_slixmpp(monkeypatch)
1905 config = xmpp_adapter.XMPPConfig(
1906 jid="[email protected]",
1907 password="x",
1908 host="example.com",
1909 port=5222,
1910 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
1911 verify_certificate=False,
1912 )
1913 a = xmpp_adapter.SlixmppAdapter(
1914 config=config, targets=[], subject="s", body="b", keepalive=True
1915 )
1916
1917 loop = asyncio.new_event_loop()
1918 try:
1919 asyncio.set_event_loop(loop)
1920 a._loop = loop
1921 a._connect_lock = asyncio.Lock()
1922 a._session_started = asyncio.Event()
1923 a._session_started.set()
1924
1925 called = {"connect": 0}
1926
1927 class _Client:
1928 def connect(self, **kwargs: Any) -> Any:
1929 called["connect"] += 1
1930 fut = loop.create_future()
1931 fut.set_result(True)
1932 return fut
1933
1934 a._client = _Client()
1935 assert run_on_loop(loop, a._connect_if_required()) is True
1936 assert called["connect"] == 0
1937
1938 finally:
1939 with contextlib.suppress(Exception):
1940 asyncio.set_event_loop(None)
1941
1942 loop.close()
1943
1944
1945 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
1946 def test_adapter_connect_if_required_connect_timeout(
1947 monkeypatch: pytest.MonkeyPatch,
1948 ) -> None:
1949 install_fake_slixmpp(monkeypatch)
1950 config = xmpp_adapter.XMPPConfig(
1951 jid="[email protected]",
1952 password="x",
1953 host="example.com",
1954 port=5222,
1955 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
1956 verify_certificate=False,
1957 )
1958 a = xmpp_adapter.SlixmppAdapter(
1959 config=config,
1960 targets=[],
1961 subject="s",
1962 body="b",
1963 timeout=5.0,
1964 keepalive=True,
1965 )
1966
1967 loop = asyncio.new_event_loop()
1968 try:
1969 asyncio.set_event_loop(loop)
1970 a._loop = loop
1971 a._connect_lock = asyncio.Lock()
1972 a._session_started = asyncio.Event()
1973
1974 fut = loop.create_future()
1975
1976 class _Client:
1977 def connect(self, **kwargs: Any) -> Any:
1978 return fut
1979
1980 a._client = _Client()
1981
1982 real_wait_for = xmpp_adapter.asyncio.wait_for
1983
1984 def wait_for_patched(aw: Any, timeout: Optional[float] = None) -> Any:
1985 if aw is fut:
1986 raise asyncio.TimeoutError()
1987 return real_wait_for(aw, timeout=timeout)
1988
1989 monkeypatch.setattr(
1990 xmpp_adapter.asyncio, "wait_for", wait_for_patched, raising=True
1991 )
1992
1993 assert run_on_loop(loop, a._connect_if_required()) is False
1994
1995 finally:
1996 with contextlib.suppress(Exception):
1997 asyncio.set_event_loop(None)
1998
1999 loop.close()
2000
2001
2002 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2003 def test_adapter_connect_if_required_connect_exception(
2004 monkeypatch: pytest.MonkeyPatch,
2005 ) -> None:
2006 install_fake_slixmpp(monkeypatch)
2007 config = xmpp_adapter.XMPPConfig(
2008 jid="[email protected]",
2009 password="x",
2010 host="example.com",
2011 port=5222,
2012 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2013 verify_certificate=False,
2014 )
2015 a = xmpp_adapter.SlixmppAdapter(
2016 config=config, targets=[], subject="s", body="b", keepalive=True
2017 )
2018
2019 loop = asyncio.new_event_loop()
2020 try:
2021 asyncio.set_event_loop(loop)
2022 a._loop = loop
2023 a._connect_lock = asyncio.Lock()
2024 a._session_started = asyncio.Event()
2025
2026 class _Client:
2027 def connect(self, **kwargs: Any) -> Any:
2028 raise RuntimeError("boom")
2029
2030 a._client = _Client()
2031 assert run_on_loop(loop, a._connect_if_required()) is False
2032
2033 finally:
2034 with contextlib.suppress(Exception):
2035 asyncio.set_event_loop(None)
2036
2037 loop.close()
2038
2039
2040 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2041 def test_adapter_connect_if_required_session_start_timeout(
2042 monkeypatch: pytest.MonkeyPatch,
2043 ) -> None:
2044 install_fake_slixmpp(monkeypatch)
2045 config = xmpp_adapter.XMPPConfig(
2046 jid="[email protected]",
2047 password="x",
2048 host="example.com",
2049 port=5222,
2050 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2051 verify_certificate=False,
2052 )
2053 a = xmpp_adapter.SlixmppAdapter(
2054 config=config,
2055 targets=[],
2056 subject="s",
2057 body="b",
2058 timeout=5.0,
2059 keepalive=True,
2060 )
2061
2062 loop = asyncio.new_event_loop()
2063 try:
2064 asyncio.set_event_loop(loop)
2065 a._loop = loop
2066 a._connect_lock = asyncio.Lock()
2067 a._session_started = asyncio.Event()
2068
2069 fut = loop.create_future()
2070 fut.set_result(True)
2071
2072 class _Client:
2073 def connect(self, **kwargs: Any) -> Any:
2074 return fut
2075
2076 a._client = _Client()
2077
2078 # First wait_for succeeds (connect), second one raises
2079 # (session start wait)
2080 real_wait_for = xmpp_adapter.asyncio.wait_for
2081 calls = {"n": 0}
2082
2083 async def wait_for_patched(
2084 aw: Any, timeout: Optional[float] = None
2085 ) -> Any:
2086 calls["n"] += 1
2087 if calls["n"] == 2:
2088 # Prevent "coroutine Event.wait was never awaited"
2089 with contextlib.suppress(Exception):
2090 if hasattr(aw, "close"):
2091 aw.close()
2092
2093 raise asyncio.TimeoutError()
2094 return await real_wait_for(aw, timeout=timeout)
2095
2096 monkeypatch.setattr(
2097 xmpp_adapter.asyncio, "wait_for", wait_for_patched, raising=True
2098 )
2099
2100 assert run_on_loop(loop, a._connect_if_required()) is False
2101
2102 finally:
2103 with contextlib.suppress(Exception):
2104 asyncio.set_event_loop(None)
2105 loop.close()
2106
2107
2108 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2109 def test_adapter_send_keepalive_async_default_target_and_send_error(
2110 monkeypatch: pytest.MonkeyPatch,
2111 ) -> None:
2112 install_fake_slixmpp(monkeypatch)
2113 config = xmpp_adapter.XMPPConfig(
2114 jid="[email protected]",
2115 password="x",
2116 host="example.com",
2117 port=5222,
2118 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2119 verify_certificate=False,
2120 )
2121 a = xmpp_adapter.SlixmppAdapter(
2122 config=config, targets=[], subject="s", body="b", keepalive=True
2123 )
2124
2125 loop = asyncio.new_event_loop()
2126 try:
2127 asyncio.set_event_loop(loop)
2128 a._loop = loop
2129 a._connect_lock = asyncio.Lock()
2130 a._session_started = asyncio.Event()
2131 a._session_started.set()
2132
2133 sent: list[str] = []
2134
2135 class _Client:
2136 def send_message(self, **kwargs: Any) -> None:
2137 sent.append(kwargs.get("mto"))
2138
2139 a._client = _Client()
2140
2141 async def ok_connect() -> bool:
2142 return True
2143
2144 monkeypatch.setattr(
2145 a, "_connect_if_required", ok_connect, raising=True
2146 )
2147
2148 assert (
2149 run_on_loop(
2150 loop,
2151 a._send_keepalive_async(targets=[], subject="s", body="b"),
2152 )
2153 is True
2154 )
2155 assert sent == ["[email protected]"]
2156
2157 # Now force send_message to raise and ensure session_started clears
2158 def boom_send_message(self: _Client, **kwargs: Any) -> None:
2159 raise RuntimeError("boom-send")
2160
2161 monkeypatch.setattr(
2162 _Client, "send_message", boom_send_message, raising=True
2163 )
2164
2165 assert a._session_started.is_set() is True
2166
2167 assert (
2168 run_on_loop(
2169 loop,
2170 a._send_keepalive_async(targets=[], subject="s", body="b"),
2171 )
2172 is False
2173 )
2174 assert a._session_started.is_set() is False
2175
2176 finally:
2177 with contextlib.suppress(Exception):
2178 asyncio.set_event_loop(None)
2179 loop.close()
2180
2181
2182 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2183 def test_adapter_send_message_keepalive_timeout_and_exception(
2184 monkeypatch: pytest.MonkeyPatch,
2185 ) -> None:
2186 install_fake_slixmpp(monkeypatch)
2187 config = xmpp_adapter.XMPPConfig(
2188 jid="[email protected]",
2189 password="x",
2190 host="example.com",
2191 port=5222,
2192 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2193 verify_certificate=False,
2194 )
2195 a = xmpp_adapter.SlixmppAdapter(
2196 config=config,
2197 targets=[],
2198 subject="s",
2199 body="b",
2200 timeout=5.0,
2201 keepalive=True,
2202 )
2203
2204 # Ensure worker exists without spinning a real thread
2205 monkeypatch.setattr(
2206 a, "_ensure_keepalive_worker", lambda: True, raising=True
2207 )
2208
2209 calls: list[str] = []
2210
2211 class _Loop:
2212 def call_soon_threadsafe(self, cb: Any, *args: Any) -> None:
2213 calls.append(getattr(cb, "__name__", "cb"))
2214 cb(*args)
2215
2216 a._loop = _Loop()
2217
2218 cleared = {"n": 0}
2219
2220 class _Evt:
2221 def clear(self) -> None:
2222 cleared["n"] += 1
2223
2224 a._session_started = _Evt()
2225
2226 # Timeout path
2227 class _FutureTimeout:
2228 def result(self, timeout: Optional[float] = None) -> Any:
2229 raise xmpp_adapter.FuturesTimeoutError()
2230
2231 def run_coroutine_threadsafe_timeout(coro: Any, loop: Any) -> Any:
2232 # Prevent "never awaited" warnings
2233 with contextlib.suppress(Exception):
2234 coro.close()
2235 return _FutureTimeout()
2236
2237 monkeypatch.setattr(
2238 xmpp_adapter.asyncio,
2239 "run_coroutine_threadsafe",
2240 run_coroutine_threadsafe_timeout,
2241 raising=True,
2242 )
2243
2244 assert a.send_message(targets=[], subject="s", body="b") is False
2245 assert cleared["n"] == 1
2246
2247 # Exception path
2248 class _FutureError:
2249 def result(self, timeout: Optional[float] = None) -> Any:
2250 raise RuntimeError("boom")
2251
2252 monkeypatch.setattr(
2253 xmpp_adapter.asyncio,
2254 "run_coroutine_threadsafe",
2255 run_coroutine_threadsafe_timeout,
2256 raising=True,
2257 )
2258
2259 assert a.send_message(targets=[], subject="s", body="b") is False
2260
2261
2262 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2263 def test_adapter_del_suppresses_close_exception(
2264 monkeypatch: pytest.MonkeyPatch,
2265 ) -> None:
2266 """
2267 Cover SlixmppAdapter.__del__() exception suppression
2268 """
2269 install_fake_slixmpp(monkeypatch)
2270
2271 cfg = xmpp_adapter.XMPPConfig(
2272 jid="[email protected]",
2273 password="x",
2274 host="example.com",
2275 port=5222,
2276 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2277 verify_certificate=False,
2278 )
2279
2280 a = xmpp_adapter.SlixmppAdapter(
2281 config=cfg, targets=[], subject="s", body="b", keepalive=True
2282 )
2283
2284 def boom_close() -> None:
2285 raise RuntimeError("boom-close")
2286
2287 monkeypatch.setattr(a, "close", boom_close, raising=True)
2288
2289 # Ensure __del__ runs and does not raise
2290 del a
2291 gc.collect()
2292
2293
2294 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2295 def test_adapter_close_shutdown_paths_and_state_reset(
2296 monkeypatch: pytest.MonkeyPatch,
2297 ) -> None:
2298 """
2299 Cover close(): _shutdown() branches and loop.call_soon_threadsafe exception
2300 suppression, plus state reset
2301 """
2302 install_fake_slixmpp(monkeypatch)
2303
2304 cfg = xmpp_adapter.XMPPConfig(
2305 jid="[email protected]",
2306 password="x",
2307 host="example.com",
2308 port=5222,
2309 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2310 verify_certificate=False,
2311 )
2312
2313 a = xmpp_adapter.SlixmppAdapter(
2314 config=cfg, targets=[], subject="s", body="b", keepalive=True
2315 )
2316
2317 class _Client:
2318 def disconnect(self) -> None:
2319 raise RuntimeError("disconnect boom")
2320
2321 class _Loop:
2322 def __init__(self) -> None:
2323 self.called: list[str] = []
2324
2325 def stop(self) -> None:
2326 self.called.append("stop")
2327 raise RuntimeError("stop boom")
2328
2329 def call_soon_threadsafe(self, cb: Any, *args: Any) -> None:
2330 self.called.append("call_soon_threadsafe")
2331 # Execute immediately so _shutdown() runs in this test
2332 cb(*args)
2333
2334 class _Thread:
2335 def join(self, timeout: Optional[float] = None) -> None:
2336 return None
2337
2338 # Populate internals so close() takes the full path
2339 loop = _Loop()
2340 a._loop = loop
2341 a._client = _Client()
2342 a._thread = _Thread()
2343
2344 # Also set asyncio primitives to ensure they are nulled out
2345 a._connect_lock = asyncio.Lock()
2346 a._session_started = asyncio.Event()
2347
2348 a.close()
2349
2350 # State must be cleared
2351 assert a._thread is None
2352 assert a._loop is None
2353 assert a._client is None
2354 assert a._connect_lock is None
2355 assert a._session_started is None
2356
2357 # Ensure call_soon_threadsafe ran (and stop attempted inside _shutdown)
2358 assert "call_soon_threadsafe" in loop.called
2359 assert "stop" in loop.called
2360
2361
2362 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2363 def test_adapter_close_call_soon_threadsafe_raises_still_resets(
2364 monkeypatch: pytest.MonkeyPatch,
2365 ) -> None:
2366 """
2367 Cover close(): loop.call_soon_threadsafe(_shutdown) raising and being
2368 suppressed, while still joining and clearing state.
2369 """
2370 install_fake_slixmpp(monkeypatch)
2371
2372 cfg = xmpp_adapter.XMPPConfig(
2373 jid="[email protected]",
2374 password="x",
2375 host="example.com",
2376 port=5222,
2377 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2378 verify_certificate=False,
2379 )
2380
2381 a = xmpp_adapter.SlixmppAdapter(
2382 config=cfg, targets=[], subject="s", body="b", keepalive=True
2383 )
2384
2385 class _Loop:
2386 def call_soon_threadsafe(self, cb: Any, *args: Any) -> None:
2387 raise RuntimeError("csts boom")
2388
2389 def stop(self) -> None:
2390 return None
2391
2392 class _Thread:
2393 def join(self, timeout: Optional[float] = None) -> None:
2394 return None
2395
2396 a._loop = _Loop()
2397 a._client = SimpleNamespace(disconnect=lambda: None)
2398 a._thread = _Thread()
2399 a._connect_lock = asyncio.Lock()
2400 a._session_started = asyncio.Event()
2401
2402 a.close()
2403
2404 assert a._thread is None
2405 assert a._loop is None
2406 assert a._client is None
2407 assert a._connect_lock is None
2408 assert a._session_started is None
2409
2410
2411 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2412 def test_adapter_ensure_keepalive_worker_returns_true_at_end(
2413 monkeypatch: pytest.MonkeyPatch,
2414 ) -> None:
2415 """
2416 Hit _ensure_keepalive_worker() bottom return True
2417 """
2418 install_fake_slixmpp(monkeypatch)
2419
2420 cfg = xmpp_adapter.XMPPConfig(
2421 jid="[email protected]",
2422 password="x",
2423 host="example.com",
2424 port=5222,
2425 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2426 verify_certificate=False,
2427 )
2428
2429 a = xmpp_adapter.SlixmppAdapter(
2430 config=cfg,
2431 targets=[],
2432 subject="s",
2433 body="b",
2434 timeout=5.0,
2435 keepalive=True,
2436 )
2437
2438 # Make the runner set loop_ready quickly and exit, using a real thread.
2439 def runner() -> None:
2440 a._loop_ready.set()
2441 return None
2442
2443 monkeypatch.setattr(a, "_keepalive_runner", runner, raising=True)
2444
2445 assert a._ensure_keepalive_worker() is True
2446
2447
2448 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2449 def test_adapter_keepalive_runner_executes_and_register_plugin_suppressed(
2450 monkeypatch: pytest.MonkeyPatch,
2451 ) -> None:
2452 """
2453 Execute _keepalive_runner() including:
2454 - secure mode config
2455 - register_plugin() suppression
2456 - loop.run_forever() exit
2457 - finally: loop.stop/close
2458 """
2459 install_fake_slixmpp(monkeypatch)
2460
2461 # Force register_plugin to raise so the suppress(Exception) is exercised
2462 def boom_register_plugin(
2463 self: FakeClientXMPP, name: str, config: Optional[Any] = None
2464 ) -> None:
2465 raise RuntimeError("boom-plugin")
2466
2467 monkeypatch.setattr(
2468 FakeClientXMPP, "register_plugin", boom_register_plugin, raising=True
2469 )
2470
2471 # Wrap new_event_loop so we can make run_forever return immediately, and
2472 # make stop/close callable.
2473 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
2474
2475 def new_event_loop_wrapped() -> asyncio.AbstractEventLoop:
2476 loop = real_new_event_loop()
2477
2478 # Exit immediately instead of blocking forever
2479 monkeypatch.setattr(loop, "run_forever", lambda: None, raising=True)
2480
2481 # Ensure stop/close are callable (real loop has them already)
2482 return loop
2483
2484 monkeypatch.setattr(
2485 xmpp_adapter.asyncio,
2486 "new_event_loop",
2487 new_event_loop_wrapped,
2488 raising=True,
2489 )
2490
2491 cfg = xmpp_adapter.XMPPConfig(
2492 jid="[email protected]",
2493 password="x",
2494 host="example.com",
2495 port=5222,
2496 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2497 verify_certificate=False,
2498 )
2499
2500 a = xmpp_adapter.SlixmppAdapter(
2501 config=cfg, targets=[], subject="s", body="b", keepalive=True
2502 )
2503
2504 # Run synchronously. Since run_forever() is patched to return, this
2505 # should exit quickly.
2506 a._keepalive_runner()
2507
2508 # Worker should have published these before entering run_forever()
2509 assert a._loop is not None
2510 assert a._client is not None
2511 assert a._connect_lock is not None
2512 assert a._session_started is not None
2513
2514
2515 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2516 def test_adapter_connect_if_required_hits_bottom_return_true(
2517 monkeypatch: pytest.MonkeyPatch,
2518 ) -> None:
2519 """
2520 Cover _connect_if_required() success path reaching the final return True,
2521 not the early already-connected return.
2522 """
2523 install_fake_slixmpp(monkeypatch)
2524
2525 cfg = xmpp_adapter.XMPPConfig(
2526 jid="[email protected]",
2527 password="x",
2528 host="example.com",
2529 port=5222,
2530 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2531 verify_certificate=False,
2532 )
2533
2534 a = xmpp_adapter.SlixmppAdapter(
2535 config=cfg,
2536 targets=[],
2537 subject="s",
2538 body="b",
2539 timeout=5.0,
2540 keepalive=True,
2541 )
2542
2543 loop = asyncio.new_event_loop()
2544 try:
2545 asyncio.set_event_loop(loop)
2546 a._loop = loop
2547 a._connect_lock = asyncio.Lock()
2548 a._session_started = asyncio.Event()
2549
2550 fut = loop.create_future()
2551 fut.set_result(True)
2552
2553 class _Client:
2554 def connect(self, **kwargs: Any) -> Any:
2555 return fut
2556
2557 a._client = _Client()
2558
2559 # Patch wait_for so the second wait_for (session_started.wait()) sets
2560 # the event just in time, forcing the bottom return True.
2561 real_wait_for = xmpp_adapter.asyncio.wait_for
2562 calls = {"n": 0}
2563
2564 async def wait_for_patched(
2565 aw: Any, timeout: Optional[float] = None
2566 ) -> Any:
2567 calls["n"] += 1
2568 if calls["n"] == 2:
2569 assert a._session_started is not None
2570 a._session_started.set()
2571 return await real_wait_for(aw, timeout=timeout)
2572
2573 monkeypatch.setattr(
2574 xmpp_adapter.asyncio, "wait_for", wait_for_patched, raising=True
2575 )
2576
2577 assert run_on_loop(loop, a._connect_if_required()) is True
2578 finally:
2579 with contextlib.suppress(Exception):
2580 asyncio.set_event_loop(None)
2581 loop.close()
2582
2583
2584 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2585 def test_adapter_send_keepalive_async_connect_fail_branch(
2586 monkeypatch: pytest.MonkeyPatch,
2587 ) -> None:
2588 """
2589 Cover _send_keepalive_async(): if not ok: return False
2590 """
2591 install_fake_slixmpp(monkeypatch)
2592
2593 cfg = xmpp_adapter.XMPPConfig(
2594 jid="[email protected]",
2595 password="x",
2596 host="example.com",
2597 port=5222,
2598 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2599 verify_certificate=False,
2600 )
2601
2602 a = xmpp_adapter.SlixmppAdapter(
2603 config=cfg, targets=[], subject="s", body="b", keepalive=True
2604 )
2605
2606 # Must not be None, or it returns False earlier
2607 a._client = SimpleNamespace(send_message=lambda **kw: None)
2608
2609 async def fail_connect() -> bool:
2610 return False
2611
2612 monkeypatch.setattr(a, "_connect_if_required", fail_connect, raising=True)
2613
2614 assert (
2615 asyncio.run(
2616 a._send_keepalive_async(targets=["x"], subject="s", body="b")
2617 )
2618 is False
2619 )
2620
2621
2622 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2623 def test_adapter_send_keepalive_async_exception_when_session_started_none(
2624 monkeypatch: pytest.MonkeyPatch,
2625 ) -> None:
2626 """
2627 Cover _send_keepalive_async() exception path where _session_started is None
2628 so clear() is skipped
2629 """
2630 install_fake_slixmpp(monkeypatch)
2631
2632 cfg = xmpp_adapter.XMPPConfig(
2633 jid="[email protected]",
2634 password="x",
2635 host="example.com",
2636 port=5222,
2637 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2638 verify_certificate=False,
2639 )
2640
2641 a = xmpp_adapter.SlixmppAdapter(
2642 config=cfg, targets=[], subject="s", body="b", keepalive=True
2643 )
2644
2645 async def ok_connect() -> bool:
2646 return True
2647
2648 monkeypatch.setattr(a, "_connect_if_required", ok_connect, raising=True)
2649
2650 class _Client:
2651 def send_message(self, **kwargs: Any) -> None:
2652 raise RuntimeError("boom-send")
2653
2654 a._client = _Client()
2655
2656 # Key detail: explicitly set to None to take the "skip clear()" branch
2657 a._session_started = None
2658
2659 assert (
2660 asyncio.run(
2661 a._send_keepalive_async(targets=["x"], subject="s", body="b")
2662 )
2663 is False
2664 )
2665
2666
2667 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2668 def test_adapter_close_shutdown_client_none_branch(
2669 monkeypatch: pytest.MonkeyPatch,
2670 ) -> None:
2671 """
2672 Cover close(): _shutdown() path where client is None.
2673 """
2674 install_fake_slixmpp(monkeypatch)
2675
2676 cfg = xmpp_adapter.XMPPConfig(
2677 jid="[email protected]",
2678 password="x",
2679 host="example.com",
2680 port=5222,
2681 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2682 verify_certificate=False,
2683 )
2684 a = xmpp_adapter.SlixmppAdapter(
2685 config=cfg, targets=[], subject="s", body="b", keepalive=True
2686 )
2687
2688 class _Loop:
2689 def __init__(self) -> None:
2690 self.stopped = False
2691 self.called = False
2692
2693 def stop(self) -> None:
2694 self.stopped = True
2695
2696 def call_soon_threadsafe(self, cb: Any, *args: Any) -> None:
2697 self.called = True
2698 cb(*args)
2699
2700 class _Thread:
2701 def join(self, timeout: Optional[float] = None) -> None:
2702 return None
2703
2704 loop = _Loop()
2705 a._loop = loop
2706 a._thread = _Thread()
2707
2708 # Key: ensure client is None so if client is not None is False
2709 a._client = None
2710
2711 a.close()
2712
2713 assert loop.called is True
2714 assert loop.stopped is True
2715 assert a._loop is None
2716 assert a._thread is None
2717 assert a._client is None
2718
2719
2720 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2721 def test_adapter_close_thread_alive_returns_without_clearing_state(
2722 monkeypatch: pytest.MonkeyPatch,
2723 ) -> None:
2724 """Cover close() branch where worker thread is still alive."""
2725 install_fake_slixmpp(monkeypatch)
2726
2727 cfg = xmpp_adapter.XMPPConfig(
2728 jid="[email protected]",
2729 password="x",
2730 host="example.com",
2731 port=5222,
2732 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2733 verify_certificate=False,
2734 )
2735
2736 a = xmpp_adapter.SlixmppAdapter(
2737 config=cfg, targets=[], subject="s", body="b", keepalive=True
2738 )
2739
2740 class _Client:
2741 def disconnect(self) -> None:
2742 return None
2743
2744 class _Loop:
2745 def __init__(self) -> None:
2746 self.called: list[str] = []
2747
2748 def stop(self) -> None:
2749 self.called.append("stop")
2750
2751 def call_soon_threadsafe(self, cb: Any, *args: Any) -> None:
2752 self.called.append("call_soon_threadsafe")
2753 cb(*args)
2754
2755 class _Thread:
2756 def join(self, timeout: Optional[float] = None) -> None:
2757 return None
2758
2759 def is_alive(self) -> bool:
2760 return True
2761
2762 loop = _Loop()
2763 thread = _Thread()
2764
2765 a._loop = loop
2766 a._client = _Client()
2767 a._thread = thread
2768 a._connect_lock = asyncio.Lock()
2769 a._session_started = asyncio.Event()
2770
2771 a.close()
2772
2773 assert a._loop is loop
2774 assert a._thread is thread
2775 assert loop.called[0] == "call_soon_threadsafe"
2776
2777
2778 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2779 def test_adapter_keepalive_runner_returns_if_closing_before_publish(
2780 monkeypatch: pytest.MonkeyPatch,
2781 ) -> None:
2782 """Cover _keepalive_runner() state-lock early return when closing."""
2783 install_fake_slixmpp(monkeypatch)
2784
2785 cfg = xmpp_adapter.XMPPConfig(
2786 jid="[email protected]",
2787 password="x",
2788 host="example.com",
2789 port=5222,
2790 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2791 verify_certificate=False,
2792 )
2793
2794 a = xmpp_adapter.SlixmppAdapter(
2795 config=cfg, targets=[], subject="s", body="b", keepalive=True
2796 )
2797
2798 def _closing_register_plugin(
2799 self: FakeClientXMPP, name: str, config: Optional[Any] = None
2800 ) -> None:
2801 a._closing = True
2802 return None
2803
2804 monkeypatch.setattr(
2805 FakeClientXMPP,
2806 "register_plugin",
2807 _closing_register_plugin,
2808 raising=True,
2809 )
2810
2811 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
2812
2813 def _new_event_loop() -> asyncio.AbstractEventLoop:
2814 loop = real_new_event_loop()
2815 monkeypatch.setattr(
2816 loop,
2817 "run_forever",
2818 lambda: (_ for _ in ()).throw(AssertionError("run_forever")),
2819 raising=True,
2820 )
2821 return loop
2822
2823 monkeypatch.setattr(
2824 xmpp_adapter.asyncio,
2825 "new_event_loop",
2826 _new_event_loop,
2827 raising=True,
2828 )
2829
2830 a._loop_ready.clear()
2831 a._keepalive_runner()
2832
2833 assert a._loop_ready.is_set() is False
2834 assert a._loop is None
2835 assert a._client is None
2836
2837
2838 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2839 def test_adapter_keepalive_runner_finally_clears_state_when_closing(
2840 monkeypatch: pytest.MonkeyPatch,
2841 ) -> None:
2842 """Cover _keepalive_runner() finally state-clear when closing."""
2843 install_fake_slixmpp(monkeypatch)
2844
2845 cfg = xmpp_adapter.XMPPConfig(
2846 jid="[email protected]",
2847 password="x",
2848 host="example.com",
2849 port=5222,
2850 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2851 verify_certificate=False,
2852 )
2853
2854 a = xmpp_adapter.SlixmppAdapter(
2855 config=cfg, targets=[], subject="s", body="b", keepalive=True
2856 )
2857
2858 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
2859 created: list[asyncio.AbstractEventLoop] = []
2860
2861 def _new_event_loop() -> asyncio.AbstractEventLoop:
2862 loop = real_new_event_loop()
2863 created.append(loop)
2864
2865 def _run_forever() -> None:
2866 a._closing = True
2867 return None
2868
2869 monkeypatch.setattr(loop, "run_forever", _run_forever, raising=True)
2870 return loop
2871
2872 monkeypatch.setattr(
2873 xmpp_adapter.asyncio,
2874 "new_event_loop",
2875 _new_event_loop,
2876 raising=True,
2877 )
2878
2879 a._loop_ready.clear()
2880 a._keepalive_runner()
2881
2882 assert a._loop_ready.is_set() is True
2883 assert a._loop is None
2884 assert a._client is None
2885 assert a._connect_lock is None
2886 assert a._session_started is None
2887
2888 assert created
2889 assert created[0].is_closed()
2890
2891
2892 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2893 def test_adapter_keepalive_session_start_signals_on_error(
2894 monkeypatch: pytest.MonkeyPatch,
2895 ) -> None:
2896 """Cover keepalive _Client._session_start() exception handling."""
2897
2898 install_fake_slixmpp(monkeypatch)
2899
2900 cfg = xmpp_adapter.XMPPConfig(
2901 jid="[email protected]",
2902 password="x",
2903 host="ex.com",
2904 port=5222,
2905 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
2906 verify_certificate=False,
2907 )
2908
2909 a = xmpp_adapter.SlixmppAdapter(
2910 config=cfg,
2911 targets=[],
2912 subject="s",
2913 body="b",
2914 keepalive=True,
2915 roster=True,
2916 timeout=5.0,
2917 )
2918
2919 loop = asyncio.new_event_loop()
2920 # Detach from policy initially
2921 asyncio.set_event_loop(None)
2922
2923 try:
2924
2925 def run_forever_hook() -> None:
2926 client = a._client
2927 started = a._session_started
2928
2929 monkeypatch.setattr(
2930 client,
2931 "send_presence",
2932 lambda: (_ for _ in ()).throw(RuntimeError("fail")),
2933 raising=True,
2934 )
2935
2936 client._on_session_start()
2937
2938 async def wait_for_event():
2939 while not started.is_set():
2940 await asyncio.sleep(0.01)
2941
2942 # Assign to variable so we can explicitly close it if needed
2943 coro = wait_for_event()
2944 try:
2945 wf = asyncio.wait_for(coro, timeout=1.0)
2946 try:
2947 loop.run_until_complete(wf)
2948 finally:
2949 with contextlib.suppress(Exception):
2950 wf.close()
2951
2952 finally:
2953 # Prevent "coroutine was never awaited" warnings
2954 with contextlib.suppress(Exception):
2955 coro.close()
2956
2957 assert started.is_set() is True
2958 return None
2959
2960 monkeypatch.setattr(
2961 xmpp_adapter.asyncio,
2962 "new_event_loop",
2963 lambda: loop,
2964 )
2965 monkeypatch.setattr(loop, "run_forever", run_forever_hook)
2966
2967 a._keepalive_runner()
2968
2969 finally:
2970 if not loop.is_closed():
2971 # Cancel all tasks, including those from internal asyncio
2972 # machinery
2973 for task in asyncio.all_tasks(loop):
2974 task.cancel()
2975
2976 with contextlib.suppress(Exception):
2977 loop.run_until_complete(asyncio.sleep(0))
2978
2979 loop.close()
2980
2981 # Clean up global policies
2982 asyncio.set_event_loop(None)
2983
2984
2985 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
2986 def test_client_session_start_roster_timeout_closes_awaitable(
2987 monkeypatch: pytest.MonkeyPatch,
2988 ) -> None:
2989 """Cover roster timeout close path in _session_start()."""
2990 install_fake_slixmpp(monkeypatch)
2991
2992 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
2993
2994 called: list[object] = []
2995
2996 orig_close = xmpp_adapter._close_awaitable
2997
2998 def _spy_close(obj: object) -> None:
2999 called.append(obj)
3000 orig_close(obj)
3001
3002 monkeypatch.setattr(
3003 xmpp_adapter, "_close_awaitable", _spy_close, raising=True
3004 )
3005
3006 async def _raise_timeout(*args: object, **kwargs: object) -> None:
3007 raise asyncio.TimeoutError()
3008
3009 monkeypatch.setattr(
3010 xmpp_adapter.asyncio, "wait_for", _raise_timeout, raising=True
3011 )
3012
3013 loop = asyncio.new_event_loop()
3014 asyncio.set_event_loop(loop)
3015 try:
3016 evt = asyncio.Event()
3017 client = client_cls(
3018 jid="[email protected]",
3019 password="pass",
3020 oneshot=False,
3021 want_roster=True,
3022 roster_timeout=1.0,
3023 session_started_evt=evt,
3024 )
3025
3026 loop.run_until_complete(client._session_start())
3027 assert len(called) == 1
3028
3029 finally:
3030 asyncio.set_event_loop(None)
3031 loop.close()
3032
3033
3034 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3035 def test_client_session_start_keepalive_sets_ready_event(
3036 monkeypatch: pytest.MonkeyPatch,
3037 ) -> None:
3038 """Cover non-oneshot path in _session_start()."""
3039 install_fake_slixmpp(monkeypatch)
3040
3041 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
3042
3043 loop = asyncio.new_event_loop()
3044 asyncio.set_event_loop(loop)
3045 try:
3046 evt = asyncio.Event()
3047
3048 client = client_cls(
3049 jid="[email protected]",
3050 password="pass",
3051 oneshot=False,
3052 targets=["a", "b"],
3053 subject="s",
3054 body="b",
3055 before_message=lambda: None,
3056 want_roster=False,
3057 roster_timeout=0.0,
3058 session_started_evt=evt,
3059 )
3060
3061 monkeypatch.setattr(
3062 client,
3063 "send_message",
3064 lambda **k: (_ for _ in ()).throw(AssertionError()),
3065 raising=True,
3066 )
3067 monkeypatch.setattr(
3068 client,
3069 "disconnect",
3070 lambda: (_ for _ in ()).throw(AssertionError()),
3071 raising=True,
3072 )
3073
3074 loop.run_until_complete(client._session_start())
3075 assert evt.is_set() is True
3076
3077 finally:
3078 asyncio.set_event_loop(None)
3079 loop.close()
3080
3081
3082 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3083 def test_client_session_start_oneshot_sends_and_disconnects(
3084 monkeypatch: pytest.MonkeyPatch,
3085 ) -> None:
3086 """Cover oneshot path in _session_start() and finally disconnect."""
3087 install_fake_slixmpp(monkeypatch)
3088
3089 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
3090
3091 sent: list[dict[str, Any]] = []
3092 before: list[int] = []
3093 disconnected: list[bool] = []
3094
3095 def _before() -> None:
3096 before.append(1)
3097
3098 def _send_message(**kwargs: Any) -> None:
3099 sent.append(kwargs)
3100
3101 def _disconnect() -> None:
3102 disconnected.append(True)
3103
3104 loop = asyncio.new_event_loop()
3105 asyncio.set_event_loop(loop)
3106 try:
3107 client = client_cls(
3108 jid="[email protected]",
3109 password="pass",
3110 oneshot=True,
3111 targets=[("chat", "[email protected]"), ("chat", "[email protected]")],
3112 subject="sub",
3113 body="body",
3114 before_message=_before,
3115 want_roster=False,
3116 roster_timeout=0.0,
3117 session_started_evt=None,
3118 )
3119
3120 monkeypatch.setattr(
3121 client, "send_message", _send_message, raising=True
3122 )
3123 monkeypatch.setattr(client, "disconnect", _disconnect, raising=True)
3124
3125 loop.run_until_complete(client._session_start())
3126
3127 assert len(before) == 2
3128 assert len(sent) == 2
3129 assert all(msg.get("mtype") == "chat" for msg in sent)
3130 assert disconnected == [True]
3131
3132 finally:
3133 asyncio.set_event_loop(None)
3134 loop.close()
3135
3136
3137 def test_adapter_keepalive_runner_failed_handlers(
3138 monkeypatch: pytest.MonkeyPatch,
3139 ) -> None:
3140 """
3141 Cover keepalive _Client._failed_auth() and _disconnected().
3142 """
3143 install_fake_slixmpp(monkeypatch)
3144
3145 cfg = xmpp_adapter.XMPPConfig(
3146 jid="[email protected]",
3147 password="x",
3148 host="example.com",
3149 port=5222,
3150 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3151 verify_certificate=False,
3152 )
3153
3154 a = xmpp_adapter.SlixmppAdapter(
3155 config=cfg,
3156 targets=[],
3157 subject="s",
3158 body="b",
3159 keepalive=True,
3160 roster=False,
3161 )
3162
3163 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
3164
3165 def new_event_loop_wrapped() -> asyncio.AbstractEventLoop:
3166 loop = real_new_event_loop()
3167
3168 def run_forever_hook() -> None:
3169 client = a._client
3170 started = a._session_started
3171 assert client is not None
3172 assert started is not None
3173
3174 disconnected = {"called": 0}
3175
3176 def disconnect_spy() -> None:
3177 disconnected["called"] += 1
3178
3179 monkeypatch.setattr(
3180 client, "disconnect", disconnect_spy, raising=True
3181 )
3182
3183 # Mark started True, then failed_auth must clear + disconnect
3184 started.set()
3185 client._failed_auth()
3186 assert started.is_set() is False
3187 assert disconnected["called"] == 1
3188
3189 # Mark started True again, disconnected must clear, no disconnect
3190 # call
3191 started.set()
3192 client._disconnected()
3193 assert started.is_set() is False
3194 assert disconnected["called"] == 1
3195
3196 return None
3197
3198 monkeypatch.setattr(
3199 loop, "run_forever", run_forever_hook, raising=True
3200 )
3201 return loop
3202
3203 monkeypatch.setattr(
3204 xmpp_adapter.asyncio,
3205 "new_event_loop",
3206 new_event_loop_wrapped,
3207 raising=True,
3208 )
3209
3210 a._keepalive_runner()
3211
3212
3213 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3214 def test_keepalive_runner_rejects_secure_mode(
3215 monkeypatch: pytest.MonkeyPatch,
3216 ) -> None:
3217 """The keepalive runner handles an unsupported secure mode."""
3218 install_fake_slixmpp(monkeypatch)
3219
3220 cfg = xmpp_adapter.XMPPConfig(
3221 jid="[email protected]",
3222 password="x",
3223 host="example.com",
3224 port=5222,
3225 secure="definitely-not-supported",
3226 verify_certificate=False,
3227 )
3228
3229 a = xmpp_adapter.SlixmppAdapter(
3230 config=cfg, targets=[], subject="s", body="b", keepalive=True
3231 )
3232
3233 # Ensure clean initial state
3234 a._loop_ready.clear()
3235
3236 # Patch run_forever to be safe if it ever reaches it (it should not)
3237 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
3238
3239 def new_event_loop_wrapped() -> asyncio.AbstractEventLoop:
3240 loop = real_new_event_loop()
3241 monkeypatch.setattr(loop, "run_forever", lambda: None, raising=True)
3242 return loop
3243
3244 monkeypatch.setattr(
3245 xmpp_adapter.asyncio,
3246 "new_event_loop",
3247 new_event_loop_wrapped,
3248 raising=True,
3249 )
3250
3251 a._keepalive_runner()
3252
3253 # Since secure mode invalid, it should not publish loop/client state
3254 assert a._loop_ready.is_set() is False
3255 assert a._loop is None
3256 assert a._client is None
3257 assert a._connect_lock is None
3258 assert a._session_started is None
3259
3260
3261 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3262 def test_adapter_keepalive_session_start_try_finally_and_roster(
3263 monkeypatch: pytest.MonkeyPatch,
3264 ) -> None:
3265 """
3266 Cover _session_start() try/finally and roster handling:
3267 - try/finally always sets _session_started_evt
3268 - roster path is taken and roster errors are suppressed
3269 - send_presence exception still leads to finally:set()
3270 """
3271 install_fake_slixmpp(monkeypatch)
3272
3273 cfg = xmpp_adapter.XMPPConfig(
3274 jid="[email protected]",
3275 password="x",
3276 host="example.com",
3277 port=5222,
3278 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3279 verify_certificate=False,
3280 )
3281
3282 a = xmpp_adapter.SlixmppAdapter(
3283 config=cfg,
3284 targets=[],
3285 subject="s",
3286 body="b",
3287 keepalive=True,
3288 roster=True,
3289 timeout=5.0,
3290 )
3291
3292 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
3293
3294 def new_event_loop_wrapped() -> asyncio.AbstractEventLoop:
3295 loop = real_new_event_loop()
3296
3297 def run_forever_hook() -> None:
3298 client = a._client
3299 evt = a._session_started
3300 assert client is not None
3301 assert evt is not None
3302
3303 # Case 1: roster enabled, get_roster raises but suppressed
3304 def send_presence_ok() -> None:
3305 return None
3306
3307 async def get_roster_boom() -> None:
3308 raise RuntimeError("boom-roster")
3309
3310 monkeypatch.setattr(
3311 client, "send_presence", send_presence_ok, raising=True
3312 )
3313 monkeypatch.setattr(
3314 client, "get_roster", get_roster_boom, raising=True
3315 )
3316
3317 evt.clear()
3318 client._on_session_start()
3319 # Drive the loop without creating extra coroutine objects
3320 for _ in range(10):
3321 fut = loop.create_future()
3322 loop.call_soon(fut.set_result, None)
3323 loop.run_until_complete(fut)
3324 if evt.is_set():
3325 break
3326 xmpp_adapter.SlixmppAdapter._finalize_loop(loop)
3327 assert evt.is_set() is True
3328
3329 # Case 2: send_presence raises, finally must still set
3330 def send_presence_boom() -> None:
3331 raise RuntimeError("boom-presence")
3332
3333 monkeypatch.setattr(
3334 client, "send_presence", send_presence_boom, raising=True
3335 )
3336
3337 evt.clear()
3338 client._on_session_start()
3339 # Drive the loop without creating extra coroutine objects
3340 for _ in range(10):
3341 fut = loop.create_future()
3342 loop.call_soon(fut.set_result, None)
3343 loop.run_until_complete(fut)
3344 if evt.is_set():
3345 break
3346 xmpp_adapter.SlixmppAdapter._finalize_loop(loop)
3347 assert evt.is_set() is True
3348
3349 return None
3350
3351 monkeypatch.setattr(
3352 loop, "run_forever", run_forever_hook, raising=True
3353 )
3354 return loop
3355
3356 monkeypatch.setattr(
3357 xmpp_adapter.asyncio,
3358 "new_event_loop",
3359 new_event_loop_wrapped,
3360 raising=True,
3361 )
3362
3363 a._keepalive_runner()
3364
3365
3366 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3367 def test_adapter_keepalive_runner_plaintext_mode_skips_ssl_context(
3368 monkeypatch: pytest.MonkeyPatch,
3369 ) -> None:
3370 """
3371 Cover adapter.py - ensuring enable_plaintext=True,
3372 so 'if not client.enable_plaintext' is False and ssl_context is not set.
3373 """
3374 install_fake_slixmpp(monkeypatch)
3375
3376 cfg = xmpp_adapter.XMPPConfig(
3377 jid="[email protected]",
3378 password="x",
3379 host="example.com",
3380 port=5222,
3381 secure=xmpp_adapter.SecureXMPPMode.NONE,
3382 verify_certificate=False,
3383 )
3384
3385 a = xmpp_adapter.SlixmppAdapter(
3386 config=cfg,
3387 targets=[],
3388 subject="s",
3389 body="b",
3390 keepalive=True,
3391 timeout=5.0,
3392 )
3393
3394 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
3395
3396 def new_event_loop_wrapped() -> asyncio.AbstractEventLoop:
3397 loop = real_new_event_loop()
3398
3399 def run_forever_hook() -> None:
3400 # At this point the client has been created and configured.
3401 assert a._client is not None
3402
3403 # In plaintext mode we expect ssl_context not to be forced by
3404 # adapter.
3405 assert getattr(a._client, "enable_plaintext", None) is True
3406 assert getattr(a._client, "ssl_context", None) is None
3407 return None
3408
3409 monkeypatch.setattr(
3410 loop, "run_forever", run_forever_hook, raising=True
3411 )
3412 return loop
3413
3414 monkeypatch.setattr(
3415 xmpp_adapter.asyncio,
3416 "new_event_loop",
3417 new_event_loop_wrapped,
3418 raising=True,
3419 )
3420
3421 a._keepalive_runner()
3422
3423
3424 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3425 def test_adapter_keepalive_runner_finally_loop_none(
3426 monkeypatch: pytest.MonkeyPatch,
3427 ) -> None:
3428 """
3429 Cover adapter.py when loop is None (new_event_loop fails),
3430 so both 'if loop is not None' conditions are False.
3431 """
3432 install_fake_slixmpp(monkeypatch)
3433
3434 monkeypatch.setattr(
3435 xmpp_adapter.asyncio,
3436 "new_event_loop",
3437 lambda: (_ for _ in ()).throw(RuntimeError("boom")),
3438 raising=True,
3439 )
3440
3441 cfg = xmpp_adapter.XMPPConfig(
3442 jid="[email protected]",
3443 password="x",
3444 host="example.com",
3445 port=5222,
3446 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3447 verify_certificate=False,
3448 )
3449 a = xmpp_adapter.SlixmppAdapter(
3450 config=cfg, targets=[], subject="s", body="b", keepalive=True
3451 )
3452
3453 # Should not raise, finally must handle loop=None
3454 a._keepalive_runner()
3455
3456
3457 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3458 def test_adapter_runner_suppresses_cleanup_errors(
3459 monkeypatch: pytest.MonkeyPatch,
3460 ) -> None:
3461 """Ensure event-loop cleanup errors do not escape the runner."""
3462 install_fake_slixmpp(monkeypatch)
3463
3464 cfg = xmpp_adapter.XMPPConfig(
3465 jid="[email protected]",
3466 password="x",
3467 host="ex.com",
3468 port=5222,
3469 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3470 verify_certificate=False,
3471 )
3472
3473 a = xmpp_adapter.SlixmppAdapter(
3474 config=cfg,
3475 targets=[],
3476 subject="s",
3477 body="b",
3478 keepalive=True,
3479 roster=True,
3480 timeout=5.0,
3481 )
3482
3483 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
3484
3485 def new_event_loop_wrapped() -> asyncio.AbstractEventLoop:
3486 loop = real_new_event_loop()
3487
3488 # Force finally path with a raised exception from run_forever
3489 def run_forever_boom() -> None:
3490 raise RuntimeError("boom-forever")
3491
3492 monkeypatch.setattr(
3493 loop, "run_forever", run_forever_boom, raising=True
3494 )
3495
3496 # Raise after real cleanup so the event loop does not leak resources.
3497 real_stop = loop.stop
3498 real_close = loop.close
3499
3500 def stop_boom() -> None:
3501 real_stop()
3502 raise RuntimeError("boom-stop")
3503
3504 def close_boom() -> None:
3505 real_close()
3506 raise RuntimeError("boom-close")
3507
3508 monkeypatch.setattr(loop, "stop", stop_boom, raising=True)
3509 monkeypatch.setattr(loop, "close", close_boom, raising=True)
3510
3511 return loop
3512
3513 monkeypatch.setattr(
3514 xmpp_adapter.asyncio,
3515 "new_event_loop",
3516 new_event_loop_wrapped,
3517 raising=True,
3518 )
3519
3520 cfg = xmpp_adapter.XMPPConfig(
3521 jid="[email protected]",
3522 password="x",
3523 host="example.com",
3524 port=5222,
3525 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3526 verify_certificate=False,
3527 )
3528 a = xmpp_adapter.SlixmppAdapter(
3529 config=cfg, targets=[], subject="s", body="b", keepalive=True
3530 )
3531
3532 # Should not raise, stop/close exceptions must be suppressed
3533 a._keepalive_runner()
3534
3535
3536 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3537 def test_adapter_send_keepalive_async_returns_false_when_client_none(
3538 monkeypatch: pytest.MonkeyPatch,
3539 ) -> None:
3540 """Cover adapter.py _client is None -> return False."""
3541 install_fake_slixmpp(monkeypatch)
3542
3543 cfg = xmpp_adapter.XMPPConfig(
3544 jid="[email protected]",
3545 password="x",
3546 host="example.com",
3547 port=5222,
3548 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3549 verify_certificate=False,
3550 )
3551 a = xmpp_adapter.SlixmppAdapter(
3552 config=cfg,
3553 targets=[],
3554 subject="s",
3555 body="b",
3556 keepalive=True,
3557 )
3558
3559 a._client = None
3560
3561 loop = asyncio.new_event_loop()
3562 try:
3563 asyncio.set_event_loop(loop)
3564 result = loop.run_until_complete(
3565 a._send_keepalive_async(["t"], "s", "b")
3566 )
3567 assert result is False
3568
3569 finally:
3570 with contextlib.suppress(Exception):
3571 asyncio.set_event_loop(None)
3572
3573 # Safe shutdown of asyncgens
3574 if not loop.is_closed():
3575 with contextlib.suppress(Exception):
3576 ag_coro = loop.shutdown_asyncgens()
3577 try:
3578 loop.run_until_complete(ag_coro)
3579 except Exception:
3580 # Reuse the helper from the adapter module if available,
3581 # or do a manual close
3582 if hasattr(ag_coro, "close"):
3583 ag_coro.close()
3584
3585 # Ensure close() is called even if the block above had issues
3586 with contextlib.suppress(Exception):
3587 loop.close()
3588
3589
3590 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3591 def test_adapter_keepalive_error_suppresses_close_failure(
3592 monkeypatch: pytest.MonkeyPatch,
3593 ) -> None:
3594 install_fake_slixmpp(monkeypatch)
3595
3596 config = xmpp_adapter.XMPPConfig(
3597 jid="[email protected]",
3598 password="x",
3599 host="example.com",
3600 port=5222,
3601 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3602 verify_certificate=False,
3603 )
3604 a = xmpp_adapter.SlixmppAdapter(
3605 config=config,
3606 targets=[],
3607 subject="s",
3608 body="b",
3609 timeout=5.0,
3610 keepalive=True,
3611 )
3612
3613 monkeypatch.setattr(
3614 a, "_ensure_keepalive_worker", lambda: True, raising=True
3615 )
3616
3617 class _Loop:
3618 def call_soon_threadsafe(self, cb: Any, *args: Any) -> None:
3619 cb(*args)
3620
3621 a._loop = _Loop()
3622
3623 class _BadCoro:
3624 def close(self) -> None:
3625 raise RuntimeError("close-failed")
3626
3627 monkeypatch.setattr(
3628 a, "_send_keepalive_async", lambda **kwargs: _BadCoro(), raising=True
3629 )
3630
3631 def run_coroutine_threadsafe_raises(coro: Any, loop: Any) -> Any:
3632 raise RuntimeError("schedule-failed")
3633
3634 monkeypatch.setattr(
3635 xmpp_adapter.asyncio,
3636 "run_coroutine_threadsafe",
3637 run_coroutine_threadsafe_raises,
3638 raising=True,
3639 )
3640
3641 assert a.send_message(targets=[], subject="s", body="b") is False
3642
3643
3644 def test_adapter_keepalive_failure_keeps_default_params(
3645 monkeypatch: pytest.MonkeyPatch,
3646 ) -> None:
3647 install_fake_slixmpp(monkeypatch)
3648
3649 config = xmpp_adapter.XMPPConfig(
3650 jid="[email protected]",
3651 password="x",
3652 host="example.com",
3653 port=5222,
3654 secure=xmpp_adapter.SecureXMPPMode.NONE,
3655 verify_certificate=False,
3656 )
3657
3658 a = xmpp_adapter.SlixmppAdapter(
3659 config=config,
3660 targets=[("chat", "[email protected]")],
3661 subject="orig-subj",
3662 body="orig-body",
3663 keepalive=False,
3664 )
3665
3666 called = {"process": 0}
3667
3668 def process() -> bool:
3669 called["process"] += 1
3670 return True
3671
3672 monkeypatch.setattr(a, "process", process, raising=True)
3673
3674 assert a.send_message() is True
3675 assert called["process"] == 1
3676 assert a.targets == [("chat", "[email protected]")]
3677 assert a.subject == "orig-subj"
3678 assert a.body == "orig-body"
3679
3680
3681 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3682 def test_adapter_send_message_keepalive_worker_failure_returns_false(
3683 monkeypatch: pytest.MonkeyPatch,
3684 ) -> None:
3685 install_fake_slixmpp(monkeypatch)
3686
3687 config = xmpp_adapter.XMPPConfig(
3688 jid="[email protected]",
3689 password="x",
3690 host="example.com",
3691 port=5222,
3692 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3693 verify_certificate=False,
3694 )
3695
3696 a = xmpp_adapter.SlixmppAdapter(
3697 config=config,
3698 targets=[("chat", "[email protected]")],
3699 subject="s",
3700 body="b",
3701 keepalive=True,
3702 )
3703
3704 monkeypatch.setattr(
3705 a, "_ensure_keepalive_worker", lambda: False, raising=True
3706 )
3707
3708 assert a.send_message() is False
3709
3710
3711 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3712 def test_adapter_keepalive_timeout_without_session_event(
3713 monkeypatch: pytest.MonkeyPatch,
3714 caplog: pytest.LogCaptureFixture,
3715 ) -> None:
3716 install_fake_slixmpp(monkeypatch)
3717 # See test_xmpp_invalid_targets_logged for why this is needed: older
3718 # pytest releases don't un-suppress a prior logging.disable(CRITICAL)
3719 # left by another test module's import-time call.
3720 logging.disable(logging.NOTSET)
3721 caplog.set_level(logging.WARNING, logger="apprise.xmpp")
3722
3723 try:
3724 config = xmpp_adapter.XMPPConfig(
3725 jid="[email protected]",
3726 password="x",
3727 host="example.com",
3728 port=5222,
3729 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3730 verify_certificate=False,
3731 )
3732
3733 a = xmpp_adapter.SlixmppAdapter(
3734 config=config,
3735 targets=[("chat", "[email protected]")],
3736 subject="s",
3737 body="b",
3738 timeout=5.0,
3739 keepalive=True,
3740 )
3741
3742 monkeypatch.setattr(
3743 a, "_ensure_keepalive_worker", lambda: True, raising=True
3744 )
3745
3746 class _Loop:
3747 def call_soon_threadsafe(self, cb: Any, *args: Any) -> None:
3748 raise AssertionError(
3749 "should not be called when _session_started is None"
3750 )
3751
3752 a._loop = _Loop()
3753 a._session_started = None # key for branch coverage
3754
3755 class _FutureTimeout:
3756 def result(self, timeout: Optional[float] = None) -> Any:
3757 raise xmpp_adapter.FuturesTimeoutError()
3758
3759 def run_coroutine_threadsafe_timeout(coro: Any, loop: Any) -> Any:
3760 # Close coroutine to avoid RuntimeWarning
3761 with contextlib.suppress(Exception):
3762 coro.close()
3763 return _FutureTimeout()
3764
3765 monkeypatch.setattr(
3766 xmpp_adapter.asyncio,
3767 "run_coroutine_threadsafe",
3768 run_coroutine_threadsafe_timeout,
3769 raising=True,
3770 )
3771
3772 assert a.send_message() is False
3773 assert "XMPP keepalive send timed out" in caplog.text
3774
3775 finally:
3776 logging.disable(logging.CRITICAL)
3777
3778
3779 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3780 def test_client_session_start_keepalive_evt_none_no_set(
3781 monkeypatch: pytest.MonkeyPatch,
3782 ) -> None:
3783 """Cover _session_start() when session event is None."""
3784 install_fake_slixmpp(monkeypatch)
3785
3786 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
3787
3788 loop = asyncio.new_event_loop()
3789 try:
3790 asyncio.set_event_loop(loop)
3791 client = client_cls(
3792 jid="[email protected]",
3793 password="pass",
3794 oneshot=False,
3795 targets=[],
3796 subject="s",
3797 body="b",
3798 before_message=None,
3799 want_roster=False,
3800 roster_timeout=0.0,
3801 session_started_evt=None,
3802 )
3803
3804 loop.run_until_complete(client._session_start())
3805
3806 finally:
3807 with contextlib.suppress(Exception):
3808 asyncio.set_event_loop(None)
3809 loop.close()
3810
3811
3812 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3813 def test_adapter_general_function(
3814 monkeypatch: pytest.MonkeyPatch,
3815 caplog: pytest.LogCaptureFixture,
3816 ) -> None:
3817 install_fake_slixmpp(monkeypatch)
3818
3819 def _close():
3820 raise Exception("boom")
3821
3822 arg = {"close": _close}
3823
3824 # does nothing
3825 xmpp_adapter._close_awaitable(None)
3826 xmpp_adapter._close_awaitable(arg)
3827
3828
3829 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3830 def test_client_on_session_start_create_task_failure_closes_coro(
3831 monkeypatch: pytest.MonkeyPatch,
3832 ) -> None:
3833 """Cover loop.create_task() failure that closes the awaitable."""
3834 install_fake_slixmpp(monkeypatch)
3835
3836 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
3837
3838 loop = asyncio.new_event_loop()
3839 try:
3840 asyncio.set_event_loop(loop)
3841
3842 client = client_cls(
3843 jid="[email protected]",
3844 password="pass",
3845 oneshot=False,
3846 targets=[],
3847 subject="s",
3848 body="b",
3849 before_message=None,
3850 want_roster=False,
3851 roster_timeout=0.0,
3852 session_started_evt=asyncio.Event(),
3853 )
3854
3855 class _FakeCoro:
3856 def __init__(self) -> None:
3857 self.closed = False
3858
3859 def close(self) -> None:
3860 self.closed = True
3861
3862 fake_coro = _FakeCoro()
3863
3864 def _session_start(*args: object, **kwargs: object) -> _FakeCoro:
3865 return fake_coro
3866
3867 monkeypatch.setattr(
3868 client, "_session_start", _session_start, raising=True
3869 )
3870
3871 class _FakeLoop:
3872 def is_running(self) -> bool:
3873 return True
3874
3875 def create_task(self, coro: object) -> object:
3876 raise RuntimeError("boom")
3877
3878 client.loop = _FakeLoop() # type: ignore[assignment]
3879 client._on_session_start()
3880 assert fake_coro.closed is True
3881
3882 finally:
3883 with contextlib.suppress(Exception):
3884 asyncio.set_event_loop(None)
3885 loop.close()
3886
3887
3888 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3889 def test_client_disconnected_evt_none_no_clear(
3890 monkeypatch: pytest.MonkeyPatch,
3891 ) -> None:
3892 """Cover _disconnected() branch where session event is None."""
3893 install_fake_slixmpp(monkeypatch)
3894
3895 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
3896
3897 loop = asyncio.new_event_loop()
3898 try:
3899 asyncio.set_event_loop(loop)
3900 client = client_cls(
3901 jid="[email protected]",
3902 password="pass",
3903 oneshot=False,
3904 targets=[],
3905 subject="s",
3906 body="b",
3907 before_message=None,
3908 want_roster=False,
3909 roster_timeout=0.0,
3910 session_started_evt=None,
3911 )
3912
3913 client._disconnected()
3914
3915 finally:
3916 with contextlib.suppress(Exception):
3917 asyncio.set_event_loop(None)
3918 loop.close()
3919
3920
3921 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3922 def test_adapter_send_message_keepalive_loop_none_returns_false(
3923 monkeypatch: pytest.MonkeyPatch,
3924 ) -> None:
3925 """Cover send_message(): loop is None -> return False."""
3926 install_fake_slixmpp(monkeypatch)
3927
3928 cfg = xmpp_adapter.XMPPConfig(
3929 jid="[email protected]",
3930 password="x",
3931 host="example.com",
3932 port=5222,
3933 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3934 verify_certificate=False,
3935 )
3936 a = xmpp_adapter.SlixmppAdapter(
3937 config=cfg,
3938 targets=[("chat", "[email protected]")],
3939 subject="s",
3940 body="b",
3941 keepalive=True,
3942 )
3943
3944 monkeypatch.setattr(
3945 a, "_ensure_keepalive_worker", lambda: True, raising=True
3946 )
3947 a._loop = None
3948 assert a.send_message() is False
3949
3950
3951 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
3952 def test_adapter_send_message_keepalive_exception_returns_false(
3953 monkeypatch: pytest.MonkeyPatch,
3954 ) -> None:
3955 """Cover send_message(): exception path returns False."""
3956 install_fake_slixmpp(monkeypatch)
3957
3958 cfg = xmpp_adapter.XMPPConfig(
3959 jid="[email protected]",
3960 password="x",
3961 host="example.com",
3962 port=5222,
3963 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
3964 verify_certificate=False,
3965 )
3966 a = xmpp_adapter.SlixmppAdapter(
3967 config=cfg,
3968 targets=[("chat", "[email protected]")],
3969 subject="s",
3970 body="b",
3971 timeout=5.0,
3972 keepalive=True,
3973 )
3974
3975 monkeypatch.setattr(
3976 a, "_ensure_keepalive_worker", lambda: True, raising=True
3977 )
3978
3979 class _Loop:
3980 pass
3981
3982 a._loop = _Loop()
3983
3984 def run_coroutine_threadsafe_boom(coro: Any, loop: Any) -> Any:
3985 with contextlib.suppress(Exception):
3986 coro.close()
3987 raise RuntimeError("boom")
3988
3989 monkeypatch.setattr(
3990 xmpp_adapter.asyncio,
3991 "run_coroutine_threadsafe",
3992 run_coroutine_threadsafe_boom,
3993 raising=True,
3994 )
3995
3996 assert a.send_message() is False
3997
3998
3999 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4000 def test_adapter_send_keepalive_async_auth_failed_returns_false(
4001 monkeypatch: pytest.MonkeyPatch,
4002 ) -> None:
4003 """Cover _send_keepalive_async(): auth_failed -> return False."""
4004 install_fake_slixmpp(monkeypatch)
4005
4006 cfg = xmpp_adapter.XMPPConfig(
4007 jid="[email protected]",
4008 password="x",
4009 host="example.com",
4010 port=5222,
4011 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
4012 verify_certificate=False,
4013 )
4014 a = xmpp_adapter.SlixmppAdapter(
4015 config=cfg,
4016 targets=[],
4017 subject="s",
4018 body="b",
4019 keepalive=True,
4020 )
4021
4022 class _Client:
4023 _auth_failed = True
4024
4025 def send_message(self, **kwargs: Any) -> None:
4026 raise AssertionError("send must not occur")
4027
4028 a._client = _Client()
4029
4030 async def ok_connect() -> bool:
4031 return True
4032
4033 monkeypatch.setattr(a, "_connect_if_required", ok_connect, raising=True)
4034
4035 assert (
4036 asyncio.run(a._send_keepalive_async(["[email protected]"], "s", "b"))
4037 is False
4038 )
4039
4040
4041 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4042 def test_adapter_connect_if_required_auth_failed_returns_false(
4043 monkeypatch: pytest.MonkeyPatch,
4044 ) -> None:
4045 """Cover _connect_if_required(): auth_failed -> return False."""
4046 install_fake_slixmpp(monkeypatch)
4047
4048 cfg = xmpp_adapter.XMPPConfig(
4049 jid="[email protected]",
4050 password="x",
4051 host="example.com",
4052 port=5222,
4053 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
4054 verify_certificate=False,
4055 )
4056 a = xmpp_adapter.SlixmppAdapter(
4057 config=cfg, targets=[], subject="s", body="b", keepalive=True
4058 )
4059
4060 loop = asyncio.new_event_loop()
4061 try:
4062 asyncio.set_event_loop(loop)
4063 a._loop = loop
4064 a._connect_lock = asyncio.Lock()
4065 a._session_started = asyncio.Event()
4066
4067 class _Client:
4068 _auth_failed = True
4069
4070 a._client = _Client()
4071
4072 assert run_on_loop(loop, a._connect_if_required()) is False
4073
4074 finally:
4075 with contextlib.suppress(Exception):
4076 asyncio.set_event_loop(None)
4077 loop.close()
4078
4079
4080 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4081 def test_adapter_connect_if_required_connect_ok_false_disconnects(
4082 monkeypatch: pytest.MonkeyPatch,
4083 caplog: pytest.LogCaptureFixture,
4084 ) -> None:
4085 """Cover _connect_if_required(): connect_ok False path."""
4086 install_fake_slixmpp(monkeypatch)
4087 # See test_xmpp_invalid_targets_logged for why this is needed: older
4088 # pytest releases don't un-suppress a prior logging.disable(CRITICAL)
4089 # left by another test module's import-time call.
4090 logging.disable(logging.NOTSET)
4091 caplog.set_level(logging.WARNING, logger="apprise.xmpp")
4092
4093 cfg = xmpp_adapter.XMPPConfig(
4094 jid="[email protected]",
4095 password="x",
4096 host="example.com",
4097 port=5222,
4098 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
4099 verify_certificate=False,
4100 )
4101 a = xmpp_adapter.SlixmppAdapter(
4102 config=cfg, targets=[], subject="s", body="b", keepalive=True
4103 )
4104
4105 loop = asyncio.new_event_loop()
4106 try:
4107 asyncio.set_event_loop(loop)
4108 a._loop = loop
4109 a._connect_lock = asyncio.Lock()
4110 a._session_started = asyncio.Event()
4111
4112 disconnected = {"n": 0}
4113
4114 class _Client:
4115 def connect(self, **kwargs: Any) -> Any:
4116 fut = loop.create_future()
4117 fut.set_result(False)
4118 return fut
4119
4120 def disconnect(self) -> None:
4121 disconnected["n"] += 1
4122
4123 a._client = _Client()
4124
4125 assert run_on_loop(loop, a._connect_if_required()) is False
4126 assert disconnected["n"] == 1
4127 assert "XMPP connect failed" in caplog.text
4128
4129 finally:
4130 with contextlib.suppress(Exception):
4131 asyncio.set_event_loop(None)
4132 loop.close()
4133 logging.disable(logging.CRITICAL)
4134
4135
4136 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4137 def test_adapter_connect_if_required_session_wait_exception_closes(
4138 monkeypatch: pytest.MonkeyPatch,
4139 ) -> None:
4140 """Cover _connect_if_required(): session_wait Exception path."""
4141 install_fake_slixmpp(monkeypatch)
4142
4143 cfg = xmpp_adapter.XMPPConfig(
4144 jid="[email protected]",
4145 password="x",
4146 host="example.com",
4147 port=5222,
4148 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
4149 verify_certificate=False,
4150 )
4151 a = xmpp_adapter.SlixmppAdapter(
4152 config=cfg, targets=[], subject="s", body="b", keepalive=True
4153 )
4154
4155 loop = asyncio.new_event_loop()
4156 try:
4157 asyncio.set_event_loop(loop)
4158 a._loop = loop
4159 a._connect_lock = asyncio.Lock()
4160 a._session_started = asyncio.Event()
4161
4162 fut = loop.create_future()
4163 fut.set_result(True)
4164
4165 class _Client:
4166 def connect(self, **kwargs: Any) -> Any:
4167 return fut
4168
4169 a._client = _Client()
4170
4171 called: list[object] = []
4172 real_close = xmpp_adapter._close_awaitable
4173
4174 def close_spy(obj: object) -> None:
4175 called.append(obj)
4176 real_close(obj)
4177
4178 monkeypatch.setattr(
4179 xmpp_adapter, "_close_awaitable", close_spy, raising=True
4180 )
4181
4182 real_wait_for = xmpp_adapter.asyncio.wait_for
4183 calls = {"n": 0}
4184
4185 async def wait_for_patched(
4186 aw: Any, timeout: Optional[float] = None
4187 ) -> Any:
4188 calls["n"] += 1
4189 if calls["n"] == 2:
4190 raise RuntimeError("boom")
4191 return await real_wait_for(aw, timeout=timeout)
4192
4193 monkeypatch.setattr(
4194 xmpp_adapter.asyncio, "wait_for", wait_for_patched, raising=True
4195 )
4196
4197 assert run_on_loop(loop, a._connect_if_required()) is False
4198 assert len(called) == 1
4199
4200 finally:
4201 with contextlib.suppress(Exception):
4202 asyncio.set_event_loop(None)
4203 loop.close()
4204
4205
4206 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4207 def test_client_on_session_start_add_done_callback_executes(
4208 monkeypatch: pytest.MonkeyPatch,
4209 ) -> None:
4210 """
4211 Cover adapter.py _on_session_start() keepalive path where we create a
4212 task and attach a done callback that calls t.exception() when not
4213 cancelled.
4214
4215 This test avoids patching asyncio.Task (immutable on newer Pythons) by
4216 using a fake loop and fake task object.
4217 """
4218 install_fake_slixmpp(monkeypatch)
4219
4220 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
4221
4222 loop = asyncio.new_event_loop()
4223 try:
4224 asyncio.set_event_loop(loop)
4225
4226 evt = asyncio.Event()
4227
4228 client = client_cls(
4229 jid="[email protected]",
4230 password="x",
4231 oneshot=False,
4232 targets=[],
4233 subject="s",
4234 body="b",
4235 before_message=None,
4236 want_roster=False,
4237 roster_timeout=0.0,
4238 session_started_evt=evt,
4239 )
4240
4241 class _FakeTask:
4242 def __init__(self) -> None:
4243 self.exception_called = False
4244 self.callback_called = False
4245
4246 def add_done_callback(self, cb: Any) -> None:
4247 self.callback_called = True
4248 cb(self)
4249
4250 def cancelled(self) -> bool:
4251 return False
4252
4253 def exception(self) -> None:
4254 self.exception_called = True
4255 return None
4256
4257 class _FakeLoop:
4258 def __init__(self) -> None:
4259 self.task = _FakeTask()
4260 self.create_task_called = False
4261
4262 def is_running(self) -> bool:
4263 return True
4264
4265 def create_task(self, coro: Any) -> _FakeTask:
4266 self.create_task_called = True
4267 return self.task
4268
4269 fake_loop = _FakeLoop()
4270 client.loop = fake_loop # type: ignore[assignment]
4271
4272 class _FakeCoro:
4273 def close(self) -> None:
4274 return None
4275
4276 def _session_start(*args: object, **kwargs: object) -> _FakeCoro:
4277 return _FakeCoro()
4278
4279 monkeypatch.setattr(
4280 client, "_session_start", _session_start, raising=True
4281 )
4282
4283 client._on_session_start()
4284
4285 assert fake_loop.create_task_called is True
4286 assert fake_loop.task.callback_called is True
4287 assert fake_loop.task.exception_called is True
4288
4289 finally:
4290 with contextlib.suppress(Exception):
4291 asyncio.set_event_loop(None)
4292 with contextlib.suppress(Exception):
4293 loop.close()
4294
4295
4296 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4297 def test_client_on_session_start_done_callback_cancelled_returns(
4298 monkeypatch: pytest.MonkeyPatch,
4299 ) -> None:
4300 """Cover _log_task() early return when task is cancelled."""
4301 install_fake_slixmpp(monkeypatch)
4302
4303 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
4304
4305 loop = asyncio.new_event_loop()
4306 try:
4307 asyncio.set_event_loop(loop)
4308
4309 evt = asyncio.Event()
4310 client = client_cls(
4311 jid="[email protected]",
4312 password="x",
4313 oneshot=False,
4314 targets=[],
4315 subject="s",
4316 body="b",
4317 before_message=None,
4318 want_roster=False,
4319 roster_timeout=0.0,
4320 session_started_evt=evt,
4321 )
4322
4323 errors: list[str] = []
4324
4325 class _Logger:
4326 def error(self, msg: str, *args: Any) -> None:
4327 errors.append(msg % args if args else msg)
4328
4329 client.logger = _Logger() # type: ignore[assignment]
4330
4331 class _FakeTask:
4332 def __init__(self) -> None:
4333 self.exception_called = False
4334
4335 def add_done_callback(self, cb: Any) -> None:
4336 cb(self)
4337
4338 def cancelled(self) -> bool:
4339 return True
4340
4341 def exception(self) -> None:
4342 self.exception_called = True
4343 return RuntimeError("should-not-be-read")
4344
4345 class _FakeLoop:
4346 def is_running(self) -> bool:
4347 return True
4348
4349 def create_task(self, coro: Any) -> _FakeTask:
4350 return _FakeTask()
4351
4352 client.loop = _FakeLoop() # type: ignore[assignment]
4353
4354 class _FakeCoro:
4355 def close(self) -> None:
4356 return None
4357
4358 monkeypatch.setattr(
4359 client,
4360 "_session_start",
4361 lambda *_a, **_k: _FakeCoro(),
4362 raising=True,
4363 )
4364
4365 client._on_session_start()
4366
4367 assert errors == []
4368
4369 finally:
4370 with contextlib.suppress(Exception):
4371 asyncio.set_event_loop(None)
4372 with contextlib.suppress(Exception):
4373 loop.close()
4374
4375
4376 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4377 def test_client_on_session_start_done_callback_logs_exception(
4378 monkeypatch: pytest.MonkeyPatch,
4379 ) -> None:
4380 """Cover _log_task() error log when task.exception() is not None."""
4381 install_fake_slixmpp(monkeypatch)
4382
4383 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
4384
4385 loop = asyncio.new_event_loop()
4386 try:
4387 asyncio.set_event_loop(loop)
4388
4389 evt = asyncio.Event()
4390 client = client_cls(
4391 jid="[email protected]",
4392 password="x",
4393 oneshot=False,
4394 targets=[],
4395 subject="s",
4396 body="b",
4397 before_message=None,
4398 want_roster=False,
4399 roster_timeout=0.0,
4400 session_started_evt=evt,
4401 )
4402
4403 errors: list[str] = []
4404
4405 class _Logger:
4406 def error(self, msg: str, *args: Any) -> None:
4407 errors.append(msg % args if args else msg)
4408
4409 client.logger = _Logger() # type: ignore[assignment]
4410
4411 class _FakeTask:
4412 def add_done_callback(self, cb: Any) -> None:
4413 cb(self)
4414
4415 def cancelled(self) -> bool:
4416 return False
4417
4418 def exception(self) -> Exception:
4419 return RuntimeError("boom-task")
4420
4421 class _FakeLoop:
4422 def is_running(self) -> bool:
4423 return True
4424
4425 def create_task(self, coro: Any) -> _FakeTask:
4426 return _FakeTask()
4427
4428 client.loop = _FakeLoop() # type: ignore[assignment]
4429
4430 class _FakeCoro:
4431 def close(self) -> None:
4432 return None
4433
4434 monkeypatch.setattr(
4435 client,
4436 "_session_start",
4437 lambda *_a, **_k: _FakeCoro(),
4438 raising=True,
4439 )
4440
4441 client._on_session_start()
4442
4443 assert len(errors) == 1
4444 assert "XMPP task failed" in errors[0]
4445
4446 finally:
4447 with contextlib.suppress(Exception):
4448 asyncio.set_event_loop(None)
4449 with contextlib.suppress(Exception):
4450 loop.close()
4451
4452
4453 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4454 def test_xmpp_muc_url_parsing_and_reconstruction() -> None:
4455 """MUC targets parse from '#[email protected]' and round-trip via url()."""
4456 n = NotifyXMPP(
4457 host="example.com",
4458 user="me",
4459 password="secret",
4460 targets=["#[email protected]", "[email protected]"],
4461 )
4462 # MUC target becomes groupchat, regular becomes chat
4463 assert ("groupchat", "[email protected]") in n.targets
4464 assert ("chat", "[email protected]") in n.targets
4465 assert n.want_muc is True
4466
4467 # url() encodes MUC '#' as %23 to avoid URL fragment misparse
4468 u = n.url()
4469 assert "%23room%40conference.example.com" in u
4470 # Verify round-trip: parse_url -> NotifyXMPP reconstructs same targets
4471 results = NotifyXMPP.parse_url(u)
4472 assert results is not None
4473 n2 = NotifyXMPP(**results)
4474 assert ("groupchat", "[email protected]") in n2.targets
4475 assert ("chat", "[email protected]") in n2.targets
4476 assert n2.want_muc is True
4477
4478
4479 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4480 def test_xmpp_name_parameter() -> None:
4481 """name= is stored, emitted in url(), and round-trips via parse_url()."""
4482 # Valid name: stored as-is and emitted in the URL
4483 n = NotifyXMPP(
4484 host="example.com",
4485 user="me",
4486 password="secret",
4487 name="my_bot",
4488 )
4489 assert n.name == "my_bot"
4490 u = n.url()
4491 assert "name=my_bot" in u
4492
4493 # Round-trip through parse_url
4494 results = NotifyXMPP.parse_url(u)
4495 assert results is not None
4496 assert results.get("name") == "my_bot"
4497 n2 = NotifyXMPP(**results)
4498 assert n2.name == "my_bot"
4499
4500 # Invalid name falls back to user (then app_id if no user)
4501 n3 = NotifyXMPP(
4502 host="example.com",
4503 user="me",
4504 password="secret",
4505 name="bad name!",
4506 )
4507 assert n3.name == n3.user
4508
4509 # No name provided -> defaults to user (then app_id if no user);
4510 # not emitted in URL
4511 n4 = NotifyXMPP(
4512 host="example.com",
4513 user="me",
4514 password="secret",
4515 )
4516 assert n4.name == n4.user
4517 assert "name=" not in n4.url()
4518
4519
4520 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4521 def test_xmpp_muc_only_no_regular_targets() -> None:
4522 """NotifyXMPP with only MUC targets sets want_muc=True."""
4523 n = NotifyXMPP(
4524 host="example.com",
4525 user="me",
4526 password="secret",
4527 targets=["#[email protected]"],
4528 )
4529 assert n.want_muc is True
4530 assert len(n.targets) == 1
4531 assert n.targets[0] == ("groupchat", "[email protected]")
4532
4533
4534 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4535 def test_client_session_start_oneshot_muc_join(
4536 monkeypatch: pytest.MonkeyPatch,
4537 ) -> None:
4538 """Cover join_muc() in _session_start() for oneshot groupchat target."""
4539 install_fake_slixmpp(monkeypatch)
4540
4541 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
4542
4543 sent: list[dict[str, Any]] = []
4544 join_calls: list[tuple[str, str]] = []
4545
4546 async def fake_join_muc(room: str, nick: str) -> None:
4547 join_calls.append((room, nick))
4548
4549 class FakeMucPlugin:
4550 def join_muc(self, room: str, nick: str, **kw: Any) -> Any:
4551 return fake_join_muc(room, nick)
4552
4553 loop = asyncio.new_event_loop()
4554 asyncio.set_event_loop(loop)
4555 try:
4556 client = client_cls(
4557 jid="[email protected]",
4558 password="pass",
4559 oneshot=True,
4560 targets=[("groupchat", "[email protected]")],
4561 subject="s",
4562 body="b",
4563 want_muc=True,
4564 want_roster=False,
4565 roster_timeout=0.0,
4566 session_started_evt=None,
4567 )
4568
4569 # Inject fake xep_0045 plugin and boundjid (not on FakeClientXMPP)
4570 class _BoundJID:
4571 user = "me"
4572
4573 monkeypatch.setattr(client, "boundjid", _BoundJID(), raising=False)
4574 monkeypatch.setattr(
4575 client, "plugin", {"xep_0045": FakeMucPlugin()}, raising=False
4576 )
4577 monkeypatch.setattr(
4578 client, "send_message", lambda **kw: sent.append(kw), raising=True
4579 )
4580 monkeypatch.setattr(client, "disconnect", lambda: None, raising=True)
4581
4582 loop.run_until_complete(client._session_start())
4583
4584 assert len(join_calls) == 1
4585 assert join_calls[0][0] == "[email protected]"
4586 assert join_calls[0][1] == "me"
4587 assert len(sent) == 1
4588 assert sent[0]["mtype"] == "groupchat"
4589
4590 finally:
4591 asyncio.set_event_loop(None)
4592 loop.close()
4593
4594
4595 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4596 def test_client_session_start_oneshot_muc_join_error(
4597 monkeypatch: pytest.MonkeyPatch,
4598 ) -> None:
4599 """Cover join_muc() error path: exception is caught, send still happens."""
4600 install_fake_slixmpp(monkeypatch)
4601
4602 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
4603
4604 sent: list[dict[str, Any]] = []
4605
4606 async def join_muc_fail(room: str, nick: str) -> None:
4607 raise asyncio.TimeoutError() # simulate timeout
4608
4609 class FakeMucPlugin:
4610 def join_muc(self, room: str, nick: str, **kw: Any) -> Any:
4611 return join_muc_fail(room, nick)
4612
4613 loop = asyncio.new_event_loop()
4614 asyncio.set_event_loop(loop)
4615 try:
4616 client = client_cls(
4617 jid="[email protected]",
4618 password="pass",
4619 oneshot=True,
4620 targets=[("groupchat", "[email protected]")],
4621 subject="s",
4622 body="b",
4623 want_muc=True,
4624 want_roster=False,
4625 roster_timeout=0.0,
4626 session_started_evt=None,
4627 )
4628
4629 class _BoundJID:
4630 user = "me"
4631
4632 monkeypatch.setattr(client, "boundjid", _BoundJID(), raising=False)
4633 monkeypatch.setattr(
4634 client, "plugin", {"xep_0045": FakeMucPlugin()}, raising=False
4635 )
4636 monkeypatch.setattr(
4637 client, "send_message", lambda **kw: sent.append(kw), raising=True
4638 )
4639 monkeypatch.setattr(client, "disconnect", lambda: None, raising=True)
4640
4641 loop.run_until_complete(client._session_start())
4642
4643 # Message is still sent even when MUC join errors
4644 assert len(sent) == 1
4645 assert sent[0]["mtype"] == "groupchat"
4646
4647 finally:
4648 asyncio.set_event_loop(None)
4649 loop.close()
4650
4651
4652 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4653 def test_send_keepalive_async_muc_join(
4654 monkeypatch: pytest.MonkeyPatch,
4655 ) -> None:
4656 """Cover join_muc() in _send_keepalive_async() for groupchat target."""
4657 install_fake_slixmpp(monkeypatch)
4658
4659 cfg = xmpp_adapter.XMPPConfig(
4660 jid="[email protected]",
4661 password="x",
4662 host="example.com",
4663 port=5222,
4664 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
4665 verify_certificate=False,
4666 )
4667 a = xmpp_adapter.SlixmppAdapter(
4668 config=cfg,
4669 targets=[("groupchat", "[email protected]")],
4670 subject="s",
4671 body="b",
4672 keepalive=True,
4673 want_muc=True,
4674 )
4675
4676 join_calls: list[tuple[str, str]] = []
4677 sent: list[dict[str, Any]] = []
4678
4679 async def fake_join_muc(room: str, nick: str) -> None:
4680 join_calls.append((room, nick))
4681
4682 class FakeBoundJID:
4683 user = "me"
4684
4685 class FakeMucPlugin:
4686 def join_muc(self, room: str, nick: str, **kw: Any) -> Any:
4687 return fake_join_muc(room, nick)
4688
4689 class _Client:
4690 _auth_failed = False
4691 boundjid = FakeBoundJID()
4692 plugin = {"xep_0045": FakeMucPlugin()}
4693
4694 def send_message(self, **kwargs: Any) -> None:
4695 sent.append(kwargs)
4696
4697 a._client = _Client()
4698
4699 async def ok_connect() -> bool:
4700 return True
4701
4702 monkeypatch.setattr(a, "_connect_if_required", ok_connect, raising=True)
4703
4704 result = asyncio.run(
4705 a._send_keepalive_async(
4706 targets=[("groupchat", "[email protected]")],
4707 subject="s",
4708 body="b",
4709 )
4710 )
4711
4712 assert result is True
4713 assert len(join_calls) == 1
4714 assert join_calls[0][0] == "[email protected]"
4715 # boundjid.user == "me" -> nick must be taken from boundjid, not nickname
4716 assert join_calls[0][1] == "me"
4717 assert len(sent) == 1
4718 assert sent[0]["mtype"] == "groupchat"
4719
4720
4721 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4722 def test_send_keepalive_async_muc_join_nick_fallback(
4723 monkeypatch: pytest.MonkeyPatch,
4724 ) -> None:
4725 """When boundjid.user is empty, nick falls back to adapter nickname."""
4726 install_fake_slixmpp(monkeypatch)
4727
4728 cfg = xmpp_adapter.XMPPConfig(
4729 jid="[email protected]",
4730 password="x",
4731 host="example.com",
4732 port=5222,
4733 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
4734 verify_certificate=False,
4735 )
4736 a = xmpp_adapter.SlixmppAdapter(
4737 config=cfg,
4738 targets=[("groupchat", "[email protected]")],
4739 subject="s",
4740 body="b",
4741 keepalive=True,
4742 want_muc=True,
4743 default_nickname="mybot",
4744 )
4745
4746 join_calls: list[tuple[str, str]] = []
4747 sent: list[dict[str, Any]] = []
4748
4749 async def fake_join_muc(room: str, nick: str) -> None:
4750 join_calls.append((room, nick))
4751
4752 class FakeBoundJID:
4753 user = "" # empty -> should fall back to nickname
4754
4755 class FakeMucPlugin:
4756 def join_muc(self, room: str, nick: str, **kw: Any) -> Any:
4757 return fake_join_muc(room, nick)
4758
4759 class _Client:
4760 _auth_failed = False
4761 boundjid = FakeBoundJID()
4762 plugin = {"xep_0045": FakeMucPlugin()}
4763
4764 def send_message(self, **kwargs: Any) -> None:
4765 sent.append(kwargs)
4766
4767 a._client = _Client()
4768
4769 async def ok_connect() -> bool:
4770 return True
4771
4772 monkeypatch.setattr(a, "_connect_if_required", ok_connect, raising=True)
4773
4774 result = asyncio.run(
4775 a._send_keepalive_async(
4776 targets=[("groupchat", "[email protected]")],
4777 subject="s",
4778 body="b",
4779 )
4780 )
4781
4782 assert result is True
4783 assert len(join_calls) == 1
4784 assert join_calls[0][0] == "[email protected]"
4785 # boundjid.user is empty -> nick must fall back to adapter's nickname
4786 assert join_calls[0][1] == "mybot"
4787 assert len(sent) == 1
4788 assert sent[0]["mtype"] == "groupchat"
4789
4790
4791 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4792 def test_adapter_keepalive_runner_registers_xep_0045_when_want_muc(
4793 monkeypatch: pytest.MonkeyPatch,
4794 ) -> None:
4795 """Cover _keepalive_runner(): register_plugin('xep_0045') for want_muc."""
4796 install_fake_slixmpp(monkeypatch)
4797
4798 cfg = xmpp_adapter.XMPPConfig(
4799 jid="[email protected]",
4800 password="x",
4801 host="example.com",
4802 port=5222,
4803 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
4804 verify_certificate=False,
4805 )
4806 a = xmpp_adapter.SlixmppAdapter(
4807 config=cfg,
4808 targets=[("groupchat", "[email protected]")],
4809 subject="s",
4810 body="b",
4811 keepalive=True,
4812 want_muc=True,
4813 )
4814
4815 registered: list[str] = []
4816 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
4817
4818 def new_event_loop_wrapped() -> asyncio.AbstractEventLoop:
4819 loop = real_new_event_loop()
4820
4821 def run_forever_hook() -> None:
4822 client = a._client
4823 assert client is not None
4824 # Capture what was registered and then stop
4825 registered.extend(client.registered_plugins.keys())
4826
4827 monkeypatch.setattr(
4828 loop, "run_forever", run_forever_hook, raising=True
4829 )
4830 return loop
4831
4832 monkeypatch.setattr(
4833 xmpp_adapter.asyncio,
4834 "new_event_loop",
4835 new_event_loop_wrapped,
4836 raising=True,
4837 )
4838
4839 a._keepalive_runner()
4840
4841 assert "xep_0045" in registered
4842
4843
4844 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4845 def test_send_keepalive_async_muc_join_error(
4846 monkeypatch: pytest.MonkeyPatch,
4847 ) -> None:
4848 """Cover join_muc() exception path in _send_keepalive_async()."""
4849 install_fake_slixmpp(monkeypatch)
4850
4851 cfg = xmpp_adapter.XMPPConfig(
4852 jid="[email protected]",
4853 password="x",
4854 host="example.com",
4855 port=5222,
4856 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
4857 verify_certificate=False,
4858 )
4859 a = xmpp_adapter.SlixmppAdapter(
4860 config=cfg,
4861 targets=[("groupchat", "[email protected]")],
4862 subject="s",
4863 body="b",
4864 keepalive=True,
4865 want_muc=True,
4866 )
4867
4868 sent: list[dict[str, Any]] = []
4869
4870 async def join_muc_fail(room: str, nick: str) -> None:
4871 raise asyncio.TimeoutError() # simulate timeout -> exception path
4872
4873 class FakeBoundJID:
4874 user = "me"
4875
4876 class FakeMucPlugin:
4877 def join_muc(self, room: str, nick: str, **kw: Any) -> Any:
4878 return join_muc_fail(room, nick)
4879
4880 class _Client:
4881 _auth_failed = False
4882 boundjid = FakeBoundJID()
4883 plugin = {"xep_0045": FakeMucPlugin()}
4884
4885 def send_message(self, **kwargs: Any) -> None:
4886 sent.append(kwargs)
4887
4888 a._client = _Client()
4889
4890 async def ok_connect() -> bool:
4891 return True
4892
4893 monkeypatch.setattr(a, "_connect_if_required", ok_connect, raising=True)
4894
4895 result = asyncio.run(
4896 a._send_keepalive_async(
4897 targets=[("groupchat", "[email protected]")],
4898 subject="s",
4899 body="b",
4900 )
4901 )
4902
4903 # Exception from join_muc is caught; message is still sent
4904 assert result is True
4905 assert len(sent) == 1
4906 assert sent[0]["mtype"] == "groupchat"
4907
4908
4909 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4910 def test_xmpp_client_logger_presence_regression(monkeypatch):
4911 """
4912 Regression test: Verify that the internal _Client class automatically
4913 receives a 'logger' attribute so _log_task does not AttributeError.
4914 """
4915 install_fake_slixmpp(monkeypatch)
4916
4917 cfg = xmpp_adapter.XMPPConfig(
4918 jid="[email protected]", password="x", host="ex.com", port=5222
4919 )
4920
4921 # Test standard adapter initialization
4922 adapter = xmpp_adapter.SlixmppAdapter(
4923 config=cfg, targets=[], subject="s", body="b"
4924 )
4925
4926 # Use the same factory the adapter uses to create a client
4927 client = xmpp_adapter._build_client(
4928 jid="[email protected]", password="x", oneshot=True, logger=adapter.logger
4929 )
4930
4931 # This was the point of failure: self.logger must exist
4932 assert hasattr(client, "logger")
4933 assert client.logger == adapter.logger
4934
4935
4936 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4937 def test_xmpp_log_task_crash_regression(monkeypatch):
4938 """
4939 Regression test: Verify that _log_task can handle an exception
4940 without crashing on a missing logger attribute.
4941 """
4942 install_fake_slixmpp(monkeypatch)
4943
4944 # Create a client using the production factory
4945 client_cls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
4946 client = client_cls(
4947 jid="[email protected]",
4948 password="pass",
4949 oneshot=False,
4950 # Provide Logger
4951 logger=logging.getLogger("apprise"),
4952 )
4953
4954 # Simulate a task failure
4955 class MockTask:
4956 def cancelled(self):
4957 return False
4958
4959 def exception(self):
4960 return RuntimeError("Simulated XMPP Failure")
4961
4962 # Manually trigger the callback logic
4963 client.handlers.get("session_start")
4964
4965 # Triggers _log_task
4966 client._on_session_start()
4967
4968
4969 # ---------------------------------------------------------------------------
4970 # SCRAM-PLUS / Channel Binding Tests
4971 # ---------------------------------------------------------------------------
4972
4973
4974 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4975 def test_xmpp_scramplus_default_true() -> None:
4976 """scramplus defaults to True (SCRAM-PLUS enabled)."""
4977 n = NotifyXMPP(host="example.com", user="[email protected]", password="x")
4978 assert n.scramplus is True
4979
4980
4981 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4982 def test_xmpp_scramplus_explicit_false() -> None:
4983 """scramplus=False is stored and reflected in url()."""
4984 n = NotifyXMPP(
4985 host="example.com",
4986 user="[email protected]",
4987 password="x",
4988 scramplus=False,
4989 )
4990 assert n.scramplus is False
4991 u = n.url()
4992 assert "scramplus=no" in u
4993
4994
4995 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
4996 def test_xmpp_scramplus_url_round_trip() -> None:
4997 """scramplus round-trips through url() and parse_url()."""
4998 n = NotifyXMPP(
4999 host="example.com",
5000 user="[email protected]",
5001 password="secret",
5002 scramplus=False,
5003 )
5004 u = n.url()
5005 r = NotifyXMPP.parse_url(u)
5006 assert r is not None
5007 assert r["scramplus"] is False
5008
5009 n2 = NotifyXMPP(**r)
5010 assert n2.scramplus is False
5011
5012
5013 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5014 def test_xmpp_scramplus_parse_url_no() -> None:
5015 """?scramplus=no is parsed and stored correctly."""
5016 r = NotifyXMPP.parse_url(
5017 "xmpps://me:[email protected]/[email protected]?scramplus=no"
5018 )
5019 assert r is not None
5020 assert r["scramplus"] is False
5021
5022
5023 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5024 def test_xmpp_scramplus_parse_url_yes() -> None:
5025 """?scramplus=yes is parsed and stored correctly."""
5026 r = NotifyXMPP.parse_url(
5027 "xmpps://me:[email protected]/[email protected]?scramplus=yes"
5028 )
5029 assert r is not None
5030 assert r["scramplus"] is True
5031
5032
5033 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5034 def test_xmpp_scramplus_passes_to_config(
5035 monkeypatch: pytest.MonkeyPatch,
5036 ) -> None:
5037 """scramplus=False propagates use_channel_binding=False to XMPPConfig."""
5038 captured: dict = {}
5039
5040 class _Adapter:
5041 def __init__(self, config: Any, **kwargs: Any) -> None:
5042 captured["use_channel_binding"] = config.use_channel_binding
5043
5044 def process(self) -> bool:
5045 return True
5046
5047 monkeypatch.setattr(xmpp_base, "SlixmppAdapter", _Adapter, raising=True)
5048
5049 apobj = Apprise()
5050 apobj.add("xmpps://user:[email protected]/joe?scramplus=no")
5051 apobj.notify("hello")
5052
5053 assert captured["use_channel_binding"] is False
5054
5055
5056 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5057 def test_xmpp_scramplus_true_passes_to_config(
5058 monkeypatch: pytest.MonkeyPatch,
5059 ) -> None:
5060 """Default scramplus=True propagates use_channel_binding=True."""
5061 captured: dict = {}
5062
5063 class _Adapter:
5064 def __init__(self, config: Any, **kwargs: Any) -> None:
5065 captured["use_channel_binding"] = config.use_channel_binding
5066
5067 def process(self) -> bool:
5068 return True
5069
5070 monkeypatch.setattr(xmpp_base, "SlixmppAdapter", _Adapter, raising=True)
5071
5072 apobj = Apprise()
5073 apobj.add("xmpps://user:[email protected]/joe")
5074 apobj.notify("hello")
5075
5076 assert captured["use_channel_binding"] is True
5077
5078
5079 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5080 def test_disable_channel_binding_filters_plus_mechs() -> None:
5081 """_disable_channel_binding patches _send_auth to strip -PLUS mechs."""
5082 from types import SimpleNamespace
5083
5084 captured: list[set] = []
5085
5086 plugin = SimpleNamespace(
5087 mech_list={"SCRAM-SHA-256-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-1"},
5088 )
5089
5090 def orig_send_auth() -> None:
5091 captured.append(set(plugin.mech_list))
5092
5093 plugin._send_auth = orig_send_auth
5094
5095 class _Client:
5096 def __getitem__(self, key: str) -> Any:
5097 if key == "feature_mechanisms":
5098 return plugin
5099 raise KeyError(key)
5100
5101 xmpp_adapter._disable_channel_binding(_Client())
5102
5103 # Trigger the patched _send_auth
5104 plugin._send_auth()
5105
5106 assert len(captured) == 1
5107 assert "SCRAM-SHA-256-PLUS" not in captured[0]
5108 assert "SCRAM-SHA-256" in captured[0]
5109 assert "SCRAM-SHA-1" in captured[0]
5110
5111
5112 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5113 def test_disable_channel_binding_safe_when_no_plugin() -> None:
5114 """_disable_channel_binding no-ops when feature_mechanisms is absent."""
5115
5116 class _BadClient:
5117 def __getitem__(self, key: str) -> Any:
5118 raise KeyError(key)
5119
5120 # Must not raise
5121 xmpp_adapter._disable_channel_binding(_BadClient())
5122
5123
5124 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5125 def test_xmpp_scramplus_disabled_process(
5126 monkeypatch: pytest.MonkeyPatch,
5127 ) -> None:
5128 """process() calls _disable_channel_binding when binding disabled."""
5129 install_fake_slixmpp(monkeypatch)
5130
5131 patched: list[bool] = []
5132 orig_disable = xmpp_adapter._disable_channel_binding
5133
5134 def spy_disable(client: Any) -> None:
5135 patched.append(True)
5136 orig_disable(client)
5137
5138 monkeypatch.setattr(
5139 xmpp_adapter, "_disable_channel_binding", spy_disable, raising=True
5140 )
5141
5142 cfg = xmpp_adapter.XMPPConfig(
5143 jid="[email protected]",
5144 password="x",
5145 host="example.com",
5146 port=5222,
5147 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
5148 verify_certificate=False,
5149 use_channel_binding=False,
5150 )
5151 a = xmpp_adapter.SlixmppAdapter(
5152 config=cfg,
5153 targets=[("chat", "[email protected]")],
5154 subject="s",
5155 body="b",
5156 timeout=1.0,
5157 )
5158 assert a.process() is True
5159 assert len(patched) == 1
5160
5161
5162 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5163 def test_xmpp_scramplus_enabled_no_patch(
5164 monkeypatch: pytest.MonkeyPatch,
5165 ) -> None:
5166 """process() skips _disable_channel_binding when binding enabled."""
5167 install_fake_slixmpp(monkeypatch)
5168
5169 patched: list[bool] = []
5170 orig_disable = xmpp_adapter._disable_channel_binding
5171
5172 def spy_disable(client: Any) -> None:
5173 patched.append(True)
5174 orig_disable(client)
5175
5176 monkeypatch.setattr(
5177 xmpp_adapter, "_disable_channel_binding", spy_disable, raising=True
5178 )
5179
5180 cfg = xmpp_adapter.XMPPConfig(
5181 jid="[email protected]",
5182 password="x",
5183 host="example.com",
5184 port=5222,
5185 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
5186 verify_certificate=False,
5187 use_channel_binding=True,
5188 )
5189 a = xmpp_adapter.SlixmppAdapter(
5190 config=cfg,
5191 targets=[("chat", "[email protected]")],
5192 subject="s",
5193 body="b",
5194 timeout=1.0,
5195 )
5196 assert a.process() is True
5197 # No patching when SCRAM-PLUS is enabled
5198 assert len(patched) == 0
5199
5200
5201 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5202 def test_xmpp_scramplus_disabled_keepalive_runner(
5203 monkeypatch: pytest.MonkeyPatch,
5204 ) -> None:
5205 """_keepalive_runner calls _disable_channel_binding when disabled."""
5206 install_fake_slixmpp(monkeypatch)
5207
5208 patched: list[bool] = []
5209 orig_disable = xmpp_adapter._disable_channel_binding
5210
5211 def spy_disable(client: Any) -> None:
5212 patched.append(True)
5213 orig_disable(client)
5214
5215 monkeypatch.setattr(
5216 xmpp_adapter, "_disable_channel_binding", spy_disable, raising=True
5217 )
5218
5219 cfg = xmpp_adapter.XMPPConfig(
5220 jid="[email protected]",
5221 password="x",
5222 host="example.com",
5223 port=5222,
5224 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
5225 verify_certificate=False,
5226 use_channel_binding=False,
5227 )
5228 a = xmpp_adapter.SlixmppAdapter(
5229 config=cfg,
5230 targets=[("chat", "[email protected]")],
5231 subject="s",
5232 body="b",
5233 timeout=1.0,
5234 keepalive=True,
5235 )
5236
5237 real_new_event_loop = xmpp_adapter.asyncio.new_event_loop
5238
5239 def new_event_loop_wrapped() -> asyncio.AbstractEventLoop:
5240 loop = real_new_event_loop()
5241
5242 def run_forever_hook() -> None:
5243 pass
5244
5245 monkeypatch.setattr(
5246 loop, "run_forever", run_forever_hook, raising=True
5247 )
5248 return loop
5249
5250 monkeypatch.setattr(
5251 xmpp_adapter.asyncio,
5252 "new_event_loop",
5253 new_event_loop_wrapped,
5254 raising=True,
5255 )
5256
5257 a._keepalive_runner()
5258
5259 assert len(patched) == 1
5260
5261
5262 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5263 def test_xmpp_failed_auth_stanza_sets_channel_binding_flag(
5264 monkeypatch: pytest.MonkeyPatch,
5265 ) -> None:
5266 """_failed_auth sets _channel_binding_failed when phrase detected."""
5267 install_fake_slixmpp(monkeypatch)
5268
5269 # Clear the subclass cache so we pick up the patched FakeClientXMPP.
5270 xmpp_adapter._CLIENT_SUBCLASS_CACHE.clear()
5271
5272 # Build a _Client instance directly using the fake base class.
5273 _ClientCls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
5274 client = _ClientCls(
5275 jid="[email protected]",
5276 password="x",
5277 oneshot=True,
5278 logger=logging.getLogger("test"),
5279 )
5280
5281 # Verify initial state.
5282 assert client._auth_failed is False
5283 assert client._channel_binding_failed is False
5284
5285 # Simulate a failed_auth stanza containing the channel binding phrase.
5286 fake_stanza = (
5287 "<failure><not-authorized/>"
5288 "<text>Invalid channel binding</text></failure>"
5289 )
5290 client._failed_auth(fake_stanza)
5291
5292 assert client._auth_failed is True
5293 assert client._channel_binding_failed is True
5294
5295
5296 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5297 def test_xmpp_failed_auth_plain_does_not_set_channel_binding_flag(
5298 monkeypatch: pytest.MonkeyPatch,
5299 ) -> None:
5300 """_failed_auth skips _channel_binding_failed for plain auth failures."""
5301 install_fake_slixmpp(monkeypatch)
5302
5303 xmpp_adapter._CLIENT_SUBCLASS_CACHE.clear()
5304
5305 _ClientCls = xmpp_adapter._get_client_subclass(FakeClientXMPP)
5306 client = _ClientCls(
5307 jid="[email protected]",
5308 password="x",
5309 oneshot=True,
5310 logger=logging.getLogger("test"),
5311 )
5312
5313 # Stanza does not mention channel binding.
5314 fake_stanza = "<failure><not-authorized/></failure>"
5315 client._failed_auth(fake_stanza)
5316
5317 assert client._auth_failed is True
5318 assert client._channel_binding_failed is False
5319
5320
5321 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5322 def test_xmpp_process_raises_channel_binding_error(
5323 monkeypatch: pytest.MonkeyPatch,
5324 ) -> None:
5325 """process() raises XMPPChannelBindingError when channel binding fails."""
5326 install_fake_slixmpp(monkeypatch)
5327
5328 xmpp_adapter._CLIENT_SUBCLASS_CACHE.clear()
5329
5330 # Patch FakeClientXMPP.connect to fire failed_auth with a channel
5331 # binding stanza so the adapter detects the failure.
5332 orig_connect = FakeClientXMPP.connect
5333
5334 def connect_cb_fail(self, **kwargs: Any) -> asyncio.Future[bool]:
5335 loop = self.loop or asyncio.get_running_loop()
5336
5337 if self.disconnected is None:
5338 self.disconnected = loop.create_future()
5339
5340 fut: asyncio.Future[bool] = loop.create_future()
5341 fut.set_result(True)
5342
5343 def _fire_failed_auth() -> None:
5344 # Simulate slixmpp firing failed_auth with a channel binding
5345 # stanza before setting up session_start.
5346 failed_handler = self.handlers.get("failed_auth")
5347 if failed_handler:
5348 fake_stanza = (
5349 "<failure><not-authorized/>"
5350 "<text>Invalid channel binding</text></failure>"
5351 )
5352 failed_handler(fake_stanza)
5353 # Complete disconnect so the adapter loop unblocks.
5354 if self.disconnected is not None and not self.disconnected.done():
5355 self.disconnected.set_result(True)
5356
5357 loop.call_soon(_fire_failed_auth)
5358 return fut
5359
5360 monkeypatch.setattr(FakeClientXMPP, "connect", connect_cb_fail)
5361
5362 cfg = xmpp_adapter.XMPPConfig(
5363 jid="[email protected]",
5364 password="x",
5365 host="example.com",
5366 port=5222,
5367 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
5368 verify_certificate=False,
5369 )
5370 a = xmpp_adapter.SlixmppAdapter(
5371 config=cfg,
5372 targets=[("chat", "[email protected]")],
5373 subject="s",
5374 body="b",
5375 timeout=5.0,
5376 )
5377
5378 with pytest.raises(xmpp_adapter.XMPPChannelBindingError):
5379 a.process()
5380
5381 monkeypatch.setattr(FakeClientXMPP, "connect", orig_connect)
5382
5383
5384 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5385 def test_xmpp_send_catches_channel_binding_error_and_logs(
5386 monkeypatch: pytest.MonkeyPatch,
5387 caplog: pytest.LogCaptureFixture,
5388 ) -> None:
5389 """base.py send() catches XMPPChannelBindingError and logs the hint."""
5390
5391 class _RaisingAdapter:
5392 def __init__(self, **kwargs: Any) -> None:
5393 pass
5394
5395 def process(self) -> bool:
5396 raise xmpp_adapter.XMPPChannelBindingError()
5397
5398 monkeypatch.setattr(xmpp_base, "SlixmppAdapter", _RaisingAdapter)
5399 monkeypatch.setattr(
5400 xmpp_base, "SLIXMPP_SUPPORT_AVAILABLE", True, raising=False
5401 )
5402 monkeypatch.setattr(xmpp_base.NotifyXMPP, "enabled", True, raising=False)
5403
5404 n = NotifyXMPP(host="example.com", user="me", password="x")
5405
5406 # See test_xmpp_invalid_targets_logged for why this is needed: older
5407 # pytest releases don't un-suppress a prior logging.disable(CRITICAL)
5408 # left by another test module's import-time call.
5409 logging.disable(logging.NOTSET)
5410 try:
5411 with caplog.at_level(logging.WARNING, logger="apprise"):
5412 result = n.send(body="hi")
5413
5414 assert result is False
5415 assert "scramplus=no" in caplog.text
5416
5417 finally:
5418 logging.disable(logging.CRITICAL)
5419
5420
5421 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5422 def test_xmpp_send_channel_binding_error_scramplus_already_disabled(
5423 monkeypatch: pytest.MonkeyPatch,
5424 caplog: pytest.LogCaptureFixture,
5425 ) -> None:
5426 """No ?scramplus=no hint when scramplus is already False."""
5427
5428 class _RaisingAdapter:
5429 def __init__(self, **kwargs: Any) -> None:
5430 pass
5431
5432 def process(self) -> bool:
5433 raise xmpp_adapter.XMPPChannelBindingError()
5434
5435 monkeypatch.setattr(xmpp_base, "SlixmppAdapter", _RaisingAdapter)
5436 monkeypatch.setattr(
5437 xmpp_base, "SLIXMPP_SUPPORT_AVAILABLE", True, raising=False
5438 )
5439 monkeypatch.setattr(xmpp_base.NotifyXMPP, "enabled", True, raising=False)
5440
5441 # scramplus explicitly disabled -- the hint must NOT repeat the advice
5442 n = NotifyXMPP(
5443 host="example.com", user="me", password="x", scramplus=False
5444 )
5445
5446 # See test_xmpp_invalid_targets_logged for why this is needed: older
5447 # pytest releases don't un-suppress a prior logging.disable(CRITICAL)
5448 # left by another test module's import-time call.
5449 logging.disable(logging.NOTSET)
5450 try:
5451 with caplog.at_level(logging.WARNING, logger="apprise"):
5452 result = n.send(body="hi")
5453
5454 assert result is False
5455 # The "Add ?scramplus=no" suggestion must not appear when already
5456 # set
5457 assert "Add ?scramplus=no" not in caplog.text
5458 # A compatibility-oriented message must appear instead
5459 assert "compatibility" in caplog.text
5460
5461 finally:
5462 logging.disable(logging.CRITICAL)
5463
5464
5465 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5466 def test_connect_if_required_channel_binding_early_raises(
5467 monkeypatch: pytest.MonkeyPatch,
5468 ) -> None:
5469 """_connect_if_required() raises early when _channel_binding_failed."""
5470 install_fake_slixmpp(monkeypatch)
5471
5472 cfg = xmpp_adapter.XMPPConfig(
5473 jid="[email protected]",
5474 password="x",
5475 host="example.com",
5476 port=5222,
5477 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
5478 verify_certificate=False,
5479 )
5480 a = xmpp_adapter.SlixmppAdapter(
5481 config=cfg, targets=[], subject="s", body="b", keepalive=True
5482 )
5483
5484 loop = asyncio.new_event_loop()
5485 try:
5486 asyncio.set_event_loop(loop)
5487 a._loop = loop
5488 # Client with channel binding already flagged before connect.
5489 a._client = SimpleNamespace(
5490 _channel_binding_failed=True, _auth_failed=False
5491 )
5492 a._connect_lock = asyncio.Lock()
5493 a._session_started = asyncio.Event()
5494
5495 with pytest.raises(xmpp_adapter.XMPPChannelBindingError):
5496 run_on_loop(loop, a._connect_if_required())
5497 finally:
5498 with contextlib.suppress(Exception):
5499 asyncio.set_event_loop(None)
5500 loop.close()
5501
5502
5503 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5504 def test_connect_if_required_channel_binding_bottom_raises(
5505 monkeypatch: pytest.MonkeyPatch,
5506 ) -> None:
5507 """_connect_if_required() raises XMPPChannelBindingError check."""
5508 install_fake_slixmpp(monkeypatch)
5509
5510 cfg = xmpp_adapter.XMPPConfig(
5511 jid="[email protected]",
5512 password="x",
5513 host="example.com",
5514 port=5222,
5515 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
5516 verify_certificate=False,
5517 )
5518 a = xmpp_adapter.SlixmppAdapter(
5519 config=cfg, targets=[], subject="s", body="b", keepalive=True
5520 )
5521
5522 loop = asyncio.new_event_loop()
5523 try:
5524 asyncio.set_event_loop(loop)
5525 a._loop = loop
5526 a._connect_lock = asyncio.Lock()
5527 a._session_started = asyncio.Event()
5528
5529 fut = loop.create_future()
5530 fut.set_result(True)
5531
5532 class _Client:
5533 def __init__(self) -> None:
5534 self._channel_binding_failed = False
5535 self._auth_failed = False
5536
5537 def connect(self, **kwargs: Any) -> Any:
5538 return fut
5539
5540 a._client = _Client()
5541
5542 # Patch wait_for to set channel-binding flag after session wait.
5543 real_wait_for = xmpp_adapter.asyncio.wait_for
5544 calls: dict[str, int] = {"n": 0}
5545
5546 async def wait_for_patched(
5547 aw: Any, timeout: Optional[float] = None
5548 ) -> Any:
5549 calls["n"] += 1
5550 if calls["n"] == 2:
5551 assert a._session_started is not None
5552 a._session_started.set()
5553 assert isinstance(a._client, _Client)
5554 a._client._channel_binding_failed = True
5555 return await real_wait_for(aw, timeout=timeout)
5556
5557 monkeypatch.setattr(
5558 xmpp_adapter.asyncio, "wait_for", wait_for_patched, raising=True
5559 )
5560
5561 with pytest.raises(xmpp_adapter.XMPPChannelBindingError):
5562 run_on_loop(loop, a._connect_if_required())
5563
5564 finally:
5565 with contextlib.suppress(Exception):
5566 asyncio.set_event_loop(None)
5567 loop.close()
5568
5569
5570 @pytest.mark.skipif(not SLIXMPP_AVAILABLE, reason="Requires slixmpp")
5571 def test_send_message_keepalive_reraises_channel_binding_error(
5572 monkeypatch: pytest.MonkeyPatch,
5573 ) -> None:
5574 """send_message() keepalive path re-raises XMPPChannelBindingError."""
5575 install_fake_slixmpp(monkeypatch)
5576
5577 cfg = xmpp_adapter.XMPPConfig(
5578 jid="[email protected]",
5579 password="x",
5580 host="example.com",
5581 port=5222,
5582 secure=xmpp_adapter.SecureXMPPMode.STARTTLS,
5583 verify_certificate=False,
5584 )
5585 a = xmpp_adapter.SlixmppAdapter(
5586 config=cfg,
5587 targets=[("chat", "[email protected]")],
5588 subject="s",
5589 body="b",
5590 timeout=5.0,
5591 keepalive=True,
5592 )
5593
5594 monkeypatch.setattr(
5595 a, "_ensure_keepalive_worker", lambda: True, raising=True
5596 )
5597
5598 class _Loop:
5599 pass
5600
5601 a._loop = _Loop()
5602
5603 def run_coroutine_threadsafe_cb_fail(coro: Any, loop: Any) -> Any:
5604 # Close the coroutine to avoid RuntimeWarning about it not being run.
5605 with contextlib.suppress(Exception):
5606 coro.close()
5607
5608 class _Fut:
5609 def result(self, timeout: Optional[float] = None) -> bool:
5610 raise xmpp_adapter.XMPPChannelBindingError()
5611
5612 return _Fut()
5613
5614 monkeypatch.setattr(
5615 xmpp_adapter.asyncio,
5616 "run_coroutine_threadsafe",
5617 run_coroutine_threadsafe_cb_fail,
5618 raising=True,
5619 )
5620
5621 with pytest.raises(xmpp_adapter.XMPPChannelBindingError):
5622 a.send_message()