-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_case_endpoint.py
More file actions
233 lines (189 loc) · 8.8 KB
/
test_case_endpoint.py
File metadata and controls
233 lines (189 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""Unit tests for CaseEndpoint class."""
import unittest
from unittest.mock import MagicMock
from pyflowintel.endpoints.cases import CaseEndpoint
from pyflowintel.api_wrapper import PyFlowintel
from pyflowintel.commons.utils import read_yaml
from pyflowintel.settings import DEFAULT_CONFIG_FILE
# Load configuration for integration tests
_test_config = {}
if DEFAULT_CONFIG_FILE.exists():
_test_config = read_yaml(DEFAULT_CONFIG_FILE).get("testing", {}) or {}
TEST_BASE_URL = _test_config.get("base_url")
TEST_API_KEY = _test_config.get("api_key")
TEST_TIMEOUT = _test_config.get("timeout", 5)
def skip_if_no_credentials(test_item):
"""Decorator to skip integration tests if credentials are not set."""
return unittest.skipIf(
not TEST_API_KEY or not TEST_BASE_URL,
"Skipping integration test: api_key or base_url for testing not set in the configuration file"
)(test_item)
class TestCaseEndpointValidations(unittest.TestCase):
"""Unit tests for CaseEndpoint."""
def setUp(self):
self.mock_client = MagicMock()
self.endpoint = CaseEndpoint(self.mock_client)
def test_init_sets_base_endpoint_path(self):
self.assertEqual(self.endpoint.base_endpoint_path, "/case")
def test_build_endpoint_path(self):
self.assertEqual(self.endpoint.build_endpoint_path("/create"), "/case/create")
self.assertEqual(self.endpoint.build_endpoint_path("/42"), "/case/42")
# --- search_by_id ---
def test_search_by_id_rejects_non_int(self):
with self.assertRaises(ValueError):
self.endpoint.search_by_id("not-an-int")
self.mock_client.get.assert_not_called()
def test_search_by_id_rejects_zero(self):
with self.assertRaises(ValueError):
self.endpoint.search_by_id(0)
self.mock_client.get.assert_not_called()
def test_search_by_id_rejects_negative(self):
with self.assertRaises(ValueError):
self.endpoint.search_by_id(-5)
self.mock_client.get.assert_not_called()
def test_create_merges_kwargs_into_payload(self):
self.mock_client.post.return_value = {"case_id": 2}
self.endpoint.create("Test Case", description="desc", deadline="2026-12-31")
_, kwargs = self.mock_client.post.call_args
self.assertEqual(kwargs["json_data"]["title"], "Test Case")
self.assertEqual(kwargs["json_data"]["description"], "desc")
self.assertEqual(kwargs["json_data"]["deadline"], "2026-12-31")
# --- update ---
def test_update_rejects_non_int_id(self):
with self.assertRaises(ValueError):
self.endpoint.update("abc", {"title": "New title"})
self.mock_client.post.assert_not_called()
# --- delete ---
def test_delete_rejects_non_int_id(self):
with self.assertRaises(ValueError):
self.endpoint.delete(None)
self.mock_client.get.assert_not_called()
# --- complete ---
def test_complete_rejects_non_int_id(self):
with self.assertRaises(ValueError):
self.endpoint.complete("five")
self.mock_client.get.assert_not_called()
# --- add_task ---
def test_add_task_rejects_non_int_case_id(self):
with self.assertRaises(ValueError):
self.endpoint.add_task("not-int", "My Task")
self.mock_client.post.assert_not_called()
# --- append_note ---
def test_append_note_rejects_non_int_case_id(self):
with self.assertRaises(ValueError):
self.endpoint.append_note("not-int", "Some note")
self.mock_client.post.assert_not_called()
@skip_if_no_credentials
class TestCaseOperations(unittest.TestCase):
"""Integration tests for case CRUD operations."""
@classmethod
def setUpClass(cls):
cls.client = PyFlowintel.from_args(TEST_BASE_URL, TEST_API_KEY, TEST_TIMEOUT)
cls.case_payload = {
"title": "Integration unit test case",
"description": "Created by automated integration tests",
}
created = cls.client.cases.create(**cls.case_payload) # expand the case_payload as keyword args
cls.case_id = created.get("case_id", 0)
@classmethod
def tearDownClass(cls):
try:
cls.client.cases.delete(cls.case_id)
cls.client.close()
except Exception as e:
print(f"Cleanup failed (ignoring): {e}")
def test_create_case_returns_valid_id(self):
"""Verify the created case has a positive integer ID."""
self.assertIsInstance(self.case_id, int)
self.assertGreater(self.case_id, 0)
def test_search_by_id(self):
"""Retrieve the created case and verify its fields."""
fetched = self.client.cases.search_by_id(self.case_id)
self.assertIsInstance(fetched, dict)
self._check_fields_equality(fetched)
def test_search_by_title(self):
"""Search by title substring and verify the created case appears.
Note: the endpoint's response structure is as follows:
{'cases': [
{'id': 52,
'uuid': '...',
'title': 'Test..",
...
}
]}
"""
results = self.client.cases.search_by_title(self.case_payload.get("title"))
self.assertIsInstance(results, dict)
cases = results.get("cases", [])
orig = None
for c in cases:
if c.get("id") == self.case_id:
orig = c
break
self.assertTrue(orig) # assert not none
self._check_fields_equality(orig)
def test_list_all_contains_created_case(self):
"""Verify the created case is present in the list of all cases."""
cases = self.client.cases.list_all()
self.assertIsInstance(cases, list)
ids = [c.get("id") for c in cases]
self.assertIn(self.case_id, ids)
def test_update_case(self):
"""Update the case and verify that changes took place.
Correctly updated values are verified here; for all the other fields defined in the
API, see test_flowintel_erroneous.py"""
new_fields = {
"title": "Updated title",
"description": "Updated description",
"is_private": True,
"privileged_case": True,
"ticket_id": "T178",
}
result = self.client.cases.update(self.case_id, new_fields)
self.assertIn("message", result)
self.assertIn("edited", result.get("message"))
# Verify that the updates took effect
updated = self.client.cases.search_by_id(self.case_id)
for key, value in new_fields.items():
self.assertEqual(updated.get(key), value)
def test_add_task_to_case(self):
"""Add a task to the created case and verify that it is correctly created and associated."""
# get the current number of tasks for the case before adding a new one
case_tasks_num = self.client.cases.search_by_id(self.case_id).get("nb_tasks", 0) or 0
result = self.client.cases.add_task(self.case_id, "Investigation task")
task = result.get("task_id", 0)
self.assertGreater(task, 0)
# verify that one task was added
self.assertEqual(
self.client.cases.search_by_id(self.case_id).get("nb_tasks", 0),
case_tasks_num + 1
)
# verify that the task is associated with the case
task_data = self.client.tasks.search_by_id(task)
self.assertEqual(task_data.get("task",{}).get("case_id"), self.case_id)
def test_complete_case(self):
"""Create and complete a case, then verify its completion status.
Clean up afterwards by deleting the case.
"""
case2 = self.client.cases.create("Test case for completion", description="To be marked as completed in test")
case2_id = case2.get("case_id", 0)
self.assertGreater(case2_id, 0)
self.assertFalse(self.client.cases.isComplete(case2_id))
self.client.cases.complete(case2_id)
self.assertTrue(self.client.cases.isComplete(case2_id))
self.client.cases.delete(case2_id)
def test_create_template_from_case(self):
resp = self.client.cases.create_template_from_case(self.case_id, "My Template")
tid = resp.get("template_id", 0)
self.assertGreater(tid, 0)
temp = self.client.templates.find_case_temp_by_id(tid)
self.assertEqual(temp.get("id"), tid)
# Cleanup: delete the created template
self.client.templates.delete_case(tid)
def _check_fields_equality(self, fetched):
for key, value in self.case_payload.items():
if key == "deadline_date" or key == "deadline_time":
# The API collapses deadline_date and deadline_time into a single "deadline" field in the format "YYYY-MM-DD HH:MM"
self.assertIn(value, fetched.get("deadline", ""))
else:
self.assertEqual(fetched.get(key), value)