Repository navigation
test: expand unit test coverage for recommendations, cursor pagination, logger, and metrics - #747
Merged
DeFiVC merged 4 commits intoOct 21, 2026
Conversation
…earnOfficial#593) targetLevel, scoreCourse, and rankCourses already had tests covering the scoring algorithm and basic difficulty progression; add the two edge cases the issue specifically calls out: a learner who has completed every difficulty level (targetLevel must cap at the top level instead of going out of bounds), and a brand-new learner with no history at all (rankCourses must still rank beginner-level courses sensibly, and an all-zero-signal candidate pool must return an empty list rather than erroring). Also covers an empty candidate list and a limit larger than the pool.
…fficial#594) Existing tests covered the encode/decode roundtrip, opacity, and basic garbage-input rejection. Add type-mismatch cases for each field individually (id present but not a string, createdAt present but not a string), a JSON array and a JSON primitive in place of an object, a payload with extra unexpected fields (must still decode), an id containing special characters, two cursors sharing a createdAt but differing only by id (the actual tie-break case this cursor format exists for), and the Unix epoch boundary.
New tests/unit/utils/logger.test.ts. Covers the level/transport decision
for each NODE_ENV (production, test, development, unset), the req/res
serializers (dropping sensitive headers and response bodies, keeping only
method/url and statusCode), and the mixin's request-context injection
(requestId present when a request context is active, absent otherwise,
and an explicit requestId in the log call's own fields winning over the
mixin per pino's merge order).
Since logger.ts builds its pino instance once at import time from
process.env.NODE_ENV, each level/transport case resets the module
registry and re-imports both logger.js and request-context.js together
in the same reset cycle (the same convention as
tests/unit/config/cors-origins.test.ts) - re-importing only one of the
two would leave them bound to different AsyncLocalStorage instances that
never share state. Mixin/serializer functions are reached via reflection
on pino's own non-registry Symbol('pino.mixin')/Symbol('pino.serializers')
properties, since Symbol.for() looks up the global registry and does not
match pino's internal symbols despite stringifying the same.
…#602) Existing tests only checked httpRequestsTotal and httpRequestDurationSeconds exist and accept a call, with no assertions on actual recorded values. Expand to cover every registered metric (stellarTxDurationSeconds, quizSubmissionsTotal, rewardClaimsTotal, credentialsMintedTotal, dependencyHealthCheckSeconds), label handling (accumulating repeated increments for the same label combination, tracking distinct label combinations as separate time series, a histogram observation landing in the correct bucket), the Prometheus exposition format via registry.metrics(), and registry.resetMetrics() actually clearing values. Also add coverage for setupInfraMetrics(), which previously had none: db_active_connections derived from the live pool's totalCount minus idleCount (re-read on every collection, not cached at setup time), and redis_connected tracking connect/close/error events on the Redis client. Since setupInfraMetrics registers its Gauges on the shared registry on every call and registry.resetMetrics() only clears values (not registrations), each test unregisters them in an afterEach to avoid an 'already registered' error on the next call.
|
@ElizabethChi Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This batch expands or adds unit test coverage for four modules: the course recommendations engine, cursor pagination, the logger utility, and metrics collection.
closes #593
closes #594
closes #601
closes #602
Changes
tests/unit/users/recommendations.test.tsalready covered the scoring algorithm and basic difficulty progression. Added the two edge cases the issue specifically calls out: a learner who has completed every difficulty level (targetLevelmust cap at the top level instead of going out of bounds for a fast learner with high scores), and a brand-new learner with no history at all (rankCoursesmust still rank beginner-level courses sensibly, and an all-zero-signal candidate pool must return an empty list rather than erroring). Also added an empty-candidate-list case and a limit larger than the pool.tests/unit/utils/cursor-pagination.test.tsalready covered the encode/decode roundtrip, opacity, and basic garbage-input rejection. Added per-field type-mismatch cases (idpresent but not a string,createdAtpresent but not a string, checked individually rather than only together), a JSON array and a JSON primitive in place of an object, a payload with extra unexpected fields (must still decode successfully), anidcontaining special characters, two cursors sharing acreatedAtbut differing only byid(the actual tie-break case this cursor format exists for, per the module's own doc comment), and the Unix epoch boundary.tests/unit/utils/logger.test.ts. Covers the level/transport decision for eachNODE_ENVvalue (production, test, development, unset), thereq/resserializers (dropping sensitive headers and response bodies, keeping onlymethod/urlandstatusCode), and themixin's request-context injection (requestIdpresent when a request context is active, absent otherwise, and an explicitrequestIdin the log call's own fields winning over the mixin, per pino's documented merge order). Sincelogger.tsbuilds its pino instance once at import time fromprocess.env.NODE_ENV, each level/transport case resets the module registry and re-imports bothlogger.jsandrequest-context.jstogether in the same reset cycle, the same conventiontests/unit/config/cors-origins.test.tsalready uses; re-importing only one of the two would leave them bound to differentAsyncLocalStorageinstances that never share state. The mixin/serializer functions are reached via reflection on pino's own non-registrySymbol('pino.mixin')/Symbol('pino.serializers')properties, sinceSymbol.for()looks up the global symbol registry and does not match pino's internal symbols despite stringifying identically.tests/unit/metrics/metrics.test.tspreviously only checked that two of the seven registered metrics exist and accept a call, with no assertions on actual recorded values. Expanded to cover every registered metric (stellarTxDurationSeconds,quizSubmissionsTotal,rewardClaimsTotal,credentialsMintedTotal,dependencyHealthCheckSeconds), label handling (accumulating repeated increments for the same label combination, tracking distinct label combinations as separate time series, a histogram observation landing in the correct bucket), the Prometheus exposition format viaregistry.metrics(), andregistry.resetMetrics()actually clearing values. Also added coverage forsetupInfraMetrics(), which previously had none:db_active_connectionsderived from the live pool'stotalCountminusidleCount(re-read on every collection, not cached at setup time), andredis_connectedtracking connect/close/error events on the Redis client.Test plan
npx vitest run tests/unit/users/recommendations.test.ts tests/unit/utils/cursor-pagination.test.ts tests/unit/utils/logger.test.ts tests/unit/metrics/metrics.test.ts, 64 tests total, all green.upstream/mainbaseline (separate worktree, freshnpm ci, pulled after chizube's earlier batch had already merged), then diffed the sortedFAILlines from each: identical 71 failing test files/cases in both, all pre-existing (the same class of e2e/integration tests needing a live DB/Redis connection noted in the prior batch's PR). Zero new failures introduced by this PR; 41 new tests added, all passing.npx eslinton all four touched/added files: 0 errors, 0 warnings.npx tsc --noEmit: confirmed zero errors specifically attributable to any of the four touched test files (the repo has a number of pre-existing unrelated type errors elsewhere, e.g.quiz.service.ts,server.ts,reward.service.ts, none touched by this diff).Did not run against a live Postgres/Redis instance locally; the pre-existing e2e/integration failures on both branches are consistent with that infrastructure being unavailable here, not with a real regression.