Skip to content

refactor: tests to use testing package helpers instead of manual context handling#891

Open
Not-Dhananjay-Mishra wants to merge 16 commits into
OneBusAway:mainfrom
Not-Dhananjay-Mishra:tcontext
Open

refactor: tests to use testing package helpers instead of manual context handling#891
Not-Dhananjay-Mishra wants to merge 16 commits into
OneBusAway:mainfrom
Not-Dhananjay-Mishra:tcontext

Conversation

@Not-Dhananjay-Mishra
Copy link
Copy Markdown
Contributor

@Not-Dhananjay-Mishra Not-Dhananjay-Mishra commented Apr 25, 2026

Refactor tests to use built-in testing.T helpers for context, environment variables, and temporary resources. This removes manual handling and makes tests safer and more isolated.

Changes

  • Replace manual context usage with t.Context()
  • Replace os.Setenv() with t.Setenv()
  • Replace os.CreateTemp("", ...) with os.CreateTemp(t.TempDir(), ...)
  • Replace os.MkdirTemp() with t.TempDir()
  • Replace os.TempDir() with t.TempDir()

Summary by CodeRabbit

  • Tests
    • Standardized tests to use the testing framework’s context (t.Context()/b.Context()/tb.Context()) so cancellations/timeouts follow each test’s lifecycle.
    • Bound temp files/dirs, environment, and working-directory handling to the test harness (t.TempDir(), t.Setenv(), t.Chdir()) for better isolation and automatic cleanup.
    • Minor hygiene: removed unused imports, import/order and whitespace cleanup, and modernized permission-literal formatting.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 25, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Tests were changed to derive contexts and temporary resources from the testing framework (e.g., t.Context(), b.Context(), t.TempDir(), t.Setenv(), t.Chdir()), many unused context imports were removed, and file permission literals were modernized to 0o notation. No public APIs were modified.

Changes

Cohort / File(s) Summary
cmd/api
cmd/api/app_test.go, cmd/api/lock_safety_test.go
Replaced context.Background() with t.Context() for all contexts (including shutdown/timeout contexts); updated temp config file permission literal to 0o644.
gtfsdb tests
gtfsdb/bulk_insert_frequency_test.go, gtfsdb/bulk_insert_test.go, gtfsdb/conditional_import_test.go, gtfsdb/connection_pool_test.go, gtfsdb/fts_queries_test.go, gtfsdb/helpers_test.go, gtfsdb/nil_shape_test.go, gtfsdb/query_latency_test.go, gtfsdb/sqlite_performance_test.go, gtfsdb/synthetic_gtfs_frequency_test.go
Switched DB/query contexts to t.Context()/b.Context(); removed unused context imports; moved temp dirs/files to t.TempDir() and updated permission literals (e.g., 0o755, 0o600). Minor formatting tweaks.
internal/gtfs tests
internal/gtfs/... (advanced_direction_calculator_test.go, agency_filter_test.go, gtfs_manager_test.go, hot_swap_test.go, multi_feed_test.go, parallel_realtime_test.go, realtime_test.go, route_search_test.go, shape_cache_test.go, shapes_test.go, shutdown_test.go, tidy_test.go)
Replaced context.Background() with t.Context() across manager init and query calls; removed context imports; used t.Setenv where applicable. Minor whitespace/formatting cleanup.
internal/restapi tests
internal/restapi/... (arrival_and_departure_for_stop_handler_test.go, arrivals_and_departures_for_stop_handler_test.go, block_handler_test.go, calculate_block_trip_sequence_test.go, context_cancellation_test.go, http_test.go, id_helpers_test.go, input_validation_integration_test.go, openapi_conformance_test.go, route_handler_test.go, servicedate_timezone_regression_test.go, shapes_handler_test.go, stop_handler_test.go, stops_for_route_handler_test.go, trip_for_vehicle_handler_test.go, trip_handler_test.go, trips_helper_test.go, vehicles_for_agency_handler_test.go, vehicles_helper_test.go)
Moved request/DB/handler contexts to t.Context()/b.Context(); removed unused context imports; adjusted some helper signatures/formatting and permission literals.
internal/appconf, logging, metrics, utils
internal/appconf/config_test.go, internal/appconf/json_config_test.go, internal/logging/structured_logging_test.go, internal/metrics/metrics_test.go, internal/utils/filters_test.go
Switched to t.Context() for test contexts; used t.TempDir() for temp files where applicable; removed unused context imports and adjusted import ordering/formatting.
internal/clock & webui
internal/clock/clock_test.go, internal/webui/static_handler_test.go, internal/webui/test_helper_test.go
Created temp files under t.TempDir() and simplified working-dir handling to t.Chdir(); replaced context.Background() with t.Context() for GTFS init; removed explicit cleanup and unused imports.
Miscellaneous small test updates
various test files (e.g., internal/logging/structured_logging_test.go, internal/metrics/metrics_test.go, internal/restapi/block_handler_test.go, internal/restapi/stops_for_route_test.go, etc.)
Various test-specific context replacements, permission-literal modernizations, and minor formatting changes. No behavior or assertions altered.

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • fletcherw
  • Ahmedhossamdev
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.68% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main purpose of this pull request: refactoring tests to use built-in Go testing package helpers instead of manual context and resource handling.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
internal/clock/clock_test.go (1)

137-137: Optional cleanup: remove redundant os.Remove defers.

On Line 137, Line 155, Line 178, Line 243, and Line 299, file-level cleanup is now redundant because t.TempDir() will remove the directory and all created files.

♻️ Suggested simplification
-	defer func() { _ = os.Remove(tmpFile.Name()) }()

Apply this deletion at each listed occurrence.

Also applies to: 155-155, 178-178, 243-243, 299-299

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/clock/clock_test.go` at line 137, Remove the redundant defer calls
that call os.Remove(tmpFile.Name()) in the tests: where tmpFile is created under
t.TempDir() (the five occurrences that currently use defer func() { _ =
os.Remove(tmpFile.Name()) }()). Since t.TempDir() already cleans up the
directory and files, delete those defer statements (references to tmpFile and
the os.Remove defer) to simplify the tests.
gtfsdb/sqlite_performance_test.go (1)

66-67: t.TempDir() cleanup is redundant with explicit os.RemoveAll.

Since t.TempDir() already handles cleanup, these extra defers can be removed to simplify the tests.

♻️ Suggested cleanup
 func TestFileDatabaseConnectionPool(t *testing.T) {
 	// Create temporary directory for test database
 	tmpDir := t.TempDir()
-	defer func() { _ = os.RemoveAll(tmpDir) }()
 
 	dbPath := filepath.Join(tmpDir, "test.db")
 	...
 }
 
 func TestConnectionPoolBehaviorWithFileDatabase(t *testing.T) {
 	// Create temporary directory for test database
 	tmpDir := t.TempDir()
-	defer func() { _ = os.RemoveAll(tmpDir) }()
 
 	dbPath := filepath.Join(tmpDir, "test_concurrent.db")
 	...
 }

Also applies to: 95-96

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gtfsdb/sqlite_performance_test.go` around lines 66 - 67, The test creates
tmpDir with t.TempDir() and then redundantly defers os.RemoveAll(tmpDir); remove
the explicit defer that calls os.RemoveAll for the tmpDir created by t.TempDir()
(i.e., delete the defer func() { _ = os.RemoveAll(tmpDir) }() lines that follow
tmpDir := t.TempDir()), and do the same for the other occurrence around the
second tmpDir usage so cleanup relies on t.TempDir() only.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/gtfs/advanced_direction_calculator_test.go`:
- Around line 35-36: The inline comment above the InitGTFSManager call is stale
(mentions context.Background())—update it to reference the actual context source
t.Context() used here; i.e., change the comment that precedes the
InitGTFSManager(t.Context(), gtfsConfig) invocation to state that we pass
t.Context() to satisfy the new cancellable startup logic so it matches the call
involving InitGTFSManager, sharedManager and gtfsConfig.

---

Nitpick comments:
In `@gtfsdb/sqlite_performance_test.go`:
- Around line 66-67: The test creates tmpDir with t.TempDir() and then
redundantly defers os.RemoveAll(tmpDir); remove the explicit defer that calls
os.RemoveAll for the tmpDir created by t.TempDir() (i.e., delete the defer
func() { _ = os.RemoveAll(tmpDir) }() lines that follow tmpDir := t.TempDir()),
and do the same for the other occurrence around the second tmpDir usage so
cleanup relies on t.TempDir() only.

In `@internal/clock/clock_test.go`:
- Line 137: Remove the redundant defer calls that call os.Remove(tmpFile.Name())
in the tests: where tmpFile is created under t.TempDir() (the five occurrences
that currently use defer func() { _ = os.Remove(tmpFile.Name()) }()). Since
t.TempDir() already cleans up the directory and files, delete those defer
statements (references to tmpFile and the os.Remove defer) to simplify the
tests.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 44e1c1f9-2090-4a17-9fb3-648a6533e9dc

📥 Commits

Reviewing files that changed from the base of the PR and between fc7a10a and 3d21e42.

📒 Files selected for processing (51)
  • cmd/api/app_test.go
  • cmd/api/lock_safety_test.go
  • gtfsdb/bulk_insert_frequency_test.go
  • gtfsdb/bulk_insert_test.go
  • gtfsdb/conditional_import_test.go
  • gtfsdb/connection_pool_test.go
  • gtfsdb/fts_queries_test.go
  • gtfsdb/helpers_test.go
  • gtfsdb/nil_shape_test.go
  • gtfsdb/query_latency_test.go
  • gtfsdb/sqlite_performance_test.go
  • gtfsdb/synthetic_gtfs_frequency_test.go
  • internal/appconf/config_test.go
  • internal/appconf/json_config_test.go
  • internal/clock/clock_test.go
  • internal/gtfs/advanced_direction_calculator_test.go
  • internal/gtfs/agency_filter_test.go
  • internal/gtfs/gtfs_manager_test.go
  • internal/gtfs/hot_swap_test.go
  • internal/gtfs/multi_feed_test.go
  • internal/gtfs/parallel_realtime_test.go
  • internal/gtfs/realtime_test.go
  • internal/gtfs/route_search_test.go
  • internal/gtfs/shape_cache_test.go
  • internal/gtfs/shapes_test.go
  • internal/gtfs/shutdown_test.go
  • internal/gtfs/tidy_test.go
  • internal/logging/structured_logging_test.go
  • internal/metrics/metrics_test.go
  • internal/restapi/arrival_and_departure_for_stop_handler_test.go
  • internal/restapi/arrivals_and_departures_for_stop_handler_test.go
  • internal/restapi/block_handler_test.go
  • internal/restapi/calculate_block_trip_sequence_test.go
  • internal/restapi/context_cancellation_test.go
  • internal/restapi/http_test.go
  • internal/restapi/id_helpers_test.go
  • internal/restapi/input_validation_integration_test.go
  • internal/restapi/openapi_conformance_test.go
  • internal/restapi/route_handler_test.go
  • internal/restapi/servicedate_timezone_regression_test.go
  • internal/restapi/shapes_handler_test.go
  • internal/restapi/stop_handler_test.go
  • internal/restapi/stops_for_route_handler_test.go
  • internal/restapi/trip_for_vehicle_handler_test.go
  • internal/restapi/trip_handler_test.go
  • internal/restapi/trips_helper_test.go
  • internal/restapi/vehicles_for_agency_handler_test.go
  • internal/restapi/vehicles_helper_test.go
  • internal/utils/filters_test.go
  • internal/webui/static_handler_test.go
  • internal/webui/test_helper_test.go

Comment thread internal/gtfs/advanced_direction_calculator_test.go Outdated
Co-authored-by: Copilot <copilot@github.com>
@Not-Dhananjay-Mishra
Copy link
Copy Markdown
Contributor Author

Not-Dhananjay-Mishra commented Apr 25, 2026

@fletcherw If you allow me, I can add .golangci.yml config file that enables the usetesting linter to ensure we use testing package helpers in tests.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
internal/clock/clock_test.go (1)

131-146: Optional: extract repeated temp-file setup into a test helper.

The same CreateTemp + WriteString + Close setup appears in multiple tests. A small helper (e.g., writeTempClockFile(t, content) string) would reduce duplication and make these cases easier to maintain.

Also applies to: 148-163, 165-186, 236-250, 292-309

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/clock/clock_test.go` around lines 131 - 146, Extract the repeated
temp-file creation logic into a helper (e.g., writeTempClockFile(t testing.TB,
content string) string) that calls os.CreateTemp, writes content, closes the
file and returns the path; then update TestEnvironmentClock_FromFile and the
other tests (the ones around lines 148-163, 165-186, 236-250, 292-309) to call
writeTempClockFile(t, expectedTime.Format(time.RFC3339)) and pass the returned
filename into NewEnvironmentClock instead of duplicating
CreateTemp+WriteString+Close in each test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@internal/clock/clock_test.go`:
- Around line 131-146: Extract the repeated temp-file creation logic into a
helper (e.g., writeTempClockFile(t testing.TB, content string) string) that
calls os.CreateTemp, writes content, closes the file and returns the path; then
update TestEnvironmentClock_FromFile and the other tests (the ones around lines
148-163, 165-186, 236-250, 292-309) to call writeTempClockFile(t,
expectedTime.Format(time.RFC3339)) and pass the returned filename into
NewEnvironmentClock instead of duplicating CreateTemp+WriteString+Close in each
test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 792aeb86-3cf4-431b-8c20-ba66f0f4ed0a

📥 Commits

Reviewing files that changed from the base of the PR and between 7b23915 and 403e1ae.

📒 Files selected for processing (2)
  • gtfsdb/sqlite_performance_test.go
  • internal/clock/clock_test.go

@Not-Dhananjay-Mishra Not-Dhananjay-Mishra changed the title Refactor tests to use testing package helpers instead of manual context handling refactor: tests to use testing package helpers instead of manual context handling Apr 25, 2026
@sonarqubecloud
Copy link
Copy Markdown

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.

1 participant