Skip to content

test: warehouse connections — env-var loading and MongoDB auth detection#490

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

test: warehouse connections — env-var loading and MongoDB auth detection#490
anandgupta42 wants to merge 1 commit intomainfrom
test/hourly-20260326-2211

Conversation

@anandgupta42
Copy link
Contributor

@anandgupta42 anandgupta42 commented Mar 26, 2026

What does this PR do?

1. loadFromEnv via Registry.load()src/altimate/native/connections/registry.ts (5 new tests)

The loadFromEnv function parses ALTIMATE_CODE_CONN_* environment variables to configure database connections. This is the primary connection method for CI/CD pipelines, Docker containers, and Codespaces users. Zero unit tests existed for this code path — a parsing regression would silently break all env-var-based connections with no test signal.

New coverage includes:

  • Valid JSON parsing from ALTIMATE_CODE_CONN_* env vars
  • Connection name lowercasing from env var suffix (PROD_DBprod_db)
  • Graceful handling of invalid JSON (no crash, connection silently skipped)
  • Rejection of configs missing the required type field
  • Rejection of non-object JSON values (strings, numbers, arrays)

2. detectAuthMethod for MongoDB — src/altimate/native/connections/registry.ts (4 new tests)

MongoDB driver support was added in #482. The detectAuthMethod function has a MongoDB-specific branch (line 229) that returns "connection_string" when no password is present, or "password" when one is. This branch was completely untested. Auth method detection feeds into telemetry and provider UI — incorrect detection would cause misleading warehouse analytics.

New coverage includes:

  • MongoDB without password → connection_string auth
  • MongoDB with password → password auth
  • mongo type alias (shorthand) without password → connection_string
  • Explicit connection_string field takes precedence over MongoDB type fallback

Type of change

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

Issue for this PR

N/A — proactive test coverage from automated test discovery

How did you verify your code works?

bun test test/altimate/connections.test.ts          # 44 pass (39 existing + 5 new)
bun test test/altimate/warehouse-telemetry.test.ts  # 45 pass (41 existing + 4 new)

Marker check: bun run script/upstream/analyze.ts --markers --base main --strict — passed (no upstream-shared files modified).

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_015egWH6W5HdaVuMysv9tFHq

Summary by CodeRabbit

  • Tests
    • Added test coverage for environment variable-based connection loading and validation.
    • Added unit tests for MongoDB authentication detection scenarios.

Cover two untested code paths in the connection registry:
1. ALTIMATE_CODE_CONN_* env var parsing (CI/Docker users)
2. MongoDB-specific detectAuthMethod branches added in #482

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

https://claude.ai/code/session_015egWH6W5HdaVuMysv9tFHq
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 test files are enhanced with expanded unit test coverage: connections.test.ts gains env-var-based connection loading tests with proper cleanup logic, and warehouse-telemetry.test.ts adds MongoDB auth detection tests for the Registry.detectAuthMethod method.

Changes

Cohort / File(s) Summary
Connection Loading Tests
packages/opencode/test/altimate/connections.test.ts
Added afterEach import and new test suite covering env-var-based connection registration via Registry.load(), including validation of JSON parsing, invalid JSON handling, missing type field rejection, and per-test cleanup of saved env state.
Auth Detection Tests
packages/opencode/test/altimate/warehouse-telemetry.test.ts
Added four synchronous unit tests for Registry.detectAuthMethod validating MongoDB auth method detection: connection string vs. password-based auth selection, support for both "mongodb" and "mongo" type aliases, and explicit connection_string field precedence.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested labels

contributor

Poem

🐰 A rabbit hops through test-written halls,
Where env vars dance in connection calls,
MongoDB auth types now verified bright,
Cleanup logic keeps the state just right,
Coverage grows—the tests take flight! 🚀

🚥 Pre-merge checks | ✅ 2 | ❌ 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 (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically identifies the two main changes: env-var loading and MongoDB auth detection for warehouse connections.
Description check ✅ Passed The description comprehensively covers what changed, why it matters, test coverage details, and how the author verified the changes. All required template sections (Summary, Test Plan, Checklist) are present.

✏️ 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-2211

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/opencode/test/altimate/connections.test.ts (1)

84-87: Capture original env value only once in setEnv.

At Line 85, repeated calls with the same key in one test would overwrite the true original value and make restoration inaccurate. Consider guarding the first snapshot only.

♻️ Suggested tweak
 function setEnv(key: string, value: string) {
-  saved[key] = process.env[key]
+  if (!(key in saved)) saved[key] = process.env[key]
   process.env[key] = value
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/opencode/test/altimate/connections.test.ts` around lines 84 - 87,
The setEnv helper currently overwrites saved[key] each time it's called, losing
the true original environment value; modify setEnv (the function named setEnv)
to only capture and store process.env[key] into saved[key] if saved[key] is
undefined (i.e., guard the assignment so the original value is preserved on the
first call), then set process.env[key] to the new value as before so
tearDown/restore logic can accurately restore the original.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/opencode/test/altimate/warehouse-telemetry.test.ts`:
- Around line 186-188: The test for Registry.detectAuthMethod currently doesn't
distinguish the explicit connection_string branch from the MongoDB fallback
because the input lacks a password so both return "connection_string"; update
the test case used in the "prefers explicit connection_string field over mongodb
type fallback" test to include a password field (e.g., add password: "x") so
that the MongoDB fallback would produce a different result and the assertion
actually verifies precedence of the connection_string over the mongodb type
fallback.

---

Nitpick comments:
In `@packages/opencode/test/altimate/connections.test.ts`:
- Around line 84-87: The setEnv helper currently overwrites saved[key] each time
it's called, losing the true original environment value; modify setEnv (the
function named setEnv) to only capture and store process.env[key] into
saved[key] if saved[key] is undefined (i.e., guard the assignment so the
original value is preserved on the first call), then set process.env[key] to the
new value as before so tearDown/restore logic can accurately restore the
original.
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3e30099f-c815-4ddc-93b8-a4c3f23c16cf

📥 Commits

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

📒 Files selected for processing (2)
  • packages/opencode/test/altimate/connections.test.ts
  • packages/opencode/test/altimate/warehouse-telemetry.test.ts

Comment on lines +186 to +188
test("prefers explicit connection_string field over mongodb type fallback", () => {
expect(Registry.detectAuthMethod({ type: "mongodb", connection_string: "mongodb://localhost/test" } as any)).toBe("connection_string")
})
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

Precedence test does not currently differentiate the fallback path.

At Line 186, the input has no password, so MongoDB fallback also returns "connection_string". This test won’t catch precedence regressions. Add password to make the fallback outcome different.

✅ Make the assertion branch-distinguishing
 test("prefers explicit connection_string field over mongodb type fallback", () => {
-  expect(Registry.detectAuthMethod({ type: "mongodb", connection_string: "mongodb://localhost/test" } as any)).toBe("connection_string")
+  expect(
+    Registry.detectAuthMethod({
+      type: "mongodb",
+      password: "secret",
+      connection_string: "mongodb://localhost/test",
+    } as any),
+  ).toBe("connection_string")
 })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test("prefers explicit connection_string field over mongodb type fallback", () => {
expect(Registry.detectAuthMethod({ type: "mongodb", connection_string: "mongodb://localhost/test" } as any)).toBe("connection_string")
})
test("prefers explicit connection_string field over mongodb type fallback", () => {
expect(
Registry.detectAuthMethod({
type: "mongodb",
password: "secret",
connection_string: "mongodb://localhost/test",
} as any),
).toBe("connection_string")
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/opencode/test/altimate/warehouse-telemetry.test.ts` around lines 186
- 188, The test for Registry.detectAuthMethod currently doesn't distinguish the
explicit connection_string branch from the MongoDB fallback because the input
lacks a password so both return "connection_string"; update the test case used
in the "prefers explicit connection_string field over mongodb type fallback"
test to include a password field (e.g., add password: "x") so that the MongoDB
fallback would produce a different result and the assertion actually verifies
precedence of the connection_string over the mongodb type fallback.

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.

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