Skip to content

fix: add testify import for utils migration#167

Closed
ReneWerner87 wants to merge 1 commit into
masterfrom
codex/2025-08-22-22-55-47
Closed

fix: add testify import for utils migration#167
ReneWerner87 wants to merge 1 commit into
masterfrom
codex/2025-08-22-22-55-47

Conversation

@ReneWerner87
Copy link
Copy Markdown
Member

@ReneWerner87 ReneWerner87 commented Aug 22, 2025

Summary

  • ensure utils.AssertEqual is migrated to assert.Equal with testify import
  • cover assert import handling in utils migration tests

Testing

  • go mod tidy
  • go mod download
  • go mod vendor
  • go test ./...

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

Summary by CodeRabbit

  • New Features

    • Migration now automatically adds the assertion library import when assertions are introduced.
    • Enhanced utils migration to update legacy utility imports and usages to their modern equivalents.
  • Bug Fixes

    • Ensures migrated code compiles without manual import edits by injecting missing imports as needed.
  • Tests

    • Updated tests to verify new import injection and utils replacement logic, confirming old imports are removed and new ones are present.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 22, 2025

Walkthrough

Introduces addImport to inject Go imports and updates MigrateUtilsImport to auto-add github.com/stretchr/testify/assert when replacing utils.AssertEqual with assert.Equal. Corresponding tests are updated to reflect rewritten utils imports/usages and the new assert import and usage.

Changes

Cohort / File(s) Summary
Migration logic updates
cmd/internal/migrations/v3/common.go
Adds addImport helper handling multi-line, single-line, or absent import blocks; updates MigrateUtilsImport to detect "assert.Equal" and ensure github.com/stretchr/testify/assert is imported after utils-to-utils/v2 and AssertEqual→assert.Equal rewrites.
Tests for migration logic
cmd/internal/migrations/v3/common_test.go
Adjusts expectations to assert testify import and assert.Equal usage; verifies utils package path rewrites and function replacements (Trim*, EqualFold, GetString/GetBytes) and removal of obsolete utils.AssertEqual/ImmutableString; confirms old fiber/v3/utils import removal.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Developer
  participant Mig as MigrateUtilsImport
  participant AI as addImport

  Dev->>Mig: Run migration on Go source content
  activate Mig
  Mig->>Mig: Rewrite utils.* usages<br/>Replace utils.AssertEqual → assert.Equal
  alt "assert.Equal" detected
    Mig->>AI: addImport(content, "github.com/stretchr/testify/assert")
    activate AI
    AI-->>Mig: content with assert import injected
    deactivate AI
  else No assert usage
    Mig-->>Dev: content with utils rewrites only
  end
  Mig-->>Dev: Final migrated content
  deactivate Mig
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested labels

☢️ Bug

Poem

I nibble on code like clover at dawn,
Hop-hop through imports—then poof, they’re on!
Assert I shall, with whiskers bright,
addImport burrows and sets it right.
Carrots compiled, my tests all pass—
Thump! Migration done, swift as grass.

✨ 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-22-22-55-47

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.

@github-actions github-actions Bot added ☢️ Bug Something isn't working ✏️ Feature New feature or request 🧹 Updates labels Aug 22, 2025
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 introduces a fix to the v3 migration script, specifically enhancing the MigrateUtilsImport function. The primary goal is to ensure that when utils.AssertEqual is migrated to assert.Equal, the necessary github.com/stretchr/testify/assert import is automatically added to the Go files. This change also includes new test cases to validate the correct handling of this import.

Highlights

  • Automated Testify Import: Implemented a new addImport helper function to dynamically add Go package imports, ensuring github.com/stretchr/testify/assert is included when utils.AssertEqual is replaced with assert.Equal.
  • Migration Logic Enhancement: Updated the MigrateUtilsImport function to utilize the new addImport logic, making the migration of utils.AssertEqual more robust by handling its dependency.
  • Improved Migration Test Coverage: Extended the test suite for utils migration to explicitly cover the utils.AssertEqual replacement and verify the correct addition of the testify/assert import.
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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cmd/internal/migrations/v3/common.go (1)

560-564: Add missing stdlib import for strings helpers introduced by this migration.

You rewrite utils string helpers to strings.Trim*/strings.EqualFold but never ensure the "strings" package is imported. This will break compilation for files that didn’t already import strings.

Add this guard right after mapping utils.* → strings.*:

  // map removed string helpers to the strings package
  content = strings.ReplaceAll(content, "utils.TrimRight", "strings.TrimRight")
  content = strings.ReplaceAll(content, "utils.TrimLeft", "strings.TrimLeft")
  content = strings.ReplaceAll(content, "utils.Trim", "strings.Trim")
  content = strings.ReplaceAll(content, "utils.EqualFold", "strings.EqualFold")
+
+ // ensure stdlib strings import exists when we introduced strings.* calls
+ if strings.Contains(content, "strings.Trim") || strings.Contains(content, "strings.EqualFold") {
+ 	content = addImport(content, "strings")
+ }

Consider extending tests to assert that the "strings" import is present after migration. I can add that if you want.

🧹 Nitpick comments (2)
cmd/internal/migrations/v3/common.go (1)

535-538: Avoid creating multiple import blocks when multiple single-line imports exist.

The ReplaceAllString call will convert every single-line import into a separate import block, which can break files that have multiple single import declarations. Convert only the first single-line import into a block and insert the new import there.

Apply this diff:

-reSingle := regexp.MustCompile(`(?m)^import\s+([^\n]+)`) // matches single import line
-if reSingle.MatchString(content) {
-	return reSingle.ReplaceAllString(content, fmt.Sprintf("import (\n\t$1\n\t%s\n)", importStmt))
-}
+reSingle := regexp.MustCompile(`(?m)^import\s+([^\n]+)$`) // matches a single import declaration on its own line
+if loc := reSingle.FindStringIndex(content); loc != nil {
+	sub := reSingle.FindStringSubmatch(content[loc[0]:loc[1]])
+	if len(sub) == 2 {
+		repl := fmt.Sprintf("import (\n\t%s\n\t%s\n)", sub[1], importStmt)
+		return content[:loc[0]] + repl + content[loc[1]:]
+	}
+}
cmd/internal/migrations/v3/common_test.go (1)

587-588: Assertion for testify import is correct and necessary.

This verifies the core objective of the PR (auto-import assert). Once you add the “strings” import guard in the migration, consider adding a sibling assertion to ensure "strings" is imported when strings.* calls are introduced.

I can update the test to also assert the presence of the strings import if you apply the migration change.

📜 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 0a9ffbb and 7070462.

📒 Files selected for processing (2)
  • cmd/internal/migrations/v3/common.go (2 hunks)
  • cmd/internal/migrations/v3/common_test.go (4 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.
📚 Learning: 2024-11-15T07:56:21.623Z
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
📚 Learning: 2024-12-13T08:14:22.851Z
Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
🪛 GitHub Check: lint
cmd/internal/migrations/v3/common.go

[failure] 525-525:
sprintfQuotedString: use %q instead of "%s" for quoted strings (gocritic)

🪛 GitHub Actions: golangci-lint
cmd/internal/migrations/v3/common.go

[error] 525-525: golangci-lint (gocritic): sprintfQuotedString should use %q instead of "%s" for quoted strings.

🔇 Additional comments (4)
cmd/internal/migrations/v3/common.go (1)

576-578: Good: conditional assert import injection is idempotent and localized.

Replacing utils.AssertEqual → assert.Equal and then calling addImport only when assert.Equal is present keeps the change tight and avoids duplicate imports.

cmd/internal/migrations/v3/common_test.go (3)

578-579: Nice trigger for the migration path.

Adding a utils.AssertEqual usage in the fixture is a clean way to exercise the assert import injection.


597-597: Covers removal of legacy helper usage.

Ensuring utils.AssertEqual no longer appears post-migration is the right negative check.


609-609: Validates new API usage.

Checking for assert.Equal confirms the rewrite outcome.

}

func addImport(content, pkg string) string {
importStmt := fmt.Sprintf("\"%s\"", pkg)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix lint: use %q instead of "%s" when building a quoted string.

golangci-lint/gocritic is right here. Use %q to build a quoted import literal.

Apply this diff:

-	importStmt := fmt.Sprintf("\"%s\"", pkg)
+	importStmt := fmt.Sprintf("%q", pkg)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
importStmt := fmt.Sprintf("\"%s\"", pkg)
importStmt := fmt.Sprintf("%q", pkg)
🧰 Tools
🪛 GitHub Check: lint

[failure] 525-525:
sprintfQuotedString: use %q instead of "%s" for quoted strings (gocritic)

🪛 GitHub Actions: golangci-lint

[error] 525-525: golangci-lint (gocritic): sprintfQuotedString should use %q instead of "%s" for quoted strings.

🤖 Prompt for AI Agents
In cmd/internal/migrations/v3/common.go around line 525, the code builds a
quoted import string using fmt.Sprintf("\"%s\"", pkg); replace that with
fmt.Sprintf("%q", pkg) to use the correct formatting verb for quoted strings and
satisfy the linter; update the call accordingly so the resulting string remains
the same but uses %q.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@ReneWerner87 ReneWerner87 deleted the codex/2025-08-22-22-55-47 branch September 4, 2025 10:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

☢️ Bug Something isn't working codex ✏️ Feature New feature or request 🧹 Updates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant