Skip to content

[test] Add tests for cmd.newCompletionCmd#4082

Merged
lpcox merged 3 commits intomainfrom
test-coverage-completion-cmd-45d14009c011bd09
Apr 18, 2026
Merged

[test] Add tests for cmd.newCompletionCmd#4082
lpcox merged 3 commits intomainfrom
test-coverage-completion-cmd-45d14009c011bd09

Conversation

@github-actions
Copy link
Copy Markdown
Contributor

Test Coverage Improvement: newCompletionCmd

Function Analyzed

  • Package: internal/cmd
  • Function: newCompletionCmd
  • File: internal/cmd/completion.go
  • Previous Coverage: 0% (no test file existed)
  • New Coverage: ~100% (all branches covered)
  • Complexity: Medium — multi-case switch, Args validator, PersistentPreRunE override

Why This Function?

newCompletionCmd had zero test coverage despite being a user-facing CLI command. It contains:

  • A 4-way switch (bash / zsh / fish / powershell) where each case calls a different cobra generator
  • A default defensive error path that cobra's OnlyValidArgs normally prevents from being reached
  • A PersistentPreRunE override that intentionally skips the root command's config-file validation — a critical correctness property with no regression test

Previous agent runs (tracked in cache memory) had improved coverage for cmd.detectGuardWasm, oidc.extractJWTExpiry, and config.AllowOnlyPolicy, leaving this function as the next high-priority target.

Tests Added

  • Structure testUse, Short, Long, DisableFlagsInUseLine, and ValidArgs metadata
  • PersistentPreRunE override — always returns nil (no args or with args)
  • Args validation — table-driven: all 4 valid shells pass; empty, unknown shell, and 2-arg cases fail
  • Bash completion output — non-empty, contains shell-specific tokens
  • Zsh completion output — non-empty
  • Fish completion output — non-empty
  • PowerShell completion output — non-empty
  • Default branch fallback — calls RunE directly with unknown shell to exercise the defensive default case
  • All shells produce distinct output — regression guard preventing handler mix-ups
  • Parent PersistentPreRunE override — regression guard: completion succeeds even when root's PersistentPreRunE would fail (no config file)

Coverage Report

Before: 0% (no tests)
After:  ~100% (all branches covered, including defensive default)

Test Infrastructure

Tests use an isolated root command (newTestRootWithCompletion) to avoid triggering the real rootCmd's config-validation PersistentPreRunE. Output is captured via captureStdoutDuring, which uses os.Pipe() with immediate os.Stdout restoration (plus a t.Cleanup safety net) — safe for sequential calls within a single test.


Generated by Test Coverage Improver
Next candidates: internal/server/response_writer.go, validateCustomServerConfig, resolveGuardPolicyOverride

Warning

⚠️ Firewall blocked 2 domains

The following domains were blocked by the firewall during workflow execution:

  • proxy.golang.org
  • releaseassets.githubusercontent.com

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "proxy.golang.org"
    - "releaseassets.githubusercontent.com"

See Network Configuration for more information.

Generated by Test Coverage Improver · ● 3.8M ·

Comprehensive test coverage for the newCompletionCmd function in
internal/cmd/completion.go, which previously had zero test coverage.

Tests added:
- TestNewCompletionCmd_CommandStructure: verifies Use, Short, Long,
  DisableFlagsInUseLine, and ValidArgs metadata
- TestNewCompletionCmd_PersistentPreRunE: verifies the override always
  returns nil, bypassing the root's config-validation preRun
- TestNewCompletionCmd_ArgsValidation: table-driven test covering all
  four valid shells plus invalid cases (empty, unknown, too many args)
- TestNewCompletionCmd_BashOutput: verifies bash completion generates
  non-empty output with expected shell tokens
- TestNewCompletionCmd_ZshOutput: verifies zsh completion generates
  non-empty output
- TestNewCompletionCmd_FishOutput: verifies fish completion generates
  non-empty output
- TestNewCompletionCmd_PowerShellOutput: verifies powershell completion
  generates non-empty output
- TestNewCompletionCmd_DefaultCaseFallback: exercises the defensive
  default branch directly via RunE to achieve 100% branch coverage
- TestNewCompletionCmd_AllShellsProduceDifferentOutput: ensures each
  shell generates a distinct completion script
- TestNewCompletionCmd_OverridesParentPersistentPreRunE: regression
  guard confirming completions work without a config file

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@lpcox lpcox marked this pull request as ready for review April 18, 2026 15:59
Copilot AI review requested due to automatic review settings April 18, 2026 15:59
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds unit tests for the internal/cmd.newCompletionCmd Cobra subcommand to raise coverage from 0% to near-complete, including validation behavior and shell-specific completion generation.

Changes:

  • Introduces internal/cmd/completion_test.go covering command metadata, args validation, and PersistentPreRunE override behavior.
  • Executes completion for bash/zsh/fish/powershell and asserts non-empty output.
  • Directly exercises the defensive default branch in RunE for coverage.
Show a summary per file
File Description
internal/cmd/completion_test.go Adds comprehensive tests for the completion command, including output generation and pre-run override regression coverage.

Copilot's findings

Tip

Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

  • Files reviewed: 1/1 changed files
  • Comments generated: 1

Comment on lines +19 to +44
func captureStdoutDuring(t *testing.T, fn func()) string {
t.Helper()
r, w, err := os.Pipe()
require.NoError(t, err)

orig := os.Stdout
os.Stdout = w
// Safety net: restore if the function panics before we can restore manually.
t.Cleanup(func() {
if os.Stdout != orig {
os.Stdout = orig
}
})

fn()

w.Close()
os.Stdout = orig // restore immediately so repeated calls in the same test work

var buf bytes.Buffer
_, err = io.Copy(&buf, r)
r.Close()
require.NoError(t, err)

return buf.String()
}
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

captureStdoutDuring writes to an os.Pipe() and only starts reading from the pipe after fn() returns. If the completion generator writes more than the pipe buffer (common risk for shell completion scripts as the CLI grows), the write can block and the test can deadlock/hang. Consider draining r concurrently (start a goroutine to io.Copy into a buffer before calling fn()), and use defer to close w/restore os.Stdout so resources are cleaned up even if fn() panics.

Copilot uses AI. Check for mistakes.
@lpcox
Copy link
Copy Markdown
Collaborator

lpcox commented Apr 18, 2026

@copilot address the review feedback #4082 (review)

@lpcox lpcox merged commit 9b86c07 into main Apr 18, 2026
2 checks passed
@lpcox lpcox deleted the test-coverage-completion-cmd-45d14009c011bd09 branch April 18, 2026 16:15
Copilot stopped work on behalf of lpcox due to an error April 18, 2026 16:15
Copilot AI requested a review from lpcox April 18, 2026 16:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants