github.com/msales/pkg/v3@v3.24.0/httpx/middleware/query_transformer_test.go (about)

     1  package middleware_test
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/msales/pkg/v3/httpx/middleware"
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  func TestWithQueryTransformer(t *testing.T) {
    14  	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    15  		assert.Equal(t, "a=VA&b=VB&c=VC&d=vd", r.URL.RawQuery)
    16  	})
    17  	seenVals := make([]string, 0)
    18  	fn := func(s string) string {
    19  		seenVals = append(seenVals, s)
    20  		return strings.ToUpper(s)
    21  	}
    22  
    23  	var tr middleware.QueryTransformer
    24  	tr.Register([]string{"a", "b"}, fn)
    25  	tr.Register([]string{"c"}, fn)
    26  	tr.Register([]string{}, fn)
    27  
    28  	h = middleware.WithQueryTransformer(h, tr)
    29  
    30  	req, _ := http.NewRequest("GET", "/?a=va&b=vb&c=vc&d=vd", nil)
    31  	resp := httptest.NewRecorder()
    32  
    33  	h.ServeHTTP(resp, req)
    34  
    35  	assert.Equal(t, []string{"va", "vb", "vc"}, seenVals)
    36  }
    37  
    38  func TestWithQueryTransformerFunc(t *testing.T) {
    39  	url := "/?a=va&b=vb&c=vc&d=vd"
    40  
    41  	tests := []struct{
    42  		name string
    43  		keys []string
    44  		seenVals []string
    45  		wantQuery string
    46  	}{
    47  		{
    48  			name: "some keys defined",
    49  			keys: []string{"a", "b", "c"},
    50  			seenVals: []string{"va", "vb", "vc"},
    51  			wantQuery: "a=VA&b=VB&c=VC&d=vd",
    52  		},
    53  		{
    54  			name: "keys not in the query",
    55  			keys: []string{"x", "y", "z"},
    56  			seenVals: []string{},
    57  			wantQuery:"a=va&b=vb&c=vc&d=vd",
    58  		},
    59  		{
    60  			name: "no keys defined",
    61  			keys: []string{},
    62  			seenVals: []string{},
    63  			wantQuery:"a=va&b=vb&c=vc&d=vd",
    64  		},
    65  		{
    66  			name: "nil keys",
    67  			keys: nil,
    68  			seenVals: []string{},
    69  			wantQuery:"a=va&b=vb&c=vc&d=vd",
    70  		},
    71  	}
    72  
    73  	for _, tt := range tests {
    74  		t.Run(tt.name, func(t *testing.T) {
    75  			var h http.Handler
    76  
    77  			h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    78  				assert.Equal(t, tt.wantQuery, r.URL.RawQuery)
    79  
    80  			})
    81  			seenVals := make([]string, 0)
    82  			fn := func(s string) string {
    83  				seenVals = append(seenVals, s)
    84  				return strings.ToUpper(s)
    85  			}
    86  
    87  			h = middleware.WithQueryTransformerFunc(h, tt.keys, fn)
    88  
    89  			req, _ := http.NewRequest("GET", url, nil)
    90  			resp := httptest.NewRecorder()
    91  
    92  			h.ServeHTTP(resp, req)
    93  
    94  			assert.Equal(t, tt.seenVals, seenVals)
    95  		})
    96  	}
    97  
    98  }