github.com/blend/go-sdk@v1.20220411.3/web/middleware_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package web
     9  
    10  import (
    11  	"testing"
    12  
    13  	"github.com/blend/go-sdk/assert"
    14  )
    15  
    16  func TestNestMiddleware(t *testing.T) {
    17  	assert := assert.New(t)
    18  
    19  	values := make(chan string, 4)
    20  	createMiddleware := func(v string) Middleware {
    21  		return func(action Action) Action {
    22  			return func(r *Ctx) Result {
    23  				values <- v
    24  				return action(r)
    25  			}
    26  		}
    27  	}
    28  
    29  	set0 := []Middleware{
    30  		createMiddleware("set0-0"),
    31  		createMiddleware("set0-1"),
    32  		createMiddleware("set0-2"),
    33  	}
    34  
    35  	action := func(_ *Ctx) Result {
    36  		values <- "action"
    37  		return nil
    38  	}
    39  
    40  	finalAction := NestMiddleware(action, set0...)
    41  	assert.NotNil(finalAction)
    42  	result := finalAction(nil)
    43  	assert.Nil(result)
    44  
    45  	assert.Equal("set0-2", <-values)
    46  	assert.Equal("set0-1", <-values)
    47  	assert.Equal("set0-0", <-values)
    48  	assert.Equal("action", <-values)
    49  }
    50  
    51  func TestNestMiddleware_Append(t *testing.T) {
    52  	assert := assert.New(t)
    53  
    54  	values := make(chan string, 6)
    55  	createMiddleware := func(v string) Middleware {
    56  		return func(action Action) Action {
    57  			return func(r *Ctx) Result {
    58  				values <- v
    59  				return action(r)
    60  			}
    61  		}
    62  	}
    63  
    64  	set0 := []Middleware{
    65  		createMiddleware("set0-0"),
    66  		createMiddleware("set0-1"),
    67  		createMiddleware("set0-2"),
    68  	}
    69  	set1 := []Middleware{
    70  		createMiddleware("set1-0"),
    71  		createMiddleware("set1-1"),
    72  	}
    73  
    74  	action := func(_ *Ctx) Result {
    75  		values <- "action"
    76  		return nil
    77  	}
    78  
    79  	finalAction := NestMiddleware(action, append(set0, set1...)...)
    80  	assert.NotNil(finalAction)
    81  	result := finalAction(nil)
    82  	assert.Nil(result)
    83  
    84  	assert.Equal("set1-1", <-values)
    85  	assert.Equal("set1-0", <-values)
    86  	assert.Equal("set0-2", <-values)
    87  	assert.Equal("set0-1", <-values)
    88  	assert.Equal("set0-0", <-values)
    89  	assert.Equal("action", <-values)
    90  }