-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtype.go
More file actions
49 lines (39 loc) · 1.22 KB
/
type.go
File metadata and controls
49 lines (39 loc) · 1.22 KB
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
package test
import (
"fmt"
"reflect"
"github.com/blugnu/test/opt"
"github.com/blugnu/test/test"
)
// ExpectType tests that a value is of an expected type. If the test passes,
// the value is returned as that type, with true. If the test fails the zero
// value of the specified type is returned, with false.
func ExpectType[T any](got any, opts ...any) (T, bool) {
GetT().Helper()
z := *new(T)
gotType := reflect.TypeOf(got)
expectedType := reflect.TypeOf(z)
if expectedType == reflect.Type(nil) {
test.Invalid("ExpectType: cannot be used to test for interfaces")
return z, false
}
Expect(gotType, opts...).To(Equal(expectedType), opt.FailureReport(func(...any) []string {
return []string{
fmt.Sprintf("expected: %s", expectedType),
fmt.Sprintf("got : %s", gotType),
}
}))
if gotType == expectedType {
got, ok := got.(T)
return got, ok
}
return z, false
}
// RequireType tests that a value is of an expected type. If the test passes,
// the value is returned as that type otherwise the test fails immediately
// without evaluating any further expectations.
func RequireType[T any](got any, opts ...any) T {
GetT().Helper()
z, _ := ExpectType[T](got, append(opts, opt.Required())...)
return z
}