Debian Codegraph @

tests/test_plugin_irc.py

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