github.skymusic.top/operator-framework/operator-sdk@v0.8.2/pkg/test/context.go (about)

     1  // Copyright 2018 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 test
    16  
    17  import (
    18  	"strconv"
    19  	"strings"
    20  	"testing"
    21  	"time"
    22  
    23  	log "github.com/sirupsen/logrus"
    24  )
    25  
    26  type TestCtx struct {
    27  	id         string
    28  	cleanupFns []cleanupFn
    29  	namespace  string
    30  	t          *testing.T
    31  }
    32  
    33  type CleanupOptions struct {
    34  	TestContext   *TestCtx
    35  	Timeout       time.Duration
    36  	RetryInterval time.Duration
    37  }
    38  
    39  type cleanupFn func() error
    40  
    41  func NewTestCtx(t *testing.T) *TestCtx {
    42  	var prefix string
    43  	if t != nil {
    44  		// TestCtx is used among others for namespace names where '/' is forbidden
    45  		prefix = strings.TrimPrefix(
    46  			strings.Replace(
    47  				strings.ToLower(t.Name()),
    48  				"/",
    49  				"-",
    50  				-1,
    51  			),
    52  			"test",
    53  		)
    54  	} else {
    55  		prefix = "main"
    56  	}
    57  
    58  	id := prefix + "-" + strconv.FormatInt(time.Now().Unix(), 10)
    59  	return &TestCtx{
    60  		id: id,
    61  		t:  t,
    62  	}
    63  }
    64  
    65  func (ctx *TestCtx) GetID() string {
    66  	return ctx.id
    67  }
    68  
    69  func (ctx *TestCtx) Cleanup() {
    70  	failed := false
    71  	for i := len(ctx.cleanupFns) - 1; i >= 0; i-- {
    72  		err := ctx.cleanupFns[i]()
    73  		if err != nil {
    74  			failed = true
    75  			if ctx.t != nil {
    76  				ctx.t.Errorf("A cleanup function failed with error: (%v)\n", err)
    77  			} else {
    78  				log.Errorf("A cleanup function failed with error: (%v)", err)
    79  			}
    80  		}
    81  	}
    82  	if ctx.t == nil && failed {
    83  		log.Fatal("A cleanup function failed")
    84  	}
    85  }
    86  
    87  func (ctx *TestCtx) AddCleanupFn(fn cleanupFn) {
    88  	ctx.cleanupFns = append(ctx.cleanupFns, fn)
    89  }