1package command
2
3import (
4	"strings"
5	"testing"
6
7	"github.com/hashicorp/nomad/acl"
8	"github.com/hashicorp/nomad/command/agent"
9	"github.com/hashicorp/nomad/nomad/mock"
10	"github.com/hashicorp/nomad/nomad/structs"
11	"github.com/mitchellh/cli"
12	"github.com/stretchr/testify/assert"
13)
14
15func TestACLPolicyListCommand(t *testing.T) {
16	assert := assert.New(t)
17	t.Parallel()
18	config := func(c *agent.Config) {
19		c.ACL.Enabled = true
20	}
21
22	srv, _, url := testServer(t, true, config)
23	state := srv.Agent.Server().State()
24	defer srv.Shutdown()
25
26	// Bootstrap an initial ACL token
27	token := srv.RootToken
28	assert.NotNil(token, "failed to bootstrap ACL token")
29
30	// Create a test ACLPolicy
31	policy := &structs.ACLPolicy{
32		Name:  "testPolicy",
33		Rules: acl.PolicyWrite,
34	}
35	policy.SetHash()
36	assert.Nil(state.UpsertACLPolicies(1000, []*structs.ACLPolicy{policy}))
37
38	ui := new(cli.MockUi)
39	cmd := &ACLPolicyListCommand{Meta: Meta{Ui: ui, flagAddress: url}}
40
41	// Attempt to list policies without a valid management token
42	invalidToken := mock.ACLToken()
43	code := cmd.Run([]string{"-address=" + url, "-token=" + invalidToken.SecretID})
44	assert.Equal(1, code)
45
46	// Apply a policy with a valid management token
47	code = cmd.Run([]string{"-address=" + url, "-token=" + token.SecretID})
48	assert.Equal(0, code)
49
50	// Check the output
51	out := ui.OutputWriter.String()
52	if !strings.Contains(out, policy.Name) {
53		t.Fatalf("bad: %v", out)
54	}
55
56	// List json
57	if code := cmd.Run([]string{"-address=" + url, "-token=" + token.SecretID, "-json"}); code != 0 {
58		t.Fatalf("expected exit 0, got: %d; %v", code, ui.ErrorWriter.String())
59	}
60	out = ui.OutputWriter.String()
61	if !strings.Contains(out, "CreateIndex") {
62		t.Fatalf("expected json output, got: %s", out)
63	}
64	ui.OutputWriter.Reset()
65}
66