github.com/dgsb/consul@v1.4.5/command/intention/check/check_test.go (about)

     1  package check
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  
     7  	"github.com/hashicorp/consul/agent"
     8  	"github.com/hashicorp/consul/api"
     9  	"github.com/mitchellh/cli"
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func TestCommand_noTabs(t *testing.T) {
    14  	t.Parallel()
    15  	if strings.ContainsRune(New(nil).Help(), '\t') {
    16  		t.Fatal("help has tabs")
    17  	}
    18  }
    19  
    20  func TestCommand_Validation(t *testing.T) {
    21  	t.Parallel()
    22  
    23  	ui := cli.NewMockUi()
    24  	c := New(ui)
    25  
    26  	cases := map[string]struct {
    27  		args   []string
    28  		output string
    29  	}{
    30  		"0 args": {
    31  			[]string{},
    32  			"requires exactly two",
    33  		},
    34  
    35  		"1 args": {
    36  			[]string{"a"},
    37  			"requires exactly two",
    38  		},
    39  
    40  		"3 args": {
    41  			[]string{"a", "b", "c"},
    42  			"requires exactly two",
    43  		},
    44  	}
    45  
    46  	for name, tc := range cases {
    47  		t.Run(name, func(t *testing.T) {
    48  			require := require.New(t)
    49  
    50  			c.init()
    51  
    52  			// Ensure our buffer is always clear
    53  			if ui.ErrorWriter != nil {
    54  				ui.ErrorWriter.Reset()
    55  			}
    56  			if ui.OutputWriter != nil {
    57  				ui.OutputWriter.Reset()
    58  			}
    59  
    60  			require.Equal(2, c.Run(tc.args))
    61  			output := ui.ErrorWriter.String()
    62  			require.Contains(output, tc.output)
    63  		})
    64  	}
    65  }
    66  
    67  func TestCommand(t *testing.T) {
    68  	t.Parallel()
    69  
    70  	require := require.New(t)
    71  	a := agent.NewTestAgent(t, t.Name(), ``)
    72  	defer a.Shutdown()
    73  	client := a.Client()
    74  
    75  	// Create the intention
    76  	{
    77  		_, _, err := client.Connect().IntentionCreate(&api.Intention{
    78  			SourceName:      "web",
    79  			DestinationName: "db",
    80  			Action:          api.IntentionActionDeny,
    81  		}, nil)
    82  		require.NoError(err)
    83  	}
    84  
    85  	// Get it
    86  	{
    87  		ui := cli.NewMockUi()
    88  		c := New(ui)
    89  
    90  		args := []string{
    91  			"-http-addr=" + a.HTTPAddr(),
    92  			"foo", "db",
    93  		}
    94  		require.Equal(0, c.Run(args), ui.ErrorWriter.String())
    95  		require.Contains(ui.OutputWriter.String(), "Allow")
    96  	}
    97  
    98  	{
    99  		ui := cli.NewMockUi()
   100  		c := New(ui)
   101  
   102  		args := []string{
   103  			"-http-addr=" + a.HTTPAddr(),
   104  			"web", "db",
   105  		}
   106  		require.Equal(1, c.Run(args), ui.ErrorWriter.String())
   107  		require.Contains(ui.OutputWriter.String(), "Denied")
   108  	}
   109  }