-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
grpctest.go
69 lines (63 loc) · 2.03 KB
/
grpctest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// Package grpctest implements testing helpers.
package grpctest
import (
"reflect"
"strings"
"testing"
)
func getTestFunc(t *testing.T, xv reflect.Value, name string) func(*testing.T) {
if m := xv.MethodByName(name); m.IsValid() {
if f, ok := m.Interface().(func(*testing.T)); ok {
return f
}
// Method exists but has the wrong type signature.
t.Fatalf("grpctest: function %v has unexpected signature (%T)", name, m.Interface())
}
return func(*testing.T) {}
}
// RunSubTests runs all "Test___" functions that are methods of x as subtests
// of the current test. If x contains methods "Setup(*testing.T)" or
// "Teardown(*testing.T)", those are run before or after each of the test
// functions, respectively.
//
// For example usage, see example_test.go. Run it using:
// $ go test -v -run TestExample .
//
// To run a specific test/subtest:
// $ go test -v -run 'TestExample/^Something$' .
func RunSubTests(t *testing.T, x interface{}) {
xt := reflect.TypeOf(x)
xv := reflect.ValueOf(x)
setup := getTestFunc(t, xv, "Setup")
teardown := getTestFunc(t, xv, "Teardown")
for i := 0; i < xt.NumMethod(); i++ {
methodName := xt.Method(i).Name
if !strings.HasPrefix(methodName, "Test") {
continue
}
tfunc := getTestFunc(t, xv, methodName)
t.Run(strings.TrimPrefix(methodName, "Test"), func(t *testing.T) {
setup(t)
// defer teardown to guarantee it is run even if tfunc uses t.Fatal()
defer teardown(t)
tfunc(t)
})
}
}