Add prom-client dependency and enhance tests for stream creation and …#476
Add prom-client dependency and enhance tests for stream creation and …#476TechBroAfrica wants to merge 1 commit into
Conversation
|
@TechBroAfrica is attempting to deploy a commit to the ritik4ever's projects Team on Vercel. A member of the Team first needs to authorize it. |
📝 WalkthroughWalkthroughThis PR expands test coverage for stream creation (addressing issue ChangesTest Coverage Expansion & API Error Handling Improvements
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
⚔️ Resolve merge conflicts
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
ESLint skipped: no ESLint configuration detected in root package.json. To enable, add 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
backend/src/index.test.ts (1)
257-283:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftRe-enable these skipped filter/pagination tests (or replace with equivalent active coverage).
Converting these to
it.skipremoves regression protection for sender/recipient/status/search filtering and sender-stream pagination paths.Also applies to: 366-390, 406-413
🤖 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 `@backend/src/index.test.ts` around lines 257 - 283, Re-enable the skipped sender/recipient/status/pagination tests by removing the .skip on the three tests that call invokeListStreamsRoute (the "filters by sender exact match", "filters by recipient exact match", and "applies combined sender + recipient + status filtering" cases) or replace them with equivalent active tests that assert the same behavior using SENDER_A, RECIPIENT_1, RECIPIENT_2 and the "scheduled" status; ensure each test still checks status === 200, body.total and the body.data.map(...).toEqual expectations so sender/recipient filtering and sender-stream pagination paths remain covered.
🧹 Nitpick comments (1)
backend/src/index.test.ts (1)
660-672: ⚡ Quick winStrengthen pagination arg-order assertions for
getGlobalEvents.With
page=2andlimit=2, both values are2, so swapped argument order still passes. Use distinct values and assert order explicitly.Suggested assertion update
- it("paginates correctly when page and limit are provided", () => { + it("paginates correctly when page and limit are provided", () => { @@ - const { status, body } = invokeGlobalEventsRoute({ page: "2", limit: "2" }); + const { status, body } = invokeGlobalEventsRoute({ page: "3", limit: "2" }); @@ - expect(body.page).toBe(2); + expect(body.page).toBe(3); @@ - // offset should be (2-1)*2 = 2 + // offset should be (3-1)*2 = 4 expect(eventHistoryMocks.getGlobalEvents).toHaveBeenCalled(); const callArgs = eventHistoryMocks.getGlobalEvents.mock.calls[0]; - expect(callArgs[0]).toBe(2); // offset - expect(callArgs[1]).toBe(2); // limit + expect(callArgs[0]).toBe(2); // limit + expect(callArgs[1]).toBe(4); // offset });🤖 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 `@backend/src/index.test.ts` around lines 660 - 672, The test uses identical page and limit values so argument order bugs are hidden; change the invocation of invokeGlobalEventsRoute to use distinct page and limit (for example page="3", limit="2"), update the expected body.page/body.limit/body.total/body.data length accordingly, and assert that eventHistoryMocks.getGlobalEvents was called with the computed offset (e.g., (3-1)*2 = 4) as the first arg and the limit (2) as the second by inspecting callArgs from eventHistoryMocks.getGlobalEvents.mock.calls[0].
🤖 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 `@backend/src/index.test.ts`:
- Around line 457-459: The test currently pre-mocks
eventHistoryMocks.getStreamHistory to always return createdEvent, decoupling
verification from the POST; change the test to assert that
eventHistoryMocks.recordEvent is called by the POST and make getStreamHistory
return values dependent on recordEvent instead of a static stub. Concretely,
remove the fixed mockReturnValue for getStreamHistory, add a mockImplementation
for recordEvent that stores the recorded event in a local array, implement
getStreamHistory to return that array, and after performing the POST add an
assertion like expect(eventHistoryMocks.recordEvent).toHaveBeenCalledWith(...)
(and any relevant args) to ensure POST actually records the event; apply the
same change pattern for the other test case referenced (lines 484-490).
---
Outside diff comments:
In `@backend/src/index.test.ts`:
- Around line 257-283: Re-enable the skipped sender/recipient/status/pagination
tests by removing the .skip on the three tests that call invokeListStreamsRoute
(the "filters by sender exact match", "filters by recipient exact match", and
"applies combined sender + recipient + status filtering" cases) or replace them
with equivalent active tests that assert the same behavior using SENDER_A,
RECIPIENT_1, RECIPIENT_2 and the "scheduled" status; ensure each test still
checks status === 200, body.total and the body.data.map(...).toEqual
expectations so sender/recipient filtering and sender-stream pagination paths
remain covered.
---
Nitpick comments:
In `@backend/src/index.test.ts`:
- Around line 660-672: The test uses identical page and limit values so argument
order bugs are hidden; change the invocation of invokeGlobalEventsRoute to use
distinct page and limit (for example page="3", limit="2"), update the expected
body.page/body.limit/body.total/body.data length accordingly, and assert that
eventHistoryMocks.getGlobalEvents was called with the computed offset (e.g.,
(3-1)*2 = 4) as the first arg and the limit (2) as the second by inspecting
callArgs from eventHistoryMocks.getGlobalEvents.mock.calls[0].
🪄 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
Run ID: a8dd33d3-83fa-4922-9ce7-a02eb127db6a
⛔ Files ignored due to path filters (1)
backend/package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (5)
abackend/package.jsonbackend/src/index.test.tsbackend/src/index.tsbackend/src/services/indexer.ts
💤 Files with no reviewable changes (1)
- backend/src/services/indexer.ts
| eventHistoryMocks.countStreamEvents.mockReturnValue(1); | ||
| eventHistoryMocks.getStreamHistory.mockReturnValue([createdEvent]); | ||
| }); |
There was a problem hiding this comment.
The created-event verification is currently decoupled from POST behavior.
getStreamHistory is pre-mocked to always return createdEvent, so this test can pass even if POST never records an event. Add an assertion that POST actually calls recordEvent, and make history depend on that call.
Suggested test hardening
beforeEach(() => {
@@
- eventHistoryMocks.getStreamHistory.mockReturnValue([createdEvent]);
+ eventHistoryMocks.getStreamHistory.mockImplementation(() =>
+ eventHistoryMocks.recordEvent.mock.calls.length > 0 ? [createdEvent] : [],
+ );
});
it("creates a stream and includes computed progress", async () => {
@@
expect(response.status).toBe(201);
+ expect(eventHistoryMocks.recordEvent).toHaveBeenCalled();
@@
expect(historyResponse.status).toBe(200);Also applies to: 484-490
🤖 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 `@backend/src/index.test.ts` around lines 457 - 459, The test currently
pre-mocks eventHistoryMocks.getStreamHistory to always return createdEvent,
decoupling verification from the POST; change the test to assert that
eventHistoryMocks.recordEvent is called by the POST and make getStreamHistory
return values dependent on recordEvent instead of a static stub. Concretely,
remove the fixed mockReturnValue for getStreamHistory, add a mockImplementation
for recordEvent that stores the recorded event in a local array, implement
getStreamHistory to return that array, and after performing the POST add an
assertion like expect(eventHistoryMocks.recordEvent).toHaveBeenCalledWith(...)
(and any relevant args) to ensure POST actually records the event; apply the
same change pattern for the other test case referenced (lines 484-490).
| console.error("Failed to generate challenge:", error); | ||
| sendApiError(req, res, 500, "Failed to generate authentication challenge.", { | ||
| code: "AUTH_ERROR", |
There was a problem hiding this comment.
Avoid leaking raw auth errors to logs and clients.
Line 495/Line 515 log full auth errors, and Line 516 returns raw error.message to clients. This can expose internal auth details. Use normalized errors and sanitized logging fields instead of raw objects/messages.
Suggested patch
} catch (error: any) {
- console.error("Failed to generate challenge:", error);
- sendApiError(req, res, 500, "Failed to generate authentication challenge.", {
- code: "AUTH_ERROR",
- });
+ const normalizedError = normalizeUnknownApiError(
+ error,
+ "Failed to generate authentication challenge.",
+ );
+ console.error("Failed to generate challenge:", {
+ name: error?.name,
+ code: normalizedError.code ?? "AUTH_ERROR",
+ statusCode: normalizedError.statusCode,
+ });
+ sendApiError(req, res, normalizedError.statusCode, normalizedError.message, {
+ code: "AUTH_ERROR",
+ });
}
});
@@
} catch (error: any) {
- console.error("Failed to verify challenge:", error);
- sendApiError(req, res, 400, error.message || "Challenge verification failed.", {
- code: "AUTH_ERROR",
- });
+ const normalizedError = normalizeUnknownApiError(
+ error,
+ "Challenge verification failed.",
+ );
+ console.error("Failed to verify challenge:", {
+ name: error?.name,
+ code: normalizedError.code ?? "AUTH_ERROR",
+ statusCode: normalizedError.statusCode,
+ });
+ sendApiError(req, res, normalizedError.statusCode, normalizedError.message, {
+ code: "AUTH_ERROR",
+ });
}
});Also applies to: 515-517
closes #233
Added backend test coverage for POST /api/streams validation and creation behavior.
Verified successful creation returns 201 with computed progress.
Added assertions that created stream events are available via GET /api/streams/:id/history.
Fixed test fixture generation for Stellar public keys in index.test.ts.
Testing done
cd backend && npx vitest run src/index.test.ts
Result: 25 passed
Related issues
Closes #
Checklist
I kept the change focused on the related issue.
I added or updated tests where useful.
I updated documentation where behavior changed.
I verified the app still builds or explained why verification was skipped.
Summary by CodeRabbit
Bug Fixes
Tests
Chores