Skip to content

fix: persistentPreRun overwrites injected writer, complicating test authoring #220

@jmeridth

Description

@jmeridth

What

persistentPreRun in cli.go unconditionally sets c.writer = tabwriter.NewWriter(os.Stdout, ...). Tests use newTestCLI to inject a buffer-backed writer, but if a test ever calls c.rootCmd.Execute() instead of directly invoking cmd.Run(), the Cobra hook chain fires persistentPreRun which overwrites the test writer with os.Stdout, silently breaking buffer assertions.

Why

This is a latent trap for future test authors. Current tests work because they bypass the hook chain, but the divergence between test and production execution paths is fragile.

Suggested fix

Guard the writer assignment in persistentPreRun to only set it when nil:

if c.writer == nil {
    c.writer = tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
}

Or document the constraint in newTestCLI.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions