| 1 |
// Copyright (c) 2020, 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 |
"sync" |
| 12 |
|
| 13 |
"github.com/maxatome/go-testdeep/internal/ctxerr" |
| 14 |
) |
| 15 |
|
| 16 |
type tdDelay struct { |
| 17 |
base |
| 18 |
operator TestDeep |
| 19 |
once sync.Once |
| 20 |
delayed func() TestDeep |
| 21 |
} |
| 22 |
|
| 23 |
var _ TestDeep = &tdDelay{} |
| 24 |
|
| 25 |
// summary(Delay): delays the operator construction till first use |
| 26 |
// input(Delay): all |
| 27 |
|
| 28 |
// Delay operator allows to delay the construction of an operator to |
| 29 |
// the time it is used for the first time. Most of the time, it is |
| 30 |
// used with helpers. See the example for a very simple use case. |
| 31 |
func Delay(delayed func() TestDeep) TestDeep { |
| 32 |
d := tdDelay{ |
| 33 |
base: newBase(3), |
| 34 |
delayed: delayed, |
| 35 |
} |
| 36 |
|
| 37 |
if delayed == nil { |
| 38 |
d.err = ctxerr.OpBad("Delay", "Delay(DELAYED): DELAYED must be non-nil") |
| 39 |
} |
| 40 |
return &d |
| 41 |
} |
| 42 |
|
| 43 |
func (d *tdDelay) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error { |
| 44 |
if d.err != nil { |
| 45 |
return ctx.CollectError(d.err) |
| 46 |
} |
| 47 |
|
| 48 |
op := d.getOperator() |
| 49 |
ctx.CurOperator = op // to have correct location |
| 50 |
return op.Match(ctx, got) |
| 51 |
} |
| 52 |
|
| 53 |
func (d *tdDelay) String() string { |
| 54 |
if d.err != nil { |
| 55 |
return d.stringError() |
| 56 |
} |
| 57 |
return d.getOperator().String() |
| 58 |
} |
| 59 |
|
| 60 |
func (d *tdDelay) TypeBehind() reflect.Type { |
| 61 |
if d.err != nil { |
| 62 |
return nil |
| 63 |
} |
| 64 |
return d.getOperator().TypeBehind() |
| 65 |
} |
| 66 |
|
| 67 |
func (d *tdDelay) HandleInvalid() bool { |
| 68 |
return d.getOperator().HandleInvalid() |
| 69 |
} |
| 70 |
|
| 71 |
func (d *tdDelay) getOperator() TestDeep { |
| 72 |
d.once.Do(func() { d.operator = d.delayed() }) |
| 73 |
return d.operator |
| 74 |
} |