Debian Codegraph @

api/client_test.go

raw
1 // Copyright 2015 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 api
15
16 import (
17 "bytes"
18 "context"
19 "errors"
20 "fmt"
21 "net/http"
22 "net/http/httptest"
23 "net/url"
24 "testing"
25 "time"
26 )
27
28 func TestConfig(t *testing.T) {
29 c := Config{}
30 if c.roundTripper() != DefaultRoundTripper {
31 t.Fatalf("expected default roundtripper for nil RoundTripper field")
32 }
33 }
34
35 func TestClientURL(t *testing.T) {
36 tests := []struct {
37 address string
38 endpoint string
39 args map[string]string
40 expected string
41 }{
42 {
43 address: "http://localhost:9090",
44 endpoint: "/test",
45 expected: "http://localhost:9090/test",
46 },
47 {
48 address: "http://localhost",
49 endpoint: "/test",
50 expected: "http://localhost/test",
51 },
52 {
53 address: "http://localhost:9090",
54 endpoint: "test",
55 expected: "http://localhost:9090/test",
56 },
57 {
58 address: "http://localhost:9090/prefix",
59 endpoint: "/test",
60 expected: "http://localhost:9090/prefix/test",
61 },
62 {
63 address: "https://localhost:9090/",
64 endpoint: "/test/",
65 expected: "https://localhost:9090/test",
66 },
67 {
68 address: "http://localhost:9090",
69 endpoint: "/test/:param",
70 args: map[string]string{
71 "param": "content",
72 },
73 expected: "http://localhost:9090/test/content",
74 },
75 {
76 address: "http://localhost:9090",
77 endpoint: "/test/:param/more/:param",
78 args: map[string]string{
79 "param": "content",
80 },
81 expected: "http://localhost:9090/test/content/more/content",
82 },
83 {
84 address: "http://localhost:9090",
85 endpoint: "/test/:param/more/:foo",
86 args: map[string]string{
87 "param": "content",
88 "foo": "bar",
89 },
90 expected: "http://localhost:9090/test/content/more/bar",
91 },
92 {
93 address: "http://localhost:9090",
94 endpoint: "/test/:param",
95 args: map[string]string{
96 "nonexistent": "content",
97 },
98 expected: "http://localhost:9090/test/:param",
99 },
100 }
101
102 for _, test := range tests {
103 ep, err := url.Parse(test.address)
104 if err != nil {
105 t.Fatal(err)
106 }
107
108 hclient := &httpClient{
109 endpoint: ep,
110 client: http.Client{Transport: DefaultRoundTripper},
111 }
112
113 u := hclient.URL(test.endpoint, test.args)
114 if u.String() != test.expected {
115 t.Errorf("unexpected result: got %s, want %s", u, test.expected)
116 continue
117 }
118 }
119 }
120
121 func TestDoContextCancellation(t *testing.T) {
122 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
123 _, _ = w.Write([]byte("partial"))
124 if f, ok := w.(http.Flusher); ok {
125 f.Flush()
126 }
127
128 <-r.Context().Done()
129 }))
130
131 defer ts.Close()
132
133 client, err := NewClient(Config{
134 Address: ts.URL,
135 })
136 if err != nil {
137 t.Fatalf("failed to create client: %v", err)
138 }
139
140 req, err := http.NewRequest(http.MethodGet, ts.URL, nil)
141 if err != nil {
142 t.Fatalf("failed to create request: %v", err)
143 }
144
145 ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
146 defer cancel()
147
148 start := time.Now()
149 resp, body, err := client.Do(ctx, req)
150 elapsed := time.Since(start)
151
152 if !errors.Is(err, context.DeadlineExceeded) {
153 t.Errorf("expected error %v, got: %v", context.DeadlineExceeded, err)
154 }
155 if body != nil {
156 t.Errorf("expected no body due to cancellation, got: %q", string(body))
157 }
158 if elapsed > 200*time.Millisecond {
159 t.Errorf("Do did not return promptly on cancellation: took %v", elapsed)
160 }
161
162 if resp != nil && resp.Body != nil {
163 resp.Body.Close()
164 }
165 }
166
167 // Serve any http request with a response of N KB of spaces.
168 type serveSpaces struct {
169 sizeKB int
170 }
171
172 func (t serveSpaces) ServeHTTP(w http.ResponseWriter, req *http.Request) {
173 kb := bytes.Repeat([]byte{' '}, 1024)
174 for i := 0; i < t.sizeKB; i++ {
175 w.Write(kb)
176 }
177 }
178
179 func BenchmarkClient(b *testing.B) {
180 b.ReportAllocs()
181 ctx := context.Background()
182
183 for _, sizeKB := range []int{4, 50, 1000, 2000} {
184 b.Run(fmt.Sprintf("%dKB", sizeKB), func(b *testing.B) {
185 testServer := httptest.NewServer(serveSpaces{sizeKB})
186 defer testServer.Close()
187
188 client, err := NewClient(Config{
189 Address: testServer.URL,
190 })
191 if err != nil {
192 b.Fatalf("Failed to initialize client: %v", err)
193 }
194 url, err := url.Parse(testServer.URL + "/prometheus/api/v1/query?query=up")
195 if err != nil {
196 b.Fatalf("Failed to parse url: %v", err)
197 }
198 req := &http.Request{
199 URL: url,
200 }
201 b.ResetTimer()
202 for i := 0; i < b.N; i++ {
203 _, _, err := client.Do(ctx, req)
204 if err != nil {
205 b.Fatalf("Query failed: %v", err)
206 }
207 }
208 b.StopTimer()
209 })
210 }
211 }