@@ -19,7 +19,9 @@ package assert
19
19
20
20
import (
21
21
"fmt"
22
+ "path/filepath"
22
23
"reflect"
24
+ "regexp"
23
25
"runtime"
24
26
"testing"
25
27
)
@@ -80,6 +82,77 @@ func NotEqual(t *testing.T, exp, got interface{}, args ...interface{}) {
80
82
assert (t , result , fn , 1 )
81
83
}
82
84
85
+ // Panic asserts that function fn() panics.
86
+ // It assumes that recover() either returns a string or
87
+ // an error and fails if the message does not match
88
+ // the regular expression in 'matches'.
89
+ // @param t tet
90
+ // @param fn function
91
+ // @param matches matcher
92
+ func Panic (t * testing.T , fn func (), matches string ) {
93
+ if x := doesPanic (2 , fn , matches ); x != "" {
94
+ fmt .Println (x )
95
+ t .Fail ()
96
+ }
97
+ }
98
+
99
+ // doesPanic do panic
100
+ // @param skip judge skip
101
+ // @param fn func
102
+ // @param expr got
103
+ // @return err error
104
+ func doesPanic (skip int , fn func (), expr string ) (err string ) {
105
+ defer func () {
106
+ r := recover ()
107
+ if r == nil {
108
+ err = fail (skip , "did not panic" )
109
+ return
110
+ }
111
+ var v string
112
+ switch r .(type ) {
113
+ case error :
114
+ v = r .(error ).Error ()
115
+ case string :
116
+ v = r .(string )
117
+ }
118
+ err = matches (skip , v , expr )
119
+ }()
120
+ fn ()
121
+ return ""
122
+ }
123
+
124
+ // Matches asserts that a value matches a given regular expression.
125
+ // @param t test
126
+ // @param value value
127
+ // @param expr got
128
+ func Matches (t * testing.T , value , expr string ) {
129
+ if x := matches (2 , value , expr ); x != "" {
130
+ fmt .Println (x )
131
+ t .Fail ()
132
+ }
133
+ }
134
+
135
+ // matches matches got and expr value
136
+ // @param skip judge skip
137
+ // @param value value
138
+ // @param expr got
139
+ // @return string result
140
+ func matches (skip int , value , expr string ) string {
141
+ ok , err := regexp .MatchString (expr , value )
142
+ if err != nil {
143
+ return fail (skip , "invalid pattern %q. %s" , expr , err )
144
+ }
145
+ if ! ok {
146
+ return fail (skip , "got %s which does not match %s" , value , expr )
147
+ }
148
+ return ""
149
+ }
150
+
151
+ func fail (skip int , format string , args ... interface {}) string {
152
+ _ , file , line , _ := runtime .Caller (skip )
153
+ return fmt .Sprintf ("\t %s:%d: %s\n " , filepath .Base (file ), line , fmt .Sprintf (format , args ... ))
154
+ }
155
+
83
156
// assert assertion
84
157
// @param t test
85
158
// @param result result
0 commit comments