github.com/defensepoint-snyk-test/helm-new@v0.0.0-20211130153739-c57ea64d6603/cmd/helm/release_testing.go (about) 1 /* 2 Copyright The Helm Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "fmt" 21 "io" 22 23 "github.com/spf13/cobra" 24 25 "k8s.io/helm/pkg/helm" 26 "k8s.io/helm/pkg/proto/hapi/release" 27 ) 28 29 const releaseTestDesc = ` 30 The test command runs the tests for a release. 31 32 The argument this command takes is the name of a deployed release. 33 The tests to be run are defined in the chart that was installed. 34 ` 35 36 type releaseTestCmd struct { 37 name string 38 out io.Writer 39 client helm.Interface 40 timeout int64 41 cleanup bool 42 } 43 44 func newReleaseTestCmd(c helm.Interface, out io.Writer) *cobra.Command { 45 rlsTest := &releaseTestCmd{ 46 out: out, 47 client: c, 48 } 49 50 cmd := &cobra.Command{ 51 Use: "test [RELEASE]", 52 Short: "test a release", 53 Long: releaseTestDesc, 54 PreRunE: func(_ *cobra.Command, _ []string) error { return setupConnection() }, 55 RunE: func(cmd *cobra.Command, args []string) error { 56 if err := checkArgsLength(len(args), "release name"); err != nil { 57 return err 58 } 59 60 rlsTest.name = args[0] 61 rlsTest.client = ensureHelmClient(rlsTest.client) 62 return rlsTest.run() 63 }, 64 } 65 66 f := cmd.Flags() 67 settings.AddFlagsTLS(f) 68 f.Int64Var(&rlsTest.timeout, "timeout", 300, "time in seconds to wait for any individual Kubernetes operation (like Jobs for hooks)") 69 f.BoolVar(&rlsTest.cleanup, "cleanup", false, "delete test pods upon completion") 70 71 // set defaults from environment 72 settings.InitTLS(f) 73 74 return cmd 75 } 76 77 func (t *releaseTestCmd) run() (err error) { 78 c, errc := t.client.RunReleaseTest( 79 t.name, 80 helm.ReleaseTestTimeout(t.timeout), 81 helm.ReleaseTestCleanup(t.cleanup), 82 ) 83 testErr := &testErr{} 84 85 for { 86 select { 87 case err := <-errc: 88 if prettyError(err) == nil && testErr.failed > 0 { 89 return testErr.Error() 90 } 91 return prettyError(err) 92 case res, ok := <-c: 93 if !ok { 94 break 95 } 96 97 if res.Status == release.TestRun_FAILURE { 98 testErr.failed++ 99 } 100 101 fmt.Fprintf(t.out, res.Msg+"\n") 102 103 } 104 } 105 106 } 107 108 type testErr struct { 109 failed int 110 } 111 112 func (err *testErr) Error() error { 113 return fmt.Errorf("%v test(s) failed", err.failed) 114 }