Debian Codegraph @

td/td_expected_type.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 "github.com/maxatome/go-testdeep/internal/types"
14 )
15
16 type tdExpectedType struct {
17 base
18 expectedType reflect.Type
19 isPtr bool
20 }
21
22 func (t *tdExpectedType) errorTypeMismatch(gotType reflect.Type) *ctxerr.Error {
23 expectedType := t.expectedType
24 if t.isPtr {
25 expectedType = reflect.PtrTo(expectedType)
26 }
27 return ctxerr.TypeMismatch(gotType, expectedType)
28 }
29
30 func (t *tdExpectedType) checkPtr(ctx ctxerr.Context, pGot *reflect.Value, nilAllowed bool) *ctxerr.Error {
31 if t.isPtr {
32 got := *pGot
33 if got.Kind() != reflect.Ptr {
34 if ctx.BooleanError {
35 return ctxerr.BooleanError
36 }
37 return t.errorTypeMismatch(got.Type())
38 }
39
40 if !nilAllowed && got.IsNil() {
41 if ctx.BooleanError {
42 return ctxerr.BooleanError
43 }
44 return &ctxerr.Error{
45 Message: "values differ",
46 Got: got,
47 Expected: types.RawString("non-nil"),
48 }
49 }
50
51 *pGot = got.Elem()
52 }
53 return nil
54 }
55
56 func (t *tdExpectedType) checkType(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
57 if got.Type() != t.expectedType {
58 if ctx.BeLax && t.expectedType.ConvertibleTo(got.Type()) {
59 return nil
60 }
61
62 if ctx.BooleanError {
63 return ctxerr.BooleanError
64 }
65 gt := got.Type()
66 if t.isPtr {
67 gt = reflect.PtrTo(gt)
68 }
69 return t.errorTypeMismatch(gt)
70 }
71 return nil
72 }
73
74 func (t *tdExpectedType) TypeBehind() reflect.Type {
75 if t.err != nil {
76 return nil
77 }
78 if t.isPtr {
79 return reflect.New(t.expectedType).Type()
80 }
81 return t.expectedType
82 }
83
84 func (t *tdExpectedType) expectedTypeStr() string {
85 if t.isPtr {
86 return "*" + t.expectedType.String()
87 }
88 return t.expectedType.String()
89 }