Skip to content

assert.Regexp panics with invalid rx expression #1794

@brackendawson

Description

@brackendawson

Description

Because assert.Regexp uses regexp.MustCompile which is for "initialization of global variables holding compiled regular expressions" a runtime panic is possible. We should use Compile and handle the error.

Step To Reproduce

package kata_test

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func TestIfy(t *testing.T) {
	require.Regexp(t, "\\C", "I don't like this at all")
}

Expected behavior

The test fails with a useful error.

Actual behavior

A panic:

Running tool: /Users/brackendawson/sdk/go1.24.5/bin/go test -timeout 30s -coverprofile=/var/folders/8c/f9y61rb14cn8c6_6lnz10q300000gn/T/vscode-gohVso1s/go-code-cover github.com/brackendawson/kata -race

--- FAIL: TestIfy (0.00s)
panic: regexp: Compile(`\C`): error parsing regexp: invalid escape sequence: `\C` [recovered]
	panic: regexp: Compile(`\C`): error parsing regexp: invalid escape sequence: `\C`

goroutine 35 [running]:
testing.tRunner.func1.2({0x1025cc440, 0xc0000924f0})
	/Users/brackendawson/sdk/go1.24.5/src/testing/testing.go:1734 +0x2bc
testing.tRunner.func1()
	/Users/brackendawson/sdk/go1.24.5/src/testing/testing.go:1737 +0x47c
panic({0x1025cc440?, 0xc0000924f0?})
	/Users/brackendawson/sdk/go1.24.5/src/runtime/panic.go:792 +0x124
regexp.MustCompile({0xc000090d4e, 0x2})
	/Users/brackendawson/sdk/go1.24.5/src/regexp/regexp.go:313 +0xcc
github.com/stretchr/testify/assert.matchRegexp({0x1025cc440, 0x1026239f0}, {0x1025cc440, 0x102623a00})
	/Users/brackendawson/src/github.com/stretchr/testify/assert/assertions.go:1715 +0x88
github.com/stretchr/testify/assert.Regexp({0x103cb8170, 0xc000082c40}, {0x1025cc440, 0x1026239f0}, {0x1025cc440, 0x102623a00}, {0x0, 0x0, 0x0})
	/Users/brackendawson/src/github.com/stretchr/testify/assert/assertions.go:1737 +0x90
github.com/stretchr/testify/require.Regexp({0x102626398, 0xc000082c40}, {0x1025cc440, 0x1026239f0}, {0x1025cc440, 0x102623a00}, {0x0, 0x0, 0x0})
	/Users/brackendawson/src/github.com/stretchr/testify/require/require.go:1970 +0xc8
github.com/brackendawson/kata_test.TestIfy(0xc000082c40)
	/Users/brackendawson/src/github.com/brackendawson/kata/kata_test.go:10 +0x5c
testing.tRunner(0xc000082c40, 0x1026228d0)
	/Users/brackendawson/sdk/go1.24.5/src/testing/testing.go:1792 +0x184
created by testing.(*T).Run in goroutine 1
	/Users/brackendawson/sdk/go1.24.5/src/testing/testing.go:1851 +0x688
FAIL	github.com/brackendawson/kata	0.181s
FAIL

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugpkg-assertChange related to package testify/assert

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions