Skip to content

test: keybind + git utilities — parsing, matching, error handling#485

Closed
anandgupta42 wants to merge 1 commit intomainfrom
test/hourly-20260326-2115
Closed

test: keybind + git utilities — parsing, matching, error handling#485
anandgupta42 wants to merge 1 commit intomainfrom
test/hourly-20260326-2115

Conversation

@anandgupta42
Copy link
Contributor

@anandgupta42 anandgupta42 commented Mar 26, 2026

What does this PR do?

Adds 27 new tests across two previously untested utility modules that are widely used in critical code paths.

1. Keybindsrc/util/keybind.ts (22 new tests)

This module powers keyboard shortcut parsing, matching, and display across 6+ TUI components (dialog-select, textarea-keybindings, dialog-mcp, dialog-skill, permission, keybind context). Zero tests existed. A parsing bug would silently break user keybindings. New coverage includes:

  • parse(): simple keys, modifier combos (ctrl+shift+a), all meta aliases (alt/meta/option), super modifier, <leader> prefix, escescape normalization, "none" sentinel, comma-separated multi-bindings
  • toString(): modifier ordering, deletedel mapping, leader prefix formatting, undefined handling
  • match(): identical bindings, undefined first arg, super field normalization (undefined treated as false), non-matching keys
  • Roundtrip: parse → toString for ctrl+shift+a, and verification that meta aliases (meta/option) normalize to alt on roundtrip (lossy but correct behavior)

2. git()src/util/git.ts (5 new tests)

This thin wrapper around Process.run is used in 8+ files (file/index, project, vcs, storage, github, pr, worktree). It shapes Process.run results into GitResult and has a .catch() branch for thrown errors. Zero tests existed. New coverage includes:

  • Happy path: rev-parse returns stdout with exitCode 0
  • Unknown subcommand returns non-zero exit code
  • stderr is populated on checkout of nonexistent branch
  • Custom env vars are passed through (verified via GIT_CONFIG_COUNT injection — the config value only exists because of the env var)
  • Non-existent cwd returns exitCode != 0 with empty stdout

Type of change

  • New feature (non-breaking change which adds functionality)

Issue for this PR

N/A — proactive test coverage via /test-discovery

How did you verify your code works?

bun test test/util/keybind.test.ts   # 22 pass
bun test test/util/git.test.ts       #  5 pass

Checklist

  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

https://claude.ai/code/session_014mq5rKy5AhzTbSNH9rhxFF

Summary by CodeRabbit

  • Tests
    • Added comprehensive test coverage for git operations and keybinding functionality to ensure reliability and correct behavior across the codebase.

Add 27 tests for two untested utility modules that are used across multiple
critical code paths (TUI keybindings, git operations in 8+ files).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

https://claude.ai/code/session_014mq5rKy5AhzTbSNH9rhxFF
Copy link

@claude claude bot left a comment

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review and subscribe this PR to future pushes, or @claude review once for a one-time review.

Tip: disable this comment in your organization's Code Review settings.

@coderabbitai
Copy link

coderabbitai bot commented Mar 26, 2026

📝 Walkthrough

Walkthrough

Two new test suites added for git and keybind utilities. The git test suite validates command execution, exit codes, stderr handling, environment variable propagation, and error cases. The keybind test suite covers parsing, string formatting, matching logic, and roundtrip transformations.

Changes

Cohort / File(s) Summary
Test Utilities
packages/opencode/test/util/git.test.ts, packages/opencode/test/util/keybind.test.ts
Added comprehensive test suites for git and keybind utilities with coverage for success cases, error handling, environment variables, edge cases, and roundtrip transformations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

contributor

Poem

🐰 Tests now guard the git and key,
Each case checked with certainty,
Parse and bind with confidence true,
The code hops forward, shiny and new!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change—adding tests for keybind and git utilities with focus on parsing, matching, and error handling.
Description check ✅ Passed The description covers all required sections: summary of what changed and why, detailed test plan with verification commands, and completed checklist. All critical information is present and well-organized.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test/hourly-20260326-2115

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

@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)
packages/opencode/test/util/keybind.test.ts (1)

45-49: Consider adding a test for <leader> without a following key.

The parse tests cover <leader>a but don't test <leader> alone. While toString tests this case (lines 99-104), a corresponding parse test would ensure symmetry.

Optional test for parsing leader-only binding
   test("parses <leader> prefix", () => {
     const [info] = Keybind.parse("<leader>a")
     expect(info.leader).toBe(true)
     expect(info.name).toBe("a")
   })
+
+  test("parses <leader> without following key", () => {
+    const [info] = Keybind.parse("<leader>")
+    expect(info.leader).toBe(true)
+    expect(info.name).toBe("")
+  })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/opencode/test/util/keybind.test.ts` around lines 45 - 49, Add a unit
test that calls Keybind.parse("<leader>") and asserts the parsed result marks
leader as true and has an empty name to mirror the existing toString coverage;
locate the test near the other parse cases (the existing "parses <leader>
prefix" test) and assert on Keybind.parse's returned info.leader and info.name
(expect info.leader toBe(true) and info.name toBe("")).
packages/opencode/test/util/git.test.ts (1)

52-56: Hardcoded /tmp/ path may not be portable across platforms.

The path /tmp/nonexistent-dir-... assumes a Unix-like filesystem. On Windows, this path doesn't exist and the test behavior may differ (though it would still fail with a non-zero exit code). Consider using path.join(os.tmpdir(), ...) for better portability, or document that this test is Unix-specific.

Portable alternative using Node's os.tmpdir()
+import * as os from "os"
+import * as path from "path"
+
 // ...
 
   test("returns exitCode 1 and empty stdout when cwd does not exist", async () => {
-    const result = await git(["status"], { cwd: "/tmp/nonexistent-dir-" + Math.random().toString(36) })
+    const nonexistentPath = path.join(os.tmpdir(), "nonexistent-dir-" + Math.random().toString(36))
+    const result = await git(["status"], { cwd: nonexistentPath })
     expect(result.exitCode).not.toBe(0)
     expect(result.stdout.length).toBe(0)
   })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/opencode/test/util/git.test.ts` around lines 52 - 56, The test uses
a hardcoded "/tmp/..." path which isn't portable; update the test that calls
git(["status"], { cwd: ... }) to construct the non-existent directory using
Node's os.tmpdir() and path.join (e.g., path.join(os.tmpdir(),
`nonexistent-dir-${Math.random().toString(36)}`)), and add the necessary imports
for os and path at the top of the test file; keep the assertion logic the same
so the test still expects a non-zero exitCode and empty stdout.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/opencode/test/util/git.test.ts`:
- Around line 52-56: The test uses a hardcoded "/tmp/..." path which isn't
portable; update the test that calls git(["status"], { cwd: ... }) to construct
the non-existent directory using Node's os.tmpdir() and path.join (e.g.,
path.join(os.tmpdir(), `nonexistent-dir-${Math.random().toString(36)}`)), and
add the necessary imports for os and path at the top of the test file; keep the
assertion logic the same so the test still expects a non-zero exitCode and empty
stdout.

In `@packages/opencode/test/util/keybind.test.ts`:
- Around line 45-49: Add a unit test that calls Keybind.parse("<leader>") and
asserts the parsed result marks leader as true and has an empty name to mirror
the existing toString coverage; locate the test near the other parse cases (the
existing "parses <leader> prefix" test) and assert on Keybind.parse's returned
info.leader and info.name (expect info.leader toBe(true) and info.name
toBe("")).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5f8df291-efbd-409a-b4c9-cc86e1fc3a55

📥 Commits

Reviewing files that changed from the base of the PR and between abcaa1d and 8fa12f7.

📒 Files selected for processing (2)
  • packages/opencode/test/util/git.test.ts
  • packages/opencode/test/util/keybind.test.ts

anandgupta42 added a commit that referenced this pull request Mar 27, 2026
Consolidates tests from PRs #440, #441, #479, #483, #484, #485, #490, #491, #492, #495, #496.
Deduplicates overlapping MongoDB normalize tests (3 PRs → 1), `keybind` tests (2 PRs → 1),
and `connections.test.ts` additions (4 PRs → 1 merged file).

New test files:
- `sql-analyze-tool.test.ts` — `SqlAnalyzeTool` formatting (6 tests)
- `sql-analyze-format.test.ts` — `sql.analyze` success semantics + dispatcher (5 tests)
- `builtin-commands.test.ts` — altimate builtin command registration (10 tests)
- `hints-discover-mcps.test.ts` — `Command.hints()` + discover-and-add-mcps (11 tests)
- `fingerprint-detect.test.ts` — file-based project detection rules (11 tests)
- `dbt-lineage-helpers.test.ts` — dbt lineage helper functions (13 tests)
- `registry-env-loading.test.ts` — `ALTIMATE_CODE_CONN_*` env var loading (8 tests)
- `warehouse-telemetry.test.ts` — MongoDB auth detection telemetry (4 tests)
- `bus-event.test.ts` — bus event registry payloads (5 tests)
- `git.test.ts` — git utility functions (5 tests)
- `keybind.test.ts` — keybind parsing, matching, `fromParsedKey` (22 tests)

Merged into existing files:
- `connections.test.ts` — `loadFromEnv` (5), `detectAuthMethod` (14), credential stripping (1),
  `containerToConfig` (1), dbt profiles edge cases (3)
- `driver-normalize.test.ts` — MongoDB alias resolution (13 tests)

Fixes:
- `fixture.ts` — disable `commit.gpgsign` in test tmpdir to prevent CI failures
- `hints-discover-mcps.test.ts` — corrected sort order expectation
- `registry-env-loading.test.ts` — fixed flaky assertion that assumed isolated env

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@anandgupta42
Copy link
Contributor Author

Consolidated into #498. Tests deduplicated and merged into a single PR.

anandgupta42 added a commit that referenced this pull request Mar 27, 2026
* test: consolidate 11 test PRs into single suite — 305 new tests

Consolidates tests from PRs #440, #441, #479, #483, #484, #485, #490, #491, #492, #495, #496.
Deduplicates overlapping MongoDB normalize tests (3 PRs → 1), `keybind` tests (2 PRs → 1),
and `connections.test.ts` additions (4 PRs → 1 merged file).

New test files:
- `sql-analyze-tool.test.ts` — `SqlAnalyzeTool` formatting (6 tests)
- `sql-analyze-format.test.ts` — `sql.analyze` success semantics + dispatcher (5 tests)
- `builtin-commands.test.ts` — altimate builtin command registration (10 tests)
- `hints-discover-mcps.test.ts` — `Command.hints()` + discover-and-add-mcps (11 tests)
- `fingerprint-detect.test.ts` — file-based project detection rules (11 tests)
- `dbt-lineage-helpers.test.ts` — dbt lineage helper functions (13 tests)
- `registry-env-loading.test.ts` — `ALTIMATE_CODE_CONN_*` env var loading (8 tests)
- `warehouse-telemetry.test.ts` — MongoDB auth detection telemetry (4 tests)
- `bus-event.test.ts` — bus event registry payloads (5 tests)
- `git.test.ts` — git utility functions (5 tests)
- `keybind.test.ts` — keybind parsing, matching, `fromParsedKey` (22 tests)

Merged into existing files:
- `connections.test.ts` — `loadFromEnv` (5), `detectAuthMethod` (14), credential stripping (1),
  `containerToConfig` (1), dbt profiles edge cases (3)
- `driver-normalize.test.ts` — MongoDB alias resolution (13 tests)

Fixes:
- `fixture.ts` — disable `commit.gpgsign` in test tmpdir to prevent CI failures
- `hints-discover-mcps.test.ts` — corrected sort order expectation
- `registry-env-loading.test.ts` — fixed flaky assertion that assumed isolated env

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address CodeRabbit review comments

- `bus-event.test.ts`: move `BusEvent.define` into tests instead of module scope
- `builtin-commands.test.ts`: fix misleading "lexicographic" → "numeric" sort label
- `git.test.ts`: use `tmpdir({ git: true })` fixture instead of manual `git init`
- `registry-env-loading.test.ts`: remove unused `fs`, `os`, `path` imports

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
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.

2 participants