11# Unit Tests for Kubernetes Dashboard
22
3- import pytest
43import json
54from unittest .mock import MagicMock , patch
5+
6+ import pytest
67from flask import Flask
78
8- # Import the modules to test
9- from system_monitor import get_system_metrics , get_metrics_history , clear_metrics_cache
10- from security_scanner import scan_image , get_scan_summary , clear_scan_cache
11- from kubernetes_client import init_kubernetes , get_resource_counts
12- from security import sanitize_input , validate_image_name
139from dashboard_types import KubernetesInfo , PodStatus
10+ from kubernetes_client import get_resource_counts , init_kubernetes
11+ from security import sanitize_input , validate_image_name
12+ from security_scanner import clear_scan_cache , get_scan_summary , scan_image
13+ # Import the modules to test
14+ from system_monitor import (clear_metrics_cache , get_metrics_history ,
15+ get_system_metrics )
1416
1517
1618class TestSystemMonitor :
@@ -25,33 +27,35 @@ def cpu_percent_side_effect(interval=None, percpu=False):
2527 return [25.0 , 25.0 , 25.0 , 25.0 ]
2628 else :
2729 return 50.0
28-
30+
2931 mock_psutil .cpu_percent .side_effect = cpu_percent_side_effect
3032 mock_psutil .cpu_count .return_value = 4
31- mock_psutil .cpu_freq .return_value = MagicMock (current = 2000.0 , min = 1000.0 , max = 3000.0 )
32-
33+ mock_psutil .cpu_freq .return_value = MagicMock (
34+ current = 2000.0 , min = 1000.0 , max = 3000.0
35+ )
36+
3337 mock_memory = MagicMock ()
3438 mock_memory .total = 8589934592 # 8GB
3539 mock_memory .available = 4294967296 # 4GB
3640 mock_memory .used = 4294967296 # 4GB
3741 mock_memory .percent = 50.0
3842 mock_psutil .virtual_memory .return_value = mock_memory
39-
43+
4044 mock_disk = MagicMock ()
4145 mock_disk .total = 107374182400 # 100GB
4246 mock_disk .used = 53687091200 # 50GB
4347 mock_disk .free = 53687091200 # 50GB
4448 mock_disk .percent = 50.0
4549 mock_psutil .disk_usage .return_value = mock_disk
46-
50+
4751 mock_psutil .boot_time .return_value = 1640995200
48-
52+
4953 mock_psutil .platform .platform .return_value = "Linux-5.15.0"
5054 mock_psutil .platform .architecture .return_value = ("x86_64" , "" )
5155 mock_psutil .platform .machine .return_value = "x86_64"
52-
56+
5357 metrics = get_system_metrics ()
54-
58+
5559 assert metrics ["cpu_percent" ] == 50.0
5660 assert metrics ["memory_usage" ]["percent" ] == 50.0
5761 assert metrics ["disk_usage" ]["percent" ] == 50.0
@@ -81,29 +85,33 @@ def test_clear_metrics_cache(self):
8185class TestSecurityScanner :
8286 """Test security scanning functionality."""
8387
84- @patch (' security_scanner.subprocess.run' )
85- @patch (' security_scanner.validate_image_name' )
88+ @patch (" security_scanner.subprocess.run" )
89+ @patch (" security_scanner.validate_image_name" )
8690 def test_scan_image_success (self , mock_validate , mock_subprocess ):
8791 """Test successful image scanning."""
8892 mock_validate .return_value = True
89-
93+
9094 # Mock successful Trivy scan
9195 mock_result = MagicMock ()
9296 mock_result .returncode = 0
93- mock_result .stdout = json .dumps ([{
94- "Vulnerabilities" : [
95- {"Severity" : "CRITICAL" },
96- {"Severity" : "HIGH" },
97- {"Severity" : "MEDIUM" }
97+ mock_result .stdout = json .dumps (
98+ [
99+ {
100+ "Vulnerabilities" : [
101+ {"Severity" : "CRITICAL" },
102+ {"Severity" : "HIGH" },
103+ {"Severity" : "MEDIUM" },
104+ ]
105+ }
98106 ]
99- }] )
100-
107+ )
108+
101109 # Mock version check
102110 mock_version_check = MagicMock (returncode = 0 )
103111 mock_subprocess .side_effect = [mock_version_check , mock_result ]
104-
112+
105113 result = scan_image ("nginx:latest" )
106-
114+
107115 assert result ["image" ] == "nginx:latest"
108116 assert result ["vulnerabilities" ]["critical" ] == 1
109117 assert result ["vulnerabilities" ]["high" ] == 1
@@ -117,20 +125,20 @@ def test_scan_image_invalid_name(self):
117125
118126 def test_get_scan_summary (self ):
119127 """Test scan summary generation."""
120- with patch (' security_scanner.scan_image' ) as mock_scan :
128+ with patch (" security_scanner.scan_image" ) as mock_scan :
121129 mock_scan .return_value = {
122- ' image' : ' nginx:latest' ,
123- ' timestamp' : ' 2023-01-01T00:00:00' ,
124- ' vulnerabilities' : {' critical' : 1 , ' high' : 1 , ' medium' : 1 , ' low' : 0 },
125- ' total_vulnerabilities' : 3
130+ " image" : " nginx:latest" ,
131+ " timestamp" : " 2023-01-01T00:00:00" ,
132+ " vulnerabilities" : {" critical" : 1 , " high" : 1 , " medium" : 1 , " low" : 0 },
133+ " total_vulnerabilities" : 3 ,
126134 }
127-
128- summary = get_scan_summary (' nginx:latest' )
129-
130- assert summary [' image' ] == ' nginx:latest'
131- assert summary [' total_vulnerabilities' ] == 3
132- assert summary [' has_critical' ] == True
133- assert summary [' has_high' ] == True
135+
136+ summary = get_scan_summary (" nginx:latest" )
137+
138+ assert summary [" image" ] == " nginx:latest"
139+ assert summary [" total_vulnerabilities" ] == 3
140+ assert summary [" has_critical" ] == True
141+ assert summary [" has_high" ] == True
134142
135143
136144class TestSecurity :
@@ -179,43 +187,43 @@ def test_init_kubernetes_success(self, mock_client, mock_config):
179187 assert result == True
180188 mock_config .load_kube_config .assert_called_once ()
181189
182- @patch (' kubernetes_client.config' )
190+ @patch (" kubernetes_client.config" )
183191 def test_init_kubernetes_failure (self , mock_config ):
184192 """Test Kubernetes initialization failure."""
185193 # Reset global state
186194 import kubernetes_client
195+
187196 kubernetes_client ._k8s_available = False
188197 kubernetes_client ._core_v1 = None
189198 kubernetes_client ._apps_v1 = None
190199 kubernetes_client ._last_init_attempt = 0
191-
200+
192201 mock_config .load_kube_config .side_effect = Exception ("Config not found" )
193- mock_config .load_incluster_config .side_effect = Exception ("In-cluster config not found" )
194-
202+ mock_config .load_incluster_config .side_effect = Exception (
203+ "In-cluster config not found"
204+ )
205+
195206 result = init_kubernetes ()
196-
207+
197208 assert result == False
198209
199210 @patch ("kubernetes_client.get_k8s_clients" )
200211 def test_get_resource_counts (self , mock_clients ):
201212 """Test resource count retrieval."""
202213 # Reset global state to make Kubernetes available
203214 import kubernetes_client
215+
204216 kubernetes_client ._k8s_available = True
205-
217+
206218 mock_core_v1 , mock_apps_v1 = MagicMock (), MagicMock ()
207219 mock_clients .return_value = (mock_core_v1 , mock_apps_v1 )
208220
209221 # Mock API responses
210222 mock_apps_v1 .list_namespaced_deployment .return_value = MagicMock (
211223 items = [1 , 2 , 3 ]
212224 )
213- mock_core_v1 .list_namespaced_service .return_value = MagicMock (
214- items = [1 , 2 ]
215- )
216- mock_core_v1 .list_namespaced_pod .return_value = MagicMock (
217- items = [1 , 2 , 3 , 4 ]
218- )
225+ mock_core_v1 .list_namespaced_service .return_value = MagicMock (items = [1 , 2 ])
226+ mock_core_v1 .list_namespaced_pod .return_value = MagicMock (items = [1 , 2 , 3 , 4 ])
219227
220228 with patch ("kubernetes_client.get_pod_status_counts" ) as mock_status :
221229 mock_status .return_value = {
0 commit comments