Are you running test run tests at the same time?

At startup, go testit launches your files ending in _test.go, running functions starting in the format TestXxx, and use the module (* t testing.T). I was wondering if each function in the file was running at the _test.gosame time, or if it finally performed each function separately? Does he create a routine for each of them? If he creates a routine for each of them, can I somehow control the go routines? Is it possible to someday do something like golibrary.GoRoutines()and get an instance for each of them and control them somehow or something like that?


Note. This question assumes that you are using the testing platform that comes with go (testing).

+4
source share
3 answers

Yes , tests run as goroutines and thus run simultaneously .

However, tests do not run in parallel by default , as pointed out by @jacobsa . To enable parallel execution, you need to call t.Parallel()in the test case and set GOMAXPROCSaccordingly or put -parallel N.

, . , . :

import "sync/atomic"

var ports [...]uint64 = {10, 5, 55}
var portIndex uint32

func nextPort() uint32 {
    return atomic.AddUint32(&portIndex, 1)
}
+2

, t.Parallel , -parallel.

+3

(, ), , :

package foo_test

var forceSequential chan bool = make(chan bool, 1)

func Test1(t *testing.T) {
    forceSequential <- true
    // Your test here
    <- forceSequential
}

func Test2(t *testing.T) {
    forceSequential <- true
    // Your test here
    <- forceSequential
}

func Test3(t *testing.T) {
    forceSequential <- true
    // Your test here
    <- forceSequential
}

, , . :

package foo_test

var (
    chan1 bool = make(chan bool, 1)
    chan2 bool = make(chan bool, 1)
)

func Test1(t *testing.T) {
    // Your test here
    chan1 <- true
}

func Test2(t *testing.T) {
    <- chan1
    // Your test here
    chan2 <- true
}

func Test3(t *testing.T) {
    <- chan2
    // Your test here
}

But then again, does not do this . If your tests (and, accordingly, your code) depend on the global state for proper execution, you are doing something wrong . Fix it and you will not have problems with parallel tests.

0
source

Source: https://habr.com/ru/post/1545771/


All Articles