stretchr / testify

A toolkit with common assertions and mocks that plays nicely with the standard library
MIT License
23.53k stars 1.6k forks source link

Can't assert a panic from a sub goroutine ? #1632

Closed kuchaguangjie closed 1 month ago

kuchaguangjie commented 3 months ago
package error_learn

import (
    "fmt"
    "github.com/stretchr/testify/assert"
    "testing"
    "time"
)

// panic in sub goroutine, recover in main goroutine,
func panicInSubGoroutine() {
    // recover,  in main goroutine,
    defer func() {
        if r := recover(); r != nil {
            fmt.Printf("recover from panic: %v\n", r)
        }
    }()

    go func() {
        // panic, in sub goroutine,
        panic("panic occurred!")
    }()

    time.Sleep(1 * time.Second)
}

func TestPanicInSubGoroutine(t *testing.T) {
    assert.Panics(t, panicInSubGoroutine)
}

Sub goroutine panic, assert the main goroutine, the test still fail with:

panic: panic occurred!

Does that means assert.Panics() can't assert a panic from sub goroutine ?

Antonboom commented 2 months ago

This is not testify issue, this is Golang panic-recover design.

A panic cannot be recovered by a different goroutine.

P.S. Also, look at testifylint#go-require

Antonboom commented 2 months ago

Duplicate of https://github.com/stretchr/testify/discussions/1617

brackendawson commented 1 month ago

Thank you @Antonboom, quite correct.