-
Notifications
You must be signed in to change notification settings - Fork 1.7k
fix(assert): avoid panic on invalid regex in Regexp/NotRegexp (#1794) #1818
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kdt523
wants to merge
2
commits into
stretchr:master
Choose a base branch
from
kdt523:fix/assert-regexp-compile-error
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+41
−8
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -1708,22 +1708,28 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in | |||||
| return true | ||||||
| } | ||||||
|
|
||||||
| // matchRegexp return true if a specified regexp matches a string. | ||||||
| func matchRegexp(rx interface{}, str interface{}) bool { | ||||||
| // matchRegexp returns whether the compiled regular expression matches the provided | ||||||
| // value. If rx is not a *regexp.Regexp, rx is formatted with fmt.Sprint and compiled. | ||||||
| // When compilation fails, an error is returned instead of panicking. | ||||||
| func matchRegexp(rx interface{}, str interface{}) (bool, error) { | ||||||
| var r *regexp.Regexp | ||||||
| if rr, ok := rx.(*regexp.Regexp); ok { | ||||||
| r = rr | ||||||
| } else { | ||||||
| r = regexp.MustCompile(fmt.Sprint(rx)) | ||||||
| var err error | ||||||
| r, err = regexp.Compile(fmt.Sprint(rx)) | ||||||
| if err != nil { | ||||||
| return false, err | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| switch v := str.(type) { | ||||||
| case []byte: | ||||||
| return r.Match(v) | ||||||
| return r.Match(v), nil | ||||||
| case string: | ||||||
| return r.MatchString(v) | ||||||
| return r.MatchString(v), nil | ||||||
| default: | ||||||
| return r.MatchString(fmt.Sprint(v)) | ||||||
| return r.MatchString(fmt.Sprint(v)), nil | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
|
|
@@ -1736,7 +1742,11 @@ func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface | |||||
| h.Helper() | ||||||
| } | ||||||
|
|
||||||
| match := matchRegexp(rx, str) | ||||||
| match, err := matchRegexp(rx, str) | ||||||
| if err != nil { | ||||||
| Fail(t, fmt.Sprintf("invalid regular expression %q: %v", fmt.Sprint(rx), err), msgAndArgs...) | ||||||
| return false | ||||||
| } | ||||||
|
|
||||||
| if !match { | ||||||
| Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) | ||||||
|
|
@@ -1753,7 +1763,11 @@ func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interf | |||||
| if h, ok := t.(tHelper); ok { | ||||||
| h.Helper() | ||||||
| } | ||||||
| match := matchRegexp(rx, str) | ||||||
| match, err := matchRegexp(rx, str) | ||||||
| if err != nil { | ||||||
| Fail(t, fmt.Sprintf("invalid regular expression %q: %v", fmt.Sprint(rx), err), msgAndArgs...) | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This would be better, no?
Suggested change
|
||||||
| return false | ||||||
| } | ||||||
|
|
||||||
| if match { | ||||||
| Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) | ||||||
|
|
||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| package assert | ||
|
|
||
| import "testing" | ||
|
|
||
| // Verifies that invalid patterns no longer cause a panic when using Regexp/NotRegexp. | ||
| // Instead, the assertion should fail and return false. | ||
| func TestRegexp_InvalidPattern_NoPanic(t *testing.T) { | ||
| NotPanics(t, func() { | ||
| mockT := new(testing.T) | ||
| False(t, Regexp(mockT, "\\C", "whatever")) | ||
| }) | ||
| } | ||
|
|
||
| func TestNotRegexp_InvalidPattern_NoPanic(t *testing.T) { | ||
| NotPanics(t, func() { | ||
| mockT := new(testing.T) | ||
| False(t, NotRegexp(mockT, "\\C", "whatever")) | ||
| }) | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This would be better, no?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @ccoVeille — thanks for the suggestion, very helpful to question that line.
Quick reason I didn’t pass rx directly to %q: %q expects a string (or string-like) value. In our code rx is an interface{} and callers sometimes pass a compiled *regexp.Regexp. If you do fmt.Sprintf("%q", rx) with a *regexp.Regexp, Go prints an unhelpful %!q(...) type dump instead of the pattern. That makes the error message confusing.
Small examples:
rx := "start" → fmt.Sprintf("%q", rx) => "start" (good)
rx := regexp.MustCompile("start") → fmt.Sprintf("%q", rx) => %!q(*regexp.Regexp=...) (bad)
Safe alternatives
1.Keep the quoted style by converting rx to a string first:
fmt.Sprintf("invalid regular expression %q: %v", fmt.Sprint(rx), err)
Pros: preserves a quoted pattern; simple.
2.Don’t quote, just use %v:
fmt.Sprintf("invalid regular expression %v: %v", rx, err)
Pros: always works for any type; no weird %!q output. Cons: loses the quoted look.
3.(Preferred) Be explicit: if rx is a *regexp.Regexp, call .String(), otherwise fall back to fmt.Sprint:
var rxStr string
switch v := rx.(type) {
case *regexp.Regexp:
rxStr = v.String()
default:
rxStr = fmt.Sprint(rx)
}
Fail(t, fmt.Sprintf("invalid regular expression %q: %v", rxStr, err), msgAndArgs...)
Pros: most robust and readable; shows the actual pattern for compiled regexps and handles any other types cleanly.
If you’re OK with that, I can apply option 3 (tiny, explicit change) to the fix/assert-regexp-compile-error branch and push it. If you prefer a simpler tweak, I can apply option 1 instead — tell me which and I’ll open a small commit/PR.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I thought %q would behave the same way %s with quote.
I checked https://cs.opensource.google/go/go/+/master:src/fmt/format.go
I'm a bit surprised it would differ.
Your reply sounds like it would, I will have to check further.
But for now, let's say the code can stay like you did.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm still doubtful
https://go.dev/play/p/WBwS5ClJU0i
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You’re right that for *regexp.Regexp, %q and %s both output the pattern, with %q just adding quotes. In most cases, this isn’t harmful.
My main reason for switching to %v (or [fmt.Sprint]) was to avoid unnecessary quoting and ensure consistent, clear error messages—especially if the input isn’t a string or is a different type. This way, the formatting is robust for all cases, not just regex patterns.
If you find any edge cases where %q would be preferable, I’m happy to revisit! For now, I think the current approach is a bit safer and more general. Thanks again for your thoughtful feedback!