Debian Codegraph @

tests/test_plugin_twilio.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 json import dumps
29
30 # Disable logging for a cleaner testing output
31 import logging
32 from unittest import mock
33
34 from helpers import AppriseURLTester
35 import pytest
36 import requests
37
38 from apprise import Apprise
39 from apprise.plugins.twilio import NotifyTwilio, TwilioNotificationMethod
40
41 logging.disable(logging.CRITICAL)
42
43 # Our Testing URLs
44 apprise_url_tests = (
45 (
46 "twilio://",
47 {
48 # No Account SID specified
49 "instance": TypeError,
50 },
51 ),
52 (
53 "twilio://:@/",
54 {
55 # invalid Auth token
56 "instance": TypeError,
57 },
58 ),
59 (
60 "twilio://AC{}@12345678".format("a" * 32),
61 {
62 # Just sid provided
63 "instance": TypeError,
64 },
65 ),
66 (
67 "twilio://AC{}:{}@_".format("a" * 32, "b" * 32),
68 {
69 # sid and token provided but invalid from
70 "instance": TypeError,
71 },
72 ),
73 (
74 "twilio://AC{}:{}@{}".format("a" * 32, "b" * 32, "3" * 5),
75 {
76 # using short-code (5 characters) without a target
77 # We can still instantiate ourselves with a valid short code
78 "instance": NotifyTwilio,
79 # Since there are no targets specified we expect a False return on
80 # send()
81 "notify_response": False,
82 },
83 ),
84 (
85 "twilio://AC{}:{}@{}".format("a" * 32, "b" * 32, "3" * 9),
86 {
87 # sid and token provided and from but invalid from no
88 "instance": TypeError,
89 },
90 ),
91 (
92 "twilio://AC{}:{}@{}/123/{}/abcd/w:{}".format(
93 "a" * 32, "b" * 32, "3" * 11, "9" * 15, 8 * 11
94 ),
95 {
96 # valid everything but target numbers
97 "instance": NotifyTwilio,
98 },
99 ),
100 (
101 "twilio://AC{}:{}@12345/{}".format("a" * 32, "b" * 32, "4" * 11),
102 {
103 # using short-code (5 characters)
104 "instance": NotifyTwilio,
105 # Our expected url(privacy=True) startswith() response:
106 "privacy_url": "twilio://...aaaa:b...b@12345",
107 },
108 ),
109 (
110 "twilio://AC{}:{}@98765/{}/w:{}/".format(
111 "a" * 32, "b" * 32, "4" * 11, "5" * 11
112 ),
113 {
114 # using short-code (5 characters) and 1 twillio address ignored
115 # because source phone number can not be a short code
116 "instance": NotifyTwilio,
117 # Our expected url(privacy=True) startswith() response:
118 "privacy_url": "twilio://...aaaa:b...b@98765",
119 },
120 ),
121 (
122 "twilio://AC{}:{}@w:12345/{}/{}".format(
123 "a" * 32, "b" * 32, "4" * 11, "5" * 11
124 ),
125 {
126 # Invalid short-code
127 "instance": TypeError,
128 },
129 ),
130 (
131 "twilio://AC{}:{}@123456/{}".format("a" * 32, "b" * 32, "4" * 11),
132 {
133 # using short-code (6 characters)
134 "instance": NotifyTwilio,
135 },
136 ),
137 (
138 "twilio://AC{}:{}@{}".format("a" * 32, "b" * 32, "5" * 11),
139 {
140 # using phone no with no target - we text ourselves in
141 # this case
142 "instance": NotifyTwilio,
143 },
144 ),
145 (
146 "twilio://AC{}:{}@{}?method=sms".format("a" * 32, "b" * 32, "5" * 11),
147 {
148 # Specify explicitly notification method sms
149 "instance": NotifyTwilio,
150 },
151 ),
152 (
153 "twilio://AC{}:{}@{}?method=mms".format("a" * 32, "b" * 32, "5" * 11),
154 {
155 # Invalid notification method
156 "instance": TypeError,
157 },
158 ),
159 (
160 "twilio://AC{}:{}@{}?method=call".format(
161 "a" * 32, "b" * 32, "w:" + "5" * 11
162 ),
163 {
164 # Incompatibility between Whatsapp mode and CALL method
165 "instance": TypeError,
166 },
167 ),
168 (
169 "twilio://_?sid=AC{}&token={}&from={}".format(
170 "a" * 32, "b" * 32, "5" * 11
171 ),
172 {
173 # use get args to acomplish the same thing
174 "instance": NotifyTwilio,
175 },
176 ),
177 (
178 "twilio://_?sid=AC{}&token={}&from={}&to=w:{}".format(
179 "a" * 32, "b" * 32, "5" * 11, "6" * 11
180 ),
181 {
182 # Support whatsapp (w: before number)
183 "instance": NotifyTwilio,
184 },
185 ),
186 (
187 "twilio://_?sid=AC{}&token={}&source={}".format(
188 "a" * 32, "b" * 32, "5" * 11
189 ),
190 {
191 # use get args to acomplish the same thing (use source instead of
192 # from)
193 "instance": NotifyTwilio,
194 },
195 ),
196 (
197 "twilio://_?sid=AC{}&token={}&from={}&to={}".format(
198 "a" * 32, "b" * 32, "5" * 11, "7" * 13
199 ),
200 {
201 # use to=
202 "instance": NotifyTwilio,
203 },
204 ),
205 (
206 "twilio://_?sid=AC{}&token={}&from={}&to={}method=call".format(
207 "a" * 32, "b" * 32, "5" * 11, "7" * 13
208 ),
209 {
210 # Specify notification method call
211 "instance": NotifyTwilio,
212 },
213 ),
214 (
215 "twilio://AC{}:{}@{}".format("a" * 32, "b" * 32, "6" * 11),
216 {
217 "instance": NotifyTwilio,
218 # throw a bizarre code forcing us to fail to look it up
219 "response": False,
220 "requests_response_code": 999,
221 },
222 ),
223 (
224 "twilio://AC{}:{}@{}".format("a" * 32, "b" * 32, "6" * 11),
225 {
226 "instance": NotifyTwilio,
227 # Throws a series of i/o exceptions with this flag
228 # is set and tests that we gracefully handle them
229 "test_requests_exceptions": True,
230 },
231 ),
232 )
233
234
235 def test_plugin_twilio_urls():
236 """NotifyTwilio() Apprise URLs."""
237
238 # Run our general tests
239 AppriseURLTester(tests=apprise_url_tests).run_all()
240
241
242 @mock.patch("requests.post")
243 def test_plugin_twilio_auth(mock_post):
244 """NotifyTwilio() Auth.
245
246 - account-wide auth token
247 - API key and its own auth token
248 """
249
250 response = mock.Mock()
251 response.content = ""
252 response.status_code = requests.codes.ok
253
254 # Prepare Mock
255 mock_post.return_value = response
256
257 # Initialize some generic (but valid) tokens
258 account_sid = "AC{}".format("b" * 32)
259 apikey = "SK{}".format("b" * 32)
260 auth_token = "{}".format("b" * 32)
261 source = "+1 (555) 123-3456"
262 dest = "+1 (555) 987-6543"
263 message_contents = "test"
264
265 # Variation of initialization without API key
266 obj = Apprise.instantiate(
267 f"twilio://{account_sid}:{auth_token}@{source}/{dest}"
268 )
269 assert isinstance(obj, NotifyTwilio)
270 assert isinstance(obj.url(), str)
271
272 # Send Notification
273 assert obj.send(body=message_contents) is True
274
275 # Variation of initialization with API key
276 obj = Apprise.instantiate(
277 f"twilio://{account_sid}:{auth_token}@{source}/{dest}?apikey={apikey}"
278 )
279 assert isinstance(obj, NotifyTwilio)
280 assert isinstance(obj.url(), str)
281
282 # Send Notification
283 assert obj.send(body=message_contents) is True
284
285 # Variation of initialization with method call
286 obj = Apprise.instantiate(
287 f"twilio://{account_sid}:{auth_token}@{source}/{dest}?method=call"
288 )
289 assert isinstance(obj, NotifyTwilio)
290 assert isinstance(obj.url(), str)
291
292 # Send Notification
293 assert obj.send(body=message_contents) is True
294
295 # Validate expected call parameters
296 assert mock_post.call_count == 3
297 first_call = mock_post.call_args_list[0]
298 second_call = mock_post.call_args_list[1]
299 third_call = mock_post.call_args_list[2]
300
301 # URL and message parameters are the same for both calls
302 assert (
303 first_call[0][0]
304 == second_call[0][0]
305 == (
306 "https://api.twilio.com/2010-04-01/Accounts"
307 f"/{account_sid}/Messages.json"
308 )
309 )
310 assert (
311 first_call[1]["data"]["Body"]
312 == second_call[1]["data"]["Body"]
313 == message_contents
314 )
315 assert third_call[0][0] == (
316 f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Calls.json"
317 )
318 assert third_call[1]["data"]["Twiml"] == message_contents
319 assert (
320 first_call[1]["data"]["From"]
321 == second_call[1]["data"]["From"]
322 == third_call[1]["data"]["From"]
323 == "+15551233456"
324 )
325 assert (
326 first_call[1]["data"]["To"]
327 == second_call[1]["data"]["To"]
328 == third_call[1]["data"]["To"]
329 == "+15559876543"
330 )
331
332 # Auth differs depending on if API Key is used
333 assert first_call[1]["auth"] == (account_sid, auth_token)
334 assert second_call[1]["auth"] == (apikey, auth_token)
335 assert third_call[1]["auth"] == (account_sid, auth_token)
336
337
338 @mock.patch("requests.post")
339 def test_plugin_twilio_edge_cases(mock_post):
340 """NotifyTwilio() Edge Cases."""
341
342 # Prepare our response
343 response = requests.Request()
344 response.status_code = requests.codes.ok
345
346 # Prepare Mock
347 mock_post.return_value = response
348
349 # Initialize some generic (but valid) tokens
350 account_sid = "AC{}".format("b" * 32)
351 auth_token = "{}".format("b" * 32)
352 source = "+1 (555) 123-3456"
353 whatsapp_source = "w:" + "+1 (555) 123-3456"
354
355 # No account_sid specified
356 with pytest.raises(TypeError):
357 NotifyTwilio(account_sid=None, auth_token=auth_token, source=source)
358
359 # No auth_token specified
360 with pytest.raises(TypeError):
361 NotifyTwilio(account_sid=account_sid, auth_token=None, source=source)
362
363 # Source is bad
364 with pytest.raises(TypeError):
365 NotifyTwilio(account_sid=account_sid, auth_token=auth_token, source="")
366
367 # Incompatibility between mode and method
368 with pytest.raises(TypeError):
369 NotifyTwilio(
370 account_sid=account_sid,
371 auth_token=auth_token,
372 source=whatsapp_source,
373 method=TwilioNotificationMethod.CALL,
374 )
375
376 # a error response
377 response.status_code = 400
378 response.content = dumps(
379 {
380 "code": 21211,
381 "message": "The 'To' number +1234567 is not a valid phone number.",
382 }
383 )
384 mock_post.return_value = response
385
386 # Initialize our object
387 obj = NotifyTwilio(
388 account_sid=account_sid, auth_token=auth_token, source=source
389 )
390
391 # We will fail with the above error code
392 assert obj.notify("title", "body", "info") is False