You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

70 lines
2.0 KiB

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