common.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Copyright © The ESO Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package commontest provides testing utilities for controllers.
  14. package commontest
  15. import (
  16. "context"
  17. "fmt"
  18. "time"
  19. v1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/util/wait"
  22. "sigs.k8s.io/controller-runtime/pkg/client"
  23. )
  24. // CreateNamespace creates a new namespace in the cluster.
  25. func CreateNamespace(baseName string, c client.Client) (string, error) {
  26. return CreateNamespaceWithLabels(baseName, c, map[string]string{})
  27. }
  28. // CreateNamespaceWithLabels creates a namespace with the given labels and returns its name.
  29. func CreateNamespaceWithLabels(baseName string, c client.Client, labels map[string]string) (string, error) {
  30. genName := fmt.Sprintf("ctrl-test-%v", baseName)
  31. ns := &v1.Namespace{
  32. ObjectMeta: metav1.ObjectMeta{
  33. GenerateName: genName,
  34. Labels: labels,
  35. },
  36. }
  37. err := wait.PollUntilContextTimeout(context.Background(), time.Second, 10*time.Second, true, func(ctx context.Context) (done bool, err error) {
  38. err = c.Create(ctx, ns)
  39. if err != nil {
  40. return false, nil
  41. }
  42. return true, nil
  43. })
  44. if err != nil {
  45. return "", err
  46. }
  47. return ns.Name, nil
  48. }
  49. // HasOwnerRef checks if the given ObjectMeta has an owner reference with the specified kind and name.
  50. func HasOwnerRef(meta metav1.ObjectMeta, kind, name string) bool {
  51. for _, ref := range meta.OwnerReferences {
  52. if ref.Kind == kind && ref.Name == name {
  53. return true
  54. }
  55. }
  56. return false
  57. }
  58. // FirstManagedFieldForManager returns the JSON representation of the first `metadata.managedFields` entry for a given manager.
  59. func FirstManagedFieldForManager(meta metav1.ObjectMeta, managerName string) string {
  60. for _, ref := range meta.ManagedFields {
  61. if ref.Manager == managerName {
  62. return ref.FieldsV1.String()
  63. }
  64. }
  65. return fmt.Sprintf("No managed fields managed by %s", managerName)
  66. }