Skip to content

Assert on silenced console output instead of blanket-suppressing it - #722

Merged
kody-bot merged 3 commits into
mainfrom
cursor/assert-suppressed-output-b0fb
Jul 11, 2026
Merged

kody-bot merged 3 commits into
mainfrom
cursor/assert-suppressed-output-b0fb

Conversation

@kentcdodds

@kentcdodds kentcdodds commented Jul 11, 2026 •

Copy link
Copy Markdown
Member

Why

Follow-up to #721. When output is silenced in tests, we must assert on the output we expect — and assert the absence of output we don't — so a suppression can never hide a real regression. Several suppressions from the console-noise cleanup were blanket silences that violated that principle.

What changed

Vite warnings: blanket logLevel: 'error' → targeted filter

  • logLevel: 'error' suppressed every Vite warning. Replaced with a tools/vite-suppress-sourcemap-warnings.ts plugin that drops only the exact Sourcemap for "…/node_modules/…" points to missing source files message; all other warnings (including first-party sourcemap breakage) still surface.
  • tools/vite-suppress-sourcemap-warnings.node.test.ts asserts both directions: the third-party message is dropped, and first-party/unknown warnings pass through.

Audit log: silent stubs → one shared spy with assertions

  • New packages/worker/src/test-support/audit-log-spy.ts setup file (wired into the node-unit project) routes logAuditEvent through a single exported logAuditEventSpy, replacing the per-file vi.hoisted + vi.mock blocks that were previously repeated in seven handler test files (auth-handler, auth-provider, two-factor, account-resend-verification, account-profile, password-reset, admin-users).
  • An auditEventSummaries() helper returns the ordered action:result list so tests assert the exact audit event sequence — extra unexpected events fail, not just missing ones. Tests also assert not.toHaveBeenCalled() where no audit is expected (profile reads).
  • admin-capabilities.node.test.ts asserts real audit_events rows, so it opts out with vi.unmock('#app/audit-log.ts'); password-reset/admin-users keep a file-local mock only to pin getRequestIp, routing the sink back through the shared spy.

Console silences: blanket mockImplementation(() => {}) → allowlists or assertions

  • New silenceExpectedConsoleWarns / silenceExpectedConsoleErrors helpers in console-spies.ts: swallow only an explicit allowlist of expected messages and throw on anything else.
  • New incidental-runtime-warnings.ts shared allowlist for the recurring bundler/registry-runtime noise ([worker-bundler] experimental notice, mcp-server-refs-load-failed, usage-*-failed, package-runtime-debug-*).
  • Converted all 44 previously-unasserted blanket silences across 16 test files (jobs service, run-kody-registry, email inbound/outbound/system, retention, reconcile, module-graph, observability, integration search, package-registry service, remote-connector session, repo-session DO) to either targeted allowlists or explicit expect(consoleWarn).toHaveBeenCalledWith(...) assertions.
  • Every remaining mockImplementation(() => {}) site now has an assertion on the captured calls (verified by scanning the tree).

Docs

  • docs/contributing/testing-principles.md now documents both rules: never silence blindly (assert on contract logs, use the allowlist helpers for incidental logs), and use the shared logAuditEventSpy for audit assertions.

Testing

  • ✅ npm run validate (format, lint, typecheck, 806 unit tests, 13 Playwright E2E, MCP E2E — all green)
  • ✅ Verified the sourcemap filter end-to-end: with the filter disabled the workers pool emits 28 Sourcemap … missing source files warnings; with it enabled the full unit run has zero, and the unit test proves non-matching warnings still pass through.
  • ✅ Full-suite output scan: 0 hits for Sourcemap for, Using secrets defined, ExperimentalWarning, audit-event {.
System recap — composes existing primitives (low risk, test-only)

Mode: recap · Base: main @ 47c9a24e · Head: 35562e0f

Classification: composes — no runtime primitive code changes. The diff touches only test files, test-support helpers (console-spies.ts, new incidental-runtime-warnings.ts and audit-log-spy.ts), Vitest configuration, and a new Vite test plugin (tools/vite-suppress-sourcemap-warnings.ts). No entry in primitives.yaml is added or reshaped.

Primitives touched

Primitive Group Impact
(none) — Tests covering app-ui auth/account handlers, jobs, email, repo-sessions, package-runtime, and capabilities-execute gained assertions on previously-silenced console output; the primitives themselves are unchanged.

Change flow

Test harness only: console silencing now goes through allowlist helpers that throw on unexpected messages, and per-file audit-log stubs became one shared setup-file spy with exact-sequence assertions.

flowchart LR
	testGuard["console-spies.ts<br/>global console guard"]:::extended
	allowlist["incidental-runtime-warnings.ts<br/>shared warning allowlist"]:::added
	auditSpy["audit-log-spy.ts<br/>shared logAuditEvent spy (node-unit setupFiles)"]:::added
	viteFilter["vite-suppress-sourcemap-warnings.ts<br/>targeted Vite warning filter"]:::added
	tests["17 test files<br/>unit + workers suites"]:::touched
	tests -->|"silenceExpectedConsoleWarns/Errors(allowlist)"| testGuard
	tests -->|"auditEventSummaries() exact-sequence assertions"| auditSpy
	tests -->|"silenceIncidentalRuntimeWarnings()"| allowlist
	testGuard -->|"throws on non-allowlisted messages"| tests
	viteFilter -->|"drops only third-party missing-sourcemap warning"| tests
	classDef touched fill:#1a7f37,color:#fff
	classDef extended fill:#9a6700,color:#fff
	classDef added fill:#cf222e,color:#fff
	classDef untouched fill:#57606a,color:#fff
Loading

Red here means "new test-support module", not a new system primitive.

Open in Web Open in Cursor 

Summary by CodeRabbit

  • Tests
    • Strengthened audit-log assertions across authentication, account, resend verification, two-factor, password reset, admin, and other worker workflows (including call counts and ordering).
    • Tightened console warning/error handling using targeted allowlisting for expected noise, while keeping unexpected logs as test failures.
    • Improved incidental runtime-warning suppression across multiple email, job, repo, and MCP scenarios.
    • Added unit tests for third-party sourcemap warning suppression and verified plugin behavior.
  • Documentation
    • Updated testing principles to clarify expected vs incidental console log handling and audit-log mocking guidance.
  • Chores
    • Introduced shared test helpers for audit-log capturing and selective console-noise silencing; registered the sourcemap-warning suppression plugin in Vitest config.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Testing guidance and support helpers now require explicit handling of console output. Tests assert audit events and expected warnings, while Vitest uses a targeted plugin to suppress one third-party sourcemap warning.

Changes

Test observability

Layer / File(s) Summary
Console-output contracts and allowlists
docs/contributing/testing-principles.md, packages/worker/src/test-support/*
Documents and implements pattern-based suppression for expected warnings and errors, including incidental runtime warnings.
Audit event assertions
packages/worker/src/app/handlers/*, packages/worker/src/test-support/audit-log-spy.ts, vitest.node.config.ts
Node-unit tests capture and verify audit events across authentication, account, OAuth, password reset, administrative, and two-factor flows.
Targeted warning handling in tests
packages/worker/src/app/email/*, packages/worker/src/email/*, packages/worker/src/jobs/*, packages/worker/src/mcp/*, packages/worker/src/package-*, packages/worker/src/remote-connector/*, packages/worker/src/repo/*
Tests replace blanket console mocks with allowlisted suppression or explicit warning call assertions.
Vite sourcemap warning suppression
tools/vite-suppress-sourcemap-warnings*, vitest-shared.ts, vitest.config.ts
Adds and registers a plugin that filters only the specified third-party missing-sourcemap warning, with unit tests for matching and forwarding behavior.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant VitestConfig
  participant SourcemapWarningPlugin
  participant ViteLogger
  VitestConfig->>SourcemapWarningPlugin: register plugin
  ViteLogger->>SourcemapWarningPlugin: warn(message)
  SourcemapWarningPlugin->>SourcemapWarningPlugin: match third-party sourcemap warning
  SourcemapWarningPlugin-->>ViteLogger: suppress matching warning
  SourcemapWarningPlugin-->>ViteLogger: forward other warnings
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% 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
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the PR’s main testing change: replacing blanket suppression with explicit assertions or allowlisted silencing.
✨ 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 cursor/assert-suppressed-output-b0fb

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.

@kody-bot
kody-bot marked this pull request as ready for review July 11, 2026 05:18
@github-actions

github-actions Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

🔎 Preview deployed: https://kody-pr-722.kody-a99.workers.dev

Worker: kody-pr-722
D1: kody-pr-722-db
KV: kody-pr-722-oauth-kv

Mocks:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
packages/worker/src/app/handlers/two-factor.node.test.ts (1)

21-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the duplicated auditSpy + vi.mock pattern into a shared test helper.

The identical 10-line block is now copy-pasted across all 5 handler test files. The PR stack already establishes shared test-support modules (packages/worker/src/test-support/console-spies.ts). Extracting a createAuditLogSpy() helper there would eliminate the duplication and ensure consistent mock setup.

♻️ Proposed shared helper
// packages/worker/src/test-support/audit-spy.ts
import { vi } from 'vitest'

export function createAuditLogSpy() {
	const auditSpy = vi.hoisted(() => ({
		logAuditEvent: vi.fn(async () => undefined),
	}))

	function mockAuditLog() {
		vi.mock('`#app/audit-log.ts`', async (importOriginal) => {
			const actual =
				await importOriginal<typeof import('`#app/audit-log.ts`')>()
			return {
				...actual,
				logAuditEvent: (...args: Array<unknown>) =>
					auditSpy.logAuditEvent(...args),
			}
		})
	}

	return { auditSpy, mockAuditLog }
}

Usage in each test file:

-const auditSpy = vi.hoisted(() => ({
-	logAuditEvent: vi.fn(async () => undefined),
-}))
-
-vi.mock('`#app/audit-log.ts`', async (importOriginal) => {
-	const actual = await importOriginal<typeof import('`#app/audit-log.ts`')>()
-	return {
-		...actual,
-		logAuditEvent: (...args: Array<unknown>) => auditSpy.logAuditEvent(...args),
-	}
-})
+import { createAuditLogSpy } from '`#test-support/audit-spy.ts`'
+
+const { auditSpy, mockAuditLog } = createAuditLogSpy()
+mockAuditLog()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/src/app/handlers/two-factor.node.test.ts` around lines 21 -
31, Extract the repeated hoisted audit spy and `#app/audit-log.ts` mock into a
shared createAuditLogSpy helper under the existing test-support modules. Have
the helper return auditSpy and mockAuditLog, preserving the current mocked
logAuditEvent behavior, then update all five handler test files to use the
helper instead of duplicating the vi.hoisted and vi.mock blocks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/worker/src/app/handlers/auth-handler.node.test.ts`:
- Around line 378-385: Add toHaveBeenCalledTimes assertions alongside each
auditSpy.logAuditEvent toHaveBeenCalledWith block in the affected auth-handler
tests: expect 1 call for login-failure, login-success, and signup-failure, and 2
calls for signup-success. Keep the count assertions adjacent to their
corresponding expectations.

In `@packages/worker/src/app/handlers/auth-provider.node.test.ts`:
- Around line 320-327: Add
expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1) alongside both OAuth
audit assertions in the relevant tests, including the assertions around the
oauth_signup success event and the second OAuth case, to ensure exactly one
audit event is emitted.

In `@packages/worker/src/app/handlers/two-factor.node.test.ts`:
- Around line 321-342: Add explicit audit call-count assertions in the
setup/enable test around the existing auditSpy.logAuditEvent expectations,
asserting exactly three calls, and in the disable test assert exactly two calls.
Use the existing auditSpy.logAuditEvent spy and place each toHaveBeenCalledTimes
assertion alongside its corresponding event expectations.

In
`@packages/worker/src/mcp/capabilities/integrations/integration-registry-search.node.test.ts`:
- Around line 45-47: The MSW warning suppression is overly broad in the test
setup. Update the argument passed to silenceExpectedConsoleWarns in
integration-registry-search.node.test.ts to match the specific redundant
query-parameter warning text, preserving unrelated MSW warnings as test
failures.

---

Nitpick comments:
In `@packages/worker/src/app/handlers/two-factor.node.test.ts`:
- Around line 21-31: Extract the repeated hoisted audit spy and
`#app/audit-log.ts` mock into a shared createAuditLogSpy helper under the existing
test-support modules. Have the helper return auditSpy and mockAuditLog,
preserving the current mocked logAuditEvent behavior, then update all five
handler test files to use the helper instead of duplicating the vi.hoisted and
vi.mock blocks.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4ee59c1c-9196-439d-8ad1-adb787affa6f

📥 Commits

Reviewing files that changed from the base of the PR and between 47c9a24 and a86a963.

📒 Files selected for processing (28)
  • docs/contributing/testing-principles.md
  • packages/worker/src/app/email/cloudflare-email.node.test.ts
  • packages/worker/src/app/handlers/account-profile.node.test.ts
  • packages/worker/src/app/handlers/account-resend-verification.node.test.ts
  • packages/worker/src/app/handlers/auth-handler.node.test.ts
  • packages/worker/src/app/handlers/auth-provider.node.test.ts
  • packages/worker/src/app/handlers/two-factor.node.test.ts
  • packages/worker/src/app/retention.node.test.ts
  • packages/worker/src/email/inbound.workers.test.ts
  • packages/worker/src/email/outbound.workers.test.ts
  • packages/worker/src/email/system-email-subscriptions.workers.test.ts
  • packages/worker/src/email/system-email.workers.test.ts
  • packages/worker/src/jobs/reconcile-artifacts-pushes.node.test.ts
  • packages/worker/src/jobs/service.node.test.ts
  • packages/worker/src/mcp/capabilities/integrations/integration-registry-search.node.test.ts
  • packages/worker/src/mcp/execute-dynamic-worker-reuse.workers.test.ts
  • packages/worker/src/mcp/observability.workers.test.ts
  • packages/worker/src/mcp/run-kody-registry.node.test.ts
  • packages/worker/src/package-registry/service.node.test.ts
  • packages/worker/src/package-runtime/module-graph.workers.test.ts
  • packages/worker/src/remote-connector/session.node.test.ts
  • packages/worker/src/repo/repo-session-do.node.test.ts
  • packages/worker/src/test-support/console-spies.ts
  • packages/worker/src/test-support/incidental-runtime-warnings.ts
  • tools/vite-suppress-sourcemap-warnings.node.test.ts
  • tools/vite-suppress-sourcemap-warnings.ts
  • vitest-shared.ts
  • vitest.config.ts

Comment on lines +378 to +385
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'login',
result: 'failure',
reason: 'invalid_credentials',
}),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Add toHaveBeenCalledTimes assertions to match the pattern in other handler tests.

All four assertion blocks use only toHaveBeenCalledWith without toHaveBeenCalledTimes. This means extra unexpected audit events would pass silently — the exact regression class this PR aims to prevent. The account-profile and account-resend-verification tests correctly pair both assertions; this file should follow suit.

For the signup-success case (lines 416-430), the expected count is 2 (signup + invite_use). For the login-failure (378-385), login-success (535-542), and signup-failure (582-588) cases, the expected count is 1 each.

🔧 Proposed additions
 // Lines 378-385 — login failure
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'login',
 		result: 'failure',
 		reason: 'invalid_credentials',
 	}),
 )

 // Lines 416-430 — signup success + invite_use
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(2)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'signup',
 		result: 'success',
 		email: 'invited@example.com',
 	}),
 )
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'invite_use',
 		result: 'success',
 	}),
 )

 // Lines 535-542 — login success
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'login',
 		result: 'success',
 		email,
 	}),
 )

 // Lines 582-588 — signup failure
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'signup',
 		result: 'failure',
 	}),
 )

Also applies to: 416-430, 535-542, 582-588

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/src/app/handlers/auth-handler.node.test.ts` around lines 378
- 385, Add toHaveBeenCalledTimes assertions alongside each
auditSpy.logAuditEvent toHaveBeenCalledWith block in the affected auth-handler
tests: expect 1 call for login-failure, login-success, and signup-failure, and 2
calls for signup-success. Keep the count assertions adjacent to their
corresponding expectations.

Comment on lines +320 to +327
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'oauth_signup',
result: 'success',
reason: 'provider=github',
}),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Add toHaveBeenCalledTimes(1) to both OAuth audit assertions.

Same gap as auth-handler.node.test.ts — without count assertions, extra unexpected audit events go undetected, which contradicts the PR's objective.

🔧 Proposed additions
 // Lines 320-327 — oauth_signup
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'oauth_signup',
 		result: 'success',
 		reason: 'provider=github',
 	}),
 )

 // Lines 354-361 — oauth_login
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'oauth_login',
 		result: 'success',
 		reason: 'provider=github',
 	}),
 )

Also applies to: 354-361

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/src/app/handlers/auth-provider.node.test.ts` around lines 320
- 327, Add expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1) alongside
both OAuth audit assertions in the relevant tests, including the assertions
around the oauth_signup success event and the second OAuth case, to ensure
exactly one audit event is emitted.

Comment thread packages/worker/src/app/handlers/two-factor.node.test.ts Outdated
@kody-bot
kody-bot merged commit a153442 into main Jul 11, 2026
5 checks passed
@kody-bot
kody-bot deleted the cursor/assert-suppressed-output-b0fb branch July 11, 2026 05:59
@coderabbitai coderabbitai Bot mentioned this pull request Jul 20, 2026
3 of 4 tasks
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.

3 participants