Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing.M recover in golang

Tags:

go

This recovery works:

func TestSomeTest(t *testing.T) {
    defer func() {
        r := recover()
        fmt.Println("recovery")
        fmt.Println(r)
    }()
    panic("panic here")
}

But this does not:

func TestSomeTest(t *testing.T) {
    panic("panic here")
}

func TestMain(m *testing.M) {
    defer func() {
        r := recover()
        fmt.Println("recovery")
        fmt.Println(r)
    }()
    ret := m.Run()
    os.Exit(ret)
}

Why? I expect that panic here will be recovered by code in func TestMain(m *testing.M). Why not? I just have panic without any recovery in this case.

Full code:

package main

import (
    "fmt"
    "os"
    "testing"
)

func TestSomeTest(t *testing.T) {
    // defer func() {
    //  r := recover()
    //  fmt.Println("recovery")
    //  fmt.Println(r)
    // }()
    panic("panic here")
}

func TestMain(m *testing.M) {
    defer func() {
        r := recover()
        fmt.Println("recovery")
        fmt.Println(r)
    }()
    ret := m.Run()
    os.Exit(ret)
}

To run this code I used go test command.

like image 355
Maxim Yefremov Avatar asked Apr 15 '15 14:04

Maxim Yefremov


People also ask

How does recover work Golang?

In the go language recover function is used to handle any unexpected error, recovery is similar to try catch of other programming language, mostly we use the recover where we are not sure about the error and we do not want our program to stop execution (in case if exception occurs in mean time of execution of the ...

What is recover in Golang?

The recover() function in Go Language is used to recover from a goroutine that is in panic, meaning it helps recover from an error that has been raised. The program takes control through recover rather than letting the code crash. recover() is an inbuilt function in Go Language.

How do you deal with panic Goroutine?

Recover and catch a panicThe built-in recover function can be used to regain control of a panicking goroutine and resume normal execution. A call to recover stops the unwinding and returns the argument passed to panic . If the goroutine is not panicking, recover returns nil .

How do you use panic in Golang?

The panic() function in Go Language is similar to exceptions raised at runtime when an error is encountered. panic() is either raised by the program itself when an unexpected error occurs or the programmer throws the exception on purpose for handling particular errors.


1 Answers

It's because the tests are run in separate goroutines.

It's like if your fist example sent off a goroutine, which can't be recovered.

func TestSomeTest(t *testing.T) {
    defer func() {
        r := recover()
        fmt.Println("recovery")
        fmt.Println(r)
    }()

    go func() {
        // won't recover
        panic("panic here")
    }()
    time.Sleep(time.Second)
}
like image 141
JimB Avatar answered Nov 15 '22 05:11

JimB