• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

operator-framework / operator-sdk / 12323500562

13 Dec 2024 09:44PM UTC coverage: 34.569%. First build
12323500562

Pull #6878

github

acornett21
k8s 1.31 work

Signed-off-by: Adam D. Cornett <adc@redhat.com>
Pull Request #6878: k8s 1.31 work

9 of 22 new or added lines in 15 files covered. (40.91%)

4766 of 13787 relevant lines covered (34.57%)

13.62 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/internal/testutils/utils.go
1
// Copyright 2020 The Operator-SDK Authors
2
//
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
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
package testutils
16

17
import (
18
        "errors"
19
        "fmt"
20
        "os"
21
        "os/exec"
22
        "path/filepath"
23
        "strings"
24
        "time"
25

26
        . "github.com/onsi/ginkgo/v2"
27
        . "github.com/onsi/gomega"
28
        kbutil "sigs.k8s.io/kubebuilder/v4/pkg/plugin/util"
29
        kbtestutils "sigs.k8s.io/kubebuilder/v4/test/e2e/utils"
30
)
31

32
const BinaryName = "operator-sdk"
33

34
// TestContext wraps kubebuilder's e2e TestContext.
35
type TestContext struct {
36
        *kbtestutils.TestContext
37
        // BundleImageName store the image to use to build the bundle
38
        BundleImageName string
39
        // ProjectName store the project name
40
        ProjectName string
41
        // isPrometheusManagedBySuite is true when the suite tests is installing/uninstalling the Prometheus
42
        isPrometheusManagedBySuite bool
43
        // isOLMManagedBySuite is true when the suite tests is installing/uninstalling the OLM
44
        isOLMManagedBySuite bool
45
}
46

47
// NewTestContext returns a TestContext containing a new kubebuilder TestContext.
48
// Construct if your environment is connected to a live cluster, ex. for e2e tests.
49
func NewTestContext(binaryName string, env ...string) (tc TestContext, err error) {
×
50
        if tc.TestContext, err = kbtestutils.NewTestContext(binaryName, env...); err != nil {
×
51
                return tc, err
×
52
        }
×
53
        tc.ProjectName = strings.ToLower(filepath.Base(tc.Dir))
×
54
        tc.ImageName = makeImageName(tc.ProjectName)
×
55
        tc.BundleImageName = makeBundleImageName(tc.ProjectName)
×
56
        tc.isOLMManagedBySuite = true
×
57
        tc.isPrometheusManagedBySuite = true
×
58
        return tc, nil
×
59
}
60

61
// NewPartialTestContext returns a TestContext containing a partial kubebuilder TestContext.
62
// This object needs to be populated with GVK information. The underlying TestContext is
63
// created directly rather than through a constructor so cluster-based setup is skipped.
64
func NewPartialTestContext(binaryName, dir string, env ...string) (tc TestContext, err error) {
×
65
        cc := &kbtestutils.CmdContext{
×
66
                Env: env,
×
67
        }
×
68
        if cc.Dir, err = filepath.Abs(dir); err != nil {
×
69
                return tc, err
×
70
        }
×
71
        projectName := strings.ToLower(filepath.Base(dir))
×
72

×
73
        return TestContext{
×
74
                TestContext: &kbtestutils.TestContext{
×
75
                        CmdContext: cc,
×
76
                        BinaryName: binaryName,
×
77
                        ImageName:  makeImageName(projectName),
×
78
                },
×
79
                ProjectName:     projectName,
×
80
                BundleImageName: makeBundleImageName(projectName),
×
81
        }, nil
×
82
}
83

84
func makeImageName(projectName string) string {
×
85
        return fmt.Sprintf("quay.io/example/%s:v0.0.1", projectName)
×
86
}
×
87

88
func makeBundleImageName(projectName string) string {
×
89
        return fmt.Sprintf("quay.io/example/%s-bundle:v0.0.1", projectName)
×
90
}
×
91

92
// InstallOLMVersion runs 'operator-sdk olm install' for specific version
93
// and returns any errors emitted by that command.
94
func (tc TestContext) InstallOLMVersion(version string) error {
×
95
        cmd := exec.Command(tc.BinaryName, "olm", "install", "--version", version, "--timeout", "4m")
×
96
        _, err := tc.Run(cmd)
×
97
        return err
×
98
}
×
99

100
// UninstallOLM runs 'operator-sdk olm uninstall' and logs any errors emitted by that command.
101
func (tc TestContext) UninstallOLM() {
×
102
        cmd := exec.Command(tc.BinaryName, "olm", "uninstall")
×
103
        if _, err := tc.Run(cmd); err != nil {
×
104
                fmt.Fprintln(GinkgoWriter, "warning: error when uninstalling OLM:", err)
×
105
        }
×
106
}
107

108
// ReplaceInFile replaces all instances of old with new in the file at path.
109
// todo(camilamacedo86): this func can be pushed to upstream/kb
NEW
110
func ReplaceInFile(path, o, n string) error {
×
111
        info, err := os.Stat(path)
×
112
        if err != nil {
×
113
                return err
×
114
        }
×
115
        b, err := os.ReadFile(path)
×
116
        if err != nil {
×
117
                return err
×
118
        }
×
NEW
119
        if !strings.Contains(string(b), o) {
×
120
                return errors.New("unable to find the content to be replaced")
×
121
        }
×
NEW
122
        s := strings.Replace(string(b), o, n, -1)
×
123
        err = os.WriteFile(path, []byte(s), info.Mode())
×
124
        if err != nil {
×
125
                return err
×
126
        }
×
127
        return nil
×
128
}
129

130
// LoadImageToKindClusterWithName loads a local docker image with the name informed to the kind cluster
131
func (tc TestContext) LoadImageToKindClusterWithName(image string) error {
×
132
        cluster := "kind"
×
133
        if v, ok := os.LookupEnv("KIND_CLUSTER"); ok {
×
134
                cluster = v
×
135
        }
×
136
        kindOptions := []string{"load", "docker-image", "--name", cluster, image}
×
137
        cmd := exec.Command("kind", kindOptions...)
×
138
        _, err := tc.Run(cmd)
×
139
        return err
×
140
}
141

142
// InstallPrerequisites will install OLM and Prometheus
143
// when the cluster kind is Kind and when they are not present on the Cluster
144
func (tc TestContext) InstallPrerequisites() {
×
145
        By("checking API resources applied on Cluster")
×
146
        output, err := tc.Kubectl.Command("api-resources")
×
147
        Expect(err).NotTo(HaveOccurred())
×
148
        if strings.Contains(output, "servicemonitors") {
×
149
                tc.isPrometheusManagedBySuite = false
×
150
        }
×
151
        if strings.Contains(output, "clusterserviceversions") {
×
152
                tc.isOLMManagedBySuite = false
×
153
        }
×
154

155
        if tc.isPrometheusManagedBySuite {
×
156
                By("installing Prometheus")
×
157
                Expect(tc.InstallPrometheusOperManager()).To(Succeed())
×
158

×
159
                By("ensuring provisioned Prometheus Manager Service")
×
160
                Eventually(func() error {
×
161
                        _, err := tc.Kubectl.Get(
×
162
                                false,
×
163
                                "Service", "prometheus-operator")
×
164
                        return err
×
165
                }, 3*time.Minute, time.Second).Should(Succeed())
×
166
        }
167

168
        if tc.isOLMManagedBySuite {
×
169
                By("installing OLM")
×
170
                Expect(tc.InstallOLMVersion(OlmVersionForTestSuite)).To(Succeed())
×
171
        }
×
172
}
173

174
// IsRunningOnKind returns true when the tests are executed in a Kind Cluster
175
func (tc TestContext) IsRunningOnKind() (bool, error) {
×
176
        kubectx, err := tc.Kubectl.Command("config", "current-context")
×
177
        if err != nil {
×
178
                return false, err
×
179
        }
×
180
        return strings.Contains(kubectx, "kind"), nil
×
181
}
182

183
// UninstallPrerequisites will uninstall all prerequisites installed via InstallPrerequisites()
184
func (tc TestContext) UninstallPrerequisites() {
×
185
        if tc.isPrometheusManagedBySuite {
×
186
                By("uninstalling Prometheus")
×
187
                tc.UninstallPrometheusOperManager()
×
188
        }
×
189
        if tc.isOLMManagedBySuite {
×
190
                By("uninstalling OLM")
×
191
                tc.UninstallOLM()
×
192
        }
×
193
}
194

195
// WrapWarnOutput is a one-liner to wrap an error from a command that returns (string, error) in a warning.
196
func WrapWarnOutput(_ string, err error) {
×
197
        if err != nil {
×
198
                fmt.Fprintf(GinkgoWriter, "warning: %s", err)
×
199
        }
×
200
}
201

202
// WrapWarn is a one-liner to wrap an error from a command that returns (error) in a warning.
203
func WrapWarn(err error) {
×
204
        WrapWarnOutput("", err)
×
205
}
×
206

207
func (tc TestContext) UncommentRestrictivePodStandards() error {
×
208
        configManager := filepath.Join(tc.Dir, "config", "manager", "manager.yaml")
×
209

×
210
        if err := kbutil.ReplaceInFile(configManager, `# TODO(user): For common cases that do not require escalating privileges
×
211
        # it is recommended to ensure that all your Pods/Containers are restrictive.
×
212
        # More info: https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted
×
213
        # Please uncomment the following code if your project does NOT have to work on old Kubernetes
×
214
        # versions < 1.19 or on vendors versions which do NOT support this field by default (i.e. Openshift < 4.11 ).
×
215
        # seccompProfile:
×
216
        #   type: RuntimeDefault`, `seccompProfile:
×
217
          type: RuntimeDefault`); err == nil {
×
218
                return err
×
219
        }
×
220

221
        return nil
×
222
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc