1package command 2 3import ( 4 "reflect" 5 "strings" 6 "testing" 7 8 "github.com/mitchellh/cli" 9) 10 11func testPolicyDeleteCommand(tb testing.TB) (*cli.MockUi, *PolicyDeleteCommand) { 12 tb.Helper() 13 14 ui := cli.NewMockUi() 15 return ui, &PolicyDeleteCommand{ 16 BaseCommand: &BaseCommand{ 17 UI: ui, 18 }, 19 } 20} 21 22func TestPolicyDeleteCommand_Run(t *testing.T) { 23 t.Parallel() 24 25 cases := []struct { 26 name string 27 args []string 28 out string 29 code int 30 }{ 31 { 32 "not_enough_args", 33 nil, 34 "Not enough arguments", 35 1, 36 }, 37 { 38 "too_many_args", 39 []string{"foo", "bar"}, 40 "Too many arguments", 41 1, 42 }, 43 } 44 45 t.Run("validations", func(t *testing.T) { 46 t.Parallel() 47 48 for _, tc := range cases { 49 tc := tc 50 51 t.Run(tc.name, func(t *testing.T) { 52 t.Parallel() 53 54 client, closer := testVaultServer(t) 55 defer closer() 56 57 ui, cmd := testPolicyDeleteCommand(t) 58 cmd.client = client 59 60 code := cmd.Run(tc.args) 61 if code != tc.code { 62 t.Errorf("expected %d to be %d", code, tc.code) 63 } 64 65 combined := ui.OutputWriter.String() + ui.ErrorWriter.String() 66 if !strings.Contains(combined, tc.out) { 67 t.Errorf("expected %q to contain %q", combined, tc.out) 68 } 69 }) 70 } 71 }) 72 73 t.Run("integration", func(t *testing.T) { 74 t.Parallel() 75 76 client, closer := testVaultServer(t) 77 defer closer() 78 79 policy := `path "secret/" {}` 80 if err := client.Sys().PutPolicy("my-policy", policy); err != nil { 81 t.Fatal(err) 82 } 83 84 ui, cmd := testPolicyDeleteCommand(t) 85 cmd.client = client 86 87 code := cmd.Run([]string{ 88 "my-policy", 89 }) 90 if exp := 0; code != exp { 91 t.Errorf("expected %d to be %d", code, exp) 92 } 93 94 expected := "Success! Deleted policy: my-policy" 95 combined := ui.OutputWriter.String() + ui.ErrorWriter.String() 96 if !strings.Contains(combined, expected) { 97 t.Errorf("expected %q to contain %q", combined, expected) 98 } 99 100 policies, err := client.Sys().ListPolicies() 101 if err != nil { 102 t.Fatal(err) 103 } 104 105 list := []string{"default", "root"} 106 if !reflect.DeepEqual(policies, list) { 107 t.Errorf("expected %q to be %q", policies, list) 108 } 109 }) 110 111 t.Run("communication_failure", func(t *testing.T) { 112 t.Parallel() 113 114 client, closer := testVaultServerBad(t) 115 defer closer() 116 117 ui, cmd := testPolicyDeleteCommand(t) 118 cmd.client = client 119 120 code := cmd.Run([]string{ 121 "my-policy", 122 }) 123 if exp := 2; code != exp { 124 t.Errorf("expected %d to be %d", code, exp) 125 } 126 127 expected := "Error deleting my-policy: " 128 combined := ui.OutputWriter.String() + ui.ErrorWriter.String() 129 if !strings.Contains(combined, expected) { 130 t.Errorf("expected %q to contain %q", combined, expected) 131 } 132 }) 133 134 t.Run("no_tabs", func(t *testing.T) { 135 t.Parallel() 136 137 _, cmd := testPolicyDeleteCommand(t) 138 assertNoTabs(t, cmd) 139 }) 140} 141