From 532d86d72e449622a723a28ba8045d0c238e59b7 Mon Sep 17 00:00:00 2001 From: Anson Qian Date: Fri, 16 Jan 2026 16:19:07 -0500 Subject: [PATCH] fix: ensure default namespace is used when none is specified for Kubernetes resources --- modules/python/clients/kubernetes_client.py | 73 ++++------- .../tests/clients/test_kubernetes_client.py | 118 +++++++++++------- 2 files changed, 92 insertions(+), 99 deletions(-) diff --git a/modules/python/clients/kubernetes_client.py b/modules/python/clients/kubernetes_client.py index 21574331bc..9d9d0d6927 100644 --- a/modules/python/clients/kubernetes_client.py +++ b/modules/python/clients/kubernetes_client.py @@ -1102,51 +1102,31 @@ def _apply_single_manifest(self, manifest, namespace=None): Apply a single Kubernetes manifest using the appropriate API client. :param manifest: Dictionary representing a Kubernetes resource - :param namespace: Optional namespace to override the manifest namespace + :param namespace: Optional namespace to override the manifest namespace. + Defaults to 'default' for namespaced resources if not specified. :return: None """ try: kind = manifest.get("kind") - # Use provided namespace or fall back to manifest namespace - namespace = namespace or manifest.get("metadata", {}).get("namespace") + # Use provided namespace or fall back to manifest namespace, then to "default" + namespace = namespace or manifest.get("metadata", {}).get("namespace") or "default" name = manifest.get("metadata", {}).get("name") logger.info("Applying manifest %s %s in namespace %s", kind, name, namespace) if kind == "Deployment": - if namespace: - self.app.create_namespaced_deployment(namespace=namespace, body=manifest) - else: - raise ValueError("Deployment requires a namespace") + self.app.create_namespaced_deployment(namespace=namespace, body=manifest) elif kind == "DaemonSet": - if namespace: - self.app.create_namespaced_daemon_set(namespace=namespace, body=manifest) - else: - raise ValueError("DaemonSet requires a namespace") + self.app.create_namespaced_daemon_set(namespace=namespace, body=manifest) elif kind == "StatefulSet": - if namespace: - self.app.create_namespaced_stateful_set(namespace=namespace, body=manifest) - else: - raise ValueError("StatefulSet requires a namespace") + self.app.create_namespaced_stateful_set(namespace=namespace, body=manifest) elif kind == "Service": - if namespace: - self.api.create_namespaced_service(namespace=namespace, body=manifest) - else: - raise ValueError("Service requires a namespace") + self.api.create_namespaced_service(namespace=namespace, body=manifest) elif kind == "ConfigMap": - if namespace: - self.api.create_namespaced_config_map(namespace=namespace, body=manifest) - else: - raise ValueError("ConfigMap requires a namespace") + self.api.create_namespaced_config_map(namespace=namespace, body=manifest) elif kind == "Secret": - if namespace: - self.api.create_namespaced_secret(namespace=namespace, body=manifest) - else: - raise ValueError("Secret requires a namespace") + self.api.create_namespaced_secret(namespace=namespace, body=manifest) elif kind == "ServiceAccount": - if namespace: - self.api.create_namespaced_service_account(namespace=namespace, body=manifest) - else: - raise ValueError("ServiceAccount requires a namespace") + self.api.create_namespaced_service_account(namespace=namespace, body=manifest) elif kind == "ClusterRole": # ClusterRole is cluster-scoped rbac_api = client.RbacAuthorizationV1Api() @@ -1156,17 +1136,11 @@ def _apply_single_manifest(self, manifest, namespace=None): rbac_api = client.RbacAuthorizationV1Api() rbac_api.create_cluster_role_binding(body=manifest) elif kind == "Role": - if namespace: - rbac_api = client.RbacAuthorizationV1Api() - rbac_api.create_namespaced_role(namespace=namespace, body=manifest) - else: - raise ValueError("Role requires a namespace") + rbac_api = client.RbacAuthorizationV1Api() + rbac_api.create_namespaced_role(namespace=namespace, body=manifest) elif kind == "RoleBinding": - if namespace: - rbac_api = client.RbacAuthorizationV1Api() - rbac_api.create_namespaced_role_binding(namespace=namespace, body=manifest) - else: - raise ValueError("RoleBinding requires a namespace") + rbac_api = client.RbacAuthorizationV1Api() + rbac_api.create_namespaced_role_binding(namespace=namespace, body=manifest) elif kind == "Namespace": # Namespace is cluster-scoped self.api.create_namespace(body=manifest) @@ -1203,16 +1177,13 @@ def _apply_single_manifest(self, manifest, namespace=None): api_version = manifest.get("apiVersion", "") group, version = api_version.split("/") if "/" in api_version else ("", api_version) custom_api = client.CustomObjectsApi() - if namespace: - custom_api.create_namespaced_custom_object( - group=group, - version=version, - namespace=namespace, - plural="mpijobs", - body=manifest - ) - else: - raise ValueError("MPIJob requires a namespace") + custom_api.create_namespaced_custom_object( + group=group, + version=version, + namespace=namespace, + plural="mpijobs", + body=manifest + ) elif kind == "NodeFeatureRule": # NodeFeatureRule is a custom resource from Node Feature Discovery (NFD) api_version = manifest.get("apiVersion", "") diff --git a/modules/python/tests/clients/test_kubernetes_client.py b/modules/python/tests/clients/test_kubernetes_client.py index 5118d41e61..ff46948e1d 100644 --- a/modules/python/tests/clients/test_kubernetes_client.py +++ b/modules/python/tests/clients/test_kubernetes_client.py @@ -2522,8 +2522,9 @@ def test_apply_single_manifest_deployment(self, mock_create_deployment): mock_create_deployment.assert_called_once_with( namespace="test-namespace", body=manifest) - def test_apply_single_manifest_deployment_no_namespace(self): - """Test _apply_single_manifest with Deployment missing namespace.""" + @patch('kubernetes.client.AppsV1Api.create_namespaced_deployment') + def test_apply_single_manifest_deployment_no_namespace(self, mock_create_deployment): + """Test _apply_single_manifest with Deployment missing namespace uses 'default'.""" manifest = { "apiVersion": "apps/v1", "kind": "Deployment", @@ -2531,11 +2532,12 @@ def test_apply_single_manifest_deployment_no_namespace(self): "spec": {} } - with self.assertRaises(ValueError) as context: - # pylint: disable=protected-access - self.client._apply_single_manifest(manifest) + # pylint: disable=protected-access + self.client._apply_single_manifest(manifest) - self.assertEqual(str(context.exception), "Deployment requires a namespace") + # Should use "default" namespace when none is specified + mock_create_deployment.assert_called_once_with( + namespace="default", body=manifest) @patch('kubernetes.client.AppsV1Api.create_namespaced_daemon_set') def test_apply_single_manifest_daemonset(self, mock_create_daemonset): @@ -2567,8 +2569,9 @@ def test_apply_single_manifest_statefulset(self, mock_create_statefulset): mock_create_statefulset.assert_called_once_with( namespace="test-namespace", body=manifest) - def test_apply_single_manifest_statefulset_no_namespace(self): - """Test _apply_single_manifest with StatefulSet missing namespace.""" + @patch('kubernetes.client.AppsV1Api.create_namespaced_stateful_set') + def test_apply_single_manifest_statefulset_no_namespace(self, mock_create_statefulset): + """Test _apply_single_manifest with StatefulSet missing namespace uses 'default'.""" manifest = { "apiVersion": "apps/v1", "kind": "StatefulSet", @@ -2576,11 +2579,12 @@ def test_apply_single_manifest_statefulset_no_namespace(self): "spec": {} } - with self.assertRaises(ValueError) as context: - # pylint: disable=protected-access - self.client._apply_single_manifest(manifest) + # pylint: disable=protected-access + self.client._apply_single_manifest(manifest) - self.assertEqual(str(context.exception), "StatefulSet requires a namespace") + # Should use "default" namespace when none is specified + mock_create_statefulset.assert_called_once_with( + namespace="default", body=manifest) @patch('kubernetes.client.CoreV1Api.create_namespaced_service') def test_apply_single_manifest_service(self, mock_create_service): @@ -2654,8 +2658,9 @@ def test_apply_single_manifest_mpi_job(self, mock_create_custom_object): body=manifest ) - def test_apply_single_manifest_mpi_job_no_namespace(self): - """Test _apply_single_manifest with MPIJob missing namespace.""" + @patch('kubernetes.client.CustomObjectsApi.create_namespaced_custom_object') + def test_apply_single_manifest_mpi_job_no_namespace(self, mock_create_custom_object): + """Test _apply_single_manifest with MPIJob missing namespace uses 'default'.""" manifest = { "apiVersion": "kubeflow.org/v2beta1", "kind": "MPIJob", @@ -2663,11 +2668,17 @@ def test_apply_single_manifest_mpi_job_no_namespace(self): "spec": {} } - with self.assertRaises(ValueError) as context: - # pylint: disable=protected-access - self.client._apply_single_manifest(manifest) + # pylint: disable=protected-access + self.client._apply_single_manifest(manifest) - self.assertEqual(str(context.exception), "MPIJob requires a namespace") + # Should use "default" namespace when none is specified + mock_create_custom_object.assert_called_once_with( + group="kubeflow.org", + version="v2beta1", + namespace="default", + plural="mpijobs", + body=manifest + ) @patch('kubernetes.client.CustomObjectsApi.create_cluster_custom_object') def test_apply_single_manifest_node_feature_rule(self, mock_create_custom_object): @@ -2741,12 +2752,12 @@ def test_apply_single_manifest_resource_already_exists(self, mock_update_single, # pylint: disable=protected-access self.client._apply_single_manifest(manifest) expected_calls = [ - mock.call("Applying manifest %s %s in namespace %s", "Namespace", "existing-namespace", None), + mock.call("Applying manifest %s %s in namespace %s", "Namespace", "existing-namespace", "default"), mock.call("Resource %s/%s already exists, updating it", "Namespace", "existing-namespace") ] mock_logger.info.assert_has_calls(expected_calls) # Verify that _update_single_manifest was called with the correct arguments - mock_update_single.assert_called_once_with(manifest, None) + mock_update_single.assert_called_once_with(manifest, "default") @patch('kubernetes.client.CoreV1Api.create_namespace') def test_apply_single_manifest_api_exception_non_409(self, mock_create_namespace): @@ -3691,11 +3702,12 @@ def test_apply_manifest_from_file_combined_sources(self, _mock_open_file, mock_y mock_api.create_namespaced_service.assert_called_once() mock_api.create_namespaced_config_map.assert_called_once() + @patch('kubernetes.client.AppsV1Api.create_namespaced_deployment') @patch('os.path.isfile') @patch('yaml.safe_load_all') @patch('builtins.open', new_callable=mock_open) - def test_apply_manifest_from_file_deployment_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile): - """Test apply_manifest_from_file with deployment manifest missing namespace - should raise error""" + def test_apply_manifest_from_file_deployment_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile, mock_create_deployment): + """Test apply_manifest_from_file with deployment manifest missing namespace uses 'default'""" # Mock file existence check mock_isfile.return_value = True @@ -3710,17 +3722,18 @@ def test_apply_manifest_from_file_deployment_missing_namespace_error(self, _mock mock_yaml_load.return_value = [manifest_dict] - # Should raise ValueError for missing namespace - with self.assertRaises(ValueError) as context: - self.client.apply_manifest_from_file(manifest_path="/path/to/deployment.yaml") + # Should use "default" namespace when none is specified + self.client.apply_manifest_from_file(manifest_path="/path/to/deployment.yaml") - self.assertIn("Deployment requires a namespace", str(context.exception)) + mock_create_deployment.assert_called_once_with( + namespace="default", body=manifest_dict) + @patch('kubernetes.client.CoreV1Api.create_namespaced_service') @patch('os.path.isfile') @patch('yaml.safe_load_all') @patch('builtins.open', new_callable=mock_open) - def test_apply_manifest_from_file_service_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile): - """Test apply_manifest_from_file with service manifest missing namespace - should raise error""" + def test_apply_manifest_from_file_service_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile, mock_create_service): + """Test apply_manifest_from_file with service manifest missing namespace uses 'default'""" # Mock file existence check mock_isfile.return_value = True @@ -3735,17 +3748,18 @@ def test_apply_manifest_from_file_service_missing_namespace_error(self, _mock_op mock_yaml_load.return_value = [manifest_dict] - # Should raise ValueError for missing namespace - with self.assertRaises(ValueError) as context: - self.client.apply_manifest_from_file(manifest_path="/path/to/service.yaml") + # Should use "default" namespace when none is specified + self.client.apply_manifest_from_file(manifest_path="/path/to/service.yaml") - self.assertIn("Service requires a namespace", str(context.exception)) + mock_create_service.assert_called_once_with( + namespace="default", body=manifest_dict) + @patch('kubernetes.client.AppsV1Api.create_namespaced_stateful_set') @patch('os.path.isfile') @patch('yaml.safe_load_all') @patch('builtins.open', new_callable=mock_open) - def test_apply_manifest_from_file_statefulset_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile): - """Test apply_manifest_from_file with StatefulSet manifest missing namespace - should raise error""" + def test_apply_manifest_from_file_statefulset_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile, mock_create_statefulset): + """Test apply_manifest_from_file with StatefulSet manifest missing namespace uses 'default'""" # Mock file existence check mock_isfile.return_value = True @@ -3760,17 +3774,18 @@ def test_apply_manifest_from_file_statefulset_missing_namespace_error(self, _moc mock_yaml_load.return_value = [manifest_dict] - # Should raise ValueError for missing namespace - with self.assertRaises(ValueError) as context: - self.client.apply_manifest_from_file(manifest_path="/path/to/statefulset.yaml") + # Should use "default" namespace when none is specified + self.client.apply_manifest_from_file(manifest_path="/path/to/statefulset.yaml") - self.assertIn("StatefulSet requires a namespace", str(context.exception)) + mock_create_statefulset.assert_called_once_with( + namespace="default", body=manifest_dict) + @patch('kubernetes.client.CoreV1Api.create_namespaced_config_map') @patch('os.path.isfile') @patch('yaml.safe_load_all') @patch('builtins.open', new_callable=mock_open) - def test_apply_manifest_from_file_configmap_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile): - """Test apply_manifest_from_file with ConfigMap manifest missing namespace - should raise error""" + def test_apply_manifest_from_file_configmap_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile, mock_create_configmap): + """Test apply_manifest_from_file with ConfigMap manifest missing namespace uses 'default'""" # Mock file existence check mock_isfile.return_value = True @@ -3785,11 +3800,11 @@ def test_apply_manifest_from_file_configmap_missing_namespace_error(self, _mock_ mock_yaml_load.return_value = [manifest_dict] - # Should raise ValueError for missing namespace - with self.assertRaises(ValueError) as context: - self.client.apply_manifest_from_file(manifest_path="/path/to/configmap.yaml") + # Should use "default" namespace when none is specified + self.client.apply_manifest_from_file(manifest_path="/path/to/configmap.yaml") - self.assertIn("ConfigMap requires a namespace", str(context.exception)) + mock_create_configmap.assert_called_once_with( + namespace="default", body=manifest_dict) @patch('os.path.isfile') @patch('builtins.open', new_callable=mock_open) @@ -4763,7 +4778,7 @@ def test_apply_single_manifest_fallback_to_manifest_namespace(self): ) def test_apply_single_manifest_no_namespace_anywhere_raises_error(self): - """Test _apply_single_manifest raises error when no namespace is provided anywhere.""" + """Test _apply_single_manifest uses 'default' when no namespace is provided anywhere.""" # Deployment manifest without namespace manifest_dict = { "apiVersion": "apps/v1", @@ -4775,12 +4790,19 @@ def test_apply_single_manifest_no_namespace_anywhere_raises_error(self): "spec": {"replicas": 1} } - # Call _apply_single_manifest without namespace parameter - with self.assertRaises(ValueError) as context: + # Mock the app API client + with patch.object(self.client, 'app') as mock_app: + mock_app.create_namespaced_deployment.return_value = None + + # Call _apply_single_manifest without namespace parameter # pylint: disable=protected-access self.client._apply_single_manifest(manifest_dict, namespace=None) - self.assertIn("Deployment requires a namespace", str(context.exception)) + # Verify deployment was created with "default" namespace + mock_app.create_namespaced_deployment.assert_called_once_with( + namespace="default", + body=manifest_dict + ) # Tests for delete_manifest_from_file with namespace override functionality @patch('os.path.isfile')