Debian Codegraph @

tests/test_plugin_deltachat.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 # Email tests cover inherited delivery behavior. These tests cover the
29 # Delta Chat schema, plain-text envelope, and chat headers.
30
31 import logging
32 import os
33 import sys
34 from unittest import mock
35
36 import pytest
37
38 from apprise import Apprise, AppriseAsset, NotifyBase, PersistentStoreMode
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.deltachat import NotifyDeltaChat
41
42 logging.disable(logging.CRITICAL)
43
44 # PGP fixture directory (shared with test_plugin_email.py / test_utils_pgp.py)
45 PGP_VAR_DIR = os.path.join(os.path.dirname(__file__), "var", "pgp")
46 VALID_PRV_KEY = os.path.join(PGP_VAR_DIR, "valid-prv.asc")
47 VALID_PUB_KEY = os.path.join(PGP_VAR_DIR, "valid-pub.asc")
48
49 # Our Testing URLs
50 apprise_url_tests = (
51 (
52 "deltachat://",
53 {
54 "instance": AppriseImproperlyConfigured,
55 },
56 ),
57 # A minimal, valid URL: login doubles as our sender identity
58 (
59 "deltachat://user:[email protected]/[email protected]",
60 {
61 "instance": NotifyDeltaChat,
62 "privacy_url": (
63 "deltachat://user:****@smtp.example.com/friend%40example.org"
64 ),
65 },
66 ),
67 # The secure schema variant round-trips as itself
68 (
69 "deltachats://user:[email protected]/[email protected]",
70 {
71 "instance": NotifyDeltaChat,
72 "privacy_url": (
73 "deltachats://user:****@smtp.example.com/friend%40example.org"
74 ),
75 },
76 ),
77 # Multiple targets
78 (
79 "deltachat://user:[email protected]/"
80 "[email protected]/[email protected]",
81 {
82 "instance": NotifyDeltaChat,
83 },
84 ),
85 # ?to= adds an additional target
86 (
87 "deltachat://user:[email protected]/[email protected]"
88 "[email protected]",
89 {
90 "instance": NotifyDeltaChat,
91 },
92 ),
93 # Explicit insecure mode (no transport security at all)
94 (
95 "deltachat://user:[email protected]/[email protected]"
96 "?mode=insecure",
97 {
98 "instance": NotifyDeltaChat,
99 },
100 ),
101 # An invalid secure mode
102 (
103 "deltachat://user:[email protected]/[email protected]"
104 "?mode=invalid",
105 {
106 "instance": AppriseImproperlyConfigured,
107 },
108 ),
109 # An invalid PGP mode
110 (
111 "deltachat://user:[email protected]/[email protected]"
112 "?pgp=invalid",
113 {
114 "instance": AppriseImproperlyConfigured,
115 },
116 ),
117 # Encryption fails without a recipient key.
118 (
119 "deltachat://user:[email protected]/[email protected]"
120 "?pgp=encrypt",
121 {
122 "instance": NotifyDeltaChat,
123 "response": False,
124 },
125 ),
126 # A custom display name
127 (
128 "deltachat://user:[email protected]/[email protected]"
129 "?name=My%20Bot",
130 {
131 "instance": NotifyDeltaChat,
132 },
133 ),
134 # The explicit secure schema, with a custom port
135 (
136 "deltachats://user:[email protected]:2525/[email protected]",
137 {
138 "instance": NotifyDeltaChat,
139 },
140 ),
141 )
142
143
144 @mock.patch("smtplib.SMTP")
145 @mock.patch("smtplib.SMTP_SSL")
146 def test_plugin_deltachat_urls(mock_smtp, mock_smtpssl):
147 """NotifyDeltaChat() Apprise URLs."""
148
149 mock_socket = mock.Mock()
150 mock_socket.starttls.return_value = True
151 mock_socket.login.return_value = True
152 # An empty refusal map means SMTP accepted every recipient.
153 mock_socket.sendmail.return_value = {}
154 mock_smtp.return_value = mock_socket
155 mock_smtpssl.return_value = mock_socket
156
157 for url, meta in apprise_url_tests:
158 instance = meta.get("instance", None)
159 response = meta.get("response", True)
160 privacy_url = meta.get("privacy_url")
161
162 try:
163 obj = Apprise.instantiate(url, suppress_exceptions=False)
164
165 except Exception as e:
166 if instance is None or not isinstance(e, instance):
167 raise
168 continue
169
170 assert isinstance(obj, instance)
171 assert isinstance(obj, NotifyBase)
172
173 # Confirm a lossless round trip through our own generated URL
174 assert isinstance(obj.url(), str)
175 assert isinstance(obj.url_id(), str)
176 assert isinstance(len(obj), int)
177 assert isinstance(obj.url(privacy=True), str)
178
179 # Invalid input remains safe through the parse override.
180 assert instance.parse_url(None) is None
181 assert instance.parse_url(object) is None
182 assert instance.parse_url(42) is None
183
184 if privacy_url and not obj.url(privacy=True).startswith(privacy_url):
185 raise AssertionError(
186 f"URL: {url} Privacy URL:"
187 f" '{obj.url(privacy=True)[: len(privacy_url)]}' !="
188 f" expected '{privacy_url}'"
189 )
190
191 obj_cmp = Apprise.instantiate(obj.url())
192 assert isinstance(obj_cmp, NotifyBase)
193 assert len(obj) == len(obj_cmp)
194 assert obj.url_identifier == obj_cmp.url_identifier
195
196 assert obj.notify(title="test", body="body test message") == response
197
198
199 def test_plugin_deltachat_schema_identity():
200 """NotifyDeltaChat() class-level schema/format identity."""
201
202 assert NotifyDeltaChat.protocol == "deltachat"
203 assert NotifyDeltaChat.secure_protocol == "deltachats"
204 assert NotifyDeltaChat.service_name == "Delta Chat"
205
206 # Plain-text only; no separate title field, so the framework merges
207 # any title into the body for us
208 assert NotifyDeltaChat.notify_format == "text"
209 assert NotifyDeltaChat.title_maxlen == 0
210
211 # PGPy remains the one optional dependency, inherited from Email
212 assert NotifyDeltaChat.runtime_deps() == ("pgpy",)
213
214
215 def _deltachat_instance(pgp="no"):
216 """Build an instance for subject tests without sending."""
217
218 return NotifyDeltaChat(
219 host="smtp.example.com",
220 user="bot",
221 password="secret",
222 targets=["[email protected]"],
223 pgp_mode=pgp,
224 )
225
226
227 def test_plugin_deltachat_chat_subject():
228 """Plain subjects contain a shortened body excerpt."""
229
230 obj = _deltachat_instance(pgp="no")
231
232 # A short body is used verbatim
233 assert obj._chat_subject("hello there") == "Chat: hello there"
234
235 # Collapse internal whitespace, including a merged title.
236 assert (
237 obj._chat_subject("My Title\nhello world")
238 == "Chat: My Title hello world"
239 )
240
241 # An empty body still produces a valid, generic subject
242 assert obj._chat_subject("") == "Chat:"
243
244 # Truncate long bodies and append an ellipsis.
245 long_body = "x" * 80
246 subject = obj._chat_subject(long_body)
247 assert subject == f"Chat: {'x' * 50}..."
248
249
250 def test_plugin_deltachat_pgp_subject_privacy():
251 """PGP modes keep body text out of the unencrypted subject."""
252
253 secret = "CONFIDENTIAL body content must remain private"
254
255 expected = {
256 "sign": "Chat:",
257 "encrypt": "Chat: Encrypted message",
258 }
259 for pgp_mode, subject in expected.items():
260 obj = _deltachat_instance(pgp=pgp_mode)
261
262 assert obj._chat_subject(secret) == subject
263 assert secret not in obj._chat_subject(secret)
264
265 # Still a valid, generic subject for an empty body
266 assert obj._chat_subject("") == subject
267
268
269 def test_plugin_deltachat_protocol_headers():
270 """NotifyDeltaChat._protocol_headers() emits Chat-Version only."""
271
272 obj = NotifyDeltaChat(
273 host="smtp.example.com",
274 user="bot",
275 password="secret",
276 targets=["[email protected]"],
277 )
278 assert obj._protocol_headers("any body") == {"Chat-Version": "1.0"}
279
280
281 @mock.patch("smtplib.SMTP")
282 @mock.patch("smtplib.SMTP_SSL")
283 def test_plugin_deltachat_send_envelope(mock_smtp, mock_smtpssl):
284 """NotifyDeltaChat() send() builds a spec-compliant envelope."""
285
286 mock_socket = mock.Mock()
287 mock_socket.starttls.return_value = True
288 mock_socket.login.return_value = True
289 # An empty refusal map means SMTP accepted every recipient.
290 mock_socket.sendmail.return_value = {}
291 mock_smtp.return_value = mock_socket
292 mock_smtpssl.return_value = mock_socket
293
294 obj = Apprise.instantiate(
295 "deltachat://user:[email protected]/[email protected]",
296 suppress_exceptions=False,
297 )
298
299 assert obj.notify(title="My Title", body="hello world") is True
300
301 raw = mock_socket.sendmail.call_args[0][2]
302
303 # Chat-Version is a hard protocol requirement on every message
304 assert "Chat-Version: 1.0" in raw
305
306 # The subject uses the title already merged into the body.
307 assert "Subject: Chat: My Title hello world" in raw
308
309 # The body itself is always sent as plain text
310 assert 'Content-Type: text/plain; charset="utf-8"' in raw
311
312
313 @mock.patch("smtplib.SMTP")
314 @mock.patch("smtplib.SMTP_SSL")
315 def test_plugin_deltachat_send_forces_text_format(mock_smtp, mock_smtpssl):
316 """NotifyDeltaChat() send() ignores an explicit HTML body_format."""
317
318 mock_socket = mock.Mock()
319 mock_socket.starttls.return_value = True
320 mock_socket.login.return_value = True
321 # An empty refusal map means SMTP accepted every recipient.
322 mock_socket.sendmail.return_value = {}
323 mock_smtp.return_value = mock_socket
324 mock_smtpssl.return_value = mock_socket
325
326 obj = Apprise.instantiate(
327 "deltachat://user:[email protected]/[email protected]"
328 "?format=html",
329 suppress_exceptions=False,
330 )
331
332 assert obj.notify(title="T", body="<b>hi</b>") is True
333
334 raw = mock_socket.sendmail.call_args[0][2]
335 assert 'Content-Type: text/plain; charset="utf-8"' in raw
336 assert "text/html" not in raw
337
338
339 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
340 @mock.patch("smtplib.SMTP")
341 @mock.patch("smtplib.SMTP_SSL")
342 def test_plugin_deltachat_autocrypt_and_pgp_inherited(
343 mock_smtp, mock_smtpssl, tmpdir
344 ):
345 """Delta Chat inherits Email signing and Autocrypt handling."""
346
347 mock_socket = mock.Mock()
348 mock_socket.starttls.return_value = True
349 mock_socket.login.return_value = True
350 # An empty refusal map means SMTP accepted every recipient.
351 mock_socket.sendmail.return_value = {}
352 mock_smtp.return_value = mock_socket
353 mock_smtpssl.return_value = mock_socket
354
355 asset = AppriseAsset(
356 storage_mode=PersistentStoreMode.FLUSH,
357 storage_path=str(tmpdir),
358 )
359
360 obj = Apprise.instantiate(
361 "deltachat://user:[email protected]/[email protected]?pgp=sign",
362 asset=asset,
363 suppress_exceptions=False,
364 )
365
366 # Generate an Autocrypt-compatible key in this instance's store.
367 assert obj.pgp.keygen() is True
368
369 assert obj.notify(title="T", body="secret chat message") is True
370
371 raw = mock_socket.sendmail.call_args[0][2]
372 assert "Chat-Version: 1.0" in raw
373 assert "multipart/signed" in raw
374 assert raw.count("Autocrypt:") == 1
375
376 # PGP is in play, so the outer Subject must be generic
377 assert "Subject: Chat:" in raw
378 assert "Subject: Chat: T secret chat message" not in raw
379
380
381 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
382 @mock.patch("smtplib.SMTP")
383 @mock.patch("smtplib.SMTP_SSL")
384 def test_plugin_deltachat_encrypt_subject_privacy(
385 mock_smtp, mock_smtpssl, tmpdir
386 ):
387 """Encrypted sends keep body text out of the outer subject."""
388
389 mock_socket = mock.Mock()
390 mock_socket.starttls.return_value = True
391 mock_socket.login.return_value = True
392 # An empty refusal map means SMTP accepted every recipient.
393 mock_socket.sendmail.return_value = {}
394 mock_smtp.return_value = mock_socket
395 mock_smtpssl.return_value = mock_socket
396
397 asset = AppriseAsset(
398 storage_mode=PersistentStoreMode.FLUSH,
399 storage_path=str(tmpdir),
400 )
401 obj = Apprise.instantiate(
402 "deltachat://user:[email protected]/[email protected]"
403 f"?pgp=encrypt&pgppub={VALID_PUB_KEY}",
404 asset=asset,
405 suppress_exceptions=False,
406 )
407
408 secret = "CONFIDENTIAL body content must remain private"
409 assert obj.notify(title="T", body=secret) is True
410
411 raw = mock_socket.sendmail.call_args[0][2]
412
413 # Use Delta Chat's recommended placeholder without exposing the body.
414 assert "Subject: Chat: Encrypted message" in raw
415
416 # Protected body text must not appear in the outer envelope.
417 assert secret not in raw
418 assert "CONFIDENTIAL body content" not in raw