Go语言 检查测试功能是否将并行运行

dm7nw8vv  于 2023-01-06  发布在  Go
关注(0)|答案(1)|浏览(132)

如何检查*testing.T是否已设置为并行运行?
理想的解决方案可能是:

func isParellelT(t *testing.T) bool {
   // return some means to figure t has called t.Parallel().
}
5tmbdcev

5tmbdcev1#

testing.T不会提供这些信息。您的测试不应该依赖于它。如果您想这样做,几乎可以肯定您应该做其他事情。
但是,可以使用反射或通过检查testing.T.SetEnv死机😈:

package para

import (
    "reflect"
    "strings"
    "testing"
)

func TestParallelTrue(t *testing.T) {
    t.Parallel()

    if !isParallel(t) {
        t.Errorf("isParallel: got = false; want = true")
    }
    if !isParallel2(t) {
        t.Errorf("isParallel2: got = false; want = true")
    }
}

func TestParallelFalse(t *testing.T) {
    if isParallel(t) {
        t.Errorf("isParallel: got = true; want = false")
    }
    if isParallel2(t) {
        t.Errorf("isParallel2: got = true; want = false")
    }
}

// WARNING: This is terrible and should never be used.
// It will likely break on old or future versions of Go.
func isParallel(t *testing.T) (b bool) {
    v := reflect.ValueOf(t).Elem()

    // Check testing.T.isParallel first.
    isPara := v.FieldByName("isParallel")
    if isPara.IsValid() {
        return isPara.Bool()
    }

    // Otherwise try testing.T.common.isParallel.
    common := v.FieldByName("common")
    if !common.IsValid() {
        t.Fatal("isParallel: unsupported testing.T implementation")
    }

    isPara = common.FieldByName("isParallel")
    if !isPara.IsValid() {
        t.Fatal("isParallel: unsupported testing.T implementation")
    }

    return isPara.Bool()
}

// WARNING: This is terrible and should never be used.
// Requires Go1.17+.
func isParallel2(t *testing.T) (b bool) {
    defer func() {
        v := recover()
        if v == nil {
            return
        }
        if s, ok := v.(string); ok && strings.Contains(s, "parallel tests") {
            b = true
            return
        }
        panic(v)
    }()
    t.Setenv("_dummy", "value")
    return false
}

相关问题