Debian Codegraph @

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