github.com/esnet/gdg@v0.6.1-0.20240412190737-6b6eba9c14d8/cli/test/support.go (about)

     1  package test
     2  
     3  import (
     4  	"github.com/esnet/gdg/cli/support"
     5  	"github.com/esnet/gdg/internal/config"
     6  	applog "github.com/esnet/gdg/internal/log"
     7  	"github.com/esnet/gdg/internal/service"
     8  	"github.com/esnet/gdg/internal/service/mocks"
     9  	"log/slog"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  	"io"
    13  	"os"
    14  	"testing"
    15  )
    16  
    17  // setupAndExecuteMockingServices  will create a mock for varous required entities allowing to test the CLI flag parsing
    18  // process: function that setups mocks and invokes the Execute command
    19  func setupAndExecuteMockingServices(t *testing.T, process func(mock *mocks.GrafanaService, data []byte, optionMockSvc func() support.RootOption) error) (string, func()) {
    20  	testSvc := new(mocks.GrafanaService)
    21  	getMockSvc := func() service.GrafanaService {
    22  		return testSvc
    23  	}
    24  
    25  	optionMockSvc := func() support.RootOption {
    26  		return func(response *support.RootCommand) {
    27  			response.GrafanaSvc = getMockSvc
    28  		}
    29  	}
    30  
    31  	r, w, cleanup := InterceptStdout()
    32  	data, err := os.ReadFile("../../config/testing.yml")
    33  	assert.Nil(t, err)
    34  
    35  	err = process(testSvc, data, optionMockSvc)
    36  	assert.Nil(t, err)
    37  	defer cleanup()
    38  	err = w.Close()
    39  	if err != nil {
    40  		slog.Warn("unable to close write stream")
    41  	}
    42  	clean := func() {
    43  		defer r.Close()
    44  	}
    45  	out, _ := io.ReadAll(r)
    46  	outStr := string(out)
    47  	return outStr, clean
    48  
    49  }
    50  
    51  // InterceptStdout is a test helper function that will redirect all stdout in and out to a different file stream.
    52  // It returns the stdout, stderr, and a function to be invoked to close the streams.
    53  func InterceptStdout() (*os.File, *os.File, func()) {
    54  	backupStd := os.Stdout
    55  	backupErr := os.Stderr
    56  	r, w, _ := os.Pipe()
    57  	//Restore streams
    58  	config.InitGdgConfig("testing", "")
    59  	applog.InitializeAppLogger(w, w, false)
    60  	cleanup := func() {
    61  		os.Stdout = backupStd
    62  		os.Stderr = backupErr
    63  		applog.InitializeAppLogger(os.Stdout, os.Stderr, false)
    64  
    65  	}
    66  	os.Stdout = w
    67  	os.Stderr = w
    68  
    69  	return r, w, cleanup
    70  
    71  }