Skip to content

test: cover multiple context migrations#198

Merged
ReneWerner87 merged 2 commits into
masterfrom
codex/2025-08-24-17-25-49
Aug 24, 2025
Merged

test: cover multiple context migrations#198
ReneWerner87 merged 2 commits into
masterfrom
codex/2025-08-24-17-25-49

Conversation

@ReneWerner87
Copy link
Copy Markdown
Member

@ReneWerner87 ReneWerner87 commented Aug 24, 2025

Summary

  • extend context migration tests to cover multiple .Context() invocations and chained call sequences

Testing

  • make lint
  • make test

https://chatgpt.com/codex/tasks/task_e_68ab3e316144832683ee0ff32b1e8917

Summary by CodeRabbit

  • Bug Fixes

    • Improved v3 migration to correctly update chained context accesses, replacing Context() with RequestCtx() in Fiber code paths while preserving method chains and handling multiple occurrences.
  • Tests

    • Added test coverage for chained and multiple context usages to ensure accurate migration behavior.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 24, 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.

Warning

Rate limit exceeded

@ReneWerner87 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b582f13 and 0a8408e.

📒 Files selected for processing (2)
  • cmd/internal/migrations/v3/context_methods.go (2 hunks)
  • cmd/internal/migrations/v3/context_methods_test.go (2 hunks)

Walkthrough

Expands the v3 context migration to detect chained receiver calls before Context() and adjust replacements to preserve the chain for Fiber by converting the chain’s suffix to RequestCtx(). Adds tests covering chained and multiple Context() occurrences and verifying migration logs.

Changes

Cohort / File(s) Summary
Migration logic update
cmd/internal/migrations/v3/context_methods.go
Extends regex to match chained calls ending with .Context(). For Fiber, replaces the entire matched chain’s .Context() with .RequestCtx() while preserving preceding calls. Non-Fiber behavior unchanged.
Test coverage expansion
cmd/internal/migrations/v3/context_methods_test.go
Adds tests for chained .Context() replacement and multiple occurrences, asserting correct .RequestCtx() substitutions and migration logging.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Dev as Developer Code
  participant Migr as MigrateContextMethods
  participant Rx as Regex Matcher
  participant Repl as Replacer

  Dev->>Migr: Provide source with chained calls (e.g., foo.Bar().Context())
  Migr->>Rx: Scan for chains ending in .Context()
  Rx-->>Migr: Matches with root+chain (non-greedy)
  Migr->>Repl: If Fiber receiver, replace suffix .Context() -> .RequestCtx()
  Repl-->>Migr: Transformed source (foo.Bar().RequestCtx())
  Migr-->>Dev: Output migrated code + log entry
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Update context migrator logic #153 — Adjusts MigrateContextMethods to better handle .Context() replacements, including regex-based handling and preservation of chained calls.

Suggested labels

🧹 Updates

Poem

A hop and a skip through Context we go,
Chained little calls now neatly in tow.
RequestCtx appears—thump-thump—what a fix!
Logs leave a trail of migration tricks.
With ears up high, I ship this patch—
Buggy burrows? Not on my watch! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/2025-08-24-17-25-49

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @ReneWerner87, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request extends the context migration tool to handle more complex scenarios involving multiple and chained .Context() invocations, ensuring a more robust and complete migration from Context() to RequestCtx(). This is primarily achieved by updating the regular expression used for matching and adding comprehensive test cases to validate the new logic.

Highlights

  • Enhanced Context Migration Logic: The regular expression used for migrating Context() method calls has been updated to correctly identify and replace instances within chained method calls (e.g., obj.Method().Context()).
  • Improved Migration Replacement: The replacement logic for Context() calls now intelligently preserves any preceding method calls in a chain, ensuring only the Context() part is transformed to `RequestCtx().
  • New Test Cases for Chained Calls: A new test, Test_MigrateContextMethods_RequestCtxChained, has been added to verify the migration tool's ability to handle Context() calls that are part of a method chain.
  • New Test Cases for Multiple Invocations: A new test, Test_MigrateContextMethods_MultipleContextCalls, has been introduced to ensure the migration tool correctly handles scenarios where Context() is invoked multiple times within the same code block, including a mix of standalone and chained calls.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request extends the context migration logic to handle chained method calls before .Context(), which is a good improvement. The changes are supported by new test cases. However, I've identified a potential issue with the regular expression used for matching, which could lead to silent failures during migration in more complex scenarios. My review includes one high-severity comment detailing this concern.

Comment thread cmd/internal/migrations/v3/context_methods.go Outdated
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 (4)
cmd/internal/migrations/v3/context_methods.go (2)

50-50: Broaden the regex to tolerate whitespace, newlines, and generic type arguments in chained calls

The current pattern won’t match multi-line fluent chains or methods with type arguments (e.g., .Map[K,V](...)). Consider a more permissive RE2 pattern to reduce false negatives.

Apply this diff:

-		reReqCtx := regexp.MustCompile(`(\w+)(?:\.[\w]+\([^)]*\))*\.Context\(\)`)
+		// Matches: <ident>(.<Method[TypeArgs]>(...))* .Context()
+		// - Allows optional spaces/newlines around dots and calls
+		// - Allows optional generic type arguments after method names
+		// Note: Still heuristic; nested parentheses in args are not handled by regex.
+		reReqCtx := regexp.MustCompile(`\b([A-Za-z_]\w*)(?:\s*\.\s*[A-Za-z_]\w*(?:\[[^\]]*\])?\s*\([^()]*\))*\s*\.\s*Context\(\)`)

50-58: Avoid accidental rewrites inside strings/comments; consider AST-driven migration or tighter guards

Regex-based rewriting can still hit string literals or comments that contain “.Context()”. If feasible, prefer parsing with go/parser to find CallExpr whose Fun is a SelectorExpr with Sel.Name == "Context" and whose X resolves to a Fiber Ctx symbol. If AST is out of scope, minimally extend tests to assert we don’t rewrite within quotes/comments.

Would you like me to open a follow-up to prototype an AST-based rewriter, or add non-code (string/comment) fixture tests that must remain unchanged?

cmd/internal/migrations/v3/context_methods_test.go (2)

103-106: Good guard: non-Fiber types remain untouched

Verifies we don’t rewrite look-alikes on foreign types. Consider adding a chained non-Fiber call (e.g., x.Foo().Context()) to strengthen this guarantee.


149-173: Good multi-occurrence coverage; consider adding multi-line and generic cases

Covers multiple occurrences on one file including a chain. To further harden against false negatives:

  • Multi-line chain:
    • c.\n Status(...).\n Context().SetBody...
  • Generic method in chain (if present in your codebase):
    • c.Map[string,string](m).Context()...

Optionally add tests like:

+func Test_MigrateContextMethods_RequestCtxChainedMultiline(t *testing.T) {
+	t.Parallel()
+	dir, err := os.MkdirTemp("", "mcmtestchainml")
+	require.NoError(t, err)
+	defer func() { require.NoError(t, os.RemoveAll(dir)) }()
+	file := writeTempFile(t, dir, `package main
+import "github.com/gofiber/fiber/v2"
+func handler(c fiber.Ctx) error {
+    c.
+      Status(fiber.StatusOK).
+      Context().
+      SetBodyStreamWriter(nil)
+    return nil
+}`)
+	var buf bytes.Buffer
+	cmd := newCmd(&buf)
+	require.NoError(t, v3.MigrateContextMethods(cmd, dir, nil, nil))
+	content := readFile(t, file)
+	assert.Contains(t, content, ".RequestCtx().SetBodyStreamWriter")
+	assert.NotContains(t, content, ".Context().SetBodyStreamWriter")
+}
+
+func Test_MigrateContextMethods_DoesNotRewriteInStringsOrComments(t *testing.T) {
+	t.Parallel()
+	dir, err := os.MkdirTemp("", "mcmteststrings")
+	require.NoError(t, err)
+	defer func() { require.NoError(t, os.RemoveAll(dir)) }()
+	file := writeTempFile(t, dir, `package main
+import "github.com/gofiber/fiber/v2"
+// c.Context() should not be touched in comments
+func handler(c fiber.Ctx) error {
+    _ = "literal with c.Context() that must not change"
+    return nil
+}`)
+	var buf bytes.Buffer
+	cmd := newCmd(&buf)
+	require.NoError(t, v3.MigrateContextMethods(cmd, dir, nil, nil))
+	content := readFile(t, file)
+	assert.Contains(t, content, `literal with c.Context()`)
+	// If regex-based rewriting is kept, this test documents the current limitation.
+}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 23d8879 and b582f13.

📒 Files selected for processing (2)
  • cmd/internal/migrations/v3/context_methods.go (1 hunks)
  • cmd/internal/migrations/v3/context_methods_test.go (2 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
📚 Learning: 2024-11-10T23:44:13.704Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.

Applied to files:

  • cmd/internal/migrations/v3/context_methods_test.go
  • cmd/internal/migrations/v3/context_methods.go
📚 Learning: 2024-11-08T04:10:42.990Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.

Applied to files:

  • cmd/internal/migrations/v3/context_methods.go
📚 Learning: 2024-11-29T15:24:06.083Z
Learnt from: ReneWerner87
PR: gofiber/contrib#0
File: :0-0
Timestamp: 2024-11-29T15:24:06.083Z
Learning: When customizing the Fiber context to achieve version independence, using generics in methods like `Status` and `Type` allows for fluent method chaining. Implementing a generic interface for `Ctx` on the `App` prevents class switching when registering custom contexts that use fluent methods. Providing multiple `New` methods allows users who do not wish to customize the context to continue using `fiber.New` without changes.

Applied to files:

  • cmd/internal/migrations/v3/context_methods.go
🧬 Code graph analysis (1)
cmd/internal/migrations/v3/context_methods_test.go (1)
cmd/internal/migrations/v3/context_methods.go (1)
  • MigrateContextMethods (14-74)
⏰ 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). (3)
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, windows-latest)
🔇 Additional comments (2)
cmd/internal/migrations/v3/context_methods.go (1)

50-58: Chain-preserving replacement for Context() ➜ RequestCtx() is correct

Capturing the root identifier and using TrimSuffix to preserve any preceding fluent chain ensures c.Status(...).Context() migrates to c.Status(...).RequestCtx() without breaking the chain. This aligns with the Fiber v3 change where Context() was renamed to RequestCtx(). Good improvement.

cmd/internal/migrations/v3/context_methods_test.go (1)

125-147: Solid coverage for chained Context() ➜ RequestCtx()

This test validates the new chain-preserving behavior and confirms the migration log is emitted. Nicely scoped.

@ReneWerner87 ReneWerner87 merged commit 089373c into master Aug 24, 2025
13 checks passed
@ReneWerner87 ReneWerner87 deleted the codex/2025-08-24-17-25-49 branch August 24, 2025 17:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant