Skip to content

test: expand unit test coverage for recommendations, cursor pagination, logger, and metrics - #747

Merged
DeFiVC merged 4 commits into
ChainLearnOfficial:mainfrom
ElizabethChi:test/chainlearn-api-unit-tests-batch-elizabeth
Oct 21, 2026
Merged

DeFiVC merged 4 commits into
ChainLearnOfficial:mainfrom
ElizabethChi:test/chainlearn-api-unit-tests-batch-elizabeth

Conversation

@ElizabethChi

Copy link
Copy Markdown
Contributor

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

  • Add unit tests for recommendations engine #593 - Add unit tests for recommendations engine: tests/unit/users/recommendations.test.ts already 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 (targetLevel must 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 (rankCourses must 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.
  • Add unit tests for cursor pagination utility #594 - Add unit tests for cursor pagination utility: tests/unit/utils/cursor-pagination.test.ts already covered the encode/decode roundtrip, opacity, and basic garbage-input rejection. Added per-field type-mismatch cases (id present but not a string, createdAt present 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), 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, per the module's own doc comment), and the Unix epoch boundary.
  • Add unit tests for logger utility #601 - Add unit tests for logger utility: new tests/unit/utils/logger.test.ts. Covers the level/transport decision for each NODE_ENV value (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 documented 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 tests/unit/config/cors-origins.test.ts already uses; re-importing only one of the two would leave them bound to different AsyncLocalStorage instances that never share state. The 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 symbol registry and does not match pino's internal symbols despite stringifying identically.
  • Add unit tests for metrics collection #602 - Add unit tests for metrics collection: tests/unit/metrics/metrics.test.ts previously 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 via registry.metrics(), and registry.resetMetrics() actually clearing values. Also added 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.

Test plan

  • All four test files pass in isolation: 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.
  • Ran the full suite on this branch and on a fresh upstream/main baseline (separate worktree, fresh npm ci, pulled after chizube's earlier batch had already merged), then diffed the sorted FAIL lines 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 eslint on 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.

…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.
@drips-wave

drips-wave Bot commented Oct 21, 2026

Copy link
Copy Markdown

@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! 🚀

Learn more about application limits

@DeFiVC
DeFiVC merged commit 0d7e9fa into ChainLearnOfficial:main Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants