github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/testing/base/assertion.go (about)

     1  package base
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  )
    10  
    11  type AssertionFn func(ctx context.Context, args []core.Value) (bool, error)
    12  
    13  type MessageFn func(args []core.Value) string
    14  
    15  type Assertion struct {
    16  	DefaultMessage MessageFn
    17  	MinArgs        int
    18  	MaxArgs        int
    19  	Fn             AssertionFn
    20  }
    21  
    22  func NewPositiveAssertion(assertion Assertion) core.Function {
    23  	return newInternal(assertion, true)
    24  }
    25  
    26  func NewNegativeAssertion(assertion Assertion) core.Function {
    27  	return newInternal(assertion, false)
    28  }
    29  
    30  func newInternal(assertion Assertion, connotation bool) core.Function {
    31  	return func(ctx context.Context, args ...core.Value) (core.Value, error) {
    32  		err := core.ValidateArgs(args, assertion.MinArgs, assertion.MaxArgs)
    33  
    34  		if err != nil {
    35  			return values.None, err
    36  		}
    37  
    38  		res, err := assertion.Fn(ctx, args)
    39  
    40  		if err != nil {
    41  			return values.None, err
    42  		}
    43  
    44  		if res == connotation {
    45  			return values.None, nil
    46  		}
    47  
    48  		return values.None, toError(assertion, args, connotation)
    49  	}
    50  }
    51  
    52  func toError(assertion Assertion, args []core.Value, positive bool) error {
    53  	if len(args) != assertion.MaxArgs {
    54  		connotation := ""
    55  
    56  		if !positive {
    57  			connotation = "not "
    58  		}
    59  
    60  		if assertion.MaxArgs > 1 {
    61  			actual := args[0]
    62  
    63  			var msg string
    64  
    65  			if assertion.DefaultMessage != nil {
    66  				msg = assertion.DefaultMessage(args)
    67  			} else {
    68  				if len(args) > 1 {
    69  					msg = fmt.Sprintf("be %s", args[1].String())
    70  				} else {
    71  					msg = "exist"
    72  				}
    73  			}
    74  
    75  			return core.Error(ErrAssertion, fmt.Sprintf("expected %s %sto %s", FormatValue(actual), connotation, msg))
    76  		}
    77  
    78  		return core.Error(ErrAssertion, fmt.Sprintf("expected to %s%s", connotation, assertion.DefaultMessage(args)))
    79  	}
    80  
    81  	// Last argument is always is a custom message
    82  	msg := args[assertion.MaxArgs-1]
    83  
    84  	return core.Error(ErrAssertion, msg.String())
    85  }