...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package execution_test
16
17 import (
18 "reflect"
19 "runtime"
20 "strings"
21 "testing"
22
23 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/controller/errors"
24 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/execution"
25 )
26
27 func TestRecoverWithGenericError(t *testing.T) {
28 testBasicRecoverScenariosWithFunc(t, execution.RecoverWithGenericError)
29 }
30
31 func TestRecoverWithInternalError(t *testing.T) {
32 testBasicRecoverScenariosWithFunc(t, execution.RecoverWithInternalError)
33 err := testRecover(execution.RecoverWithInternalError)
34 expectedType := reflect.TypeOf(&errors.InternalError{})
35 actualType := reflect.TypeOf(err)
36 if actualType != expectedType {
37 t.Fatalf("unexpected type returned: got '%v', want' %v'", actualType, expectedType)
38 }
39 }
40
41 func testBasicRecoverScenariosWithFunc(t *testing.T, recoverFunc func(err *error)) {
42 err := testRecover(recoverFunc)
43 if err == nil {
44 t.Fatalf("expected an error, instead got 'nil'")
45 }
46 expectedRecoverSubstrings := []string{
47 "panicFunc(...)",
48 "midStackFunc",
49 "my function is panicking!",
50 }
51 errMsg := err.Error()
52 for _, expectedMessage := range expectedRecoverSubstrings {
53 if !strings.Contains(errMsg, expectedMessage) {
54 t.Errorf("expected error string to contain '%v', got: %v", expectedMessage, errMsg)
55 }
56 }
57 unexpectedRecoverSubstrings := []string{
58 getFullFunctionName(recoverFunc),
59 getPackageFunctionName(recoverFunc),
60 "debug.Stack",
61 }
62 for _, expectedMessage := range unexpectedRecoverSubstrings {
63 if strings.Contains(errMsg, expectedMessage) {
64 t.Errorf("expected error string to NOT contain '%v', got:\n%v", expectedMessage, errMsg)
65 }
66 }
67 }
68
69 func testRecover(recoverFunc func(err *error)) (err error) {
70 defer recoverFunc(&err)
71 midStackFunc()
72 return err
73 }
74
75 func midStackFunc() {
76 panicFunc()
77 }
78
79 func panicFunc() {
80 panic("my function is panicking!")
81 }
82
83
84 func getPackageFunctionName(i interface{}) string {
85 fullName := getFullFunctionName(i)
86 return fullName[strings.LastIndex(fullName, "/")+1:]
87 }
88
89
90
91
92 func getFullFunctionName(i interface{}) string {
93 return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
94 }
95
View as plain text