github.com/terraform-modules-krish/terratest@v0.29.0/modules/k8s/namespace.go (about) 1 package k8s 2 3 import ( 4 "context" 5 6 "github.com/terraform-modules-krish/terratest/modules/testing" 7 "github.com/stretchr/testify/require" 8 corev1 "k8s.io/api/core/v1" 9 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 10 ) 11 12 // CreateNamespace will create a new Kubernetes namespace on the cluster targeted by the provided options. This will 13 // fail the test if there is an error in creating the namespace. 14 func CreateNamespace(t testing.TestingT, options *KubectlOptions, namespaceName string) { 15 require.NoError(t, CreateNamespaceE(t, options, namespaceName)) 16 } 17 18 // CreateNamespaceE will create a new Kubernetes namespace on the cluster targeted by the provided options. 19 func CreateNamespaceE(t testing.TestingT, options *KubectlOptions, namespaceName string) error { 20 clientset, err := GetKubernetesClientFromOptionsE(t, options) 21 if err != nil { 22 return err 23 } 24 25 namespace := corev1.Namespace{ 26 ObjectMeta: metav1.ObjectMeta{ 27 Name: namespaceName, 28 }, 29 } 30 _, err = clientset.CoreV1().Namespaces().Create(context.Background(), &namespace, metav1.CreateOptions{}) 31 return err 32 } 33 34 // GetNamespace will query the Kubernetes cluster targeted by the provided options for the requested namespace. This will 35 // fail the test if there is an error in getting the namespace or if the namespace doesn't exist. 36 func GetNamespace(t testing.TestingT, options *KubectlOptions, namespaceName string) *corev1.Namespace { 37 namespace, err := GetNamespaceE(t, options, namespaceName) 38 require.NoError(t, err) 39 require.NotNil(t, namespace) 40 return namespace 41 } 42 43 // GetNamespaceE will query the Kubernetes cluster targeted by the provided options for the requested namespace. 44 func GetNamespaceE(t testing.TestingT, options *KubectlOptions, namespaceName string) (*corev1.Namespace, error) { 45 clientset, err := GetKubernetesClientFromOptionsE(t, options) 46 if err != nil { 47 return nil, err 48 } 49 50 return clientset.CoreV1().Namespaces().Get(context.Background(), namespaceName, metav1.GetOptions{}) 51 } 52 53 // DeleteNamespace will delete the requested namespace from the Kubernetes cluster targeted by the provided options. This will 54 // fail the test if there is an error in creating the namespace. 55 func DeleteNamespace(t testing.TestingT, options *KubectlOptions, namespaceName string) { 56 require.NoError(t, DeleteNamespaceE(t, options, namespaceName)) 57 } 58 59 // DeleteNamespaceE will delete the requested namespace from the Kubernetes cluster targeted by the provided options. 60 func DeleteNamespaceE(t testing.TestingT, options *KubectlOptions, namespaceName string) error { 61 clientset, err := GetKubernetesClientFromOptionsE(t, options) 62 if err != nil { 63 return err 64 } 65 66 return clientset.CoreV1().Namespaces().Delete(context.Background(), namespaceName, metav1.DeleteOptions{}) 67 }