Skip to content

feat(fakes/fakectx): introduce fakectx package for testing contexts 🧪#12

Merged
madflojo merged 11 commits intomainfrom
ctx
Nov 24, 2025
Merged

feat(fakes/fakectx): introduce fakectx package for testing contexts 🧪#12
madflojo merged 11 commits intomainfrom
ctx

Conversation

@madflojo
Copy link
Copy Markdown
Owner

@madflojo madflojo commented Nov 23, 2025

This pull request introduces a new package, fakes/fakectx, which provides ready-made context.Context helpers for testing cancellation and deadline scenarios in Go. The package is fully documented, tested, and integrated into the build and documentation systems. It allows test authors to easily simulate various context states (like canceled or timed out) without boilerplate code.

Key changes:

New package: fakes/fakectx

  • Added the fakes/fakectx package, which provides helpers such as Cancelled, DeadlineExceeded, TimedOut, TimesOutAfter, and CancelledWithCallback for generating contexts in specific states for testing purposes. These helpers simplify writing tests that need to trigger cancelation or deadline logic.
  • Included comprehensive unit tests (fakectx_test.go) and example usage (fakectx_example_test.go) to ensure correctness and demonstrate usage patterns. [1] [2]
  • Added a Makefile for the new package to support building, testing, linting, formatting, and benchmarking.
  • Created a standalone go.mod file for the new package, specifying module path and Go version.

Documentation and build integration

  • Updated the main README.md to document the new fakes/fakectx package, including a usage example and a new entry in the package structure table. [1] [2] [3]
  • Added fakes/fakectx to the root Makefile so its tests and builds are included in project-wide commands.
  • Updated testlazy.go to remove the "coming soon" note for fakes/fakectx, reflecting its availability.

Summary by CodeRabbit

  • New Features

    • Added a helpers module offering ready-made contexts for canceled, deadline-exceeded, and timeout scenarios.
  • Documentation

    • README updated to include helpers, a usage section for cancel-aware contexts, and structure reference.
  • Tests

    • Added example usage snippets and unit tests validating helper behaviors.
  • Chores

    • Added module-local build/test/format/lint targets to streamline developer workflows.

✏️ Tip: You can customize this high-level summary in your review settings.

Added a new `fakectx` package to simplify creation of test contexts with specific behaviors,
making it easier to fake it 'til you make it in your test suite!
Added usage examples and references for the fakectx package. Now, cancelling contexts is like waving a magic wand—wish granted! 🪄
Implemented new context helpers: `DeadlineExceeded`, `TimedOut`, and `TimesOutAfter`. Perfect for testing time-related conundrums. Pushing contexts beyond their limits, one test at a time!
Enhanced error checking in tests by adopting errors.Is. Now context errors are easier to spot.
Refined docstrings for clarity and added example tests for context helpers. Making testing as easy as pie!
Added the `CancelledWithCallback` function to invoke a callback upon context cancellation. No more excuses for lazy callbacks! Enhanced tests to ensure callbacks are punctual and polite.
Simplified example outputs for `fakectx` test functions. Because some truths deserve clarity!
Copilot AI review requested due to automatic review settings November 23, 2025 23:10
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Nov 23, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds a new package fakes/fakectx providing preconfigured contexts (cancelled, deadline-exceeded, timed out, timed future timeout, and cancelled-with-callback), with examples, tests, module file, and Makefile; integrates the package into the top-level Makefile and updates docs.

Changes

Cohort / File(s) Change Summary
Core impl & tests
fakes/fakectx/fakectx.go, fakes/fakectx/fakectx_test.go, fakes/fakectx/fakectx_example_test.go
New package exposing Cancelled(), DeadlineExceeded(), TimedOut(), TimesOutAfter(time.Duration), and CancelledWithCallback(func()) (context.Context, context.CancelFunc). Includes unit tests and example tests for Done/Err/Deadline/callback semantics.
Module & local tooling
fakes/fakectx/go.mod, fakes/fakectx/Makefile
New Go module github.com/madflojo/testlazy/fakes/fakectx (Go 1.24.3) and a Makefile with targets: all, build, tests (coverage), benchmarks, format, lint, coverage, clean; conditional checks for optional tools.
Top-level wiring
Makefile
Adds fakes/fakectx to COMPONENTS so root-level test/build/format/lint flows include the new package.
Documentation & module list
README.md, testlazy.go
README updated to list “helpers” and adds a fakectx section with examples; testlazy.go removed “(coming soon)” annotation for the fakectx module.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test code
    participant Fakectx as fakectx helpers
    participant Context as context.Context

    Note over Test,Fakectx: Acquire a test context
    Test->>Fakectx: Cancelled() / DeadlineExceeded() / TimedOut() / TimesOutAfter(d) / CancelledWithCallback(cb)
    Fakectx-->>Test: returns preconfigured Context (and CancelFunc when applicable)

    alt CancelledWithCallback
        Test->>Context: call CancelFunc()
        Context->>Fakectx: trigger callback (sync.Once guard)
        Fakectx-->>Test: Done closed, Err == context.Canceled
    else Timeout/Deadline
        Note over Context: immediate or future deadline set
        Context-->>Test: Done closed when deadline reached, Err == context.DeadlineExceeded
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review concurrency/callback behavior in CancelledWithCallback() (use of sync.Once and CancelFunc composition).
  • Verify Done/Err immediacy for Cancelled(), TimedOut(), and DeadlineExceeded().
  • Check TimesOutAfter() deadline math and test timing to avoid flakiness.
  • Inspect Makefile conditional flows for portability.

Poem

🐇 I hopped in with contexts neat and small,
Cancels and timeouts to help tests stand tall,
A callback that fires just once, not more,
Examples, tests, and tooling by the door —
Happy testing from my rabbit hole! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: introduction of a new fakectx package for testing contexts, which is the primary objective of this PR.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ctx

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 129aec2 and c24dc95.

📒 Files selected for processing (1)
  • fakes/fakectx/fakectx.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • fakes/fakectx/fakectx.go

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.

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Nov 23, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (40819cc) to head (c24dc95).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main       #12   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            2         3    +1     
  Lines          102       127   +25     
=========================================
+ Hits           102       127   +25     
Flag Coverage Δ
./fakes/fakectx-unittests 100.00% <100.00%> (?)
./helpers/counter-unittests 100.00% <ø> (ø)
./things/testurl-unittests 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR introduces the fakes/fakectx package, providing pre-built context helpers for testing cancellation and deadline scenarios. The package simplifies test authoring by offering ready-made contexts in various states (cancelled, timed out, etc.) without requiring boilerplate setup code.

Key Changes:

  • New fakes/fakectx package with five helper functions: Cancelled(), DeadlineExceeded(), TimedOut(), TimesOutAfter(), and CancelledWithCallback()
  • Comprehensive test coverage and example tests demonstrating usage patterns
  • Integration into build system and documentation

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
fakes/fakectx/go.mod Defines the module path and Go version for the new package
fakes/fakectx/fakectx.go Core implementation of context helper functions
fakes/fakectx/fakectx_test.go Comprehensive unit tests covering all helper functions
fakes/fakectx/fakectx_example_test.go Example tests demonstrating usage patterns
fakes/fakectx/Makefile Build, test, and lint configuration for the package
README.md Documentation updates including usage example and package table entry
testlazy.go Removes "coming soon" notation for fakectx package
Makefile Adds fakectx to the list of components for project-wide builds

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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: 0

🧹 Nitpick comments (1)
fakes/fakectx/fakectx_example_test.go (1)

43-45: Simplify the nil error check.

The pattern !errors.Is(ctx.Err(), nil) is unnecessarily convoluted for checking if an error is non-nil. A direct comparison improves readability.

Apply this diff to simplify the check:

-	if !errors.Is(ctx.Err(), nil) {
+	if ctx.Err() != nil {
 		fmt.Println("Timeout too soon")
 	}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78731b8 and d4de21f.

📒 Files selected for processing (8)
  • Makefile (1 hunks)
  • README.md (3 hunks)
  • fakes/fakectx/Makefile (1 hunks)
  • fakes/fakectx/fakectx.go (1 hunks)
  • fakes/fakectx/fakectx_example_test.go (1 hunks)
  • fakes/fakectx/fakectx_test.go (1 hunks)
  • fakes/fakectx/go.mod (1 hunks)
  • testlazy.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
fakes/fakectx/fakectx_example_test.go (1)
fakes/fakectx/fakectx.go (5)
  • Cancelled (20-25)
  • DeadlineExceeded (30-35)
  • TimedOut (39-44)
  • TimesOutAfter (49-57)
  • CancelledWithCallback (62-76)
fakes/fakectx/fakectx_test.go (1)
fakes/fakectx/fakectx.go (5)
  • Cancelled (20-25)
  • DeadlineExceeded (30-35)
  • TimedOut (39-44)
  • TimesOutAfter (49-57)
  • CancelledWithCallback (62-76)
🪛 checkmake (0.2.2)
fakes/fakectx/Makefile

[warning] 6-6: Target body for "tests" exceeds allowed length of 5 (6).

(maxbodylength)


[warning] 25-25: Target body for "format" exceeds allowed length of 5 (12).

(maxbodylength)


[warning] 40-40: Target body for "lint" exceeds allowed length of 5 (6).

(maxbodylength)


[warning] 1-1: Missing required phony target "test"

(minphony)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Agent
🔇 Additional comments (7)
testlazy.go (1)

11-11: LGTM! Documentation updated appropriately.

The removal of "(coming soon)" correctly reflects that the fakes/fakectx package is now available.

README.md (1)

5-5: LGTM! Documentation clearly describes the new package.

The README updates accurately document the fakectx package with a clear example demonstrating context cancellation testing. The addition of "helpers" to the project description appropriately reflects the expanded scope.

Also applies to: 97-109, 122-122

fakes/fakectx/Makefile (1)

1-57: LGTM! Well-structured Makefile with comprehensive CI targets.

The Makefile provides all necessary targets (tests, build, format, lint, coverage, benchmarks) with appropriate tool availability checks and graceful fallbacks when optional tools are missing.

Makefile (1)

5-5: LGTM! Component integration looks correct.

Adding fakes/fakectx to the COMPONENTS list properly integrates the new package into project-wide test, build, format, and lint workflows.

fakes/fakectx/fakectx_test.go (1)

11-259: LGTM! Comprehensive and well-structured tests.

The test suite thoroughly validates all helper functions with appropriate coverage of:

  • Error types and states (Canceled vs DeadlineExceeded)
  • Done channel closure timing (immediate vs delayed)
  • Deadline reporting (past vs future)
  • Callback invocation and idempotency
  • Standard library interface compatibility

Excellent use of parallel test execution and atomic operations for concurrency testing.

fakes/fakectx/fakectx.go (1)

20-76: LGTM! All context helper implementations are correct.

The five helper functions provide clear, well-documented test utilities:

  • Cancelled(): Correctly creates an immediately-cancelled context
  • DeadlineExceeded(): Properly returns a context with a past deadline
  • TimedOut(): Appropriately uses zero timeout with deferred cleanup
  • TimesOutAfter(): The goroutine calling cancel() after timeout may seem redundant since the context auto-expires, but it follows Go's recommendation to call cancel() to release resources early
  • CancelledWithCallback(): Excellent use of sync.Once to guarantee single callback execution with proper nil checking

The implementations are clean, efficient, and well-suited for test scenarios.

fakes/fakectx/go.mod (1)

3-3: I need to verify whether Go 1.24.3 is a valid, released version specifically.

Go 1.24.3 is a valid, released version—no changes needed.

Go 1.24.3 was released on May 6, 2025, and includes security fixes to the os package, as well as bug fixes to the runtime, the compiler, the linker, the go command, and the crypto/tls and os packages. While Go 1.25.4 (released November 5, 2025) is the latest stable release, using Go 1.24.3 is perfectly valid for module development. The go.mod version specifies the minimum supported Go version, not necessarily the latest.

madflojo and others added 3 commits November 23, 2025 16:25
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Added a go routine to ensure cancel is called to prevent resource leaks. Even timeouts need a tidy up!
@madflojo
Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Nov 24, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@madflojo madflojo merged commit 5510b54 into main Nov 24, 2025
15 checks passed
@madflojo madflojo deleted the ctx branch November 24, 2025 00:52
@github-actions github-actions bot mentioned this pull request Nov 24, 2025
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.

3 participants