Debian Codegraph @

tests/test_plugin_irc.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 """Unit tests for Apprise IRC plugin and helper modules."""
29
30 from __future__ import annotations
31
32 import logging
33 import time
34 from typing import Any, Optional
35 from unittest import mock
36
37 import pytest
38
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.irc import NotifyIRC
41 from apprise.plugins.irc.client import IRCClient
42 from apprise.plugins.irc.protocol import (
43 IRCAuthMode,
44 IRCMessage,
45 extract_welcome_nick,
46 is_ping,
47 normalise_channel,
48 parse_irc_line,
49 ping_payload,
50 )
51 from apprise.plugins.irc.state import (
52 IRCActionKind,
53 IRCContext,
54 IRCState,
55 IRCStateMachine,
56 )
57 from apprise.utils.socket import AppriseSocketError
58
59 # Disable logging for a cleaner testing output
60 logging.disable(logging.CRITICAL)
61
62
63 class _DummyTransport:
64 """A lightweight SocketTransport stand-in for IRCClient tests."""
65
66 def __init__(self) -> None:
67 self.connected = False
68 self.closed = False
69 self.writes: list[bytes] = []
70 self.reads: list[bytes] = []
71
72 def connect(self) -> None:
73 self.connected = True
74
75 def close(self) -> None:
76 self.closed = True
77
78 def write(self, payload: bytes, *, flush: bool, timeout: float) -> None:
79 self.writes.append(payload)
80
81 def read(
82 self,
83 max_bytes: int,
84 *,
85 blocking: bool,
86 timeout: Optional[float],
87 ) -> bytes:
88 if not self.reads:
89 return b""
90 chunk = self.reads.pop(0)
91 return chunk[:max_bytes]
92
93
94 def test_plugin_irc_init_targets() -> None:
95 """NotifyIRC parses targets."""
96 with mock.patch.object(NotifyIRC, "apply_irc_defaults"):
97 n = NotifyIRC(
98 host="irc.example.com",
99 targets=["#chan", "%23chan2:key", "@bob", "%40alice", " bad# "],
100 )
101
102 assert "chan" in n.channels
103 assert n.channels["chan"] is None
104 assert "chan2" in n.channels
105 assert n.channels["chan2"] == "key"
106 assert "bob" in n.users
107 assert "alice" in n.users
108
109
110 def test_plugin_irc_modes() -> None:
111 """NotifyIRC auth mode tests."""
112 with (
113 mock.patch.object(NotifyIRC, "apply_irc_defaults"),
114 pytest.raises(AppriseImproperlyConfigured),
115 ):
116 NotifyIRC(host="irc.example.com", targets=["#c"], mode="invalid")
117
118 with mock.patch.object(NotifyIRC, "apply_irc_defaults"):
119 # Case Insensitive
120 result = NotifyIRC(
121 host="irc.example.com", targets=["#c"], mode="NICKServ"
122 )
123 assert "mode=nickserv" in result.url()
124
125 # Case Insensitive
126 result = NotifyIRC(
127 host="irc.example.com", targets=["#c"], mode="server"
128 )
129 assert "mode=" not in result.url()
130
131
132 def test_plugin_irc_defaults_port_noop() -> None:
133 """NotifyIRC defaults are not applied when port is explicit."""
134 n = NotifyIRC(host="irc.efnet.org", targets=["#c"], port=7000)
135 n.apply_irc_defaults()
136 assert n.port == 7000
137
138
139 def test_plugin_irc_defaults_template_match() -> None:
140 """NotifyIRC defaults apply for known networks."""
141 n = NotifyIRC(host="irc.synirc.net", targets=["#c"])
142 assert n.secure is True
143 assert n.port == 6697
144 assert n.auth_mode == IRCAuthMode.NICKSERV
145
146
147 def test_plugin_irc_defaults_template_none() -> None:
148 """NotifyIRC defaults do not force unknown networks."""
149 n = NotifyIRC(host="irc.unknown.tld", targets=["#c"])
150 assert n.secure is False
151
152
153 def test_plugin_irc_send_no_targets() -> None:
154 """NotifyIRC send() rejects empty targets."""
155 n = NotifyIRC(host="irc.example.com", targets=[])
156 assert n.send("body") is False
157
158
159 def test_plugin_irc_send_ok() -> None:
160 """NotifyIRC send() valid path."""
161 n = NotifyIRC(
162 host="irc.example.com",
163 targets=["#chan:key", "@bob"],
164 user="me",
165 password="pw",
166 )
167 n.join = True
168
169 client = mock.Mock(spec=IRCClient)
170 client.nickname = "me"
171
172 with mock.patch("apprise.plugins.irc.base.IRCClient", return_value=client):
173 assert n.send("body", title="title") is True
174
175 client.connect.assert_called_once()
176 client.register.assert_called_once()
177 client.join.assert_called_once()
178 client.privmsg.assert_any_call(
179 target="#chan",
180 message="title body",
181 timeout=mock.ANY,
182 )
183 client.privmsg.assert_any_call(
184 target="bob",
185 message="title body",
186 timeout=mock.ANY,
187 )
188 client.quit.assert_called_once()
189 client.close.assert_called_once()
190
191
192 def test_plugin_irc_send_no_join() -> None:
193 """NotifyIRC avoids JOIN when join is false and no key is provided."""
194 n = NotifyIRC(host="irc.example.com", targets=["#chan", "@bob"])
195 n.join = False
196
197 client = mock.Mock(spec=IRCClient)
198 client.nickname = "x"
199
200 with mock.patch("apprise.plugins.irc.base.IRCClient", return_value=client):
201 assert n.send("body") is True
202
203 client.join.assert_not_called()
204 client.privmsg.assert_any_call(
205 target="#chan",
206 message="body",
207 timeout=mock.ANY,
208 )
209
210
211 def test_plugin_irc_send_error() -> None:
212 """NotifyIRC returns False on connect errors."""
213 n = NotifyIRC(host="irc.example.com", targets=["#chan"])
214 client = mock.Mock(spec=IRCClient)
215 client.connect.side_effect = AppriseSocketError("boom")
216
217 with mock.patch("apprise.plugins.irc.base.IRCClient", return_value=client):
218 assert n.send("body") is False
219
220 client.close.assert_called_once()
221
222
223 def test_plugin_irc_url_id() -> None:
224 """NotifyIRC url_identifier."""
225 n = NotifyIRC(
226 host="irc.example.com", targets=["#c"], user="me", password="pw"
227 )
228 assert n.url_identifier == ("irc", "irc.example.com", "me", "pw")
229
230 n.secure = True
231 assert n.url_identifier[0] == "ircs"
232
233
234 def test_plugin_irc_url_format() -> None:
235 """NotifyIRC url() basic rendering and privacy."""
236 n = NotifyIRC(
237 host="irc.example.com",
238 targets=["#chan:key", "@bob"],
239 user="me",
240 password="pw",
241 secure=False,
242 port=IRCClient.default_insecure_port,
243 nick="nick",
244 name="Real Name",
245 join=False,
246 mode=IRCAuthMode.NICKSERV,
247 )
248
249 url = n.url(privacy=False)
250 assert url.startswith("irc://me:[email protected]/")
251 assert "#chan" in url
252 assert "@bob" in url
253
254 # Mode only appears when auth_mode is not SERVER.
255 if n.auth_mode != IRCAuthMode.SERVER:
256 assert "mode=nickserv" in url
257 else:
258 assert "mode=" not in url
259
260 private = n.url(privacy=True)
261 assert "pw" not in private
262 assert "key" not in private
263
264 n = NotifyIRC(
265 host="irc.example.com",
266 targets=["#chan", "@bob"],
267 user="user2",
268 secure=True,
269 port=IRCClient.default_insecure_port,
270 join=False,
271 mode=IRCAuthMode.NICKSERV,
272 )
273
274 url = n.url(privacy=False)
275 assert url.startswith("ircs://[email protected]:6667/")
276 assert "#chan" in url
277 assert "@bob" in url
278
279 # Mode only appears when auth_mode is not SERVER.
280 if n.auth_mode != IRCAuthMode.SERVER:
281 assert "mode=nickserv" in url
282 else:
283 assert "mode=" not in url
284
285 private = n.url(privacy=True)
286 assert "pw" not in private
287 assert "key" not in private
288
289
290 def test_plugin_irc_parse_url() -> None:
291 """NotifyIRC parse_url() behaviour with host= query."""
292
293 with mock.patch(
294 "apprise.plugins.irc.base.NotifyBase.parse_url",
295 return_value=None,
296 ):
297 results = NotifyIRC.parse_url("irc://%@@")
298 assert results is None
299
300 # host= indicates the URL host is a target, it does not override host.
301 results = NotifyIRC.parse_url("irc://%23chan?host=irc.example.com")
302 assert results is not None
303 assert results["host"] == "%23chan"
304 assert "#chan" in results["targets"]
305
306 results = NotifyIRC.parse_url(
307 "irc://irc.example.com/%23a/@b?to=%23c,@d"
308 "&join=no&name=Z&nick=N&mode=none"
309 )
310 assert results is not None
311 assert results["host"] == "irc.example.com"
312 assert "#a" in results["targets"]
313 assert "@b" in results["targets"]
314 assert "#c" in results["targets"]
315 assert "@d" in results["targets"]
316 assert results["join"] is False
317 assert results["name"] == "Z"
318 assert results["nick"] == "N"
319 assert results["mode"] == "none"
320
321
322 def test_plugin_irc_protocol() -> None:
323 """Protocol helpers."""
324 msg = parse_irc_line(":srv 001 nick :welcome")
325 assert msg.numeric == 1
326 assert extract_welcome_nick(msg) == "nick"
327
328 ping = parse_irc_line("PING :abc")
329 assert is_ping(ping) is True
330 assert ping_payload(ping) == "abc"
331
332 assert normalise_channel("chan") == "#chan"
333 assert normalise_channel("#chan") == "#chan"
334 assert normalise_channel(" ") == ""
335
336
337 def test_plugin_irc_state_machine() -> None:
338 """State machine basics."""
339 ctx = IRCContext(
340 desired_nick="n", accepted_nick="n", fullname="f", password="pw"
341 )
342 sm = IRCStateMachine(ctx)
343
344 acts = sm.start_registration()
345 assert any(
346 a.kind == IRCActionKind.SEND and a.line and a.line.startswith("PASS ")
347 for a in acts
348 )
349
350 sm.on_message(parse_irc_line(":srv 001 nick :welcome"))
351 assert sm.ctx.registered is True
352 assert sm.ctx.accepted_nick == "nick"
353
354 ctx2 = IRCContext(
355 desired_nick="n", accepted_nick="n", fullname="f", password="pw"
356 )
357 sm2 = IRCStateMachine(ctx2)
358 sm2.start_registration()
359 fail = sm2.on_message(parse_irc_line(":srv 464 n :bad pass"))
360 assert fail and fail[0].kind == IRCActionKind.FAIL
361
362 ctx3 = IRCContext(desired_nick="n", accepted_nick="n", fullname="f")
363 sm3 = IRCStateMachine(ctx3)
364 sm3.start_registration()
365 sm3.on_message(parse_irc_line(":srv 001 n :welcome"))
366 sm3.request_join("#c", key=None)
367 sm3.on_message(parse_irc_line(":srv 366 n #c :End of /NAMES list."))
368 assert "#c" in sm3.ctx.joined
369
370
371 def test_plugin_irc_client_nick_handling() -> None:
372 """IRCClient nickname handling."""
373 nick0 = IRCClient.nick_generation(prefix="Apprise", length=9, collision=0)
374 assert len(nick0) == 9
375
376 nick1 = IRCClient.nick_generation(prefix="Apprise", length=9, collision=12)
377 assert len(nick1) == 9
378 assert nick1[-1].isdigit()
379
380 client = IRCClient(
381 host="irc.example.com",
382 nickname="nick",
383 fullname="full",
384 nick_generator=None,
385 )
386 with pytest.raises(AppriseSocketError):
387 client._nickname_collision_handler(prefix="x")
388
389 def gen(prefix: str, length: int, collision: int) -> str:
390 return f"{prefix}{collision}"
391
392 client = IRCClient(
393 host="irc.example.com",
394 nickname="nick",
395 fullname="full",
396 nick_generator=gen,
397 )
398 client._nick_collision = int(client.nickname_collision_max)
399 with pytest.raises(AppriseSocketError):
400 client._nickname_collision_handler(prefix="x")
401
402
403 def test_plugin_irc_client_handshake() -> None:
404 """IRCClient handshake error path."""
405
406 def gen(prefix: str, length: int, collision: int) -> str:
407 return "newnick"
408
409 client = IRCClient(
410 host="irc.example.com",
411 nickname="nick",
412 fullname="full",
413 nick_generator=gen,
414 )
415 client.transport = _DummyTransport()
416
417 # Put the state machine into REGISTERING so 464 triggers FAIL.
418 client.sm.start_registration()
419
420 lines = [
421 "PING :abc",
422 ":srv 433 nick :in use",
423 ":srv 464 nick :bad pass",
424 "",
425 ]
426
427 def _read(deadline: float) -> Optional[str]:
428 return lines.pop(0)
429
430 writes: list[str] = []
431
432 def _write(line: Any, deadline: float) -> None:
433 if isinstance(line, bytes):
434 line = line.decode("utf-8", errors="replace")
435 writes.append(str(line))
436
437 with (
438 mock.patch.object(client, "_read", side_effect=_read),
439 mock.patch.object(client, "_write", side_effect=_write),
440 pytest.raises(AppriseSocketError),
441 ):
442 client._handshake(deadline=time.monotonic() + 1.0, prefix="ap")
443
444 assert any(w.startswith("PONG") for w in writes)
445 assert any(w.startswith("NICK ") for w in writes)
446
447
448 def test_plugin_irc_client_register() -> None:
449 """IRCClient register timeout and success."""
450 client = IRCClient(
451 host="irc.example.com",
452 nickname="nick",
453 fullname="full",
454 password="pw",
455 auth_mode=IRCAuthMode.NICKSERV,
456 )
457 client.transport = _DummyTransport()
458
459 with (
460 mock.patch("time.monotonic", side_effect=[0.0, 1.0]),
461 pytest.raises(TimeoutError),
462 ):
463 client.register(timeout=0.01, prefix="ap")
464
465 client2 = IRCClient(
466 host="irc.example.com",
467 nickname="nick",
468 fullname="full",
469 password="pw",
470 auth_mode=IRCAuthMode.NICKSERV,
471 )
472 client2.transport = _DummyTransport()
473
474 def _handshake(deadline: float, prefix: str) -> None:
475 client2.sm.ctx.registered = True
476
477 with (
478 mock.patch.object(client2, "_flush"),
479 mock.patch.object(client2, "_handshake", side_effect=_handshake),
480 mock.patch.object(client2, "identify") as m_identify,
481 ):
482 client2.register(timeout=0.1, prefix="ap")
483 m_identify.assert_called_once()
484
485
486 def test_plugin_irc_client_identify() -> None:
487 """IRCClient identify early exits and send."""
488 client = IRCClient(
489 host="irc.example.com",
490 nickname="nick",
491 fullname="full",
492 password=None,
493 auth_mode=IRCAuthMode.NICKSERV,
494 )
495 client.transport = _DummyTransport()
496 client.identify(timeout=0.1)
497
498 client2 = IRCClient(
499 host="irc.example.com",
500 nickname="nick",
501 fullname="full",
502 password="pw",
503 auth_mode=IRCAuthMode.SERVER,
504 )
505 client2.transport = _DummyTransport()
506 client2.identify(timeout=0.1)
507
508 client3 = IRCClient(
509 host="irc.example.com",
510 nickname="nick",
511 fullname="full",
512 password="pw",
513 auth_mode=IRCAuthMode.NICKSERV,
514 )
515 client3.transport = _DummyTransport()
516 with (
517 mock.patch.object(client3, "_flush") as m_flush,
518 mock.patch.object(client3, "_handshake") as m_hs,
519 ):
520 client3.identify(timeout=0.1)
521 m_flush.assert_called_once()
522 m_hs.assert_called_once()
523
524
525 def test_plugin_irc_client_join() -> None:
526 """IRCClient join timeout path."""
527 client = IRCClient(
528 host="irc.example.com",
529 nickname="nick",
530 fullname="full",
531 )
532 client.transport = _DummyTransport()
533
534 # join() calls monotonic frequently; use a callable so we never exhaust
535 # a finite side_effect list.
536 calls = {"n": 0}
537
538 def _mono() -> float:
539 calls["n"] += 1
540 # Stay below deadline long enough to exercise the loop, then exceed it.
541 return 0.0 if calls["n"] < 2000 else 1.0
542
543 with (
544 mock.patch.object(client, "_flush") as m_flush,
545 mock.patch.object(client, "_handshake") as m_hs,
546 mock.patch("time.monotonic", side_effect=_mono),
547 ):
548 client.join(channel="#chan", timeout=0.01, prefix="ap", key=None)
549 assert m_flush.called
550 assert m_hs.called
551
552 with mock.patch.object(client, "_write") as m_write:
553 client.quit(message="bye", timeout=0.1)
554 assert m_write.called
555
556
557 def test_plugin_irc_protocol_parse_blank_line() -> None:
558 """Protocol parse blank input."""
559 msg = parse_irc_line(" ")
560 assert msg.command == ""
561 assert msg.params == ()
562 assert msg.trailing is None
563
564
565 def test_plugin_irc_protocol_parse_trailing_only() -> None:
566 """Protocol parse trailing only."""
567 msg = parse_irc_line(" :hello")
568 assert msg.command == ""
569 assert msg.params == ()
570 assert msg.trailing == "hello"
571
572
573 def test_plugin_irc_message() -> None:
574 """IRCMessage testing"""
575
576 message = IRCMessage("raw", None, "not-a-number", ("a", "b"), None)
577 assert message.numeric is None
578
579
580 def test_plugin_irc_protocol_ping_payload_from_params() -> None:
581 """Ping payload from params."""
582 msg = parse_irc_line("PING abc")
583 assert msg.trailing is None
584 assert msg.params == ("abc",)
585 assert ping_payload(msg) == "abc"
586
587
588 def test_plugin_irc_protocol_extract_welcome_nick_non_welcome() -> None:
589 """Welcome nick ignores non-001."""
590 msg = parse_irc_line(":srv 002 nick :Your host is")
591 assert msg.numeric == 2
592 assert extract_welcome_nick(msg) is None
593
594
595 def test_plugin_irc_protocol_normalise_channel_empty() -> None:
596 """Normalise empty channel."""
597 assert normalise_channel("") == ""
598
599
600 def test_plugin_irc_client_props_and_io() -> None:
601 """Client basics."""
602 c = IRCClient(host="h", nickname="n", fullname="f")
603 c.transport = mock.Mock()
604 c.sm.ctx.accepted_nick = "nick"
605 assert c.nickname == "nick"
606 c.connect()
607 c.close()
608 c.transport.connect.assert_called_once()
609 c.transport.close.assert_called_once()
610
611
612 def test_plugin_irc_client_write_timeout() -> None:
613 """Write timeout."""
614 c = IRCClient(host="h", nickname="n", fullname="f")
615 c.transport = mock.Mock()
616 with (
617 mock.patch("time.monotonic", return_value=10.0),
618 pytest.raises(TimeoutError),
619 ):
620 c._write("X", deadline=9.0)
621
622
623 def test_plugin_irc_client_write_bytes_and_flush() -> None:
624 """Write bytes and flush queue."""
625 c = IRCClient(host="h", nickname="n", fullname="f")
626 c.transport = mock.Mock()
627
628 with mock.patch("time.monotonic", return_value=0.0):
629 c._write(b"RAW", deadline=1.0)
630 c.transport.write.assert_called_with(b"RAW", flush=True, timeout=1.0)
631
632 c.transport.write.reset_mock()
633 c._queue("A")
634 c._queue("B")
635 with mock.patch.object(c, "_write") as m_write:
636 c._flush(deadline=1.0)
637 assert m_write.call_count == 2
638 assert len(c._out_queue) == 0
639
640
641 def test_plugin_irc_client_read_buffer_and_timeout() -> None:
642 """Read buffer and timeout."""
643 c = IRCClient(host="h", nickname="n", fullname="f")
644 c.transport = mock.Mock()
645
646 c._inbuf = bytearray(b"hello\r\n")
647 assert c._read(deadline=time.monotonic() + 1.0) == "hello"
648
649 c._inbuf = bytearray()
650 with mock.patch("time.monotonic", return_value=10.0):
651 assert c._read(deadline=9.0) is None
652
653
654 def test_plugin_irc_client_read_transport_paths() -> None:
655 """Read from transport."""
656 c = IRCClient(host="h", nickname="n", fullname="f")
657 c.transport = mock.Mock()
658
659 with mock.patch("time.monotonic", return_value=0.0):
660 c.transport.read.return_value = b""
661 assert c._read(deadline=1.0) is None
662
663 c = IRCClient(host="h", nickname="n", fullname="f")
664 c.transport = mock.Mock()
665 with mock.patch("time.monotonic", side_effect=[0.0, 0.0, 0.0]):
666 c.transport.read.side_effect = [b"he", b"llo\n"]
667 assert c._read(deadline=1.0) == "hello"
668
669
670 def test_plugin_irc_client_tick() -> None:
671 """Tick timing."""
672 c = IRCClient(host="h", nickname="n", fullname="f")
673 with mock.patch("time.monotonic", return_value=10.0):
674 assert c._tick(deadline=9.0) == pytest.approx(9.0)
675
676 with mock.patch("time.monotonic", return_value=0.0):
677 # remaining=0.5 -> 0.0 + 0.5
678 assert c._tick(deadline=0.5) == pytest.approx(0.5)
679
680
681 def test_plugin_irc_client_handshake_paths() -> None:
682 """Handshake paths."""
683 c = IRCClient(host="h", nickname="n", fullname="f")
684 c.transport = mock.Mock()
685
686 with mock.patch.object(c, "_read", return_value=None):
687 c._handshake(deadline=time.monotonic() + 1.0, prefix="")
688
689 lines = ["PING :abc", ""]
690 with (
691 mock.patch.object(
692 c, "_read", side_effect=lambda deadline: lines.pop(0)
693 ),
694 mock.patch.object(c, "_write") as m_write,
695 ):
696 c._handshake(deadline=time.monotonic() + 1.0, prefix="")
697 m_write.assert_any_call("PONG :abc", deadline=mock.ANY)
698
699 lines = [":srv 433 n :in use", ""]
700 with (
701 mock.patch.object(
702 c, "_read", side_effect=lambda deadline: lines.pop(0)
703 ),
704 mock.patch.object(
705 c, "_nickname_collision_handler", return_value="new"
706 ),
707 mock.patch.object(c, "_write") as m_write,
708 ):
709 c._handshake(deadline=time.monotonic() + 1.0, prefix="ap")
710 m_write.assert_any_call("NICK new", deadline=mock.ANY)
711
712 # FAIL action raises
713 from apprise.plugins.irc.state import IRCAction, IRCActionKind
714
715 lines = [":srv 464 n :bad pass", ""]
716 with (
717 mock.patch.object(
718 c, "_read", side_effect=lambda deadline: lines.pop(0)
719 ),
720 mock.patch.object(
721 c.sm,
722 "on_message",
723 return_value=[IRCAction(IRCActionKind.FAIL, reason="boom")],
724 ),
725 pytest.raises(AppriseSocketError),
726 ):
727 c._handshake(deadline=time.monotonic() + 1.0, prefix="")
728
729 # SEND action writes line
730 lines = [":srv 001 n :welcome", ""]
731 with (
732 mock.patch.object(
733 c, "_read", side_effect=lambda deadline: lines.pop(0)
734 ),
735 mock.patch.object(
736 c.sm,
737 "on_message",
738 return_value=[IRCAction(IRCActionKind.SEND, line="NICK x")],
739 ),
740 mock.patch.object(c, "_write") as m_write,
741 ):
742 c._handshake(deadline=time.monotonic() + 1.0, prefix="")
743 m_write.assert_any_call("NICK x", deadline=mock.ANY)
744
745
746 def test_plugin_irc_client_register_auth_modes() -> None:
747 """Register auth modes."""
748 c = IRCClient(
749 host="h",
750 nickname="n",
751 fullname="f",
752 password="pw",
753 auth_mode=IRCAuthMode.NICKSERV,
754 )
755 c.transport = mock.Mock()
756
757 # Force loop to exit by setting registered in handshake
758 def _hs(deadline: float, prefix: str) -> None:
759 c.sm.ctx.registered = True
760
761 with (
762 mock.patch.object(c, "_flush"),
763 mock.patch.object(c, "_handshake", side_effect=_hs),
764 mock.patch.object(c, "identify") as m_ident,
765 mock.patch("time.monotonic", return_value=0.0),
766 mock.patch("time.time", side_effect=[0.0, 0.1, 0.2]),
767 ):
768 c.register(timeout=1.0, prefix="ap")
769 # password cleared before registration when not SERVER
770 assert c.sm.ctx.password is None
771 m_ident.assert_called_once()
772
773 c2 = IRCClient(
774 host="h",
775 nickname="n",
776 fullname="f",
777 password="pw",
778 auth_mode=IRCAuthMode.SERVER,
779 )
780 c2.transport = mock.Mock()
781
782 def _hs2(deadline: float, prefix: str) -> None:
783 c2.sm.ctx.registered = True
784
785 with (
786 mock.patch.object(c2, "_flush"),
787 mock.patch.object(c2, "_handshake", side_effect=_hs2),
788 mock.patch.object(c2, "identify") as m_ident2,
789 mock.patch("time.monotonic", return_value=0.0),
790 mock.patch("time.time", side_effect=[0.0, 0.1, 0.2]),
791 ):
792 c2.register(timeout=1.0, prefix="ap")
793 # identify not called for SERVER
794 m_ident2.assert_not_called()
795
796
797 def test_plugin_irc_client_join_privmsg_identify_quit() -> None:
798 """Join and message helpers."""
799 c = IRCClient(
800 host="h",
801 nickname="n",
802 fullname="f",
803 password="pw",
804 auth_mode=IRCAuthMode.NICKSERV,
805 )
806 c.transport = mock.Mock()
807
808 calls = {"n": 0}
809
810 def _mono() -> float:
811 calls["n"] += 1
812 # Return 0.0 long enough to enter the loop, then jump past deadline
813 # to ensure join() exits.
814 return 0.0 if calls["n"] < 5000 else 1.0
815
816 with (
817 mock.patch.object(c, "_flush") as m_flush,
818 mock.patch.object(c, "_handshake") as m_hs,
819 mock.patch("time.monotonic", side_effect=_mono),
820 ):
821 # join never confirmed -> debug path
822 with mock.patch("apprise.plugins.irc.client.logger.debug") as m_dbg:
823 c.join(channel="#c", timeout=0.01, prefix="ap", key=None)
824 m_dbg.assert_called()
825
826 assert m_flush.called
827 assert m_hs.called
828
829 # privmsg() and identify() also call monotonic; keep them in a separate
830 # context with a simple stable time.
831 with (
832 mock.patch.object(c, "_flush") as m_flush2,
833 mock.patch.object(c, "_handshake") as m_hs2,
834 mock.patch("time.monotonic", return_value=0.0),
835 ):
836 c.privmsg(target="#c", message="m", timeout=0.1)
837 c.identify(timeout=0.1)
838 assert m_flush2.called
839 assert m_hs2.called
840
841 # identify exits early
842 c2 = IRCClient(
843 host="h",
844 nickname="n",
845 fullname="f",
846 password=None,
847 auth_mode=IRCAuthMode.NICKSERV,
848 )
849 c2.transport = mock.Mock()
850 with mock.patch.object(c2, "_flush") as m_flush3:
851 c2.identify(timeout=0.1)
852 m_flush3.assert_not_called()
853
854 c3 = IRCClient(
855 host="h",
856 nickname="n",
857 fullname="f",
858 password="pw",
859 auth_mode=IRCAuthMode.SERVER,
860 )
861 c3.transport = mock.Mock()
862 with mock.patch.object(c3, "_flush") as m_flush4:
863 c3.identify(timeout=0.1)
864 m_flush4.assert_not_called()
865
866 # quit queues and flushes
867 c4 = IRCClient(host="h", nickname="n", fullname="f")
868 c4.transport = mock.Mock()
869 with mock.patch.object(c4, "_flush") as m_flush5:
870 c4.quit(message="bye", timeout=0.1)
871 m_flush5.assert_called_once()
872
873
874 def test_plugin_irc_client_nick_generation_default_length() -> None:
875 """Nick generation defaults."""
876 nick = IRCClient.nick_generation(prefix="Ap", length=None, collision=0)
877 assert len(nick) == IRCClient.nickname_max_length
878
879
880 def test_plugin_irc_client_write_trace() -> None:
881 """Write trace logging."""
882 c = IRCClient(host="h", nickname="n", fullname="f")
883 c.transport = mock.Mock()
884
885 with (
886 mock.patch("time.monotonic", return_value=0.0),
887 mock.patch(
888 "apprise.plugins.irc.client.logger.isEnabledFor", return_value=True
889 ),
890 mock.patch("apprise.plugins.irc.client.logger.trace") as m_trace,
891 ):
892 c._write("HELLO", deadline=1.0)
893 m_trace.assert_called_once()
894 # Ensure we wrote CRLF terminated bytes
895 c.transport.write.assert_called_once()
896 payload = c.transport.write.call_args.args[0]
897 assert payload.endswith(b"\r\n")
898
899
900 def test_plugin_irc_client_handshake_send_without_line() -> None:
901 """Handshake ignores empty SEND."""
902 c = IRCClient(host="h", nickname="n", fullname="f")
903 c.transport = mock.Mock()
904
905 from apprise.plugins.irc.state import IRCAction, IRCActionKind
906
907 # One message then stop the loop
908 lines = [":srv 001 n :welcome", ""]
909 with (
910 mock.patch.object(
911 c, "_read", side_effect=lambda deadline: lines.pop(0)
912 ),
913 mock.patch.object(
914 c.sm,
915 "on_message",
916 return_value=[IRCAction(IRCActionKind.SEND, line="")],
917 ),
918 mock.patch.object(c, "_write") as m_write,
919 ):
920 c._handshake(deadline=time.monotonic() + 1.0, prefix="")
921 m_write.assert_not_called()
922
923
924 def test_plugin_irc_client_register_queue_ignores_empty_send() -> None:
925 """Register ignores empty SEND."""
926 c = IRCClient(
927 host="h", nickname="n", fullname="f", auth_mode=IRCAuthMode.NONE
928 )
929 c.transport = mock.Mock()
930
931 from apprise.plugins.irc.state import IRCAction, IRCActionKind
932
933 with (
934 mock.patch.object(
935 c.sm,
936 "start_registration",
937 return_value=[
938 IRCAction(IRCActionKind.SEND, line=None),
939 IRCAction(IRCActionKind.SEND, line=""),
940 ],
941 ),
942 mock.patch.object(c, "_queue") as m_queue,
943 mock.patch.object(c, "_flush"),
944 mock.patch.object(c, "_handshake"),
945 mock.patch("time.monotonic", return_value=0.0),
946 mock.patch("time.time", return_value=0.0),
947 ):
948 # Make it "already registered" to avoid the while loop behaviour
949 c.sm.ctx.registered = True
950 c.register(timeout=0.1, prefix="ap")
951 m_queue.assert_not_called()
952
953
954 def test_plugin_irc_client_join_queue_ignores_empty_send() -> None:
955 """Join ignores empty SEND."""
956 c = IRCClient(host="h", nickname="n", fullname="f")
957 c.transport = mock.Mock()
958
959 from apprise.plugins.irc.state import IRCAction, IRCActionKind
960
961 with (
962 mock.patch.object(
963 c.sm,
964 "request_join",
965 return_value=[
966 IRCAction(IRCActionKind.SEND, line=None),
967 IRCAction(IRCActionKind.SEND, line=""),
968 ],
969 ),
970 mock.patch.object(c, "_queue") as m_queue,
971 mock.patch.object(c, "_flush"),
972 mock.patch.object(c, "_handshake"),
973 mock.patch("time.monotonic", return_value=1.0),
974 ):
975 # deadline will be 1.0 + timeout, but we also ensure we do not enter
976 # loop by setting joined to include channel.
977 c.sm.ctx.joined.add("#c")
978 c.join(channel="#c", timeout=0.1, prefix="ap", key=None)
979 m_queue.assert_not_called()
980
981
982 def test_plugin_irc_client_quit_queue_ignores_empty_send() -> None:
983 """Quit ignores empty SEND."""
984 c = IRCClient(host="h", nickname="n", fullname="f")
985 c.transport = mock.Mock()
986
987 from apprise.plugins.irc.state import IRCAction, IRCActionKind
988
989 with (
990 mock.patch.object(
991 c.sm,
992 "request_quit",
993 return_value=[
994 IRCAction(IRCActionKind.SEND, line=None),
995 IRCAction(IRCActionKind.SEND, line=""),
996 ],
997 ),
998 mock.patch.object(c, "_queue") as m_queue,
999 mock.patch.object(c, "_flush") as m_flush,
1000 mock.patch("time.monotonic", return_value=0.0),
1001 ):
1002 c.quit(message="bye", timeout=0.1)
1003 m_queue.assert_not_called()
1004 m_flush.assert_called_once()
1005
1006
1007 def test_plugin_irc_send_znc_calls_check_connection() -> None:
1008 """NotifyIRC ZNC mode triggers a connection check."""
1009 n = NotifyIRC(
1010 host="irc.example.com",
1011 targets=["#chan"],
1012 user="zncuser",
1013 password="zncpass",
1014 mode=IRCAuthMode.ZNC,
1015 nick="mybot",
1016 )
1017
1018 client = mock.Mock(spec=IRCClient)
1019 client.nickname = "mybot"
1020 client.check_connection.return_value = True
1021
1022 with mock.patch("apprise.plugins.irc.base.IRCClient", return_value=client):
1023 assert n.send("body") is True
1024
1025 client.connect.assert_called_once()
1026 client.register.assert_called_once()
1027 client.check_connection.assert_called_once()
1028 client.privmsg.assert_called_once()
1029 client.quit.assert_called_once()
1030 client.close.assert_called_once()
1031
1032
1033 def test_plugin_irc_send_znc_check_connection_failure() -> None:
1034 """NotifyIRC ZNC mode fails fast if the bouncer liveness check fails."""
1035 n = NotifyIRC(
1036 host="irc.example.com",
1037 targets=["#chan"],
1038 user="zncuser",
1039 password="zncpass",
1040 mode=IRCAuthMode.ZNC,
1041 nick="mybot",
1042 )
1043
1044 client = mock.Mock(spec=IRCClient)
1045 client.nickname = "mybot"
1046 client.check_connection.return_value = False
1047
1048 with mock.patch("apprise.plugins.irc.base.IRCClient", return_value=client):
1049 assert n.send("body") is False
1050
1051 client.connect.assert_called_once()
1052 client.register.assert_called_once()
1053 client.check_connection.assert_called_once()
1054 client.privmsg.assert_not_called()
1055 client.quit.assert_not_called()
1056 client.close.assert_called_once()
1057
1058
1059 def test_plugin_irc_send_znc_pass_rewrite() -> None:
1060 """NotifyIRC ZNC mode passes user:pass to IRCClient password."""
1061 n = NotifyIRC(
1062 host="irc.example.com",
1063 targets=["#chan"],
1064 user="zncuser",
1065 password="zncpass",
1066 mode=IRCAuthMode.ZNC,
1067 nick="mybot",
1068 )
1069
1070 client = mock.Mock(spec=IRCClient)
1071 client.nickname = "mybot"
1072 client.check_connection.return_value = True
1073
1074 with mock.patch(
1075 "apprise.plugins.irc.base.IRCClient", return_value=client
1076 ) as m_ctor:
1077 assert n.send("body") is True
1078
1079 # Pull the kwargs passed into IRCClient(...)
1080 kwargs = m_ctor.call_args.kwargs
1081 assert kwargs["password"] == "zncuser:zncpass"
1082
1083
1084 def test_plugin_irc_client_check_connection_success_on_any_pong() -> None:
1085 """check_connection() returns True when a PONG is observed."""
1086 c = IRCClient(host="h", nickname="n", fullname="f")
1087 c.transport = mock.Mock()
1088
1089 # 0.0 used to compute deadline, then remain within deadline once, then stop
1090 times = [0.0, 0.0, 0.0]
1091
1092 def _mono() -> float:
1093 return times.pop(0) if times else 10.0
1094
1095 with (
1096 mock.patch("time.monotonic", side_effect=_mono),
1097 mock.patch.object(c, "_write") as m_write,
1098 mock.patch.object(c, "_read", side_effect=["PONG :server"]) as m_read,
1099 ):
1100 assert c.check_connection(timeout=5.0) is True
1101 m_write.assert_called_once()
1102 m_read.assert_called()
1103
1104
1105 def test_plugin_irc_client_handles_empty_reads() -> None:
1106 """check_connection() handles empty reads and returns False at deadline."""
1107 c = IRCClient(host="h", nickname="n", fullname="f")
1108 c.transport = mock.Mock()
1109
1110 # Start at 0.0, enter loop once, then exceed deadline after the empty read.
1111 times = [0.0, 0.0, 6.0]
1112
1113 def _mono() -> float:
1114 return times.pop(0)
1115
1116 with (
1117 mock.patch("time.monotonic", side_effect=_mono),
1118 mock.patch.object(c, "_write") as m_write,
1119 mock.patch.object(c, "_read", return_value=None),
1120 ):
1121 assert c.check_connection(timeout=5.0) is False
1122 m_write.assert_called_once()
1123
1124
1125 def test_plugin_irc_client_join_queues_join_line_and_completes() -> None:
1126 """join() queues the JOIN command when request_join yields a SEND line."""
1127 c = IRCClient(host="h", nickname="n", fullname="f")
1128 c.transport = mock.Mock()
1129
1130 def _handshake(deadline: float, prefix: str) -> None:
1131 # Simulate join confirmation being observed
1132 c.sm.ctx.joined.add("#c")
1133
1134 with (
1135 mock.patch("time.monotonic", return_value=0.0),
1136 mock.patch.object(c, "_queue") as m_queue,
1137 mock.patch.object(c, "_flush"),
1138 mock.patch.object(c, "_handshake", side_effect=_handshake),
1139 ):
1140 c.join(channel="#c", timeout=1.0, prefix="ap", key=None)
1141
1142 # Ensure the queue branch was taken
1143 assert any(
1144 call.args
1145 and isinstance(call.args[0], str)
1146 and call.args[0].startswith("JOIN ")
1147 for call in m_queue.call_args_list
1148 )
1149
1150
1151 def test_plugin_irc_client_join_timeout_logs_debug() -> None:
1152 """join() emits a debug line when confirmation is not observed."""
1153 c = IRCClient(host="h", nickname="n", fullname="f")
1154 c.transport = mock.Mock()
1155
1156 # timeout=0.0 forces the while-loop to be skipped and triggers debug path
1157 with (
1158 mock.patch("time.monotonic", return_value=0.0),
1159 mock.patch("apprise.plugins.irc.client.logger.debug") as m_dbg,
1160 mock.patch.object(c, "_flush"),
1161 mock.patch.object(c, "_handshake"),
1162 ):
1163 c.join(channel="#c", timeout=0.0, prefix="ap", key=None)
1164 m_dbg.assert_called_once()
1165
1166
1167 def test_plugin_irc_state_machine_joining_numeric_443_adds_channel() -> None:
1168 """State machine treats numeric 443 as joined confirmation."""
1169 ctx = IRCContext(desired_nick="n", accepted_nick="n", fullname="f")
1170 sm = IRCStateMachine(ctx)
1171
1172 # Enter JOINING state
1173 sm.request_join("#c")
1174
1175 assert sm.state == IRCState.JOINING
1176
1177 # 443 usually indicates already on channel; this should mark as joined.
1178 sm.on_message(parse_irc_line(":srv 443 n #c :is already on channel"))
1179
1180 assert "#c" in sm.ctx.joined
1181 assert sm.state == IRCState.READY
1182
1183
1184 def test_plugin_irc_client_connection_check() -> None:
1185 """check_connection() sees a non-PONG message."""
1186 c = IRCClient(host="h", nickname="n", fullname="f")
1187 c.transport = mock.Mock()
1188
1189 # monotonic() is used to compute deadline, then loop condition.
1190 # We provide values such that we enter the loop at least once, then
1191 # exceed deadline.
1192 times = [0.0, 0.0, 0.0, 6.0]
1193
1194 def _mono() -> float:
1195 return times.pop(0)
1196
1197 with (
1198 mock.patch("time.monotonic", side_effect=_mono),
1199 mock.patch.object(c, "_write") as m_write,
1200 # First read returns a non-empty line that is not a PONG, then nothing.
1201 mock.patch.object(c, "_read", side_effect=["PING :abc", None]),
1202 ):
1203 assert c.check_connection(timeout=5.0) is False
1204 m_write.assert_called_once()
1205
1206
1207 def test_plugin_irc_client_join_non_send_actions() -> None:
1208 """join() ignores non-SEND actions"""
1209 c = IRCClient(host="h", nickname="n", fullname="f")
1210 c.transport = mock.Mock()
1211
1212 from apprise.plugins.irc.state import IRCAction, IRCActionKind
1213
1214 # Return a NOOP action so: act.kind == SEND is False
1215 actions = [IRCAction(IRCActionKind.NOOP)]
1216
1217 # Skip the while loop by making monotonic() already past deadline
1218 with (
1219 mock.patch.object(c.sm, "request_join", return_value=actions),
1220 mock.patch.object(c, "_queue") as m_queue,
1221 mock.patch.object(c, "_flush") as m_flush,
1222 mock.patch.object(c, "_handshake") as m_hs,
1223 mock.patch("time.monotonic", side_effect=[0.0, 1.0]),
1224 mock.patch("apprise.plugins.irc.client.logger.debug") as m_dbg,
1225 ):
1226 c.join(channel="#c", timeout=0.0, prefix="ap", key=None)
1227
1228 # Nothing queued because our action was not SEND
1229 m_queue.assert_not_called()
1230
1231 # While loop is skipped, so these are not called
1232 m_flush.assert_not_called()
1233 m_hs.assert_not_called()
1234
1235 # Not joined, so debug path executes
1236 m_dbg.assert_called_once()