-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathhelpers_test.go
228 lines (198 loc) · 6.48 KB
/
helpers_test.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Copyright 2021 - 2024 Crunchy Data Solutions, Inc.
//
// SPDX-License-Identifier: Apache-2.0
package postgrescluster
import (
"context"
"os"
"strconv"
"testing"
"time"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/yaml"
"github.com/percona/percona-postgresql-operator/internal/controller/runtime"
"github.com/percona/percona-postgresql-operator/internal/initialize"
"github.com/percona/percona-postgresql-operator/internal/naming"
"github.com/percona/percona-postgresql-operator/internal/testing/require"
"github.com/percona/percona-postgresql-operator/pkg/apis/postgres-operator.crunchydata.com/v1beta1"
)
var (
//TODO(tjmoore4): With the new RELATED_IMAGES defaulting behavior, tests could be refactored
// to reference those environment variables instead of hard coded image values
CrunchyPostgresHAImage = "registry.developers.crunchydata.com/crunchydata/crunchy-postgres:ubi8-13.6-1"
CrunchyPGBackRestImage = "registry.developers.crunchydata.com/crunchydata/crunchy-pgbackrest:ubi8-2.38-0"
CrunchyPGBouncerImage = "registry.developers.crunchydata.com/crunchydata/crunchy-pgbouncer:ubi8-1.16-2"
)
// Scale extends d according to PGO_TEST_TIMEOUT_SCALE.
var Scale = func(d time.Duration) time.Duration { return d }
func init() {
setting := os.Getenv("PGO_TEST_TIMEOUT_SCALE")
factor, _ := strconv.ParseFloat(setting, 64)
if setting != "" {
if factor <= 0 {
panic("PGO_TEST_TIMEOUT_SCALE must be a fractional number greater than zero")
}
Scale = func(d time.Duration) time.Duration {
return time.Duration(factor * float64(d))
}
}
}
// setupKubernetes starts or connects to a Kubernetes API and returns a client
// that uses it. See [require.Kubernetes] for more details.
func setupKubernetes(t testing.TB) (*rest.Config, client.Client) {
t.Helper()
// Start and/or connect to a Kubernetes API, or Skip when that's not configured.
cfg, cc := require.Kubernetes2(t)
// Log the status of any test namespaces after this test fails.
t.Cleanup(func() {
if t.Failed() {
var namespaces corev1.NamespaceList
_ = cc.List(context.Background(), &namespaces, client.HasLabels{"postgres-operator-test"})
type shaped map[string]corev1.NamespaceStatus
result := make([]shaped, len(namespaces.Items))
for i, ns := range namespaces.Items {
result[i] = shaped{ns.Labels["postgres-operator-test"]: ns.Status}
}
formatted, _ := yaml.Marshal(result)
t.Logf("Test Namespaces:\n%s", formatted)
}
})
return cfg, cc
}
// setupNamespace creates a random namespace that will be deleted by t.Cleanup.
//
// Deprecated: Use [require.Namespace] instead.
func setupNamespace(t testing.TB, cc client.Client) *corev1.Namespace {
t.Helper()
return require.Namespace(t, cc)
}
func testVolumeClaimSpec() corev1.PersistentVolumeClaimSpec {
// Defines a volume claim spec that can be used to create instances
return corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
Resources: corev1.VolumeResourceRequirements{
Requests: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceStorage: resource.MustParse("1Gi"),
},
},
}
}
func testCluster() *v1beta1.PostgresCluster {
// Defines a base cluster spec that can be used by tests to generate a
// cluster with an expected number of instances
cluster := v1beta1.PostgresCluster{
ObjectMeta: metav1.ObjectMeta{
Name: "hippo",
},
Spec: v1beta1.PostgresClusterSpec{
PostgresVersion: 13,
Image: CrunchyPostgresHAImage,
ImagePullSecrets: []corev1.LocalObjectReference{{
Name: "myImagePullSecret"},
},
InstanceSets: []v1beta1.PostgresInstanceSetSpec{{
Name: "instance1",
Replicas: initialize.Int32(1),
DataVolumeClaimSpec: testVolumeClaimSpec(),
}},
Backups: v1beta1.Backups{
PGBackRest: v1beta1.PGBackRestArchive{
Image: CrunchyPGBackRestImage,
Repos: []v1beta1.PGBackRestRepo{{
Name: "repo1",
Volume: &v1beta1.RepoPVC{
VolumeClaimSpec: testVolumeClaimSpec(),
},
}},
},
},
Proxy: &v1beta1.PostgresProxySpec{
PGBouncer: &v1beta1.PGBouncerPodSpec{
Image: CrunchyPGBouncerImage,
},
},
},
}
return cluster.DeepCopy()
}
func testBackupJob(cluster *v1beta1.PostgresCluster, name string) *batchv1.Job {
job := batchv1.Job{
TypeMeta: metav1.TypeMeta{
APIVersion: batchv1.SchemeGroupVersion.String(),
Kind: "Job",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: cluster.Namespace,
Labels: map[string]string{
naming.LabelCluster: cluster.Name,
naming.LabelPGBackRestBackup: "",
naming.LabelPGBackRestRepo: "repo1",
},
},
Spec: batchv1.JobSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
Containers: []corev1.Container{{Name: "test", Image: "test"}},
RestartPolicy: corev1.RestartPolicyNever,
},
},
},
}
return job.DeepCopy()
}
func testRestoreJob(cluster *v1beta1.PostgresCluster) *batchv1.Job {
job := batchv1.Job{
TypeMeta: metav1.TypeMeta{
APIVersion: batchv1.SchemeGroupVersion.String(),
Kind: "Job",
},
ObjectMeta: metav1.ObjectMeta{
Name: "restore-job-1",
Namespace: cluster.Namespace,
Labels: naming.PGBackRestRestoreJobLabels(cluster.Name),
},
Spec: batchv1.JobSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
Containers: []corev1.Container{{Name: "test", Image: "test"}},
RestartPolicy: corev1.RestartPolicyNever,
},
},
},
}
return job.DeepCopy()
}
// setupManager creates the runtime manager used during controller testing
func setupManager(t *testing.T, cfg *rest.Config,
controllerSetup func(mgr manager.Manager)) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
// Disable health endpoints
options := runtime.Options{}
options.HealthProbeBindAddress = "0"
options.Metrics.BindAddress = "0"
mgr, err := runtime.NewManager(cfg, options)
if err != nil {
t.Fatal(err)
}
controllerSetup(mgr)
go func() {
if err := mgr.Start(ctx); err != nil {
t.Error(err)
}
}()
t.Log("Manager started")
return ctx, cancel
}
// teardownManager stops the runtime manager when the tests
// have completed
func teardownManager(cancel context.CancelFunc, t *testing.T) {
cancel()
t.Log("Manager stopped")
}