Skip to content

test: Add unit tests for middleware - #90

Open
Vishmayraj wants to merge 2 commits into
OneBusAway:mainfrom
Vishmayraj:test/middleware
Open

test: Add unit tests for middleware#90
Vishmayraj wants to merge 2 commits into
OneBusAway:mainfrom
Vishmayraj:test/middleware

Conversation

@Vishmayraj

Copy link
Copy Markdown

internal/middleware had no test coverage. This PR adds tests for:

SecurityHeaders: verifies all 7 security headers are set with correct
values, and that the next handler is called correctly.

CachedPromHandler: verifies empty cache fallback, correct Content-Type
when cache is populated, and concurrent read safety (verified with -race).

SentryMiddleware is intentionally skipped — it wraps a third-party SDK
with no testable surface without mocking Sentry internals.

All existing tests continue to pass.

@aaronbrethorst

Copy link
Copy Markdown
Member

Code review

Found 1 issue:

  1. The two CachedPromHandler cache tests never actually populate the cache, so they pass regardless of the caching behavior. prometheus.NewRegistry() returns an empty registry with no collectors, so refreshLoop gathers zero metric families and promhttp encodes nothing — c.cache stays len == 0 forever, and every request keeps taking the if len(c.cache) == 0 fallback branch to the live handler. The time.Sleep(200 * time.Millisecond) and its "Wait for the cache to be populated" comment therefore buy nothing, and the Content-Type assertion cannot distinguish the two paths because the live promhttp handler also negotiates text/plain; version=0.0.4. The same applies to the "Concurrent reads do not race" subtest, which exercises only the fallback path. Registering a real collector on the registry (e.g. registry.MustRegister(prometheus.NewCounter(...)) and incrementing it) would make the cached branch actually reachable.

registry := prometheus.NewRegistry()
handler := NewCachedPromHandler(ctx, registry, 50*time.Millisecond)
// Wait for the cache to be populated by the refresh loop
time.Sleep(200 * time.Millisecond)

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

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.

2 participants