From 02230f5014980819ad562cbfa63063b499bf72f0 Mon Sep 17 00:00:00 2001 From: immanuwell Date: Sat, 6 Jun 2026 16:34:37 +0400 Subject: [PATCH] fix: report the correct caller in assert panics Signed-off-by: immanuwell --- src/assert/assert.go | 10 ++++----- src/assert/assert_test.go | 44 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 5 deletions(-) create mode 100644 src/assert/assert_test.go diff --git a/src/assert/assert.go b/src/assert/assert.go index 293e43702..86b204b63 100644 --- a/src/assert/assert.go +++ b/src/assert/assert.go @@ -7,10 +7,10 @@ import ( func Assert(something bool) { if !something { - pc := make([]uintptr, 10) - runtime.Callers(2, pc) - f := runtime.FuncForPC(pc[0]) - file, line := f.FileLine(pc[0]) - panic(fmt.Sprintf("assertion failed at %s:%d %s\n", file, line, f.Name())) + pc := make([]uintptr, 1) + n := runtime.Callers(2, pc) + frames := runtime.CallersFrames(pc[:n]) + frame, _ := frames.Next() + panic(fmt.Sprintf("assertion failed at %s:%d %s\n", frame.File, frame.Line, frame.Function)) } } diff --git a/src/assert/assert_test.go b/src/assert/assert_test.go new file mode 100644 index 000000000..0c8bd978c --- /dev/null +++ b/src/assert/assert_test.go @@ -0,0 +1,44 @@ +package assert + +import ( + "strings" + "testing" +) + +func assertFailure() { + Assert(false) +} + +func TestAssertReportsCallerLocation(t *testing.T) { + var got string + + func() { + defer func() { + r := recover() + if r == nil { + t.Fatal("expected panic") + } + + msg, ok := r.(string) + if !ok { + t.Fatalf("expected panic string, got %T", r) + } + + got = msg + }() + + assertFailure() + }() + + if !strings.Contains(got, "src/assert/assert_test.go:") { + t.Fatalf("expected panic to report assert test file, got %q", got) + } + + if !strings.Contains(got, "github.com/envoyproxy/ratelimit/src/assert.assertFailure") { + t.Fatalf("expected panic to report assertFailure function, got %q", got) + } + + if strings.Contains(got, "TestAssertReportsCallerLocation") { + t.Fatalf("expected panic to report immediate caller instead of outer test frame, got %q", got) + } +}