Debian Codegraph @

tests/test_plugin_pushbullet.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 from json import dumps
29
30 # Disable logging for a cleaner testing output
31 import logging
32 import os
33 from unittest import mock
34
35 from helpers import AppriseURLTester
36 import pytest
37 import requests
38
39 from apprise import Apprise, AppriseAttachment
40 from apprise.exception import AppriseImproperlyConfigured
41 from apprise.plugins.pushbullet import NotifyPushBullet
42
43 logging.disable(logging.CRITICAL)
44
45 # Attachment Directory
46 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
47
48 # Our Testing URLs
49 apprise_url_tests = (
50 (
51 "pbul://",
52 {
53 "instance": AppriseImproperlyConfigured,
54 },
55 ),
56 (
57 "pbul://:@/",
58 {
59 "instance": AppriseImproperlyConfigured,
60 },
61 ),
62 # APIkey
63 (
64 "pbul://%s" % ("a" * 32),
65 {
66 "instance": NotifyPushBullet,
67 "check_attachments": False,
68 },
69 ),
70 # APIkey; but support attachment response
71 (
72 "pbul://%s" % ("a" * 32),
73 {
74 "instance": NotifyPushBullet,
75 # Test what happens if a batch send fails to return a messageCount
76 "requests_response_text": {
77 "file_name": "cat.jpeg",
78 "file_type": "image/jpeg",
79 "file_url": "http://file_url",
80 "upload_url": "http://upload_url",
81 },
82 },
83 ),
84 # APIkey; attachment testing that isn't an image type
85 (
86 "pbul://%s" % ("a" * 32),
87 {
88 "instance": NotifyPushBullet,
89 # Test what happens if a batch send fails to return a messageCount
90 "requests_response_text": {
91 "file_name": "test.pdf",
92 "file_type": "application/pdf",
93 "file_url": "http://file_url",
94 "upload_url": "http://upload_url",
95 },
96 },
97 ),
98 # APIkey; attachment testing were expected entry in payload is missing
99 (
100 "pbul://%s" % ("a" * 32),
101 {
102 "instance": NotifyPushBullet,
103 # Test what happens if a batch send fails to return a messageCount
104 "requests_response_text": {
105 "file_name": "test.pdf",
106 "file_type": "application/pdf",
107 "file_url": "http://file_url",
108 # upload_url missing
109 },
110 # Our Notification calls associated with attachments will fail:
111 "attach_response": False,
112 },
113 ),
114 # API Key + channel
115 (
116 "pbul://%s/#channel/" % ("a" * 32),
117 {
118 "instance": NotifyPushBullet,
119 "check_attachments": False,
120 },
121 ),
122 # API Key + channel (via to=
123 (
124 "pbul://%s/?to=#channel" % ("a" * 32),
125 {
126 "instance": NotifyPushBullet,
127 "check_attachments": False,
128 },
129 ),
130 # API Key + 2 channels
131 (
132 "pbul://%s/#channel1/#channel2" % ("a" * 32),
133 {
134 "instance": NotifyPushBullet,
135 # Our expected url(privacy=True) startswith() response:
136 "privacy_url": "pbul://a...a/",
137 "check_attachments": False,
138 },
139 ),
140 # API Key + device
141 (
142 "pbul://%s/device/" % ("a" * 32),
143 {
144 "instance": NotifyPushBullet,
145 "check_attachments": False,
146 },
147 ),
148 # API Key + 2 devices
149 (
150 "pbul://%s/device1/device2/" % ("a" * 32),
151 {
152 "instance": NotifyPushBullet,
153 "check_attachments": False,
154 },
155 ),
156 # API Key + email
157 (
158 "pbul://%s/[email protected]/" % ("a" * 32),
159 {
160 "instance": NotifyPushBullet,
161 "check_attachments": False,
162 },
163 ),
164 # API Key + 2 emails
165 (
166 "pbul://%s/[email protected]/[email protected]/" % ("a" * 32),
167 {
168 "instance": NotifyPushBullet,
169 "check_attachments": False,
170 },
171 ),
172 # API Key + Combo
173 (
174 "pbul://%s/device/#channel/[email protected]/" % ("a" * 32),
175 {
176 "instance": NotifyPushBullet,
177 "check_attachments": False,
178 },
179 ),
180 # ,
181 (
182 "pbul://%s" % ("a" * 32),
183 {
184 "instance": NotifyPushBullet,
185 # force a failure
186 "response": False,
187 "requests_response_code": requests.codes.internal_server_error,
188 "check_attachments": False,
189 },
190 ),
191 (
192 "pbul://%s" % ("a" * 32),
193 {
194 "instance": NotifyPushBullet,
195 # throw a bizarre code forcing us to fail to look it up
196 "response": False,
197 "requests_response_code": 999,
198 "check_attachments": False,
199 },
200 ),
201 (
202 "pbul://%s" % ("a" * 32),
203 {
204 "instance": NotifyPushBullet,
205 # Throws a series of i/o exceptions with this flag
206 # is set and tests that we gracefully handle them
207 "test_requests_exceptions": True,
208 "check_attachments": False,
209 },
210 ),
211 (
212 "pbul://%s" % ("a" * 32),
213 {
214 "instance": NotifyPushBullet,
215 # force a failure
216 "response": False,
217 "requests_response_code": requests.codes.internal_server_error,
218 "check_attachments": False,
219 },
220 ),
221 (
222 "pbul://%s" % ("a" * 32),
223 {
224 "instance": NotifyPushBullet,
225 # throw a bizarre code forcing us to fail to look it up
226 "response": False,
227 "requests_response_code": 999,
228 "check_attachments": False,
229 },
230 ),
231 (
232 "pbul://%s" % ("a" * 32),
233 {
234 "instance": NotifyPushBullet,
235 # Throws a series of i/o exceptions with this flag
236 # is set and tests that we gracefully handle them
237 "test_requests_exceptions": True,
238 "check_attachments": False,
239 },
240 ),
241 )
242
243
244 def test_plugin_pushbullet_urls():
245 """NotifyPushBullet() Apprise URLs."""
246
247 # Run our general tests
248 AppriseURLTester(tests=apprise_url_tests).run_all()
249
250
251 @mock.patch("requests.post")
252 def test_plugin_pushbullet_attachments(mock_post):
253 """NotifyPushBullet() Attachment Checks."""
254
255 # Initialize some generic (but valid) tokens
256 access_token = "t" * 32
257
258 # Prepare Mock return object
259 response = mock.Mock()
260 response.content = dumps(
261 {
262 "file_name": "cat.jpg",
263 "file_type": "image/jpeg",
264 "file_url": "https://dl.pushb.com/abc/cat.jpg",
265 "upload_url": "https://upload.pushbullet.com/abcd123",
266 }
267 ).encode("utf-8")
268 response.status_code = requests.codes.ok
269 mock_post.return_value = response
270
271 # prepare our attachment
272 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
273
274 # Test our markdown
275 obj = Apprise.instantiate(f"pbul://{access_token}/?format=markdown")
276
277 # Send a good attachment
278 assert bool(obj.notify(body="test", attach=attach)) is True
279
280 # Test our call count
281 assert mock_post.call_count == 4
282 # Image Prep
283 assert (
284 mock_post.call_args_list[0][0][0]
285 == "https://api.pushbullet.com/v2/upload-request"
286 )
287 assert (
288 mock_post.call_args_list[1][0][0]
289 == "https://upload.pushbullet.com/abcd123"
290 )
291 # Message
292 assert (
293 mock_post.call_args_list[2][0][0]
294 == "https://api.pushbullet.com/v2/pushes"
295 )
296 # Image Send
297 assert (
298 mock_post.call_args_list[3][0][0]
299 == "https://api.pushbullet.com/v2/pushes"
300 )
301
302 # Reset our mock object
303 mock_post.reset_mock()
304
305 # Add another attachment so we drop into the area of the PushBullet code
306 # that sends remaining attachments (if more detected)
307 attach.add(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
308
309 # Send our attachments
310 assert bool(obj.notify(body="test", attach=attach)) is True
311
312 # Test our call count
313 assert mock_post.call_count == 7
314 # Image Prep
315 assert (
316 mock_post.call_args_list[0][0][0]
317 == "https://api.pushbullet.com/v2/upload-request"
318 )
319 assert (
320 mock_post.call_args_list[1][0][0]
321 == "https://upload.pushbullet.com/abcd123"
322 )
323 assert (
324 mock_post.call_args_list[2][0][0]
325 == "https://api.pushbullet.com/v2/upload-request"
326 )
327 assert (
328 mock_post.call_args_list[3][0][0]
329 == "https://upload.pushbullet.com/abcd123"
330 )
331 # Message
332 assert (
333 mock_post.call_args_list[4][0][0]
334 == "https://api.pushbullet.com/v2/pushes"
335 )
336 # Image Send
337 assert (
338 mock_post.call_args_list[5][0][0]
339 == "https://api.pushbullet.com/v2/pushes"
340 )
341 assert (
342 mock_post.call_args_list[6][0][0]
343 == "https://api.pushbullet.com/v2/pushes"
344 )
345
346 # Reset our mock object
347 mock_post.reset_mock()
348
349 # An invalid attachment will cause a failure
350 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
351 attach = AppriseAttachment(path)
352 assert bool(obj.notify(body="test", attach=attach)) is False
353
354 # Test our call count
355 assert mock_post.call_count == 0
356
357 # prepare our attachment
358 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
359
360 # Prepare a bad response
361 bad_response = mock.Mock()
362 bad_response.content = dumps(
363 {
364 "file_name": "cat.jpg",
365 "file_type": "image/jpeg",
366 "file_url": "https://dl.pushb.com/abc/cat.jpg",
367 "upload_url": "https://upload.pushbullet.com/abcd123",
368 }
369 ).encode("utf-8")
370 bad_response.status_code = requests.codes.internal_server_error
371 bad_response.headers = {}
372
373 # Prepare a bad response
374 bad_json_response = mock.Mock()
375 bad_json_response.content = b"}"
376 bad_json_response.status_code = requests.codes.ok
377 bad_json_response.headers = {}
378
379 # Throw an exception on the first call to requests.post()
380 for side_effect in (
381 requests.RequestException(),
382 OSError(),
383 [bad_response],
384 ):
385 mock_post.reset_mock()
386 mock_post.side_effect = side_effect
387
388 # We'll fail now because of our error handling
389 assert obj.send(body="test", attach=attach) is False
390
391 # Throw an exception on the second call to requests.post()
392 for side_effect in (requests.RequestException(), OSError(), bad_response):
393 mock_post.reset_mock()
394 mock_post.side_effect = [response, side_effect]
395
396 # We'll fail now because of our error handling
397 assert obj.send(body="test", attach=attach) is False
398
399 # Throw an exception on the third call to requests.post()
400 for side_effect in (requests.RequestException(), OSError(), bad_response):
401 mock_post.reset_mock()
402 mock_post.side_effect = [response, response, side_effect]
403
404 # We'll fail now because of our error handling
405 assert obj.send(body="test", attach=attach) is False
406
407 # Throw an exception on the forth call to requests.post()
408 for side_effect in (requests.RequestException(), OSError(), bad_response):
409 mock_post.reset_mock()
410 mock_post.side_effect = [response, response, response, side_effect]
411
412 # We'll fail now because of our error handling
413 assert obj.send(body="test", attach=attach) is False
414
415 # Test case where we don't get a valid response back
416 mock_post.side_effect = None
417 mock_post.return_value = bad_json_response
418
419 # We'll fail because of an invalid json object
420 assert obj.send(body="test", attach=attach) is False
421
422
423 @mock.patch("requests.get")
424 @mock.patch("requests.post")
425 def test_plugin_pushbullet_edge_cases(mock_post, mock_get):
426 """NotifyPushBullet() Edge Cases."""
427
428 # Initialize some generic (but valid) tokens
429 accesstoken = "a" * 32
430
431 # Support strings
432 recipients = "#chan1,#chan2,device,[email protected],,,"
433
434 # Prepare Mock
435 mock_get.return_value = requests.Request()
436 mock_post.return_value = requests.Request()
437 mock_post.content = b""
438 mock_post.return_value.status_code = requests.codes.ok
439 mock_get.return_value.status_code = requests.codes.ok
440 mock_get.content = b""
441
442 # Invalid Access Token
443 with pytest.raises(AppriseImproperlyConfigured):
444 NotifyPushBullet(accesstoken=None)
445 with pytest.raises(AppriseImproperlyConfigured):
446 NotifyPushBullet(accesstoken=" ")
447
448 obj = NotifyPushBullet(accesstoken=accesstoken, targets=recipients)
449 assert isinstance(obj, NotifyPushBullet) is True
450 assert len(obj.targets) == 4
451
452 obj = NotifyPushBullet(accesstoken=accesstoken)
453 assert isinstance(obj, NotifyPushBullet) is True
454 # Default is to send to all devices, so there will be a
455 # recipient here
456 assert len(obj.targets) == 1
457
458 obj = NotifyPushBullet(accesstoken=accesstoken, targets=set())
459 assert isinstance(obj, NotifyPushBullet) is True
460 # Default is to send to all devices, so there will be a
461 # recipient here
462 assert len(obj.targets) == 1