github.com/sandwich-go/boost@v1.3.29/middleware/middleware_test.go (about)

     1  package middleware
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	. "github.com/smartystreets/goconvey/convey"
     8  )
     9  
    10  var (
    11  	someValue     = 1
    12  	parentContext = context.WithValue(context.TODO(), "parent", someValue)
    13  )
    14  
    15  func TestChain(t *testing.T) {
    16  	Convey("TestChain", t, func() {
    17  		first := func(ctx context.Context, next Handler) error {
    18  			requireContextValue(ctx, "parent", "first interceptor must know the parent context value")
    19  			ctx = context.WithValue(ctx, "first", 1)
    20  			return next(ctx)
    21  		}
    22  		second := func(ctx context.Context, next Handler) error {
    23  			requireContextValue(ctx, "parent", "second interceptor must know the parent context value")
    24  			requireContextValue(ctx, "first", "second interceptor must know the first context value")
    25  			ctx = context.WithValue(ctx, "second", 1)
    26  			return next(ctx)
    27  		}
    28  
    29  		handler := func(ctx context.Context) error {
    30  			requireContextValue(ctx, "parent", "handler must know the parent context value")
    31  			requireContextValue(ctx, "first", "handler must know the first context value")
    32  			requireContextValue(ctx, "second", "handler must know the second context value")
    33  			return nil
    34  		}
    35  		chain := Chain(first, second)
    36  		err := chain(parentContext, handler)
    37  		So(err, ShouldBeNil)
    38  	})
    39  }
    40  
    41  func requireContextValue(ctx context.Context, key string, msg string) {
    42  	Convey(msg, func() {
    43  		val := ctx.Value(key)
    44  		So(val, ShouldNotBeNil)
    45  		So(someValue, ShouldEqual, val)
    46  	})
    47  }