package uerr_test import ( "runtime" "strings" "testing" "go.jlzhjp.dev/uerr" ) func capturedFrames(t *testing.T, err error) []runtime.Frame { t.Helper() pcs := err.(interface{ StackTrace() []uintptr }).StackTrace() if len(pcs) == 0 { t.Fatal("missing stack") } frames := runtime.CallersFrames(pcs) var out []runtime.Frame for { frame, more := frames.Next() out = append(out, frame) if !more { return out } } } func TestStackCaptureLocation(t *testing.T) { option := uerr.WithStack() _, file, line, _ := runtime.Caller(0) err := uerr.New("plain").New(option) first := capturedFrames(t, err)[0] if first.File != file || first.Line != line+1 { t.Fatalf("capture location = %s:%d, want %s:%d", first.File, first.Line, file, line+1) } _, file, line, _ = runtime.Caller(0) err = uerr.NewWithPayload[int]("payload").New(42, option) first = capturedFrames(t, err)[0] if first.File != file || first.Line != line+1 { t.Fatalf("reused option capture location = %s:%d, want %s:%d", first.File, first.Line, file, line+1) } } func TestStackAbsentByDefault(t *testing.T) { for _, err := range []error{uerr.New("plain").New(), uerr.NewWithPayload[int]("payload").New(42)} { if pcs := err.(interface{ StackTrace() []uintptr }).StackTrace(); pcs != nil { t.Fatalf("unexpected stack: %v", pcs) } } } func deepStack(depth int) error { if depth == 0 { return uerr.New("deep").New(uerr.WithStack()) } return deepStack(depth - 1) } func TestDeepStack(t *testing.T) { frames := capturedFrames(t, deepStack(100)) count := 0 for _, frame := range frames { if strings.HasSuffix(frame.Function, ".deepStack") { count++ } } if count != 101 { t.Fatalf("captured %d recursive frames, want 101", count) } }