github.com/mendersoftware/go-lib-micro@v0.0.0-20240304135804-e8e39c59b148/customheader/middleware_test.go (about)

     1  // Copyright 2023 Northern.tech AS
     2  //
     3  //    Licensed under the Apache License, Version 2.0 (the "License");
     4  //    you may not use this file except in compliance with the License.
     5  //    You may obtain a copy of the License at
     6  //
     7  //        http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  //    Unless required by applicable law or agreed to in writing, software
    10  //    distributed under the License is distributed on an "AS IS" BASIS,
    11  //    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  //    See the License for the specific language governing permissions and
    13  //    limitations under the License.
    14  
    15  package customheader
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/ant0ine/go-json-rest/rest"
    21  	"github.com/ant0ine/go-json-rest/rest/test"
    22  )
    23  
    24  func TestCustomHeaderMiddleware(t *testing.T) {
    25  
    26  	testCases := map[string]struct {
    27  		Name  string
    28  		Value string
    29  	}{
    30  		"empty": {},
    31  		"no value": {
    32  			Name: "MyName",
    33  		},
    34  		"both": {
    35  			Name:  "MyName",
    36  			Value: "Lala",
    37  		},
    38  	}
    39  
    40  	for name, tc := range testCases {
    41  
    42  		t.Run(name, func(t *testing.T) {
    43  
    44  			api := rest.NewApi()
    45  
    46  			api.Use(&CustomHeaderMiddleware{
    47  				HeaderName:  tc.Name,
    48  				HeaderValue: tc.Value,
    49  			})
    50  
    51  			api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
    52  				w.WriteJson(map[string]string{"Id": "123"})
    53  			}))
    54  
    55  			handler := api.MakeHandler()
    56  
    57  			req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
    58  			recorded := test.RunRequest(t, handler, req)
    59  			recorded.CodeIs(200)
    60  			recorded.ContentTypeIsJson()
    61  			recorded.HeaderIs(tc.Name, tc.Value)
    62  		})
    63  	}
    64  }