Debian Codegraph @

tests/test_plugin_reddit.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 datetime import datetime, timedelta, timezone
29 from json import dumps
30
31 # Disable logging for a cleaner testing output
32 import logging
33 from unittest import mock
34
35 from helpers import AppriseURLTester
36 import requests
37
38 from apprise.exception import AppriseImproperlyConfigured
39 from apprise.plugins.reddit import NotifyReddit
40
41 logging.disable(logging.CRITICAL)
42
43 # Our Testing URLs
44 apprise_url_tests = (
45 (
46 "reddit://",
47 {
48 # Missing all credentials
49 "instance": AppriseImproperlyConfigured,
50 },
51 ),
52 (
53 "reddit://:@/",
54 {
55 "instance": AppriseImproperlyConfigured,
56 },
57 ),
58 (
59 "reddit://user@app_id/app_secret/",
60 {
61 # No password
62 "instance": AppriseImproperlyConfigured,
63 },
64 ),
65 (
66 "reddit://user:password@app_id/",
67 {
68 # No app secret
69 "instance": AppriseImproperlyConfigured,
70 },
71 ),
72 (
73 "reddit://user:password@app%id/appsecret/apprise",
74 {
75 # No invalid app_id (has percent)
76 "instance": AppriseImproperlyConfigured,
77 },
78 ),
79 (
80 "reddit://user:password@app%id/app_secret/apprise",
81 {
82 # No invalid app_secret (has percent)
83 "instance": AppriseImproperlyConfigured,
84 },
85 ),
86 (
87 "reddit://user:password@app-id/app-secret/apprise?kind=invalid",
88 {
89 # An Invalid Kind
90 "instance": AppriseImproperlyConfigured,
91 },
92 ),
93 (
94 "reddit://user:password@app-id/app-secret/apprise",
95 {
96 # Login failed
97 "instance": NotifyReddit,
98 # Expected notify() response is False because internally we would
99 # have failed to login
100 "notify_response": False,
101 },
102 ),
103 (
104 "reddit://user:password@app-id/app-secret",
105 {
106 # Login successful, but there was no subreddit to notify
107 "instance": NotifyReddit,
108 "requests_response_text": {
109 "access_token": "abc123",
110 "token_type": "bearer",
111 "expires_in": 100000,
112 "scope": "*",
113 "refresh_token": "def456",
114 # The below is used in the response:
115 "json": {
116 # No errors during post
117 "errors": [],
118 },
119 },
120 # Expected notify() response is False
121 "notify_response": False,
122 },
123 ),
124 (
125 "reddit://user:password@app-id/app-secret/apprise",
126 {
127 "instance": NotifyReddit,
128 "requests_response_text": {
129 "access_token": "abc123",
130 "token_type": "bearer",
131 "expires_in": 100000,
132 "scope": "*",
133 "refresh_token": "def456",
134 # The below is used in the response:
135 "json": {
136 # Identify an error
137 "errors": [
138 ("KEY", "DESC", "INFO"),
139 ],
140 },
141 },
142 # Expected notify() response is False because the
143 # reddit server provided us errors
144 "notify_response": False,
145 },
146 ),
147 (
148 "reddit://user:password@app-id/app-secret/apprise",
149 {
150 "instance": NotifyReddit,
151 "requests_response_text": {
152 "access_token": "abc123",
153 "token_type": "bearer",
154 # Test case where 'expires_in' entry is missing
155 "scope": "*",
156 "refresh_token": "def456",
157 # The below is used in the response:
158 "json": {
159 # No errors during post
160 "errors": [],
161 },
162 },
163 # Our expected url(privacy=True) startswith() response:
164 "privacy_url": "reddit://user:****@****/****/apprise",
165 },
166 ),
167 (
168 "reddit://user:password@app-id/app-secret/apprise/subreddit2",
169 {
170 # password:login acceptable
171 "instance": NotifyReddit,
172 "requests_response_text": {
173 "access_token": "abc123",
174 "token_type": "bearer",
175 "expires_in": 100000,
176 "scope": "*",
177 "refresh_token": "def456",
178 # The below is used in the response:
179 "json": {
180 # No errors during post
181 "errors": [],
182 },
183 },
184 # Our expected url(privacy=True) startswith() response:
185 "privacy_url": "reddit://user:****@****/****/apprise/subreddit2",
186 },
187 ),
188 # Pass in some arguments to over-ride defaults
189 (
190 (
191 "reddit://user:pass@id/secret/sub/"
192 "?ad=yes&nsfw=yes&replies=no&resubmit=yes&spoiler=yes&kind=self"
193 ),
194 {
195 "instance": NotifyReddit,
196 "requests_response_text": {
197 "access_token": "abc123",
198 "token_type": "bearer",
199 "expires_in": 100000,
200 "scope": "*",
201 "refresh_token": "def456",
202 # The below is used in the response:
203 "json": {
204 # No errors during post
205 "errors": [],
206 },
207 },
208 # Our expected url(privacy=True) startswith() response:
209 "privacy_url": "reddit://user:****@****/****/sub",
210 },
211 ),
212 # Pass in more arguments
213 (
214 (
215 "reddit://"
216 "?user=l2g&pass=pass&app_secret=abc123&app_id=54321&to=sub1,sub2"
217 ),
218 {
219 "instance": NotifyReddit,
220 "requests_response_text": {
221 "access_token": "abc123",
222 "token_type": "bearer",
223 "expires_in": 100000,
224 "scope": "*",
225 "refresh_token": "def456",
226 # The below is used in the response:
227 "json": {
228 # No errors during post
229 "errors": [],
230 },
231 },
232 # Our expected url(privacy=True) startswith() response:
233 "privacy_url": "reddit://l2g:****@****/****/sub1/sub2",
234 },
235 ),
236 # More arguments ...
237 (
238 (
239 "reddit://user:pass@id/secret/sub7/sub6/sub5/"
240 "?flair_id=wonder&flair_text=not%20for%20you"
241 ),
242 {
243 "instance": NotifyReddit,
244 "requests_response_text": {
245 "access_token": "abc123",
246 "token_type": "bearer",
247 "expires_in": 100000,
248 "scope": "*",
249 "refresh_token": "def456",
250 # The below is used in the response:
251 "json": {
252 # No errors during post
253 "errors": [],
254 },
255 },
256 # Our expected url(privacy=True) startswith() response:
257 "privacy_url": "reddit://user:****@****/****/sub",
258 },
259 ),
260 (
261 "reddit://user:password@app-id/app-secret/apprise",
262 {
263 "instance": NotifyReddit,
264 # throw a bizarre code forcing us to fail to look it up
265 "response": False,
266 "requests_response_code": 999,
267 },
268 ),
269 (
270 "reddit://user:password@app-id/app-secret/apprise",
271 {
272 "instance": NotifyReddit,
273 # Throws a series of i/o exceptions with this flag
274 # is set and tests that we gracefully handle them
275 "test_requests_exceptions": True,
276 },
277 ),
278 )
279
280
281 def test_plugin_reddit_urls():
282 """NotifyReddit() Apprise URLs."""
283
284 # Run our general tests
285 AppriseURLTester(tests=apprise_url_tests).run_all()
286
287
288 @mock.patch("requests.post")
289 def test_plugin_reddit_general(mock_post):
290 """NotifyReddit() General Tests."""
291 NotifyReddit.clock_skew = timedelta(seconds=0)
292
293 # Generate a valid credentials:
294 kwargs = {
295 "app_id": "a" * 10,
296 "app_secret": "b" * 20,
297 "user": "user",
298 "password": "pasword",
299 "targets": "apprise",
300 }
301
302 # Epoch time:
303 epoch = datetime.fromtimestamp(0, timezone.utc)
304
305 good_response = mock.Mock()
306 good_response.content = dumps(
307 {
308 "access_token": "abc123",
309 "token_type": "bearer",
310 "expires_in": 100000,
311 "scope": "*",
312 "refresh_token": "def456",
313 # The below is used in the response:
314 "json": {
315 # No errors during post
316 "errors": [],
317 },
318 }
319 )
320 good_response.status_code = requests.codes.ok
321 good_response.headers = {
322 "X-RateLimit-Reset": (
323 (datetime.now(timezone.utc) - epoch).total_seconds()
324 ),
325 "X-RateLimit-Remaining": 1,
326 }
327
328 # Prepare Mock
329 mock_post.return_value = good_response
330
331 # Variation Initializations
332 obj = NotifyReddit(**kwargs)
333 assert isinstance(obj, NotifyReddit)
334 assert isinstance(obj.url(), str)
335
336 # Dynamically pick up on a link
337 assert obj.send(body="http://hostname") is True
338
339 bad_response = mock.Mock()
340 bad_response.content = ""
341 bad_response.status_code = 401
342
343 # Change our status code and try again
344 mock_post.return_value = bad_response
345 assert obj.send(body="test") is False
346 assert obj.ratelimit_remaining == 1
347
348 # Return the status
349 mock_post.return_value = good_response
350
351 # Force a case where there are no more remaining posts allowed
352 good_response.headers = {
353 "X-RateLimit-Reset": (
354 (datetime.now(timezone.utc) - epoch).total_seconds()
355 ),
356 "X-RateLimit-Remaining": 0,
357 }
358 # behind the scenes, it should cause us to update our rate limit
359 assert obj.send(body="test") is True
360 assert obj.ratelimit_remaining == 0
361
362 # This should cause us to block
363 good_response.headers = {
364 "X-RateLimit-Reset": (
365 (datetime.now(timezone.utc) - epoch).total_seconds()
366 ),
367 "X-RateLimit-Remaining": 10,
368 }
369 assert obj.send(body="test") is True
370 assert obj.ratelimit_remaining == 10
371
372 # Handle cases where we simply couldn't get this field
373 del good_response.headers["X-RateLimit-Remaining"]
374 assert obj.send(body="test") is True
375 # It remains set to the last value
376 assert obj.ratelimit_remaining == 10
377
378 # Reset our variable back to 1
379 good_response.headers = {
380 "X-RateLimit-Reset": (
381 (datetime.now(timezone.utc) - epoch).total_seconds()
382 ),
383 "X-RateLimit-Remaining": 1,
384 }
385 # Handle cases where our epoch time is wrong
386 del good_response.headers["X-RateLimit-Reset"]
387 assert obj.send(body="test") is True
388
389 # Return our object, but place it in the future forcing us to block
390 good_response.headers = {
391 "X-RateLimit-Reset": (
392 (datetime.now(timezone.utc) - epoch).total_seconds() + 1
393 ),
394 "X-RateLimit-Remaining": 0,
395 }
396
397 obj.ratelimit_remaining = 0
398 assert obj.send(body="test") is True
399
400 # Return our object, but place it in the future forcing us to block
401 good_response.headers = {
402 "X-RateLimit-Reset": (
403 (datetime.now(timezone.utc) - epoch).total_seconds() - 1
404 ),
405 "X-RateLimit-Remaining": 0,
406 }
407 assert obj.send(body="test") is True
408
409 # Return our limits to always work
410 obj.ratelimit_remaining = 1
411
412 # Invalid JSON
413 response = mock.Mock()
414 response.headers = {
415 "X-RateLimit-Reset": (
416 (datetime.now(timezone.utc) - epoch).total_seconds()
417 ),
418 "X-RateLimit-Remaining": 1,
419 }
420 response.content = "{"
421 response.status_code = requests.codes.ok
422 mock_post.return_value = response
423 obj = NotifyReddit(**kwargs)
424 assert obj.send(body="test") is False
425
426 # Return it to a parseable string but missing the entries we expect
427 response.content = "{}"
428 obj = NotifyReddit(**kwargs)
429 assert obj.send(body="test") is False
430
431 # No access token provided
432 response.content = dumps(
433 {
434 "access_token": "",
435 "json": {
436 # No errors during post
437 "errors": [],
438 },
439 }
440 )
441 obj = NotifyReddit(**kwargs)
442 assert obj.send(body="test") is False
443
444 # cause a json parsing issue now
445 response.content = None
446 obj = NotifyReddit(**kwargs)
447 assert obj.send(body="test") is False
448
449 # Reset to what we consider a good response
450 good_response.content = dumps(
451 {
452 "access_token": "abc123",
453 "token_type": "bearer",
454 "expires_in": 100000,
455 "scope": "*",
456 "refresh_token": "def456",
457 # The below is used in the response:
458 "json": {
459 # No errors during post
460 "errors": [],
461 },
462 }
463 )
464 good_response.status_code = requests.codes.ok
465 good_response.headers = {
466 "X-RateLimit-Reset": (
467 (datetime.now(timezone.utc) - epoch).total_seconds()
468 ),
469 "X-RateLimit-Remaining": 1,
470 }
471
472 # Reset our mock object
473 mock_post.reset_mock()
474
475 # Test sucessful re-authentication after failed post
476 mock_post.side_effect = [
477 good_response,
478 bad_response,
479 good_response,
480 good_response,
481 ]
482 obj = NotifyReddit(**kwargs)
483 assert obj.send(body="test") is True
484 assert mock_post.call_count == 4
485 assert (
486 mock_post.call_args_list[0][0][0]
487 == "https://www.reddit.com/api/v1/access_token"
488 )
489 assert (
490 mock_post.call_args_list[1][0][0]
491 == "https://oauth.reddit.com/api/submit"
492 )
493 assert (
494 mock_post.call_args_list[2][0][0]
495 == "https://www.reddit.com/api/v1/access_token"
496 )
497 assert (
498 mock_post.call_args_list[3][0][0]
499 == "https://oauth.reddit.com/api/submit"
500 )
501
502 # Test failed re-authentication
503 mock_post.side_effect = [good_response, bad_response, bad_response]
504 obj = NotifyReddit(**kwargs)
505 assert obj.send(body="test") is False
506
507 # Test exception handing on re-auth attempt
508 response.content = "{"
509 response.status_code = requests.codes.ok
510 mock_post.side_effect = [
511 good_response,
512 bad_response,
513 good_response,
514 response,
515 ]
516 obj = NotifyReddit(**kwargs)
517 assert obj.send(body="test") is False