Skip to content

test: expand shared utility coverage#16

Open
guoqqqi wants to merge 2 commits intoapi7:mainfrom
guoqqqi:test/shared-coverage-followups
Open

test: expand shared utility coverage#16
guoqqqi wants to merge 2 commits intoapi7:mainfrom
guoqqqi:test/shared-coverage-followups

Conversation

@guoqqqi
Copy link
Copy Markdown

@guoqqqi guoqqqi commented Apr 10, 2026

Summary

  • add selector tests for non-terminal and invalid-item edge cases
  • add tableprinter tests for empty render, tabular output, and flush failures
  • add comprehensive configutil coverage for file parsing, diff helpers, pagination, plugin metadata, and secret ID extraction

Validation

  • GOCACHE=/tmp/go-build-a6 GOMODCACHE=/tmp/gomod-a6 go test ./pkg/selector ./pkg/tableprinter ./pkg/cmd/config/configutil

Refs #14

Summary by CodeRabbit

  • Tests
    • Added comprehensive test coverage for configuration file parsing, diff computation, and formatting operations.
    • Added tests validating selector behavior with missing identifiers and terminal requirements.
    • Added tests for table rendering with various data scenarios and error conditions.

Copilot AI review requested due to automatic review settings April 10, 2026 02:52
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 10, 2026

Warning

Rate limit exceeded

@guoqqqi has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 7 minutes and 26 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 7 minutes and 26 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 12dc5a45-df87-47fb-9b78-4fa6052f4ee9

📥 Commits

Reviewing files that changed from the base of the PR and between c613a58 and 5b9a815.

📒 Files selected for processing (2)
  • pkg/selector/selector.go
  • pkg/selector/selector_test.go
📝 Walkthrough

Walkthrough

This pull request adds three new test files to the project. The configutil_test.go file introduces comprehensive unit tests for configuration utilities, including tests for diff operations, file parsing, and HTTP-based resource fetching. Additional test cases are added to selector_test.go for error conditions, and a new table_test.go file provides unit tests for table rendering functionality.

Changes

Cohort / File(s) Summary
Config Utilities Tests
pkg/cmd/config/configutil/configutil_test.go
Comprehensive test suite covering diff operations (CreateCount, UpdateCount, DeleteCount), configuration file parsing (JSON/YAML), diff computation and classification, helper functions (key extraction, map normalization, secret path parsing), paginated HTTP requests, and plugin metadata fetching with error scenarios and 404 handling.
Selector Tests
pkg/selector/selector_test.go
New test cases for missing item IDs and terminal requirement validation, with error assertions and imports for os, path/filepath, and require.
Table Printer Tests
pkg/tableprinter/table_test.go
Unit tests for table rendering including empty tables, header and row rendering with output validation, row counting, and error propagation via custom failing writer.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
E2e Test Quality Review ⚠️ Warning PR adds isolated unit tests for utility packages, not end-to-end tests covering full business flows with real integrations and dependencies. Supplement with E2E tests exercising utilities through realistic application workflows involving real service dependencies and external integrations.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'test: expand shared utility coverage' accurately describes the main change—adding comprehensive unit tests across three shared utility packages (selector, tableprinter, configutil).
Security Check ✅ Passed Test files contain no hardcoded secrets, API keys, tokens, or credentials. HTTP mocking properly abstracts external dependencies without exposing sensitive data.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Copy link
Copy Markdown

@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.

🧹 Nitpick comments (2)
pkg/selector/selector_test.go (1)

29-43: Serialize os.Stdin swapping to avoid future test flakiness.

This test mutates process-global stdin. It’s safe today, but can race if package tests later use parallel execution. Consider guarding the swap with a package-level mutex.

🔧 Suggested hardening
 import (
 	"os"
 	"path/filepath"
+	"sync"
 	"testing"

 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 )
+
+var stdinSwapMu sync.Mutex

 func TestSelectOne_RequiresTerminal(t *testing.T) {
+	stdinSwapMu.Lock()
+	t.Cleanup(stdinSwapMu.Unlock)
+
 	tmpDir := t.TempDir()
 	inputPath := filepath.Join(tmpDir, "stdin.txt")
 	require.NoError(t, os.WriteFile(inputPath, []byte("not-a-tty"), 0o644))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/selector/selector_test.go` around lines 29 - 43, Test mutates global
os.Stdin in TestSelectOne_RequiresTerminal causing potential races; add a
package-level mutex (e.g., var stdinMu sync.Mutex) and lock it before swapping
os.Stdin in TestSelectOne_RequiresTerminal, then in the t.Cleanup restore the
original stdin and unlock the mutex so the swap/un-swap is protected; ensure the
mutex is declared at package scope and used around any other tests that touch
os.Stdin.
pkg/cmd/config/configutil/configutil_test.go (1)

45-49: Avoid positional assertions for section names unless order is a contract.

These checks are brittle against harmless Sections() reordering. Prefer validating expected names are present without index coupling.

🔧 Suggested assertion style
 	sections := result.Sections()
 	require.Len(t, sections, 12)
-	assert.Equal(t, "upstreams", sections[0].Name)
-	assert.Equal(t, "stream_routes", sections[len(sections)-1].Name)
+	names := make([]string, 0, len(sections))
+	for _, s := range sections {
+		names = append(names, s.Name)
+	}
+	assert.Contains(t, names, "upstreams")
+	assert.Contains(t, names, "stream_routes")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/cmd/config/configutil/configutil_test.go` around lines 45 - 49, The test
is brittle because it asserts section names by position (using sections[0].Name
and sections[len(sections)-1].Name) instead of checking presence; change the
assertions to validate that the expected section names appear in the slice
returned by result.Sections() (e.g., extract all section.Name values from the
Sections() result and use membership/collection assertions like assert.Contains
or require.ElementsMatch) and remove the index-dependent checks so the test does
not depend on ordering; keep references to Sections() and the Name field when
locating the code to update.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@pkg/cmd/config/configutil/configutil_test.go`:
- Around line 45-49: The test is brittle because it asserts section names by
position (using sections[0].Name and sections[len(sections)-1].Name) instead of
checking presence; change the assertions to validate that the expected section
names appear in the slice returned by result.Sections() (e.g., extract all
section.Name values from the Sections() result and use membership/collection
assertions like assert.Contains or require.ElementsMatch) and remove the
index-dependent checks so the test does not depend on ordering; keep references
to Sections() and the Name field when locating the code to update.

In `@pkg/selector/selector_test.go`:
- Around line 29-43: Test mutates global os.Stdin in
TestSelectOne_RequiresTerminal causing potential races; add a package-level
mutex (e.g., var stdinMu sync.Mutex) and lock it before swapping os.Stdin in
TestSelectOne_RequiresTerminal, then in the t.Cleanup restore the original stdin
and unlock the mutex so the swap/un-swap is protected; ensure the mutex is
declared at package scope and used around any other tests that touch os.Stdin.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 00784beb-6500-4770-a17e-e25fbeb888a4

📥 Commits

Reviewing files that changed from the base of the PR and between 85d58d7 and c613a58.

📒 Files selected for processing (3)
  • pkg/cmd/config/configutil/configutil_test.go
  • pkg/selector/selector_test.go
  • pkg/tableprinter/table_test.go

Copy link
Copy Markdown

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

This PR expands unit test coverage for shared utilities to address edge cases and error paths called out in Issue #14.

Changes:

  • Added selector tests for missing IDs and non-terminal stdin behavior.
  • Added tableprinter tests for empty renders, tabular output, and flush/write failures.
  • Added broad configutil tests for file parsing, diff helpers, pagination fetching, plugin metadata fetching, and secret ID extraction.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
pkg/tableprinter/table_test.go Adds TablePrinter rendering/flush error-path coverage.
pkg/selector/selector_test.go Adds SelectOne edge-case coverage (invalid items, non-terminal stdin).
pkg/cmd/config/configutil/configutil_test.go Adds comprehensive coverage for config parsing, diff/summary, pagination helpers, plugin metadata, and secret ID parsing.

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

Comment on lines +18 to +27
func TestSelectOne_AllItemsMissingIDs(t *testing.T) {
items := []Item{
{ID: "", Label: "first"},
{ID: "", Label: "second"},
}

_, err := SelectOne("Select a route", items)
require.Error(t, err)
assert.Contains(t, err.Error(), "no items available")
}
Copy link

Copilot AI Apr 10, 2026

Choose a reason for hiding this comment

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

TestSelectOne_AllItemsMissingIDs is likely to fail in CI/non-interactive runs: SelectOne checks isTerminalStdin() before filtering out items with empty IDs, so when stdin is not a TTY it returns interactive selection requires a terminal instead of no items available. To make this test deterministic, either (a) arrange for os.Stdin to be a TTY/pty for this test (skipping if unavailable), or (b) adjust SelectOne to build/filter options first and only require a terminal when there are selectable options.

Copilot uses AI. Check for mistakes.
@guoqqqi
Copy link
Copy Markdown
Author

guoqqqi commented Apr 10, 2026

Addressed the selector determinism feedback in a follow-up commit. I did not change the DiffResult.Sections() order assertions: that order is intentional in production code (base resources first, then dependents), so the test is verifying a documented contract rather than incidental slice ordering.

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.

2 participants