github.com/solo-io/cue@v0.4.7/pkg/tool/http/http_test.go (about)

     1  // Copyright 2020 CUE Authors
     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 http
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  	"testing"
    21  
    22  	"github.com/solo-io/cue/cue"
    23  )
    24  
    25  func TestParseHeaders(t *testing.T) {
    26  	req := `
    27  	header: {
    28  		"Accept-Language": "en,nl"
    29  	}
    30  	trailer: {
    31  		"Accept-Language": "en,nl"
    32  		User: "foo"
    33  	}
    34  	`
    35  	testCases := []struct {
    36  		req   string
    37  		field string
    38  		out   string
    39  	}{{
    40  		field: "header",
    41  		out:   "nil",
    42  	}, {
    43  		req:   req,
    44  		field: "non-exist",
    45  		out:   "nil",
    46  	}, {
    47  		req:   req,
    48  		field: "header",
    49  		out:   "Accept-Language: en,nl\r\n",
    50  	}, {
    51  		req:   req,
    52  		field: "trailer",
    53  		out:   "Accept-Language: en,nl\r\nUser: foo\r\n",
    54  	}, {
    55  		req: `
    56  		header: {
    57  			"1": 'a'
    58  		}
    59  		`,
    60  		field: "header",
    61  		out:   "header.\"1\": cannot use value 'a' (type bytes) as string",
    62  	}, {
    63  		req: `
    64  			header: 1
    65  			`,
    66  		field: "header",
    67  		out:   "header: cannot use value 1 (type int) as struct",
    68  	}}
    69  	for _, tc := range testCases {
    70  		t.Run("", func(t *testing.T) {
    71  			r := cue.Runtime{}
    72  			inst, err := r.Compile("http headers", tc.req)
    73  			if err != nil {
    74  				t.Fatal(err)
    75  			}
    76  
    77  			h, err := parseHeaders(inst.Value(), tc.field)
    78  
    79  			b := &strings.Builder{}
    80  			switch {
    81  			case err != nil:
    82  				fmt.Fprint(b, err)
    83  			case h == nil:
    84  				b.WriteString("nil")
    85  			default:
    86  				_ = h.Write(b)
    87  			}
    88  
    89  			got := b.String()
    90  			if got != tc.out {
    91  				t.Errorf("got %q; want %q", got, tc.out)
    92  			}
    93  		})
    94  	}
    95  }