Debian Codegraph @

ansible_collections/splunk/es/tests/unit/plugins/action/test_es_finding.py

raw
1 # Copyright 2026 Red Hat Inc.
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 #
18
19 """
20 Unit tests for the splunk_finding action plugin.
21
22 These tests verify that the splunk_finding action plugin works correctly for:
23 - Creating new findings (without ref_id)
24 - Updating existing findings (with ref_id)
25 - Idempotency (no changes when state matches)
26 - Error handling (missing parameters, finding not found)
27 - Check mode behavior
28
29 The tests use mocking to simulate Splunk API responses without requiring
30 a real Splunk server connection.
31 """
32
33
34 import copy
35 import tempfile
36
37 from unittest.mock import MagicMock, patch
38
39 from ansible.playbook.task import Task
40 from ansible.template import Templar
41
42 from ansible_collections.splunk.es.plugins.action.splunk_finding import ActionModule
43 from ansible_collections.splunk.es.plugins.module_utils.splunk import SplunkRequest
44
45
46 # Test data: API Response Payloads
47 # These represent what the Splunk API returns for findings.
48 FINDING_API_RESPONSE = {
49 "finding_id": "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865",
50 "rule_title": "Suspicious Login Activity",
51 "rule_description": "Multiple failed login attempts detected",
52 "security_domain": "access",
53 "risk_object": "testuser",
54 "risk_object_type": "user",
55 "risk_score": "50.0",
56 "owner": "admin",
57 "status": "1", # "new" in API format
58 "urgency": "high",
59 "disposition": "disposition:6", # "undetermined" in API format
60 }
61
62 FINDING_API_RESPONSE_UPDATED = {
63 "finding_id": "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865",
64 "rule_title": "Suspicious Login Activity",
65 "rule_description": "Multiple failed login attempts detected",
66 "security_domain": "access",
67 "risk_object": "testuser",
68 "risk_object_type": "user",
69 "risk_score": "50.0",
70 "owner": "analyst",
71 "status": "4", # "resolved" in API format
72 "urgency": "high",
73 "disposition": "disposition:1", # "true_positive" in API format
74 }
75
76
77 # Test data: Module Request Payloads
78 # These represent what users provide to the Ansible module. Note the
79 # human-readable field names and values.
80
81 CREATE_FINDING_PARAMS = {
82 "title": "Suspicious Login Activity",
83 "description": "Multiple failed login attempts detected",
84 "security_domain": "access",
85 "entity": "testuser",
86 "entity_type": "user",
87 "finding_score": 50,
88 "owner": "admin",
89 "status": "new",
90 "urgency": "high",
91 "disposition": "undetermined",
92 }
93
94 UPDATE_FINDING_PARAMS = {
95 "ref_id": "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865",
96 "owner": "analyst",
97 "status": "resolved",
98 "disposition": "true_positive",
99 }
100
101 MINIMAL_CREATE_PARAMS = {
102 "title": "Minimal Finding",
103 "description": "A minimal finding for testing",
104 "security_domain": "network",
105 "entity": "firewall01",
106 "entity_type": "system",
107 "finding_score": 25,
108 }
109
110
111 class TestSplunkFinding:
112 """Test class for the splunk_finding action plugin.
113
114 Each test follows this pattern:
115 1. setup_method: Creates mock Ansible components (task, connection, play_context)
116 2. Test method: Sets task.args, mocks API methods, runs plugin, asserts results
117
118 Key concepts:
119 - monkeypatch: pytest fixture that lets us replace methods at runtime
120 - MagicMock: Creates fake objects that record how they're used
121 - The plugin's run() method is what Ansible calls to execute the action
122 """
123
124 def setup_method(self):
125 """Set up test fixtures before each test method.
126
127 This creates the mock Ansible environment needed to test the action plugin:
128 - task: Represents the Ansible task being executed
129 - play_context: Contains playbook execution context (like check_mode)
130 - connection: The connection to the target (mocked for unit tests)
131 - templar: Ansible's template engine
132 """
133 # Create a mock Task object
134 task = MagicMock(Task)
135 task.check_mode = False
136
137 # Create mock play context (controls check_mode behavior)
138 play_context = MagicMock()
139 play_context.check_mode = False
140
141 # Create a mock connection (we'll set socket_path in each test)
142 connection = patch(
143 "ansible_collections.splunk.es.plugins.module_utils.splunk.Connection",
144 )
145
146 # Ansible's template engine (not used much in these tests)
147 fake_loader = {}
148 templar = Templar(loader=fake_loader)
149
150 # Create the action plugin instance
151 self._plugin = ActionModule(
152 task=task,
153 connection=connection,
154 play_context=play_context,
155 loader=fake_loader,
156 templar=templar,
157 shared_loader_obj=None,
158 )
159
160 # Set required task attributes
161 self._plugin._task.action = "splunk_finding"
162 self._plugin._task.async_val = False
163
164 # Task variables (empty for most tests)
165 self._task_vars = {}
166
167 # Create Finding Tests #
168 @patch("ansible.module_utils.connection.Connection.__rpc__")
169 def test_finding_create_success(self, connection, monkeypatch):
170 """Test successful creation of a new finding.
171
172 When creating a finding (no ref_id), the module should:
173 1. Call the findings API to create the resource
174 2. Return changed=True
175 3. Include the created finding in the result
176
177 This test mocks the create_update method to return a simulated
178 API response, then verifies the plugin handles it correctly.
179 """
180 # Set up the mock connection
181 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
182 self._plugin._connection._shell = MagicMock()
183
184 # Mock the API create method to return our test response
185 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
186 return copy.deepcopy(FINDING_API_RESPONSE)
187
188 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
189
190 # Set the task arguments (what the user provides in the playbook)
191 self._plugin._task.args = CREATE_FINDING_PARAMS.copy()
192
193 # Run the plugin
194 result = self._plugin.run(task_vars=self._task_vars)
195
196 # Verify the result
197 assert result["changed"] is True
198 assert "finding" in result
199 assert result["finding"]["after"] is not None
200 assert result.get("failed") is not True
201
202 @patch("ansible.module_utils.connection.Connection.__rpc__")
203 def test_finding_create_minimal(self, connection, monkeypatch):
204 """Test creation with only required parameters.
205
206 The module requires: title, description, security_domain, entity,
207 entity_type, and finding_score for creating a new finding.
208 """
209 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
210 self._plugin._connection._shell = MagicMock()
211
212 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
213 return {
214 "finding_id": "new-finding-id@@notable@@time1234567890",
215 "rule_title": "Minimal Finding",
216 "rule_description": "A minimal finding for testing",
217 "security_domain": "network",
218 "risk_object": "firewall01",
219 "risk_object_type": "system",
220 "risk_score": "25.0",
221 }
222
223 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
224
225 self._plugin._task.args = MINIMAL_CREATE_PARAMS.copy()
226
227 result = self._plugin.run(task_vars=self._task_vars)
228
229 assert result["changed"] is True
230 assert result.get("failed") is not True
231
232 @patch("ansible.module_utils.connection.Connection.__rpc__")
233 def test_finding_create_missing_title(self, connection):
234 """Test that missing title returns an error.
235
236 Title is a required field when creating a new finding.
237 The module should fail with a clear error message.
238 """
239 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
240 self._plugin._connection._shell = MagicMock()
241
242 # Create params without title
243 params = CREATE_FINDING_PARAMS.copy()
244 del params["title"]
245
246 self._plugin._task.args = params
247
248 result = self._plugin.run(task_vars=self._task_vars)
249
250 assert result["failed"] is True
251 assert "title" in result["msg"].lower()
252
253 @patch("ansible.module_utils.connection.Connection.__rpc__")
254 def test_finding_create_missing_required_fields(self, connection):
255 """Test that missing required fields returns an error.
256
257 When creating a finding, these fields are required:
258 - title, description, security_domain, entity, entity_type, finding_score
259 """
260 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
261 self._plugin._connection._shell = MagicMock()
262
263 # Only provide title, missing other required fields
264 self._plugin._task.args = {
265 "title": "Incomplete Finding",
266 }
267
268 result = self._plugin.run(task_vars=self._task_vars)
269
270 assert result["failed"] is True
271 assert "missing" in result["msg"].lower() or "required" in result["msg"].lower()
272
273 @patch("ansible.module_utils.connection.Connection.__rpc__")
274 def test_finding_create_with_custom_fields(self, connection, monkeypatch):
275 """Test creation with custom fields.
276
277 Custom fields are passed as a list of name/value pairs and should
278 be included in the API payload.
279 """
280 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
281 self._plugin._connection._shell = MagicMock()
282
283 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
284 return copy.deepcopy(FINDING_API_RESPONSE)
285
286 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
287
288 params = CREATE_FINDING_PARAMS.copy()
289 params["fields"] = [
290 {"name": "custom_field_a", "value": "value1"},
291 {"name": "custom_field_b", "value": "value2"},
292 ]
293
294 self._plugin._task.args = params
295
296 result = self._plugin.run(task_vars=self._task_vars)
297
298 assert result["changed"] is True
299 assert result.get("failed") is not True
300
301 # Update Finding Tests #
302 @patch("ansible.module_utils.connection.Connection.__rpc__")
303 def test_finding_update_success(self, connection, monkeypatch):
304 """Test successful update of an existing finding."""
305
306 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
307 self._plugin._connection._shell = MagicMock()
308
309 # Mock get_by_path to return existing finding
310 def get_by_path(self, path, query_params=None):
311 return copy.deepcopy(FINDING_API_RESPONSE)
312
313 # Mock create_update for the update operation
314 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
315 return copy.deepcopy(FINDING_API_RESPONSE_UPDATED)
316
317 monkeypatch.setattr(SplunkRequest, "get_by_path", get_by_path)
318 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
319
320 self._plugin._task.args = UPDATE_FINDING_PARAMS.copy()
321
322 result = self._plugin.run(task_vars=self._task_vars)
323
324 assert result["changed"] is True
325 assert result.get("failed") is not True
326 assert "finding" in result
327 # Should have both before and after states
328 assert result["finding"]["before"] is not None
329 assert result["finding"]["after"] is not None
330
331 @patch("ansible.module_utils.connection.Connection.__rpc__")
332 def test_finding_update_idempotent(self, connection, monkeypatch):
333 """Test that updating with same values returns changed=False."""
334
335 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
336 self._plugin._connection._shell = MagicMock()
337
338 # Mock get_by_path to return finding that already has the desired values
339 def get_by_path(self, path, query_params=None):
340 return copy.deepcopy(FINDING_API_RESPONSE_UPDATED)
341
342 monkeypatch.setattr(SplunkRequest, "get_by_path", get_by_path)
343
344 # Request the same values that already exist
345 self._plugin._task.args = {
346 "ref_id": "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865",
347 "owner": "analyst",
348 "status": "resolved",
349 "disposition": "true_positive",
350 }
351
352 result = self._plugin.run(task_vars=self._task_vars)
353
354 # No changes should be made
355 assert result["changed"] is False
356 assert result.get("failed") is not True
357
358 @patch("ansible.module_utils.connection.Connection.__rpc__")
359 def test_finding_update_not_found(self, connection, monkeypatch):
360 """Test updating a non-existent finding returns an error.
361
362 If the specified ref_id doesn't exist, the module should fail
363 with a clear error message rather than creating a new finding.
364 """
365 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
366 self._plugin._connection._shell = MagicMock()
367
368 # Mock get_by_path to return empty (finding not found)
369 def get_by_path(self, path, query_params=None):
370 return {}
371
372 monkeypatch.setattr(SplunkRequest, "get_by_path", get_by_path)
373
374 self._plugin._task.args = {
375 "ref_id": "non-existent-id@@notable@@time1234567890",
376 "status": "resolved",
377 }
378
379 result = self._plugin.run(task_vars=self._task_vars)
380
381 assert result["failed"] is True
382 assert "not found" in result["msg"].lower()
383
384 @patch("ansible.module_utils.connection.Connection.__rpc__")
385 def test_finding_update_only_updatable_fields(self, connection, monkeypatch):
386 """Test that only updatable fields trigger changes.
387
388 When updating, only owner, status, urgency, and disposition can be
389 modified. Other fields like title and description are ignored.
390 """
391 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
392 self._plugin._connection._shell = MagicMock()
393
394 def get_by_path(self, path, query_params=None):
395 return copy.deepcopy(FINDING_API_RESPONSE)
396
397 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
398 return copy.deepcopy(FINDING_API_RESPONSE_UPDATED)
399
400 monkeypatch.setattr(SplunkRequest, "get_by_path", get_by_path)
401 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
402
403 # Include both updatable and non-updatable fields
404 self._plugin._task.args = {
405 "ref_id": "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865",
406 "title": "This should be ignored", # Not updatable
407 "description": "Also ignored", # Not updatable
408 "status": "resolved", # Updatable - should trigger change
409 }
410
411 result = self._plugin.run(task_vars=self._task_vars)
412
413 # Should still succeed with the updatable field
414 assert result["changed"] is True
415 assert result.get("failed") is not True
416
417 @patch("ansible.module_utils.connection.Connection.__rpc__")
418 def test_finding_update_no_updatable_fields(self, connection, monkeypatch):
419 """Test that providing only non-updatable fields returns an error.
420
421 If the user tries to update a finding but only provides fields that
422 cannot be updated (like title), the module should return an error.
423 """
424 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
425 self._plugin._connection._shell = MagicMock()
426
427 def get_by_path(self, path, query_params=None):
428 return copy.deepcopy(FINDING_API_RESPONSE)
429
430 monkeypatch.setattr(SplunkRequest, "get_by_path", get_by_path)
431
432 # Only provide non-updatable fields
433 self._plugin._task.args = {
434 "ref_id": "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865",
435 "title": "Cannot update this",
436 "description": "Cannot update this either",
437 }
438
439 result = self._plugin.run(task_vars=self._task_vars)
440
441 assert result["failed"] is True
442 assert "updatable" in result["msg"].lower() or "update" in result["msg"].lower()
443
444 # Check Mode Tests #
445 @patch("ansible.module_utils.connection.Connection.__rpc__")
446 def test_finding_check_mode_create(self, connection, monkeypatch):
447 """Test check mode for creating a finding.
448
449 In check mode, the module should report what would happen without
450 actually making API calls. It should return changed=True but not
451 create the finding.
452 """
453 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
454 self._plugin._connection._shell = MagicMock()
455
456 # Enable check mode
457 self._plugin._task.check_mode = True
458
459 # Track if create_update is called (it shouldn't be)
460 create_called = []
461
462 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
463 create_called.append(True)
464 return copy.deepcopy(FINDING_API_RESPONSE)
465
466 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
467
468 self._plugin._task.args = CREATE_FINDING_PARAMS.copy()
469
470 result = self._plugin.run(task_vars=self._task_vars)
471
472 # Should report changed but not actually call API
473 assert result["changed"] is True
474 assert result.get("failed") is not True
475 assert len(create_called) == 0 # API should not be called
476 assert "check mode" in result["msg"].lower()
477
478 @patch("ansible.module_utils.connection.Connection.__rpc__")
479 def test_finding_check_mode_update(self, connection, monkeypatch):
480 """Test check mode for updating a finding.
481
482 Check mode should show what would change without making the update.
483 It should fetch the existing state but not call the update API.
484 """
485 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
486 self._plugin._connection._shell = MagicMock()
487
488 # Enable check mode
489 self._plugin._task.check_mode = True
490
491 def get_by_path(self, path, query_params=None):
492 return copy.deepcopy(FINDING_API_RESPONSE)
493
494 # Track if create_update is called (it shouldn't be for the update)
495 update_called = []
496
497 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
498 update_called.append(True)
499 return copy.deepcopy(FINDING_API_RESPONSE_UPDATED)
500
501 monkeypatch.setattr(SplunkRequest, "get_by_path", get_by_path)
502 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
503
504 self._plugin._task.args = UPDATE_FINDING_PARAMS.copy()
505
506 result = self._plugin.run(task_vars=self._task_vars)
507
508 # Should report changed but not call update API
509 assert result["changed"] is True
510 assert result.get("failed") is not True
511 assert len(update_called) == 0 # Update API should not be called
512 assert "check mode" in result["msg"].lower()
513 # Should show what the after state would be
514 assert result["finding"]["after"] is not None
515
516 @patch("ansible.module_utils.connection.Connection.__rpc__")
517 def test_finding_check_mode_no_changes(self, connection, monkeypatch):
518 """Test check mode when no changes are needed.
519
520 If the current state matches the desired state, check mode should
521 report changed=False.
522 """
523 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
524 self._plugin._connection._shell = MagicMock()
525
526 # Enable check mode
527 self._plugin._task.check_mode = True
528
529 # Return finding that already matches desired state
530 def get_by_path(self, path, query_params=None):
531 return copy.deepcopy(FINDING_API_RESPONSE_UPDATED)
532
533 monkeypatch.setattr(SplunkRequest, "get_by_path", get_by_path)
534
535 self._plugin._task.args = {
536 "ref_id": "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865",
537 "owner": "analyst",
538 "status": "resolved",
539 "disposition": "true_positive",
540 }
541
542 result = self._plugin.run(task_vars=self._task_vars)
543
544 assert result["changed"] is False
545 assert result.get("failed") is not True
546
547 # Custom API Path Tests #
548 @patch("ansible.module_utils.connection.Connection.__rpc__")
549 def test_finding_custom_api_path(self, connection, monkeypatch):
550 """Test that custom API path parameters are used."""
551
552 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
553 self._plugin._connection._shell = MagicMock()
554
555 # Capture the path used in the API call
556 captured_paths = []
557
558 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
559 captured_paths.append(rest_path)
560 return copy.deepcopy(FINDING_API_RESPONSE)
561
562 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
563
564 params = CREATE_FINDING_PARAMS.copy()
565 params["api_namespace"] = "customNS"
566 params["api_user"] = "customuser"
567 params["api_app"] = "CustomApp"
568
569 self._plugin._task.args = params
570
571 result = self._plugin.run(task_vars=self._task_vars)
572
573 assert result["changed"] is True
574 # Verify the custom path was used
575 assert len(captured_paths) > 0
576 assert "customNS" in captured_paths[0]
577 assert "customuser" in captured_paths[0]
578 assert "CustomApp" in captured_paths[0]
579
580 # Edge Case Tests #
581 @patch("ansible.module_utils.connection.Connection.__rpc__")
582 def test_finding_update_single_field(self, connection, monkeypatch):
583 """Test updating just one field.
584
585 Users should be able to update a single field without specifying
586 all other fields.
587 """
588 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
589 self._plugin._connection._shell = MagicMock()
590
591 def get_by_path(self, path, query_params=None):
592 return copy.deepcopy(FINDING_API_RESPONSE)
593
594 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
595 return copy.deepcopy(FINDING_API_RESPONSE_UPDATED)
596
597 monkeypatch.setattr(SplunkRequest, "get_by_path", get_by_path)
598 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
599
600 # Only update status
601 self._plugin._task.args = {
602 "ref_id": "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865",
603 "status": "resolved",
604 }
605
606 result = self._plugin.run(task_vars=self._task_vars)
607
608 assert result["changed"] is True
609 assert result.get("failed") is not True
610
611 @patch("ansible.module_utils.connection.Connection.__rpc__")
612 def test_finding_update_urgency(self, connection, monkeypatch):
613 """Test updating urgency field."""
614 self._plugin._connection.socket_path = tempfile.NamedTemporaryFile().name
615 self._plugin._connection._shell = MagicMock()
616
617 def get_by_path(self, path, query_params=None):
618 return copy.deepcopy(FINDING_API_RESPONSE)
619
620 def create_update(self, rest_path, data=None, query_params=None, json_payload=False):
621 response = copy.deepcopy(FINDING_API_RESPONSE)
622 response["urgency"] = "critical"
623 return response
624
625 monkeypatch.setattr(SplunkRequest, "get_by_path", get_by_path)
626 monkeypatch.setattr(SplunkRequest, "create_update", create_update)
627
628 self._plugin._task.args = {
629 "ref_id": "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865",
630 "urgency": "critical",
631 }
632
633 result = self._plugin.run(task_vars=self._task_vars)
634
635 assert result["changed"] is True
636 assert result.get("failed") is not True