jeudi 18 août 2016

Difference between main and test recovering from panic?

I have the following snippet which recovers from index out of range panics

Playground, also pasted below

The error is nil when called from main but not nil in an equivalent test case. What's the difference ?

type Foo struct {
    Is []int
}

func main() {
    fp := &Foo{}
    if err := fp.Panic(); err != nil {
        fmt.Errorf("Error: %v", err)
    } 
    fmt.Println("ok")
}

func (fp *Foo) Panic() (err error) {
    defer PanicRecovery(&err)
    fp.Is[0] = 5
    return nil
}

func PanicRecovery(err *error) {

        if r := recover(); r != nil {
                if _, ok := r.(runtime.Error); ok {
            //fmt.Println("Panicing")
                    *err = r.(error) //panic(r)
                } else {
            *err = r.(error)
        }
    }
}

Test case:

func TestPanic(t *testing.T) {
    fp := &Foo{}
    if err := fp.Panic(); err != nil {
        t.Errorf("Panic: %v", err)
    }
}

Aucun commentaire:

Enregistrer un commentaire