Debian Codegraph @

tests/test_plugin_jira.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2025, 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 import apprise
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.jira import JiraPriority, NotifyJira, NotifyType
41
42 logging.disable(logging.CRITICAL)
43
44 # a test UUID we can use
45 UUID4 = "8b799edf-6f98-4d3a-9be7-2862fb4e5752"
46
47 JIRA_GOOD_RESPONSE = dumps(
48 {
49 "result": "Request will be processed",
50 "took": 0.204,
51 "requestId": "43a29c5c-3dbf-4fa4-9c26-f4f71023e120",
52 }
53 )
54
55 # Our Testing URLs
56 apprise_url_tests = (
57 (
58 "jira://",
59 {
60 # We failed to identify any valid authentication
61 "instance": AppriseImproperlyConfigured,
62 },
63 ),
64 (
65 "jira://:@/",
66 {
67 # We failed to identify any valid authentication
68 "instance": AppriseImproperlyConfigured,
69 },
70 ),
71 (
72 "jira://%20%20/",
73 {
74 # invalid apikey specified
75 "instance": AppriseImproperlyConfigured,
76 },
77 ),
78 (
79 "jira://apikey/user/?region=xx",
80 {
81 # invalid region id
82 "instance": AppriseImproperlyConfigured,
83 },
84 ),
85 (
86 "jira://user@apikey/",
87 {
88 # No targets specified; this is allowed
89 "instance": NotifyJira,
90 "notify_type": NotifyType.WARNING,
91 # Bad response returned
92 "requests_response_text": "{",
93 # We will not be successful sending the notice
94 "notify_response": False,
95 },
96 ),
97 (
98 "jira://apikey/",
99 {
100 # No targets specified; this is allowed
101 "instance": NotifyJira,
102 "notify_type": NotifyType.FAILURE,
103 # Our response expected server response
104 "requests_response_text": JIRA_GOOD_RESPONSE,
105 },
106 ),
107 (
108 "jira://apikey/user",
109 {
110 # Valid user
111 "instance": NotifyJira,
112 "notify_type": NotifyType.FAILURE,
113 # Our response expected server response
114 "requests_response_text": JIRA_GOOD_RESPONSE,
115 "privacy_url": "jira://a...y/%40user",
116 },
117 ),
118 (
119 "jira://apikey/@user?region=eu",
120 {
121 # European Region
122 "instance": NotifyJira,
123 "notify_type": NotifyType.FAILURE,
124 # Our response expected server response
125 "requests_response_text": JIRA_GOOD_RESPONSE,
126 },
127 ),
128 (
129 "jira://apikey/@user?entity=A%20Entity",
130 {
131 # Assign an entity
132 "instance": NotifyJira,
133 "notify_type": NotifyType.FAILURE,
134 # Our response expected server response
135 "requests_response_text": JIRA_GOOD_RESPONSE,
136 },
137 ),
138 (
139 "jira://apikey/@user?alias=An%20Alias",
140 {
141 # Assign an alias
142 "instance": NotifyJira,
143 "notify_type": NotifyType.FAILURE,
144 # Our response expected server response
145 "requests_response_text": JIRA_GOOD_RESPONSE,
146 },
147 ),
148 # Bad Action
149 (
150 "jira://apikey/@user?action=invalid",
151 {
152 # Assign an entity
153 "instance": AppriseImproperlyConfigured,
154 },
155 ),
156 (
157 "jira://from@apikey/@user?:invalid=note",
158 {
159 # Assign an entity
160 "instance": AppriseImproperlyConfigured,
161 },
162 ),
163 (
164 "jira://apikey/@user?:warning=invalid",
165 {
166 # Assign an entity
167 "instance": AppriseImproperlyConfigured,
168 },
169 ),
170 # Creates an index entry
171 (
172 "jira://apikey/@user?entity=index&action=new",
173 {
174 # Assign an entity
175 "instance": NotifyJira,
176 "notify_type": NotifyType.FAILURE,
177 # Our response expected server response
178 "requests_response_text": JIRA_GOOD_RESPONSE,
179 },
180 ),
181 # Now action it
182 (
183 "jira://apikey/@user?entity=index&action=acknowledge",
184 {
185 # Assign an entity
186 "instance": NotifyJira,
187 "notify_type": NotifyType.SUCCESS,
188 # Our response expected server response
189 "requests_response_text": JIRA_GOOD_RESPONSE,
190 },
191 ),
192 (
193 "jira://from@apikey/@user?entity=index&action=note",
194 {
195 # Assign an entity
196 "instance": NotifyJira,
197 "notify_type": NotifyType.SUCCESS,
198 # Our response expected server response
199 "requests_response_text": JIRA_GOOD_RESPONSE,
200 },
201 ),
202 (
203 "jira://from@apikey/@user?entity=index&action=note",
204 {
205 # Assign an entity
206 "instance": NotifyJira,
207 "notify_type": NotifyType.SUCCESS,
208 # Our response expected server response
209 "requests_response_text": JIRA_GOOD_RESPONSE,
210 "response": False,
211 "requests_response_code": 500,
212 },
213 ),
214 (
215 "jira://apikey/@user?entity=index&action=close",
216 {
217 # Assign an entity
218 "instance": NotifyJira,
219 "notify_type": NotifyType.SUCCESS,
220 # Our response expected server response
221 "requests_response_text": JIRA_GOOD_RESPONSE,
222 },
223 ),
224 (
225 "jira://apikey/@user?entity=index&action=delete",
226 {
227 # Assign an entity
228 "instance": NotifyJira,
229 "notify_type": NotifyType.SUCCESS,
230 # Our response expected server response
231 "requests_response_text": JIRA_GOOD_RESPONSE,
232 },
233 ),
234 # map info messages to generate a new message
235 (
236 "jira://apikey/@user?entity=index2&:info=new",
237 {
238 # Assign an entity
239 "instance": NotifyJira,
240 "notify_type": NotifyType.INFO,
241 # Our response expected server response
242 "requests_response_text": JIRA_GOOD_RESPONSE,
243 },
244 ),
245 (
246 "jira://joe@apikey/@user?priority=p3",
247 {
248 # Assign our priority
249 "instance": NotifyJira,
250 "notify_type": NotifyType.FAILURE,
251 # Our response expected server response
252 "requests_response_text": JIRA_GOOD_RESPONSE,
253 },
254 ),
255 (
256 "jira://apikey/?tags=comma,separated",
257 {
258 # Test our our 'tags' (tag is reserved in Apprise) but not 'tags'
259 # Also test the fact we do not need to define a target
260 "instance": NotifyJira,
261 "notify_type": NotifyType.FAILURE,
262 # Our response expected server response
263 "requests_response_text": JIRA_GOOD_RESPONSE,
264 },
265 ),
266 (
267 "jira://apikey/@user?priority=invalid",
268 {
269 # Invalid priority (loads using default)
270 "instance": NotifyJira,
271 "notify_type": NotifyType.FAILURE,
272 # Our response expected server response
273 "requests_response_text": JIRA_GOOD_RESPONSE,
274 },
275 ),
276 (
277 "jira://apikey/[email protected]/#team/*sche/^esc/%20/a",
278 {
279 # Valid user (email), valid schedule, Escalated ID,
280 # an invalid entry (%20), and too short of an entry (a)
281 "instance": NotifyJira,
282 "notify_type": NotifyType.FAILURE,
283 # Our response expected server response
284 "requests_response_text": JIRA_GOOD_RESPONSE,
285 },
286 ),
287 (
288 "jira://apikey/@{}/#{}/*{}/^{}/".format(UUID4, UUID4, UUID4, UUID4),
289 {
290 # similar to the above, except we use the UUID's
291 "instance": NotifyJira,
292 "notify_type": NotifyType.FAILURE,
293 # Our response expected server response
294 "requests_response_text": JIRA_GOOD_RESPONSE,
295 },
296 ),
297 # Same link as before but @ missing at the front causing an ambigious
298 # lookup however the entry is treated a though a @ was in front (user)
299 (
300 "jira://apikey/{}/#{}/*{}/^{}/".format(UUID4, UUID4, UUID4, UUID4),
301 {
302 # similar to the above, except we use the UUID's
303 "instance": NotifyJira,
304 "notify_type": NotifyType.FAILURE,
305 # Our response expected server response
306 "requests_response_text": JIRA_GOOD_RESPONSE,
307 },
308 ),
309 (
310 "jira://apikey?to=#team,user&+key=value&+type=override",
311 {
312 # Test to= and details (key/value pair) also override 'type'
313 "instance": NotifyJira,
314 "notify_type": NotifyType.FAILURE,
315 # Our response expected server response
316 "requests_response_text": JIRA_GOOD_RESPONSE,
317 },
318 ),
319 (
320 "jira://apikey/#team/@user/?batch=yes",
321 {
322 # Test batch=
323 "instance": NotifyJira,
324 "notify_type": NotifyType.FAILURE,
325 # Our response expected server response
326 "requests_response_text": JIRA_GOOD_RESPONSE,
327 },
328 ),
329 (
330 "jira://apikey/#team/@user/?batch=no",
331 {
332 # Test batch=
333 "instance": NotifyJira,
334 "notify_type": NotifyType.FAILURE,
335 # Our response expected server response
336 "requests_response_text": JIRA_GOOD_RESPONSE,
337 },
338 ),
339 (
340 "jira://?apikey=abc&to=user",
341 {
342 # Test Kwargs
343 "instance": NotifyJira,
344 "notify_type": NotifyType.FAILURE,
345 # Our response expected server response
346 "requests_response_text": JIRA_GOOD_RESPONSE,
347 },
348 ),
349 (
350 "jira://apikey/#team/user/",
351 {
352 "instance": NotifyJira,
353 # throw a bizzare code forcing us to fail to look it up
354 "notify_type": NotifyType.FAILURE,
355 # Our response expected server response
356 "requests_response_text": JIRA_GOOD_RESPONSE,
357 "response": False,
358 "requests_response_code": 999,
359 },
360 ),
361 (
362 "jira://apikey/#topic1/device/",
363 {
364 "instance": NotifyJira,
365 "notify_type": NotifyType.FAILURE,
366 # Our response expected server response
367 "requests_response_text": JIRA_GOOD_RESPONSE,
368 # Throws a series of connection and transfer exceptions when this
369 # flag is set and tests that we gracfully handle them
370 "test_requests_exceptions": True,
371 },
372 ),
373 )
374
375
376 def test_plugin_jira_urls(tmpdir):
377 """
378 NotifyJira() Apprise URLs
379
380 """
381
382 # Run our general tests
383 AppriseURLTester(tests=apprise_url_tests).run_all(str(tmpdir))
384
385
386 @mock.patch("requests.post")
387 def test_plugin_jira_config_files(mock_post):
388 """
389 NotifyJira() Config File Cases
390 """
391 content = """
392 urls:
393 - jira://apikey/user:
394 - priority: 1
395 tag: jira_int low
396 - priority: "1"
397 tag: jira_str_int low
398 - priority: "p1"
399 tag: jira_pstr_int low
400 - priority: low
401 tag: jira_str low
402
403 # This will take on moderate (default) priority
404 - priority: invalid
405 tag: jira_invalid
406
407 - jira://apikey2/user2:
408 - priority: 5
409 tag: jira_int emerg
410 - priority: "5"
411 tag: jira_str_int emerg
412 - priority: "p5"
413 tag: jira_pstr_int emerg
414 - priority: emergency
415 tag: jira_str emerg
416 """
417
418 # Prepare Mock
419 mock_post.return_value = requests.Request()
420 mock_post.return_value.status_code = requests.codes.ok
421 mock_post.return_value.content = JIRA_GOOD_RESPONSE
422
423 # Create ourselves a config object
424 ac = apprise.AppriseConfig()
425 assert ac.add_config(content=content) is True
426
427 aobj = apprise.Apprise()
428
429 # Add our configuration
430 aobj.add(ac)
431
432 # We should be able to read our 9 services from that
433 # 4x low
434 # 4x emerg
435 # 1x invalid (so takes on normal priority)
436 assert len(ac.services()) == 9
437 assert len(aobj) == 9
438 assert len(list(aobj.find(tag="low"))) == 4
439 for s in aobj.find(tag="low"):
440 assert s.priority == JiraPriority.LOW
441
442 assert len(list(aobj.find(tag="emerg"))) == 4
443 for s in aobj.find(tag="emerg"):
444 assert s.priority == JiraPriority.EMERGENCY
445
446 assert len(list(aobj.find(tag="jira_str"))) == 2
447 assert len(list(aobj.find(tag="jira_str_int"))) == 2
448 assert len(list(aobj.find(tag="jira_pstr_int"))) == 2
449 assert len(list(aobj.find(tag="jira_int"))) == 2
450
451 assert len(list(aobj.find(tag="jira_invalid"))) == 1
452 assert next(aobj.find(tag="jira_invalid")).priority == JiraPriority.NORMAL
453
454
455 @mock.patch("requests.post")
456 def test_plugin_jira_edge_case(mock_post):
457 """
458 NotifyJira() Edge Cases
459 """
460 # Prepare Mock
461 mock_post.return_value = requests.Request()
462 mock_post.return_value.status_code = requests.codes.ok
463 mock_post.return_value.content = JIRA_GOOD_RESPONSE
464
465 instance = apprise.Apprise.instantiate("jira://apikey")
466 assert isinstance(instance, NotifyJira)
467
468 assert len(instance.store.keys()) == 0
469 assert bool(instance.notify("test", "key", NotifyType.FAILURE)) is True
470 assert len(instance.store.keys()) == 1
471
472 # Again just causes same index to get over-written
473 assert bool(instance.notify("test", "key", NotifyType.FAILURE)) is True
474 assert len(instance.store.keys()) == 1
475 assert "a62f2225bf" in instance.store
476
477 # Assign it garbage
478 instance.store["a62f2225bf"] = "garbage"
479 # This causes an internal check to fail where the keys are expected to be
480 # as a list (this one is now a string)
481 # content self corrects and things are fine
482 assert bool(instance.notify("test", "key", NotifyType.FAILURE)) is True
483 assert len(instance.store.keys()) == 1
484
485 # new key is new index
486 assert bool(instance.notify("test", "key2", NotifyType.FAILURE)) is True
487 assert len(instance.store.keys()) == 2
488
489
490 @mock.patch("requests.post")
491 def test_plugin_jira_mapping(mock_post):
492 """
493 NotifyJira() Action Mapping
494
495 Verify that custom :key=value URL mappings correctly override the default
496 action taken for each notification type, and that self.mapping (not the
497 removed module-level constant) is used in send().
498 """
499 # Prepare Mock
500 mock_post.return_value = requests.Request()
501 mock_post.return_value.status_code = requests.codes.ok
502 mock_post.return_value.content = JIRA_GOOD_RESPONSE
503
504 base_url = "https://api.atlassian.com/jsm/ops/integration/v2/alerts"
505
506 # --- Default mapping: INFO → NOTE ---
507 # INFO adds a note to an existing alert; with no stored request IDs there
508 # is nothing to annotate, so no HTTP call is made. send() still returns
509 # True (nothing to do is not an error).
510 instance = apprise.Apprise.instantiate("jira://apikey/@user")
511 assert isinstance(instance, NotifyJira)
512
513 assert bool(instance.notify("body", "title", NotifyType.INFO)) is True
514 assert mock_post.call_count == 0
515
516 # --- Default mapping: WARNING/FAILURE → NEW ---
517 # These should POST to the base alerts URL immediately.
518 mock_post.reset_mock()
519 assert bool(instance.notify("body", "title", NotifyType.WARNING)) is True
520 assert mock_post.call_count == 1
521 assert mock_post.call_args[0][0] == base_url
522
523 mock_post.reset_mock()
524 assert bool(instance.notify("body", "title", NotifyType.FAILURE)) is True
525 assert mock_post.call_count == 1
526 assert mock_post.call_args[0][0] == base_url
527
528 # --- Default mapping: SUCCESS → CLOSE ---
529 # instance already has stored request IDs from the WARNING/FAILURE calls
530 # above, so SUCCESS should POST to the /close endpoint.
531 mock_post.reset_mock()
532 assert bool(instance.notify("body", "title", NotifyType.SUCCESS)) is True
533 assert mock_post.call_count >= 1
534 assert mock_post.call_args[0][0].endswith("/close")
535
536 # Fresh instance: SUCCESS with no stored IDs → nothing to close, no call.
537 fresh = apprise.Apprise.instantiate("jira://apikey/@user")
538 mock_post.reset_mock()
539 assert bool(fresh.notify("body", "title", NotifyType.SUCCESS)) is True
540 assert mock_post.call_count == 0
541
542 # --- Custom mapping: :info=new overrides INFO → NOTE with INFO → NEW ---
543 instance2 = apprise.Apprise.instantiate("jira://apikey/@user?:info=new")
544 assert isinstance(instance2, NotifyJira)
545
546 mock_post.reset_mock()
547 assert bool(instance2.notify("body", "title", NotifyType.INFO)) is True
548 # A POST to the base alerts URL must have been made
549 assert mock_post.call_count == 1
550 assert mock_post.call_args[0][0] == base_url
551
552 # --- URL round-trip preserves custom mapping ---
553 # The colon prefix is kept unencoded for readability.
554 url = instance2.url()
555 assert ":info=new" in url
556
557 # Re-instantiate from the reconstructed URL and verify the mapping
558 instance3 = apprise.Apprise.instantiate(url)
559 assert isinstance(instance3, NotifyJira)
560 assert instance3.mapping[NotifyType.INFO] == "new"
561
562 mock_post.reset_mock()
563 assert bool(instance3.notify("body", "title", NotifyType.INFO)) is True
564 assert mock_post.call_count == 1
565 assert mock_post.call_args[0][0] == base_url
566
567
568 def test_plugin_jira_non_string_region():
569 """Verify a region that isn't a string is rejected cleanly."""
570
571 # Reject non-string regions with the plugin's configuration error.
572 for region in (42, 4.2, True, b"us", ["us"], {"region": "us"}, object()):
573 with pytest.raises(AppriseImproperlyConfigured):
574 NotifyJira(apikey="a" * 32, targets=["user"], region_name=region)