-
Notifications
You must be signed in to change notification settings - Fork 4
/
namespace.go
38 lines (35 loc) · 1.64 KB
/
namespace.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package framework
import (
. "github.com/onsi/gomega" // nolint:golint
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
kubeerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/mesosphere/dklb/pkg/util/retry"
)
// WithTemporaryNamespace creates a Kubernetes namespace with a randomly generated name, calls the provided function with the namespace as its parameter, and deletes the namespace after said function returns.
func (f *Framework) WithTemporaryNamespace(fn func(namespace *corev1.Namespace)) {
// Create a namespace with a randomly generated name.
ns, err := f.KubeClient.CoreV1().Namespaces().Create(&corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
GenerateName: KubernetesNamespacePrefix,
},
})
// Make sure that no error has occurred.
Expect(err).NotTo(HaveOccurred(), "failed to create temporary namespace")
// Output the name of the namespace.
log.Debugf("created namespace %q", ns.Name)
// Make sure to clean up regardless of test outcome.
defer func() {
// Delete the Kubernetes namespace and wait for it to disappear.
err = f.KubeClient.CoreV1().Namespaces().Delete(ns.Name, metav1.NewDeleteOptions(0))
Expect(err).NotTo(HaveOccurred(), "failed to delete namespace %q", ns.Name)
err = retry.WithTimeout(DefaultRetryTimeout, DefaultRetryInterval, func() (bool, error) {
_, err := f.KubeClient.CoreV1().Namespaces().Get(ns.Name, metav1.GetOptions{})
return kubeerrors.IsNotFound(err), nil
})
Expect(err).NotTo(HaveOccurred(), "timed out while waiting for namespace %q to be deleted", ns.Name)
}()
// Call the provided function with the namespace.
fn(ns)
}