Skip to content

assert: return error instead of panicking on invalid regexp#1849

Open
veeceey wants to merge 1 commit intostretchr:masterfrom
veeceey:fix/issue-1794-regexp-panic
Open

assert: return error instead of panicking on invalid regexp#1849
veeceey wants to merge 1 commit intostretchr:masterfrom
veeceey:fix/issue-1794-regexp-panic

Conversation

@veeceey
Copy link

@veeceey veeceey commented Feb 14, 2026

Fixes #1794

Regexp and NotRegexp use regexp.MustCompile internally, which panics when the regex pattern is invalid. For a test assertion, this is pretty surprising -- you'd expect the test to just fail with a useful error rather than crash the whole process.

The fix switches matchRegexp from regexp.MustCompile to regexp.Compile and threads the error back to the callers. Regexp and NotRegexp now call Fail with a message showing the invalid pattern and the compilation error, instead of panicking.

// Before: panics with "regexp: Compile(`\C`): error parsing regexp..."
require.Regexp(t, `\C`, "some string")

// After: test fails with "Invalid regexp "\C": error parsing regexp..."

Added test cases for both Regexp and NotRegexp with an invalid pattern.

matchRegexp uses regexp.MustCompile which panics on invalid regular
expressions. This is inappropriate for a test assertion - the test
should fail with a clear error message instead.

Switch from regexp.MustCompile to regexp.Compile and return the
compilation error. Regexp and NotRegexp now report the invalid
pattern via Fail instead of crashing the test process.

Fixes stretchr#1794
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.

assert.Regexp panics with invalid rx expression

1 participant