github.com/uhthomas/helm@v3.0.0-beta.3+incompatible/pkg/action/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 action
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  	"strings"
    23  	"time"
    24  
    25  	"github.com/pkg/errors"
    26  
    27  	"helm.sh/helm/pkg/release"
    28  )
    29  
    30  // ReleaseTesting is the action for testing a release.
    31  //
    32  // It provides the implementation of 'helm test'.
    33  type ReleaseTesting struct {
    34  	cfg *Configuration
    35  
    36  	Timeout time.Duration
    37  	Cleanup bool
    38  }
    39  
    40  // NewReleaseTesting creates a new ReleaseTesting object with the given configuration.
    41  func NewReleaseTesting(cfg *Configuration) *ReleaseTesting {
    42  	return &ReleaseTesting{
    43  		cfg: cfg,
    44  	}
    45  }
    46  
    47  // Run executes 'helm test' against the given release.
    48  func (r *ReleaseTesting) Run(name string) error {
    49  	if err := validateReleaseName(name); err != nil {
    50  		return errors.Errorf("releaseTest: Release name is invalid: %s", name)
    51  	}
    52  
    53  	// finds the non-deleted release with the given name
    54  	rel, err := r.cfg.Releases.Last(name)
    55  	if err != nil {
    56  		return err
    57  	}
    58  
    59  	if err := r.cfg.execHook(rel, release.HookTest, r.Timeout); err != nil {
    60  		r.cfg.Releases.Update(rel)
    61  		return err
    62  	}
    63  
    64  	if r.Cleanup {
    65  		var manifestsToDelete strings.Builder
    66  		for _, h := range rel.Hooks {
    67  			for _, e := range h.Events {
    68  				if e == release.HookTest {
    69  					fmt.Fprintf(&manifestsToDelete, "\n---\n%s", h.Manifest)
    70  				}
    71  			}
    72  		}
    73  		hooks, err := r.cfg.KubeClient.Build(bytes.NewBufferString(manifestsToDelete.String()))
    74  		if err != nil {
    75  			return fmt.Errorf("unable to build test hooks: %v", err)
    76  		}
    77  		if _, errs := r.cfg.KubeClient.Delete(hooks); errs != nil {
    78  			return fmt.Errorf("unable to delete test hooks: %v", joinErrors(errs))
    79  		}
    80  	}
    81  
    82  	return r.cfg.Releases.Update(rel)
    83  }