Skip to content

Commit 8793522

Browse files
committed
Refactor the cleaninup of created custom modules in test
1 parent caf8006 commit 8793522

File tree

1 file changed

+61
-27
lines changed

1 file changed

+61
-27
lines changed

securitycenter/snippets_management_api/event_threat_detection_custom_modules_test.py

Lines changed: 61 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -38,41 +38,26 @@
3838
LOCATION = "global"
3939
PREFIX = "python_sample_etd_custom_module" # Prefix used for identifying test modules
4040

41+
# Global list to track created modules
42+
created_modules = []
43+
4144

4245
@pytest.fixture(scope="session", autouse=True)
4346
def setup_environment():
44-
"""Fixture to ensure a clean environment by removing test modules before running tests."""
4547
if not ORGANIZATION_ID:
4648
pytest.fail("GCLOUD_ORGANIZATION environment variable is not set.")
4749

48-
print(f"Cleaning up existing custom modules for organization: {ORGANIZATION_ID}")
49-
cleanup_existing_custom_modules(ORGANIZATION_ID)
5050

51+
@pytest.fixture(scope="session", autouse=True)
52+
def cleanup_after_tests(request):
53+
"""Fixture to clean up created custom modules after the test session."""
54+
def teardown():
55+
print("\nCreated Custom Modules:")
56+
print_all_created_modules()
57+
print("Cleaning up created custom modules...")
58+
cleanup_created_custom_modules()
5159

52-
def cleanup_existing_custom_modules(org_id: str):
53-
"""
54-
Deletes all custom modules matching a specific naming pattern.
55-
Args:
56-
org_id: The organization ID.
57-
"""
58-
client = securitycentermanagement_v1.SecurityCenterManagementClient()
59-
parent = f"organizations/{org_id}/locations/global"
60-
print(f"Parent path: {parent}")
61-
try:
62-
custom_modules = client.list_event_threat_detection_custom_modules(
63-
request={"parent": parent}
64-
)
65-
for module in custom_modules:
66-
if module.display_name.startswith(PREFIX):
67-
client.delete_event_threat_detection_custom_module(
68-
request={"name": module.name}
69-
)
70-
print(f"Deleted custom module: {module.name}")
71-
except NotFound as e:
72-
print(f"Resource not found: {e}")
73-
except Exception as e:
74-
print(f"Unexpected error during cleanup: {e}")
75-
raise
60+
request.addfinalizer(teardown)
7661

7762

7863
def add_custom_module(org_id: str):
@@ -125,6 +110,7 @@ def test_create_event_threat_detection_custom_module():
125110

126111
# Run the function to create the custom module
127112
response = event_threat_detection_custom_modules.create_event_threat_detection_custom_module(parent)
113+
created_modules.append(response.name)
128114

129115
assert response is not None, "Custom module creation failed."
130116
# Verify that the custom module was created
@@ -138,6 +124,7 @@ def test_create_event_threat_detection_custom_module():
138124
def test_get_event_threat_detection_custom_module():
139125

140126
module_name, module_id = add_custom_module(ORGANIZATION_ID)
127+
created_modules.append(module_name)
141128
parent = f"organizations/{ORGANIZATION_ID}/locations/{LOCATION}"
142129

143130
# Retrieve the custom module
@@ -156,6 +143,7 @@ def test_get_event_threat_detection_custom_module():
156143
def test_list_event_threat_detection_custom_module():
157144

158145
module_name, module_id = add_custom_module(ORGANIZATION_ID)
146+
created_modules.append(module_name)
159147
parent = f"organizations/{ORGANIZATION_ID}/locations/{LOCATION}"
160148
# Retrieve the custom modules
161149
custom_modules = event_threat_detection_custom_modules.list_event_threat_detection_custom_module(parent)
@@ -181,6 +169,7 @@ def test_list_event_threat_detection_custom_module():
181169
def test_update_event_threat_detection_custom_module():
182170

183171
module_name, module_id = add_custom_module(ORGANIZATION_ID)
172+
created_modules.append(module_name)
184173
parent = f"organizations/{ORGANIZATION_ID}/locations/{LOCATION}"
185174

186175
# Retrieve the custom module
@@ -198,6 +187,7 @@ def test_update_event_threat_detection_custom_module():
198187
def test_delete_event_threat_detection_custom_module():
199188

200189
module_name, module_id = add_custom_module(ORGANIZATION_ID)
190+
created_modules.append(module_name)
201191
parent = f"organizations/{ORGANIZATION_ID}/locations/{LOCATION}"
202192
try:
203193
response = event_threat_detection_custom_modules.delete_event_threat_detection_custom_module(parent, module_id)
@@ -207,3 +197,47 @@ def test_delete_event_threat_detection_custom_module():
207197
assert response is None
208198

209199
print(f"Custom module was deleted successfully: {module_id}")
200+
201+
202+
def print_all_created_modules():
203+
"""Print all created custom modules."""
204+
if not created_modules:
205+
print("No custom modules were created.")
206+
else:
207+
for module in created_modules:
208+
print(module)
209+
210+
211+
def cleanup_created_custom_modules():
212+
"""
213+
Deletes all created custom modules in this test session.
214+
"""
215+
client = securitycentermanagement_v1.SecurityCenterManagementClient()
216+
217+
for module in list(created_modules):
218+
if not custom_module_exists(module):
219+
print(f"Module not found (already deleted): {module}")
220+
created_modules.remove(module)
221+
continue
222+
try:
223+
client.delete_event_threat_detection_custom_module(
224+
request={"name": module}
225+
)
226+
print(f"Deleted custom module: {module}")
227+
created_modules.remove(module)
228+
except Exception as e:
229+
print(f"Failed to delete module {module}: {e}")
230+
raise
231+
232+
233+
def custom_module_exists(module_name):
234+
client = securitycentermanagement_v1.SecurityCenterManagementClient()
235+
try:
236+
client.get_event_threat_detection_custom_module(
237+
request={"name": module_name}
238+
)
239+
return True
240+
except Exception as e:
241+
if "404" in str(e):
242+
return False
243+
raise

0 commit comments

Comments
 (0)