common.go 2.1 KB

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