Home:ALL Converter>Context cascading Test

Context cascading Test

Ask Time:2021-07-18T15:17:33         Author:wasmup

Json Formatter

How to improve this context cascading test:

func TestParentTimedoutContext(t *testing.T) {

    ctx1, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
    defer cancel()

    ctx2, cancel2 := context.WithTimeout(ctx1, 1000*time.Millisecond)
    defer cancel2()

    time.Sleep(15 * time.Millisecond) // make ctx1 timeout

    if ctx2.Err() == nil {
        t.Error("failed")
    }
}

Command:

go test -timeout 30s -count=1 -run ^TestParentTimedoutContext$ my/internal/services

Output:

ok 

Sometimes:

failed 

go version go1.16.6

Author:wasmup,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/68426896/context-cascading-test
yy