|
| 1 | +package cmdutil |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/spf13/cobra" |
| 7 | + "github.com/stretchr/testify/require" |
| 8 | +) |
| 9 | + |
| 10 | +// Test_EnableRepoOverride_authCheckIntegration is an integration test for the |
| 11 | +// coupling between repo override and the root auth gate, wired through cobra's |
| 12 | +// persistent pre-run hooks. EnableRepoOverride replaces a command's |
| 13 | +// PersistentPreRunE, so cobra no longer reaches the root auth gate on its own; |
| 14 | +// the override hook re-runs the ancestor hooks itself. That re-run must evaluate |
| 15 | +// the command the user actually invoked, the same way cobra hands the target |
| 16 | +// command to parent hooks: |
| 17 | +// https://github.com/spf13/cobra/blob/v1.10.2/command.go#L984-L986 |
| 18 | +// This pins that a leaf's DisableAuthCheck is honored under a repo-override |
| 19 | +// parent. |
| 20 | +func Test_EnableRepoOverride_authCheckIntegration(t *testing.T) { |
| 21 | + tests := []struct { |
| 22 | + name string |
| 23 | + disableAuthLeaf bool |
| 24 | + wantAuthChecked bool |
| 25 | + }{ |
| 26 | + { |
| 27 | + name: "leaf opts out, honored under repo-override parent", |
| 28 | + disableAuthLeaf: true, |
| 29 | + wantAuthChecked: false, |
| 30 | + }, |
| 31 | + { |
| 32 | + name: "leaf does not opt out, auth still checked", |
| 33 | + disableAuthLeaf: false, |
| 34 | + wantAuthChecked: true, |
| 35 | + }, |
| 36 | + } |
| 37 | + |
| 38 | + for _, tt := range tests { |
| 39 | + t.Run(tt.name, func(t *testing.T) { |
| 40 | + var gotAuthChecked, ranLeaf bool |
| 41 | + |
| 42 | + // Stand in for the real root auth gate: it judges whatever command |
| 43 | + // it is handed, so it must receive the invoked leaf command. |
| 44 | + root := &cobra.Command{Use: "root"} |
| 45 | + root.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { |
| 46 | + gotAuthChecked = IsAuthCheckEnabled(cmd) |
| 47 | + return nil |
| 48 | + } |
| 49 | + |
| 50 | + parent := &cobra.Command{Use: "parent"} |
| 51 | + EnableRepoOverride(parent, &Factory{}) |
| 52 | + root.AddCommand(parent) |
| 53 | + |
| 54 | + leaf := &cobra.Command{ |
| 55 | + Use: "leaf", |
| 56 | + RunE: func(cmd *cobra.Command, args []string) error { ranLeaf = true; return nil }, |
| 57 | + } |
| 58 | + if tt.disableAuthLeaf { |
| 59 | + DisableAuthCheck(leaf) |
| 60 | + } |
| 61 | + parent.AddCommand(leaf) |
| 62 | + |
| 63 | + root.SetArgs([]string{"parent", "leaf"}) |
| 64 | + require.NoError(t, root.Execute()) |
| 65 | + |
| 66 | + require.True(t, ranLeaf, "leaf command should have executed") |
| 67 | + require.Equal(t, tt.wantAuthChecked, gotAuthChecked) |
| 68 | + }) |
| 69 | + } |
| 70 | +} |
0 commit comments