Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to test inherited flags? #2249

Open
abitrolly opened this issue Mar 6, 2025 · 3 comments
Open

How to test inherited flags? #2249

abitrolly opened this issue Mar 6, 2025 · 3 comments

Comments

@abitrolly
Copy link

When I test Cobra command, I do this:

        cmd := NewCmdStatus(cmdutils.NewFactory())
        t.Run("no repo", func(t *testing.T) {
                err := cmd.Execute()
                assert.Error(t, err)
        })
        t.Run("no repo with -R", func(t *testing.T) {
                cmd.SetArgs([]string{"-R", "forkrepo"})
                err := cmd.Execute()
                assert.NoError(t, err)
        })

The problem is that -R is defined in parent command, so the test fails.

I tried to add the flag explicitly to NewCmdStatus, but that didn't work too.

cmd.InheritedFlags().StringP("repo", "R", "", "Select another repository.")

So how to test that?

@marckhouzam
Copy link
Collaborator

Try to use cmd.Flags().StringP(…)

@abitrolly
Copy link
Author

@marckhouzam then the flag won't appear in inherited flags section.

@marckhouzam
Copy link
Collaborator

Try cmd.PersistentFlags().StringP(…) instead. Although I’m not sure it will add it to the inherited flags on the current command.

An alternative is to create a fake root command in your test, add the flag as persistent and add your real command as a child of this fake root.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants