|
| 1 | +package httpgrpcutil |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/stretchr/testify/assert" |
| 7 | + "github.com/weaveworks/common/httpgrpc" |
| 8 | +) |
| 9 | + |
| 10 | +func TestGetHeader(t *testing.T) { |
| 11 | + tests := []struct { |
| 12 | + name string |
| 13 | + headers []*httpgrpc.Header |
| 14 | + key string |
| 15 | + expected string |
| 16 | + }{ |
| 17 | + { |
| 18 | + name: "returns empty string for missing key", |
| 19 | + headers: nil, |
| 20 | + key: "X-Missing", |
| 21 | + expected: "", |
| 22 | + }, |
| 23 | + { |
| 24 | + name: "returns first value for existing key", |
| 25 | + headers: []*httpgrpc.Header{ |
| 26 | + {Key: "Content-Type", Values: []string{"application/json", "text/plain"}}, |
| 27 | + }, |
| 28 | + key: "Content-Type", |
| 29 | + expected: "application/json", |
| 30 | + }, |
| 31 | + { |
| 32 | + name: "does not match different key", |
| 33 | + headers: []*httpgrpc.Header{ |
| 34 | + {Key: "Accept", Values: []string{"text/html"}}, |
| 35 | + }, |
| 36 | + key: "Content-Type", |
| 37 | + expected: "", |
| 38 | + }, |
| 39 | + } |
| 40 | + |
| 41 | + for _, tt := range tests { |
| 42 | + t.Run(tt.name, func(t *testing.T) { |
| 43 | + req := httpgrpc.HTTPRequest{Headers: tt.headers} |
| 44 | + result := GetHeader(req, tt.key) |
| 45 | + assert.Equal(t, tt.expected, result) |
| 46 | + }) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +func TestGetHeaderValues(t *testing.T) { |
| 51 | + tests := []struct { |
| 52 | + name string |
| 53 | + headers []*httpgrpc.Header |
| 54 | + key string |
| 55 | + expected []string |
| 56 | + }{ |
| 57 | + { |
| 58 | + name: "returns empty slice for missing key", |
| 59 | + headers: nil, |
| 60 | + key: "X-Missing", |
| 61 | + expected: []string{}, |
| 62 | + }, |
| 63 | + { |
| 64 | + name: "returns all values for existing key", |
| 65 | + headers: []*httpgrpc.Header{ |
| 66 | + {Key: "Accept", Values: []string{"text/html", "application/json"}}, |
| 67 | + }, |
| 68 | + key: "Accept", |
| 69 | + expected: []string{"text/html", "application/json"}, |
| 70 | + }, |
| 71 | + { |
| 72 | + name: "returns values from first matching header only", |
| 73 | + headers: []*httpgrpc.Header{ |
| 74 | + {Key: "X-Custom", Values: []string{"first"}}, |
| 75 | + {Key: "X-Custom", Values: []string{"second"}}, |
| 76 | + }, |
| 77 | + key: "X-Custom", |
| 78 | + expected: []string{"first"}, |
| 79 | + }, |
| 80 | + } |
| 81 | + |
| 82 | + for _, tt := range tests { |
| 83 | + t.Run(tt.name, func(t *testing.T) { |
| 84 | + req := httpgrpc.HTTPRequest{Headers: tt.headers} |
| 85 | + result := GetHeaderValues(req, tt.key) |
| 86 | + assert.Equal(t, tt.expected, result) |
| 87 | + }) |
| 88 | + } |
| 89 | +} |
0 commit comments