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