...

Source file src/github.com/ory/x/cmdx/noise_printer_test.go

Documentation: github.com/ory/x/cmdx

     1  package cmdx
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/spf13/cobra"
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func TestConditionalPrinter(t *testing.T) {
    15  	const (
    16  		msgAlwaysOut = "always out"
    17  		msgAlwaysErr = "always err"
    18  		msgQuietOut  = "quiet out"
    19  		msgQuietErr  = "quiet err"
    20  		msgLoudOut   = "loud out"
    21  		msgLoudErr   = "loud err"
    22  		msgArgsSet   = "args were set"
    23  	)
    24  	setup := func() *cobra.Command {
    25  		cmd := &cobra.Command{
    26  			Use: "test cmd",
    27  			Run: func(cmd *cobra.Command, args []string) {
    28  				_, _ = fmt.Fprint(cmd.OutOrStdout(), msgAlwaysOut)
    29  				_, _ = fmt.Fprint(cmd.ErrOrStderr(), msgAlwaysErr)
    30  				_, _ = NewQuietOutPrinter(cmd).Print(msgQuietOut)
    31  				_, _ = NewQuietErrPrinter(cmd).Print(msgQuietErr)
    32  				_, _ = NewLoudOutPrinter(cmd).Print(msgLoudOut)
    33  				_, _ = NewLoudErrPrinter(cmd).Print(msgLoudErr)
    34  				_, _ = NewConditionalPrinter(cmd.OutOrStdout(), len(args) > 0).Print(msgArgsSet)
    35  			},
    36  		}
    37  		RegisterNoiseFlags(cmd.Flags())
    38  		return cmd
    39  	}
    40  
    41  	for _, tc := range []struct {
    42  		stdErrMsg, stdOutMsg, args []string
    43  		setQuiet                   bool
    44  	}{
    45  		{
    46  			stdOutMsg: []string{msgLoudOut},
    47  			stdErrMsg: []string{msgLoudErr},
    48  			setQuiet:  false,
    49  			args:      []string{},
    50  		},
    51  		{
    52  			stdOutMsg: []string{msgQuietOut},
    53  			stdErrMsg: []string{msgQuietErr},
    54  			setQuiet:  true,
    55  			args:      []string{},
    56  		},
    57  		{
    58  			stdOutMsg: []string{msgQuietOut, msgArgsSet},
    59  			stdErrMsg: []string{msgQuietErr},
    60  			setQuiet:  true,
    61  			args:      []string{"foo"},
    62  		},
    63  	} {
    64  		t.Run(fmt.Sprintf("case=quiet:%v", tc.setQuiet), func(t *testing.T) {
    65  			cmd := setup()
    66  			if tc.setQuiet {
    67  				require.NoError(t, cmd.Flags().Set(FlagQuiet, "true"))
    68  			}
    69  			out, err := &bytes.Buffer{}, &bytes.Buffer{}
    70  			cmd.SetOut(out)
    71  			cmd.SetErr(err)
    72  			cmd.SetArgs(tc.args)
    73  
    74  			require.NoError(t, cmd.Execute())
    75  			assert.Equal(t, strings.Join(append([]string{msgAlwaysOut}, tc.stdOutMsg...), ""), out.String())
    76  			assert.Equal(t, strings.Join(append([]string{msgAlwaysErr}, tc.stdErrMsg...), ""), err.String())
    77  		})
    78  	}
    79  }
    80  

View as plain text