k8s.io/kubernetes@v1.29.3/test/e2e/framework/internal/unittests/helpers.go (about)

     1  /*
     2  Copyright 2023 The Kubernetes 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 unittests
    18  
    19  import (
    20  	"bytes"
    21  	"flag"
    22  	"testing"
    23  
    24  	"github.com/stretchr/testify/require"
    25  	"k8s.io/kubernetes/test/e2e/framework"
    26  )
    27  
    28  // GetFrameworkOutput captures writes to framework.Output during a test suite setup
    29  // and returns it together with any explicit Exit call code, -1 if none.
    30  // May only be called once per test binary.
    31  func GetFrameworkOutput(t *testing.T, flags map[string]string) (output string, finalExitCode int) {
    32  	// This simulates how test/e2e uses the framework and how users
    33  	// invoke test/e2e.
    34  	framework.RegisterCommonFlags(flag.CommandLine)
    35  	framework.RegisterClusterFlags(flag.CommandLine)
    36  	for flagname, value := range flags {
    37  		require.NoError(t, flag.Set(flagname, value), "set %s", flagname)
    38  	}
    39  	var buffer bytes.Buffer
    40  	framework.Output = &buffer
    41  	framework.Exit = func(code int) {
    42  		panic(exitCode(code))
    43  	}
    44  	finalExitCode = -1
    45  	defer func() {
    46  		if r := recover(); r != nil {
    47  			if code, ok := r.(exitCode); ok {
    48  				finalExitCode = int(code)
    49  			} else {
    50  				panic(r)
    51  			}
    52  		}
    53  		output = buffer.String()
    54  	}()
    55  	framework.AfterReadingAllFlags(&framework.TestContext)
    56  
    57  	// Results set by defer.
    58  	return
    59  }
    60  
    61  type exitCode int