github.com/verrazzano/verrazzano@v1.7.1/pkg/k8sutil/fake/spdy_executor.go (about)

     1  // Copyright (c) 2021, 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package fake
     5  
     6  import (
     7  	"bytes"
     8  	"net/url"
     9  
    10  	"k8s.io/client-go/rest"
    11  	"k8s.io/client-go/tools/remotecommand"
    12  )
    13  
    14  // PodExecResult can be used to output arbitrary strings during unit testing
    15  var PodExecResult = func(url *url.URL) (string, string, error) { return "", "", nil }
    16  
    17  // NewPodExecutor should be used instead of remotecommand.NewSPDYExecutor in unit tests
    18  func NewPodExecutor(config *rest.Config, method string, url *url.URL) (remotecommand.Executor, error) {
    19  	return &dummyExecutor{method: method, url: url}, nil
    20  }
    21  
    22  // dummyExecutor is for unit testing
    23  type dummyExecutor struct {
    24  	method string
    25  	url    *url.URL
    26  }
    27  
    28  // Stream on a dummyExecutor sets stdout to PodExecResult
    29  func (f *dummyExecutor) Stream(options remotecommand.StreamOptions) error {
    30  	stdout, stderr, err := PodExecResult(f.url)
    31  	if options.Stdout != nil {
    32  		buf := new(bytes.Buffer)
    33  		buf.WriteString(stdout)
    34  		if _, err := options.Stdout.Write(buf.Bytes()); err != nil {
    35  			return err
    36  		}
    37  	}
    38  	if options.Stderr != nil {
    39  		buf := new(bytes.Buffer)
    40  		buf.WriteString(stderr)
    41  		if _, err := options.Stderr.Write(buf.Bytes()); err != nil {
    42  			return err
    43  		}
    44  	}
    45  	return err
    46  }