Skip to content

Instantly share code, notes, and snippets.

@MSevey
Created July 13, 2023 01:30
Show Gist options
  • Save MSevey/a73f165f3bb640ba5339baafcd04e30b to your computer and use it in GitHub Desktop.
Save MSevey/a73f165f3bb640ba5339baafcd04e30b to your computer and use it in GitHub Desktop.
Example of how go routines will continue even after a test fails.
package temp
import (
"errors"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// This File is a simple demonstration of how goroutines will continue to run
// after a test finishes. This illustrates how in our other testing, nodes are
// continuing to run in the background if we are not closing them with a defer
// or t.Cleanup.
func TestHelloWorld(t *testing.T) {
fmt.Println("Hello, World!")
// this goroutine will continue to run after the test finishes
go func() {
c := time.After(time.Second * 5)
for {
select {
case <-c:
fmt.Println("go routine exit")
return
default:
}
fmt.Println("go routine")
time.Sleep(time.Second)
}
}()
t.Cleanup(func() {
fmt.Println("Goodbye, World!")
})
fmt.Println("before check")
require := require.New(t)
require.NoError(errors.New("require error"))
// This will not be printed because the test will exit before this line
// is reached
fmt.Println("after check")
}
// This test runs for 5 seconds, and then exits. The goroutine in the test above
// will continue to run for 5 seconds after this test exits.
func TestWait(t *testing.T) {
time.Sleep(time.Second * 5)
}
@MSevey
Copy link
Author

MSevey commented Jul 13, 2023

If you download and run this file, you will is in the terminal the go routine printout continuing even after the first test fails.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment