Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Improve test isolation when exercising Cobra commands #759

@mislav

Description

@mislav

In both runtime and tests, we only ever initialize one instance of every cobra.Command. When repeatedly running tests, we reuse the same Command instance.

The problem is that a Command seems to keep state and that it's hard to reset some of that state. For example, its FlagSet remembers the values of flags that were passed, which forced us to maintain some ad-hoc resetting code to improve isolation between tests

cli/command/pr_test.go

Lines 55 to 67 in c0c2862

// Reset flag values so they don't leak between tests
// FIXME: change how we initialize Cobra commands to render this hack unnecessary
cmd.Flags().VisitAll(func(f *pflag.Flag) {
switch v := f.Value.(type) {
case pflag.SliceValue:
_ = v.Replace([]string{})
default:
switch v.Type() {
case "bool", "string", "int":
_ = v.Set(f.DefValue)
}
}
})

A better approach would be to instantiate a new Command every time we run a test. A prerequisite for that would be to define a factory method for each currently available Command. We would also use these factories to assemble the command tree at runtime.

Metadata

Metadata

Assignees

No one assigned

    Labels

    tech-debtA chore that addresses technical debt

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions