From 9bb3fcdaab1061d0960b15c246c53299fb66db2d Mon Sep 17 00:00:00 2001 From: fei <204683769+feiiiiii5@users.noreply.github.com> Date: Tue, 29 Sep 2026 17:53:13 +0800 Subject: [PATCH] assert: report no match for a typed nil *regexp.Regexp instead of panicking matchRegexp type-asserts rx to *regexp.Regexp before use, so a typed nil passes the assertion and MatchString then dereferences it. Both Regexp and NotRegexp panic where a result was expected, in the caller's test run, with the trace pointing into this package. A typed nil is a *regexp.Regexp that was declared and never assigned. There is no pattern behind it, so nothing can match: report false, and let NotRegexp invert it as usual. --- assert/assertions.go | 5 +++++ assert/assertions_test.go | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/assert/assertions.go b/assert/assertions.go index 166f63726..9ee6a2238 100644 --- a/assert/assertions.go +++ b/assert/assertions.go @@ -1711,6 +1711,11 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in func matchRegexp(rx interface{}, str interface{}) bool { var r *regexp.Regexp if rr, ok := rx.(*regexp.Regexp); ok { + // A typed nil passes the type assertion, and MatchString would then + // dereference it. There is no pattern, so nothing can match. + if rr == nil { + return false + } r = rr } else { r = regexp.MustCompile(fmt.Sprint(rx)) diff --git a/assert/assertions_test.go b/assert/assertions_test.go index 11642e096..28e4efcf7 100644 --- a/assert/assertions_test.go +++ b/assert/assertions_test.go @@ -3634,6 +3634,21 @@ func TestNeverFailQuickly(t *testing.T) { False(t, Never(mockT, condition, 100*time.Millisecond, time.Second)) } +// A typed nil *regexp.Regexp passes the type assertion in matchRegexp and is +// then dereferenced, so Regexp and NotRegexp panic instead of reporting a +// result. +func TestRegexpNilTypedRegexp(t *testing.T) { + t.Parallel() + + var rx *regexp.Regexp + mockT := new(testing.T) + + NotPanics(t, func() { + False(t, Regexp(mockT, rx, "anything")) + }) + True(t, NotRegexp(t, rx, "anything")) +} + func Test_validateEqualArgs(t *testing.T) { t.Parallel()