Debian Codegraph @

exp/api/remote/remote_headers_test.go

raw
1 // Copyright 2024 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package remote
15
16 import (
17 "net/http"
18 "net/http/httptest"
19 "testing"
20
21 "github.com/google/go-cmp/cmp"
22 "github.com/google/go-cmp/cmp/cmpopts"
23 )
24
25 func TestWriteResponse(t *testing.T) {
26 t.Run("new response has empty headers", func(t *testing.T) {
27 resp := NewWriteResponse()
28 if len(resp.ExtraHeaders()) != 0 {
29 t.Errorf("expected empty headers, got %v", resp.ExtraHeaders())
30 }
31 })
32
33 t.Run("setters and getters", func(t *testing.T) {
34 resp := NewWriteResponse()
35
36 resp.SetStatusCode(http.StatusOK)
37 if got := resp.StatusCode(); got != http.StatusOK {
38 t.Errorf("expected status code %d, got %d", http.StatusOK, got)
39 }
40
41 stats := WriteResponseStats{
42 Samples: 10,
43 Histograms: 5,
44 Exemplars: 2,
45 confirmed: true,
46 }
47 resp.Add(stats)
48 if diff := cmp.Diff(stats, resp.Stats(), cmpopts.IgnoreUnexported(WriteResponseStats{})); diff != "" {
49 t.Errorf("stats mismatch (-want +got):\n%s", diff)
50 }
51
52 toAdd := WriteResponseStats{
53 Samples: 10,
54 Histograms: 5,
55 Exemplars: 2,
56 confirmed: true,
57 }
58 resp.Add(toAdd)
59 if diff := cmp.Diff(WriteResponseStats{
60 Samples: 20,
61 Histograms: 10,
62 Exemplars: 4,
63 confirmed: true,
64 }, resp.Stats(), cmpopts.IgnoreUnexported(WriteResponseStats{})); diff != "" {
65 t.Errorf("stats mismatch (-want +got):\n%s", diff)
66 }
67
68 resp.SetExtraHeader("Test-Header", "test-value")
69 if got := resp.ExtraHeaders().Get("Test-Header"); got != "test-value" {
70 t.Errorf("expected header value %q, got %q", "test-value", got)
71 }
72 })
73
74 t.Run("set headers on response writer", func(t *testing.T) {
75 resp := NewWriteResponse()
76 resp.Add(WriteResponseStats{
77 Samples: 10,
78 Histograms: 5,
79 Exemplars: 2,
80 confirmed: true,
81 })
82 resp.SetExtraHeader("Custom-Header", "custom-value")
83
84 w := httptest.NewRecorder()
85 resp.SetHeaders(w)
86
87 expectedHeaders := map[string]string{
88 "Custom-Header": "custom-value",
89 "X-Prometheus-Remote-Write-Samples-Written": "10",
90 "X-Prometheus-Remote-Write-Histograms-Written": "5",
91 "X-Prometheus-Remote-Write-Exemplars-Written": "2",
92 }
93
94 for k, want := range expectedHeaders {
95 if got := w.Header().Get(k); got != want {
96 t.Errorf("header %q: want %q, got %q", k, want, got)
97 }
98 }
99 })
100 }