Debian Codegraph @

td/td_isa.go

raw
1 // Copyright (c) 2018, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package td
8
9 import (
10 "reflect"
11
12 "github.com/maxatome/go-testdeep/internal/ctxerr"
13 )
14
15 type tdIsa struct {
16 tdExpectedType
17 checkImplement bool
18 }
19
20 var _ TestDeep = &tdIsa{}
21
22 // summary(Isa): checks the data type or whether data implements an
23 // interface or not
24 // input(Isa): bool,str,int,float,cplx,array,slice,map,struct,ptr,chan,func
25
26 // Isa operator checks the data type or whether data implements an
27 // interface or not.
28 //
29 // Typical type checks:
30 //
31 // td.Cmp(t, time.Now(), td.Isa(time.Time{})) // succeeds
32 // td.Cmp(t, time.Now(), td.Isa(&time.Time{})) // fails, as not a *time.Time
33 // td.Cmp(t, got, td.Isa(map[string]time.Time{}))
34 //
35 // For interfaces, it is a bit more complicated, as:
36 //
37 // fmt.Stringer(nil)
38 //
39 // is not an interface, but just nil… To bypass this golang
40 // limitation, Isa accepts pointers on interfaces. So checking that
41 // data implements [fmt.Stringer] interface should be written as:
42 //
43 // td.Cmp(t, bytes.Buffer{}, td.Isa((*fmt.Stringer)(nil))) // succeeds
44 //
45 // Of course, in the latter case, if checked data type is
46 // [*fmt.Stringer], Isa will match too (in fact before checking whether
47 // it implements [fmt.Stringer] or not).
48 //
49 // TypeBehind method returns the [reflect.Type] of model.
50 func Isa(model any) TestDeep {
51 modelType := reflect.TypeOf(model)
52 i := tdIsa{
53 tdExpectedType: tdExpectedType{
54 base: newBase(3),
55 expectedType: modelType,
56 },
57 }
58
59 if modelType == nil {
60 i.err = ctxerr.OpBad("Isa", "Isa(nil) is not allowed. To check an interface, try Isa((*fmt.Stringer)(nil)), for fmt.Stringer for example")
61 return &i
62 }
63
64 i.checkImplement = modelType.Kind() == reflect.Ptr &&
65 modelType.Elem().Kind() == reflect.Interface
66 return &i
67 }
68
69 func (i *tdIsa) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
70 if i.err != nil {
71 return ctx.CollectError(i.err)
72 }
73
74 gotType := got.Type()
75
76 if gotType == i.expectedType {
77 return nil
78 }
79
80 if i.checkImplement {
81 if gotType.Implements(i.expectedType.Elem()) {
82 return nil
83 }
84 }
85
86 if ctx.BooleanError {
87 return ctxerr.BooleanError
88 }
89 return ctx.CollectError(i.errorTypeMismatch(gotType))
90 }
91
92 func (i *tdIsa) String() string {
93 if i.err != nil {
94 return i.stringError()
95 }
96 return i.expectedType.String()
97 }