| 1 |
// Copyright (c) 2023, 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 |
"bytes" |
| 11 |
"fmt" |
| 12 |
"reflect" |
| 13 |
"sort" |
| 14 |
|
| 15 |
"github.com/maxatome/go-testdeep/internal/ctxerr" |
| 16 |
"github.com/maxatome/go-testdeep/internal/util" |
| 17 |
) |
| 18 |
|
| 19 |
type tdStructLazy struct { |
| 20 |
base |
| 21 |
cache map[reflect.Type]*tdStruct |
| 22 |
expectedFields StructFields |
| 23 |
strict bool |
| 24 |
} |
| 25 |
|
| 26 |
var _ TestDeep = &tdStructLazy{} |
| 27 |
|
| 28 |
func newStructLazy(expectedFields StructFields, strict bool) TestDeep { |
| 29 |
return &tdStructLazy{ |
| 30 |
base: newBase(4), |
| 31 |
cache: map[reflect.Type]*tdStruct{}, |
| 32 |
expectedFields: expectedFields, |
| 33 |
strict: strict, |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
func (s *tdStructLazy) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error { |
| 38 |
gotType := got.Type() |
| 39 |
tds := s.cache[gotType] |
| 40 |
if tds == nil { |
| 41 |
switch gotType.Kind() { |
| 42 |
case reflect.Struct: |
| 43 |
case reflect.Ptr: |
| 44 |
if gotType.Elem().Kind() == reflect.Struct { |
| 45 |
break |
| 46 |
} |
| 47 |
fallthrough |
| 48 |
default: |
| 49 |
if ctx.BooleanError { |
| 50 |
return ctxerr.BooleanError |
| 51 |
} |
| 52 |
return ctx.CollectError(ctxerr.BadKind(got, "struct OR *struct")) |
| 53 |
} |
| 54 |
|
| 55 |
tds = anyStruct(s.base, reflect.New(got.Type()).Elem(), s.expectedFields, s.strict) |
| 56 |
tds.location = s.location |
| 57 |
s.cache[gotType] = tds |
| 58 |
} |
| 59 |
|
| 60 |
return tds.Match(ctx, got) |
| 61 |
} |
| 62 |
|
| 63 |
func (s *tdStructLazy) String() string { |
| 64 |
buf := bytes.NewBufferString(s.location.Func) |
| 65 |
buf.WriteString("(<any struct type>{") |
| 66 |
|
| 67 |
if len(s.expectedFields) > 0 { |
| 68 |
buf.WriteByte('\n') |
| 69 |
|
| 70 |
fields := make([]string, 0, len(s.expectedFields)) |
| 71 |
maxLen := 0 |
| 72 |
for name := range s.expectedFields { |
| 73 |
fields = append(fields, name) |
| 74 |
if len(name) > maxLen { |
| 75 |
maxLen = len(name) |
| 76 |
} |
| 77 |
} |
| 78 |
sort.Strings(fields) |
| 79 |
|
| 80 |
maxLen++ |
| 81 |
for _, name := range fields { |
| 82 |
fmt.Fprintf(buf, " %-*s %s\n", //nolint: errcheck |
| 83 |
maxLen, name+":", util.ToString(s.expectedFields[name])) |
| 84 |
} |
| 85 |
} |
| 86 |
buf.WriteString("})") |
| 87 |
|
| 88 |
return buf.String() |
| 89 |
} |