Skip to content

Commit 44c2591

Browse files
committed
Refactor the cleaning up of created custom modules in the current test session
1 parent 38a91fa commit 44c2591

File tree

1 file changed

+60
-32
lines changed

1 file changed

+60
-32
lines changed

securitycenter/snippets_management_api/security_health_analytics_custom_modules_test.py

Lines changed: 60 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -35,46 +35,26 @@
3535
LOCATION = "global"
3636
PREFIX = "python_sample_sha_custom_module" # Prefix used for identifying test modules
3737

38+
# Global list to track created modules
39+
created_modules = []
40+
3841

3942
@pytest.fixture(scope="session", autouse=True)
4043
def setup_environment():
41-
"""
42-
Fixture to ensure a clean environment by removing test modules before running tests.
43-
44-
This fixture lists all SHA custom modules in the organization and deletes any
45-
that were created by previous test runs, identified by the PREFIX.
46-
"""
4744
if not ORGANIZATION_ID:
4845
pytest.fail("GCLOUD_ORGANIZATION environment variable is not set.")
4946

50-
print(f"Cleaning up existing custom modules for organization: {ORGANIZATION_ID}")
51-
cleanup_existing_custom_modules(ORGANIZATION_ID)
5247

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

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

7959

8060
def add_custom_module(org_id: str):
@@ -139,6 +119,7 @@ def add_custom_module(org_id: str):
139119
def test_get_effective_security_health_analytics_custom_module():
140120
"""Tests getting an effective SHA custom module."""
141121
module_name, module_id = add_custom_module(ORGANIZATION_ID)
122+
created_modules.append(module_name)
142123
parent = f"organizations/{ORGANIZATION_ID}/locations/{LOCATION}"
143124

144125
# Retrieve the custom module
@@ -157,6 +138,7 @@ def test_get_effective_security_health_analytics_custom_module():
157138
def test_list_descendant_security_health_analytics_custom_module():
158139
"""Tests listing descendant SHA custom modules."""
159140
module_name, module_id = add_custom_module(ORGANIZATION_ID)
141+
created_modules.append(module_name)
160142
parent = f"organizations/{ORGANIZATION_ID}/locations/{LOCATION}"
161143
# Retrieve the list descendant custom modules
162144
custom_modules = security_health_analytics_custom_modules.list_descendant_security_health_analytics_custom_module(parent)
@@ -182,6 +164,7 @@ def test_list_descendant_security_health_analytics_custom_module():
182164
def test_list_effective_security_health_analytics_custom_module():
183165
"""Tests listing effective SHA custom modules."""
184166
module_name, module_id = add_custom_module(ORGANIZATION_ID)
167+
created_modules.append(module_name)
185168
parent = f"organizations/{ORGANIZATION_ID}/locations/{LOCATION}"
186169
# Retrieve the list of custom modules
187170
custom_modules = security_health_analytics_custom_modules.list_effective_security_health_analytics_custom_module(parent)
@@ -207,6 +190,7 @@ def test_list_effective_security_health_analytics_custom_module():
207190
def test_simulate_security_health_analytics_custom_module():
208191
"""Tests simulating an SHA custom module."""
209192
module_name, module_id = add_custom_module(ORGANIZATION_ID)
193+
created_modules.append(module_name)
210194
parent = f"organizations/{ORGANIZATION_ID}/locations/{LOCATION}"
211195

212196
simulated_custom_module = security_health_analytics_custom_modules.simulate_security_health_analytics_custom_module(parent)
@@ -215,3 +199,47 @@ def test_simulate_security_health_analytics_custom_module():
215199
assert simulated_custom_module.result.no_violation is not None, (
216200
f"Expected no_violation to be present, got {simulated_custom_module.result}."
217201
)
202+
203+
204+
def print_all_created_modules():
205+
"""Print all created custom modules."""
206+
if not created_modules:
207+
print("No custom modules were created.")
208+
else:
209+
for module in created_modules:
210+
print(module)
211+
212+
213+
def cleanup_created_custom_modules():
214+
"""
215+
Deletes all created custom modules in this test session.
216+
"""
217+
client = securitycentermanagement_v1.SecurityCenterManagementClient()
218+
219+
for module in list(created_modules):
220+
if not custom_module_exists(module):
221+
print(f"Module not found (already deleted): {module}")
222+
created_modules.remove(module)
223+
continue
224+
try:
225+
client.delete_security_health_analytics_custom_module(
226+
request={"name": module}
227+
)
228+
print(f"Deleted custom module: {module}")
229+
created_modules.remove(module)
230+
except Exception as e:
231+
print(f"Failed to delete module {module}: {e}")
232+
raise
233+
234+
235+
def custom_module_exists(module_name):
236+
client = securitycentermanagement_v1.SecurityCenterManagementClient()
237+
try:
238+
client.get_security_health_analytics_custom_module(
239+
request={"name": module_name}
240+
)
241+
return True
242+
except Exception as e:
243+
if "404" in str(e):
244+
return False
245+
raise

0 commit comments

Comments
 (0)