Skip to content

test(cmd): fix preRun tests to call preRun directly#60

Merged
feloy merged 1 commit intokortex-hub:mainfrom
feloy:prerun
Mar 12, 2026
Merged

test(cmd): fix preRun tests to call preRun directly#60
feloy merged 1 commit intokortex-hub:mainfrom
feloy:prerun

Conversation

@feloy
Copy link
Contributor

@feloy feloy commented Mar 11, 2026

The preRun tests in workspace_list_test.go and workspace_remove_test.go were incorrectly calling rootCmd.Execute() instead of testing the preRun method directly. This mixed Cobra wiring with unit test logic.

Updated tests to follow the pattern from init_test.go by creating command struct instances and calling c.preRun() directly. Moved Cobra argument validation tests to E2E test sections where they belong.

Also enhanced AGENTS.md with explicit examples showing the correct pattern for both unit tests (call preRun directly) and E2E tests (call Execute).

Closes #45

@codecov-commenter
Copy link

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@coderabbitai
Copy link

coderabbitai bot commented Mar 11, 2026

📝 Walkthrough

Walkthrough

Refactors command tests to favor direct invocation of preRun handlers in unit tests and expands AGENTS.md with explicit examples and guidance for both preRun unit tests and E2E tests. Adjusts workspace list/remove tests to wire Cobra flags locally and call preRun(cmd, args) directly.

Changes

Cohort / File(s) Summary
Documentation & Testing Guidance
AGENTS.md
Rewrote testing guidance: split preRun unit tests from E2E, added concrete Go examples showing instantiation of command structs, creation of a mock *cobra.Command, flag wiring, direct preRun(cmd, args) invocation, and E2E rootCmd.Execute() examples.
Workspace Command Tests
pkg/cmd/workspace_list_test.go, pkg/cmd/workspace_remove_test.go
Refactored tests to construct command instances and a local cobra.Command, set flags directly, and call preRun(cmd, args) to verify flag parsing, ID extraction, manager creation, and error cases; removed reliance on rootCmd.Execute() for preRun unit tests while keeping E2E scenarios separate. Added explicit cobra import in tests.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • feat: remove command #31: Related — refactors workspace_list/workspace_remove tests to invoke preRun directly and modifies overlapping test logic.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly describes the main change: refactoring preRun tests to call preRun directly instead of using rootCmd.Execute().
Description check ✅ Passed The description clearly explains the problem (incorrect test pattern), the solution (calling preRun directly), and documentation updates to AGENTS.md.
Linked Issues check ✅ Passed The PR fulfills issue #45 requirements: splits PreRun tests into unit and E2E patterns, updates tests to call preRun directly, and enhances AGENTS.md with explicit examples.
Out of Scope Changes check ✅ Passed All changes align with the linked issue scope: test refactoring, documentation updates to AGENTS.md, and no unrelated modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@feloy feloy requested review from benoitf and jeffmaury March 11, 2026 15:13
@feloy feloy closed this Mar 12, 2026
@feloy feloy reopened this Mar 12, 2026
The preRun tests in workspace_list_test.go and workspace_remove_test.go
were incorrectly calling rootCmd.Execute() instead of testing the
preRun method directly. This mixed Cobra wiring with unit test logic.

Updated tests to follow the pattern from init_test.go by creating
command struct instances and calling c.preRun() directly. Moved
Cobra argument validation tests to E2E test sections where they
belong.

Also enhanced AGENTS.md with explicit examples showing the correct
pattern for both unit tests (call preRun directly) and E2E tests
(call Execute).

Closes kortex-hub#45

Co-Authored-By: Claude Code (Claude Sonnet 4.5) <noreply@anthropic.com>
Signed-off-by: Philippe Martin <phmartin@redhat.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@AGENTS.md`:
- Around line 268-335: Update the examples and guidance to call t.Parallel() at
the parent test function level as the first line (unless using t.Setenv()),
e.g., add t.Parallel() at the top of TestMyCmd_PreRun and TestMyCmd_E2E before
any t.Run subtests; keep the inner subtests optionally parallel but ensure the
parent test functions begin with t.Parallel() and document the exception when
t.Setenv() is used; references: TestMyCmd_PreRun, TestMyCmd_E2E, c.preRun,
rootCmd.Execute.

In `@pkg/cmd/workspace_remove_test.go`:
- Around line 50-58: The test currently passes an absolute path from t.TempDir()
into cmd.Flags().String("storage", ...) so workspaceRemoveCmd.preRun() never
exercises filepath.Abs() normalization; change the test to pass a relative
storage path instead (e.g., create a temporary directory, derive a relative path
to it from the current working directory or chdir to the temp parent and use the
basename) when setting cmd.Flags().String("storage", ...), then call
workspaceRemoveCmd.preRun(cmd, args) and assert it still returns nil and that
c.storage (or the field set by preRun) contains the expected absolute path after
normalization by preRun.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7d103c8b-1604-4278-9aeb-50e57401cdcc

📥 Commits

Reviewing files that changed from the base of the PR and between 8cedcb7 and d7175eb.

📒 Files selected for processing (3)
  • AGENTS.md
  • pkg/cmd/workspace_list_test.go
  • pkg/cmd/workspace_remove_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cmd/workspace_list_test.go

Comment on lines +268 to +335
1. **Unit Tests** - Test the `preRun` method directly by calling it on the command struct:
- **IMPORTANT**: Create an instance of the command struct (e.g., `c := &initCmd{}`)
- **IMPORTANT**: Create a mock `*cobra.Command` and set up required flags
- **IMPORTANT**: Call `c.preRun(cmd, args)` directly - DO NOT call `rootCmd.Execute()`
- Use `t.Run()` for subtests within a parent test function
- Test with different argument/flag combinations
- Verify struct fields are set correctly
- Verify struct fields are set correctly after `preRun()` executes
- Use `t.TempDir()` for temporary directories (automatic cleanup)

2. **E2E Tests** - Test the full command execution:
- Execute via `rootCmd.Execute()`
**Example:**
```go
func TestMyCmd_PreRun(t *testing.T) {
t.Run("sets fields correctly", func(t *testing.T) {
t.Parallel()

storageDir := t.TempDir()

c := &myCmd{} // Create command struct instance
cmd := &cobra.Command{} // Create mock cobra command
cmd.Flags().String("storage", storageDir, "test storage flag")

args := []string{"arg1"}

err := c.preRun(cmd, args) // Call preRun directly
if err != nil {
t.Fatalf("preRun() failed: %v", err)
}

// Assert on struct fields
if c.manager == nil {
t.Error("Expected manager to be created")
}
})
}
```

2. **E2E Tests** - Test the full command execution including Cobra wiring:
- Execute via `rootCmd.Execute()` to test the complete flow
- Use real temp directories with `t.TempDir()`
- Verify output messages
- Verify persistence (check storage/database)
- Verify all field values from `manager.List()` or similar
- Test multiple scenarios (default args, custom args, edge cases)
- Test Cobra's argument validation (e.g., required args, arg counts)

**Example:**
```go
func TestMyCmd_E2E(t *testing.T) {
t.Run("executes successfully", func(t *testing.T) {
t.Parallel()

storageDir := t.TempDir()

rootCmd := NewRootCmd() // Use full command construction
rootCmd.SetArgs([]string{"mycommand", "arg1", "--storage", storageDir})

err := rootCmd.Execute() // Execute the full command
if err != nil {
t.Fatalf("Execute() failed: %v", err)
}

// Verify results in storage
manager, _ := instances.NewManager(storageDir)
instancesList, _ := manager.List()
// ... assert on results
})
}
```
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Make the test examples include parent-level t.Parallel().

Both new examples show t.Parallel() only inside the subtest, but the repo rule requires it as the first line of each test function unless t.Setenv() is involved. Since this file is the canonical guidance, the examples and bullet list should show that explicitly to avoid teaching the wrong pattern.

As per coding guidelines, "All Go test functions must call t.Parallel() as the first line of the test function, except for tests using t.Setenv() which cannot use t.Parallel() on the parent test function due to Go framework restrictions".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@AGENTS.md` around lines 268 - 335, Update the examples and guidance to call
t.Parallel() at the parent test function level as the first line (unless using
t.Setenv()), e.g., add t.Parallel() at the top of TestMyCmd_PreRun and
TestMyCmd_E2E before any t.Run subtests; keep the inner subtests optionally
parallel but ensure the parent test functions begin with t.Parallel() and
document the exception when t.Setenv() is used; references: TestMyCmd_PreRun,
TestMyCmd_E2E, c.preRun, rootCmd.Execute.

Comment on lines +50 to +58
storageDir := t.TempDir()

c := &workspaceRemoveCmd{}
cmd := &cobra.Command{}
cmd.Flags().String("storage", storageDir, "test storage flag")

args := []string{"test-workspace-id"}

err := c.preRun(cmd, args)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Exercise storage-path normalization with a relative path.

This subtest passes an already-absolute t.TempDir() value into --storage, so it never actually validates the filepath.Abs() step in workspaceRemoveCmd.preRun(). A regression in path normalization would still pass here. Consider feeding a relative storage path in this unit test and asserting the preRun setup still succeeds.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/cmd/workspace_remove_test.go` around lines 50 - 58, The test currently
passes an absolute path from t.TempDir() into cmd.Flags().String("storage", ...)
so workspaceRemoveCmd.preRun() never exercises filepath.Abs() normalization;
change the test to pass a relative storage path instead (e.g., create a
temporary directory, derive a relative path to it from the current working
directory or chdir to the temp parent and use the basename) when setting
cmd.Flags().String("storage", ...), then call workspaceRemoveCmd.preRun(cmd,
args) and assert it still returns nil and that c.storage (or the field set by
preRun) contains the expected absolute path after normalization by preRun.

@feloy feloy merged commit 7c98870 into kortex-hub:main Mar 12, 2026
6 checks passed
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

Successfully merging this pull request may close these issues.

tests: fix preRun tests

4 participants