Debian Codegraph @

api/prometheus/v1/api_test.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2017 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 v1
15
16 import (
17 "context"
18 "errors"
19 "io"
20 "math"
21 "net/http"
22 "net/http/httptest"
23 "net/url"
24 "reflect"
25 "strconv"
26 "strings"
27 "testing"
28 "time"
29
30 json "github.com/json-iterator/go"
31
32 "github.com/prometheus/common/model"
33 )
34
35 type apiTest struct {
36 do func() (interface{}, Warnings, error)
37 inWarnings []string
38 inErr error
39 inStatusCode int
40 inRes interface{}
41
42 reqPath string
43 reqMethod string
44 res interface{}
45 err error
46 }
47
48 type apiTestClient struct {
49 *testing.T
50 curTest apiTest
51 }
52
53 func (c *apiTestClient) URL(ep string, args map[string]string) *url.URL {
54 path := ep
55 for k, v := range args {
56 path = strings.ReplaceAll(path, ":"+k, v)
57 }
58 u := &url.URL{
59 Host: "test:9090",
60 Path: path,
61 }
62 return u
63 }
64
65 func (c *apiTestClient) Do(_ context.Context, req *http.Request) (*http.Response, []byte, Warnings, error) {
66 test := c.curTest
67
68 if req.URL.Path != test.reqPath {
69 c.Errorf("unexpected request path: want %s, got %s", test.reqPath, req.URL.Path)
70 }
71 if req.Method != test.reqMethod {
72 c.Errorf("unexpected request method: want %s, got %s", test.reqMethod, req.Method)
73 }
74
75 b, err := json.Marshal(test.inRes)
76 if err != nil {
77 c.Fatal(err)
78 }
79
80 resp := &http.Response{}
81 if test.inStatusCode != 0 {
82 resp.StatusCode = test.inStatusCode
83 } else if test.inErr != nil {
84 resp.StatusCode = http.StatusUnprocessableEntity
85 } else {
86 resp.StatusCode = http.StatusOK
87 }
88
89 return resp, b, test.inWarnings, test.inErr
90 }
91
92 func (c *apiTestClient) DoGetFallback(ctx context.Context, u *url.URL, args url.Values) (*http.Response, []byte, Warnings, error) {
93 req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(args.Encode()))
94 if err != nil {
95 return nil, nil, nil, err
96 }
97 return c.Do(ctx, req)
98 }
99
100 func TestAPIs(t *testing.T) {
101 testTime := time.Now()
102
103 tc := &apiTestClient{
104 T: t,
105 }
106 promAPI := &httpAPI{
107 client: tc,
108 }
109
110 doAlertManagers := func() func() (interface{}, Warnings, error) {
111 return func() (interface{}, Warnings, error) {
112 v, err := promAPI.AlertManagers(context.Background())
113 return v, nil, err
114 }
115 }
116
117 doCleanTombstones := func() func() (interface{}, Warnings, error) {
118 return func() (interface{}, Warnings, error) {
119 return nil, nil, promAPI.CleanTombstones(context.Background())
120 }
121 }
122
123 doConfig := func() func() (interface{}, Warnings, error) {
124 return func() (interface{}, Warnings, error) {
125 v, err := promAPI.Config(context.Background())
126 return v, nil, err
127 }
128 }
129
130 doDeleteSeries := func(matcher string, startTime, endTime time.Time) func() (interface{}, Warnings, error) {
131 return func() (interface{}, Warnings, error) {
132 return nil, nil, promAPI.DeleteSeries(context.Background(), []string{matcher}, startTime, endTime)
133 }
134 }
135
136 doFlags := func() func() (interface{}, Warnings, error) {
137 return func() (interface{}, Warnings, error) {
138 v, err := promAPI.Flags(context.Background())
139 return v, nil, err
140 }
141 }
142
143 doBuildinfo := func() func() (interface{}, Warnings, error) {
144 return func() (interface{}, Warnings, error) {
145 v, err := promAPI.Buildinfo(context.Background())
146 return v, nil, err
147 }
148 }
149
150 doRuntimeinfo := func() func() (interface{}, Warnings, error) {
151 return func() (interface{}, Warnings, error) {
152 v, err := promAPI.Runtimeinfo(context.Background())
153 return v, nil, err
154 }
155 }
156
157 doLabelNames := func(matches []string, startTime, endTime time.Time, opts ...Option) func() (interface{}, Warnings, error) {
158 return func() (interface{}, Warnings, error) {
159 return promAPI.LabelNames(context.Background(), matches, startTime, endTime, opts...)
160 }
161 }
162
163 doLabelValues := func(matches []string, label string, startTime, endTime time.Time, opts ...Option) func() (interface{}, Warnings, error) {
164 return func() (interface{}, Warnings, error) {
165 return promAPI.LabelValues(context.Background(), label, matches, startTime, endTime, opts...)
166 }
167 }
168
169 doQuery := func(q string, ts time.Time, opts ...Option) func() (interface{}, Warnings, error) {
170 return func() (interface{}, Warnings, error) {
171 return promAPI.Query(context.Background(), q, ts, opts...)
172 }
173 }
174
175 doQueryRange := func(q string, rng Range, opts ...Option) func() (interface{}, Warnings, error) {
176 return func() (interface{}, Warnings, error) {
177 return promAPI.QueryRange(context.Background(), q, rng, opts...)
178 }
179 }
180
181 doSeries := func(matcher string, startTime, endTime time.Time, opts ...Option) func() (interface{}, Warnings, error) {
182 return func() (interface{}, Warnings, error) {
183 return promAPI.Series(context.Background(), []string{matcher}, startTime, endTime, opts...)
184 }
185 }
186
187 doSnapshot := func(skipHead bool) func() (interface{}, Warnings, error) {
188 return func() (interface{}, Warnings, error) {
189 v, err := promAPI.Snapshot(context.Background(), skipHead)
190 return v, nil, err
191 }
192 }
193
194 doRules := func() func() (interface{}, Warnings, error) {
195 return func() (interface{}, Warnings, error) {
196 v, err := promAPI.Rules(context.Background())
197 return v, nil, err
198 }
199 }
200
201 doTargets := func() func() (interface{}, Warnings, error) {
202 return func() (interface{}, Warnings, error) {
203 v, err := promAPI.Targets(context.Background())
204 return v, nil, err
205 }
206 }
207
208 doTargetsMetadata := func(matchTarget, metric, limit string) func() (interface{}, Warnings, error) {
209 return func() (interface{}, Warnings, error) {
210 v, err := promAPI.TargetsMetadata(context.Background(), matchTarget, metric, limit)
211 return v, nil, err
212 }
213 }
214
215 doMetadata := func(metric, limit string) func() (interface{}, Warnings, error) {
216 return func() (interface{}, Warnings, error) {
217 v, err := promAPI.Metadata(context.Background(), metric, limit)
218 return v, nil, err
219 }
220 }
221
222 doTSDB := func(opts ...Option) func() (interface{}, Warnings, error) {
223 return func() (interface{}, Warnings, error) {
224 v, err := promAPI.TSDB(context.Background(), opts...)
225 return v, nil, err
226 }
227 }
228
229 doWalReply := func() func() (interface{}, Warnings, error) {
230 return func() (interface{}, Warnings, error) {
231 v, err := promAPI.WalReplay(context.Background())
232 return v, nil, err
233 }
234 }
235
236 doQueryExemplars := func(query string, startTime, endTime time.Time) func() (interface{}, Warnings, error) {
237 return func() (interface{}, Warnings, error) {
238 v, err := promAPI.QueryExemplars(context.Background(), query, startTime, endTime)
239 return v, nil, err
240 }
241 }
242
243 queryTests := []apiTest{
244 {
245 do: doQuery("2", testTime, WithTimeout(5*time.Second)),
246 inRes: &queryResult{
247 Type: model.ValScalar,
248 Result: &model.Scalar{
249 Value: 2,
250 Timestamp: model.TimeFromUnix(testTime.Unix()),
251 },
252 },
253
254 reqMethod: "POST",
255 reqPath: "/api/v1/query",
256 res: &model.Scalar{
257 Value: 2,
258 Timestamp: model.TimeFromUnix(testTime.Unix()),
259 },
260 },
261 {
262 do: doQuery("2", testTime),
263 inErr: errors.New("some error"),
264
265 reqMethod: "POST",
266 reqPath: "/api/v1/query",
267 err: errors.New("some error"),
268 },
269 {
270 do: doQuery("2", testTime),
271 inRes: "some body",
272 inStatusCode: 500,
273 inErr: &Error{
274 Type: ErrServer,
275 Msg: "server error: 500",
276 Detail: "some body",
277 },
278
279 reqMethod: "POST",
280 reqPath: "/api/v1/query",
281 err: errors.New("server_error: server error: 500"),
282 },
283 {
284 do: doQuery("2", testTime),
285 inRes: "some body",
286 inStatusCode: 404,
287 inErr: &Error{
288 Type: ErrClient,
289 Msg: "client error: 404",
290 Detail: "some body",
291 },
292
293 reqMethod: "POST",
294 reqPath: "/api/v1/query",
295 err: errors.New("client_error: client error: 404"),
296 },
297 // Warning only.
298 {
299 do: doQuery("2", testTime),
300 inWarnings: []string{"warning"},
301 inRes: &queryResult{
302 Type: model.ValScalar,
303 Result: &model.Scalar{
304 Value: 2,
305 Timestamp: model.TimeFromUnix(testTime.Unix()),
306 },
307 },
308
309 reqMethod: "POST",
310 reqPath: "/api/v1/query",
311 res: &model.Scalar{
312 Value: 2,
313 Timestamp: model.TimeFromUnix(testTime.Unix()),
314 },
315 },
316 // Warning + error.
317 {
318 do: doQuery("2", testTime),
319 inWarnings: []string{"warning"},
320 inRes: "some body",
321 inStatusCode: 404,
322 inErr: &Error{
323 Type: ErrClient,
324 Msg: "client error: 404",
325 Detail: "some body",
326 },
327
328 reqMethod: "POST",
329 reqPath: "/api/v1/query",
330 err: errors.New("client_error: client error: 404"),
331 },
332
333 {
334 do: doQueryRange("2", Range{
335 Start: testTime.Add(-time.Minute),
336 End: testTime,
337 Step: 1 * time.Minute,
338 }, WithTimeout(5*time.Second)),
339 inErr: errors.New("some error"),
340
341 reqMethod: "POST",
342 reqPath: "/api/v1/query_range",
343 err: errors.New("some error"),
344 },
345
346 {
347 do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime),
348 inRes: []string{"val1", "val2"},
349 reqMethod: "POST",
350 reqPath: "/api/v1/labels",
351 res: []string{"val1", "val2"},
352 },
353 {
354 do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime),
355 inRes: []string{"val1", "val2"},
356 inWarnings: []string{"a"},
357 reqMethod: "POST",
358 reqPath: "/api/v1/labels",
359 res: []string{"val1", "val2"},
360 },
361
362 {
363 do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime),
364 inErr: errors.New("some error"),
365 reqMethod: "POST",
366 reqPath: "/api/v1/labels",
367 err: errors.New("some error"),
368 },
369 {
370 do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime),
371 inErr: errors.New("some error"),
372 inWarnings: []string{"a"},
373 reqMethod: "POST",
374 reqPath: "/api/v1/labels",
375 err: errors.New("some error"),
376 },
377 {
378 do: doLabelNames([]string{"up"}, testTime.Add(-100*time.Hour), testTime),
379 inRes: []string{"val1", "val2"},
380 reqMethod: "POST",
381 reqPath: "/api/v1/labels",
382 res: []string{"val1", "val2"},
383 },
384
385 {
386 do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime),
387 inRes: []string{"val1", "val2"},
388 reqMethod: "GET",
389 reqPath: "/api/v1/label/mylabel/values",
390 res: model.LabelValues{"val1", "val2"},
391 },
392 {
393 do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime),
394 inRes: []string{"val1", "val2"},
395 inWarnings: []string{"a"},
396 reqMethod: "GET",
397 reqPath: "/api/v1/label/mylabel/values",
398 res: model.LabelValues{"val1", "val2"},
399 },
400
401 {
402 do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime),
403 inErr: errors.New("some error"),
404 reqMethod: "GET",
405 reqPath: "/api/v1/label/mylabel/values",
406 err: errors.New("some error"),
407 },
408 {
409 do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime),
410 inErr: errors.New("some error"),
411 inWarnings: []string{"a"},
412 reqMethod: "GET",
413 reqPath: "/api/v1/label/mylabel/values",
414 err: errors.New("some error"),
415 },
416 {
417 do: doLabelValues([]string{"up"}, "mylabel", testTime.Add(-100*time.Hour), testTime),
418 inRes: []string{"val1", "val2"},
419 reqMethod: "GET",
420 reqPath: "/api/v1/label/mylabel/values",
421 res: model.LabelValues{"val1", "val2"},
422 },
423
424 {
425 do: doSeries("up", testTime.Add(-time.Minute), testTime),
426 inRes: []map[string]string{
427 {
428 "__name__": "up",
429 "job": "prometheus",
430 "instance": "localhost:9090",
431 },
432 },
433 reqMethod: "POST",
434 reqPath: "/api/v1/series",
435 res: []model.LabelSet{
436 {
437 "__name__": "up",
438 "job": "prometheus",
439 "instance": "localhost:9090",
440 },
441 },
442 },
443 // Series with data + warning.
444 {
445 do: doSeries("up", testTime.Add(-time.Minute), testTime),
446 inRes: []map[string]string{
447 {
448 "__name__": "up",
449 "job": "prometheus",
450 "instance": "localhost:9090",
451 },
452 },
453 inWarnings: []string{"a"},
454 reqMethod: "POST",
455 reqPath: "/api/v1/series",
456 res: []model.LabelSet{
457 {
458 "__name__": "up",
459 "job": "prometheus",
460 "instance": "localhost:9090",
461 },
462 },
463 },
464
465 {
466 do: doSeries("up", testTime.Add(-time.Minute), testTime),
467 inErr: errors.New("some error"),
468 reqMethod: "POST",
469 reqPath: "/api/v1/series",
470 err: errors.New("some error"),
471 },
472 // Series with error and warning.
473 {
474 do: doSeries("up", testTime.Add(-time.Minute), testTime),
475 inErr: errors.New("some error"),
476 inWarnings: []string{"a"},
477 reqMethod: "POST",
478 reqPath: "/api/v1/series",
479 err: errors.New("some error"),
480 },
481
482 {
483 do: doSnapshot(true),
484 inRes: map[string]string{
485 "name": "20171210T211224Z-2be650b6d019eb54",
486 },
487 reqMethod: "POST",
488 reqPath: "/api/v1/admin/tsdb/snapshot",
489 res: SnapshotResult{
490 Name: "20171210T211224Z-2be650b6d019eb54",
491 },
492 },
493
494 {
495 do: doSnapshot(true),
496 inErr: errors.New("some error"),
497 reqMethod: "POST",
498 reqPath: "/api/v1/admin/tsdb/snapshot",
499 err: errors.New("some error"),
500 },
501
502 {
503 do: doCleanTombstones(),
504 reqMethod: "POST",
505 reqPath: "/api/v1/admin/tsdb/clean_tombstones",
506 },
507
508 {
509 do: doCleanTombstones(),
510 inErr: errors.New("some error"),
511 reqMethod: "POST",
512 reqPath: "/api/v1/admin/tsdb/clean_tombstones",
513 err: errors.New("some error"),
514 },
515
516 {
517 do: doDeleteSeries("up", testTime.Add(-time.Minute), testTime),
518 inRes: []map[string]string{
519 {
520 "__name__": "up",
521 "job": "prometheus",
522 "instance": "localhost:9090",
523 },
524 },
525 reqMethod: "POST",
526 reqPath: "/api/v1/admin/tsdb/delete_series",
527 },
528
529 {
530 do: doDeleteSeries("up", testTime.Add(-time.Minute), testTime),
531 inErr: errors.New("some error"),
532 reqMethod: "POST",
533 reqPath: "/api/v1/admin/tsdb/delete_series",
534 err: errors.New("some error"),
535 },
536
537 {
538 do: doConfig(),
539 reqMethod: "GET",
540 reqPath: "/api/v1/status/config",
541 inRes: map[string]string{
542 "yaml": "<content of the loaded config file in YAML>",
543 },
544 res: ConfigResult{
545 YAML: "<content of the loaded config file in YAML>",
546 },
547 },
548
549 {
550 do: doConfig(),
551 reqMethod: "GET",
552 reqPath: "/api/v1/status/config",
553 inErr: errors.New("some error"),
554 err: errors.New("some error"),
555 },
556
557 {
558 do: doFlags(),
559 reqMethod: "GET",
560 reqPath: "/api/v1/status/flags",
561 inRes: map[string]string{
562 "alertmanager.notification-queue-capacity": "10000",
563 "alertmanager.timeout": "10s",
564 "log.level": "info",
565 "query.lookback-delta": "5m",
566 "query.max-concurrency": "20",
567 },
568 res: FlagsResult{
569 "alertmanager.notification-queue-capacity": "10000",
570 "alertmanager.timeout": "10s",
571 "log.level": "info",
572 "query.lookback-delta": "5m",
573 "query.max-concurrency": "20",
574 },
575 },
576
577 {
578 do: doFlags(),
579 reqMethod: "GET",
580 reqPath: "/api/v1/status/flags",
581 inErr: errors.New("some error"),
582 err: errors.New("some error"),
583 },
584
585 {
586 do: doBuildinfo(),
587 reqMethod: "GET",
588 reqPath: "/api/v1/status/buildinfo",
589 inErr: errors.New("some error"),
590 err: errors.New("some error"),
591 },
592
593 {
594 do: doBuildinfo(),
595 reqMethod: "GET",
596 reqPath: "/api/v1/status/buildinfo",
597 inRes: map[string]interface{}{
598 "version": "2.23.0",
599 "revision": "26d89b4b0776fe4cd5a3656dfa520f119a375273",
600 "branch": "HEAD",
601 "buildUser": "root@37609b3a0a21",
602 "buildDate": "20201126-10:56:17",
603 "goVersion": "go1.15.5",
604 },
605 res: BuildinfoResult{
606 Version: "2.23.0",
607 Revision: "26d89b4b0776fe4cd5a3656dfa520f119a375273",
608 Branch: "HEAD",
609 BuildUser: "root@37609b3a0a21",
610 BuildDate: "20201126-10:56:17",
611 GoVersion: "go1.15.5",
612 },
613 },
614
615 {
616 do: doRuntimeinfo(),
617 reqMethod: "GET",
618 reqPath: "/api/v1/status/runtimeinfo",
619 inErr: errors.New("some error"),
620 err: errors.New("some error"),
621 },
622
623 {
624 do: doRuntimeinfo(),
625 reqMethod: "GET",
626 reqPath: "/api/v1/status/runtimeinfo",
627 inRes: map[string]interface{}{
628 "startTime": "2020-05-18T15:52:53.4503113Z",
629 "CWD": "/prometheus",
630 "reloadConfigSuccess": true,
631 "lastConfigTime": "2020-05-18T15:52:56Z",
632 "corruptionCount": 0,
633 "goroutineCount": 217,
634 "GOMAXPROCS": 2,
635 "GOGC": "100",
636 "GODEBUG": "allocfreetrace",
637 "storageRetention": "1d",
638 },
639 res: RuntimeinfoResult{
640 StartTime: time.Date(2020, 5, 18, 15, 52, 53, 450311300, time.UTC),
641 CWD: "/prometheus",
642 ReloadConfigSuccess: true,
643 LastConfigTime: time.Date(2020, 5, 18, 15, 52, 56, 0, time.UTC),
644 CorruptionCount: 0,
645 GoroutineCount: 217,
646 GOMAXPROCS: 2,
647 GOGC: "100",
648 GODEBUG: "allocfreetrace",
649 StorageRetention: "1d",
650 },
651 },
652
653 {
654 do: doAlertManagers(),
655 reqMethod: "GET",
656 reqPath: "/api/v1/alertmanagers",
657 inRes: map[string]interface{}{
658 "activeAlertManagers": []map[string]string{
659 {
660 "url": "http://127.0.0.1:9091/api/v1/alerts",
661 },
662 },
663 "droppedAlertManagers": []map[string]string{
664 {
665 "url": "http://127.0.0.1:9092/api/v1/alerts",
666 },
667 },
668 },
669 res: AlertManagersResult{
670 Active: []AlertManager{
671 {
672 URL: "http://127.0.0.1:9091/api/v1/alerts",
673 },
674 },
675 Dropped: []AlertManager{
676 {
677 URL: "http://127.0.0.1:9092/api/v1/alerts",
678 },
679 },
680 },
681 },
682
683 {
684 do: doAlertManagers(),
685 reqMethod: "GET",
686 reqPath: "/api/v1/alertmanagers",
687 inErr: errors.New("some error"),
688 err: errors.New("some error"),
689 },
690
691 {
692 do: doRules(),
693 reqMethod: "GET",
694 reqPath: "/api/v1/rules",
695 inRes: map[string]interface{}{
696 "groups": []map[string]interface{}{
697 {
698 "file": "/rules.yaml",
699 "interval": 60,
700 "name": "example",
701 "rules": []map[string]interface{}{
702 {
703 "alerts": []map[string]interface{}{
704 {
705 "activeAt": testTime.UTC().Format(time.RFC3339Nano),
706 "annotations": map[string]interface{}{
707 "summary": "High request latency",
708 },
709 "labels": map[string]interface{}{
710 "alertname": "HighRequestLatency",
711 "severity": "page",
712 },
713 "state": "firing",
714 "value": "1e+00",
715 },
716 },
717 "annotations": map[string]interface{}{
718 "summary": "High request latency",
719 },
720 "duration": 600,
721 "health": "ok",
722 "labels": map[string]interface{}{
723 "severity": "page",
724 },
725 "name": "HighRequestLatency",
726 "query": "job:request_latency_seconds:mean5m{job=\"myjob\"} > 0.5",
727 "type": "alerting",
728 },
729 {
730 "health": "ok",
731 "name": "job:http_inprogress_requests:sum",
732 "query": "sum(http_inprogress_requests) by (job)",
733 "type": "recording",
734 },
735 },
736 },
737 },
738 },
739 res: RulesResult{
740 Groups: []RuleGroup{
741 {
742 Name: "example",
743 File: "/rules.yaml",
744 Interval: 60,
745 Rules: []interface{}{
746 AlertingRule{
747 Alerts: []*Alert{
748 {
749 ActiveAt: testTime.UTC(),
750 Annotations: model.LabelSet{
751 "summary": "High request latency",
752 },
753 Labels: model.LabelSet{
754 "alertname": "HighRequestLatency",
755 "severity": "page",
756 },
757 State: AlertStateFiring,
758 Value: "1e+00",
759 },
760 },
761 Annotations: model.LabelSet{
762 "summary": "High request latency",
763 },
764 Labels: model.LabelSet{
765 "severity": "page",
766 },
767 Duration: 600,
768 Health: RuleHealthGood,
769 Name: "HighRequestLatency",
770 Query: "job:request_latency_seconds:mean5m{job=\"myjob\"} > 0.5",
771 LastError: "",
772 },
773 RecordingRule{
774 Health: RuleHealthGood,
775 Name: "job:http_inprogress_requests:sum",
776 Query: "sum(http_inprogress_requests) by (job)",
777 LastError: "",
778 },
779 },
780 },
781 },
782 },
783 },
784
785 // This has the newer API elements like lastEvaluation, evaluationTime, etc.
786 {
787 do: doRules(),
788 reqMethod: "GET",
789 reqPath: "/api/v1/rules",
790 inRes: map[string]interface{}{
791 "groups": []map[string]interface{}{
792 {
793 "file": "/rules.yaml",
794 "interval": 60,
795 "name": "example",
796 "rules": []map[string]interface{}{
797 {
798 "alerts": []map[string]interface{}{
799 {
800 "activeAt": testTime.UTC().Format(time.RFC3339Nano),
801 "annotations": map[string]interface{}{
802 "summary": "High request latency",
803 },
804 "labels": map[string]interface{}{
805 "alertname": "HighRequestLatency",
806 "severity": "page",
807 },
808 "state": "firing",
809 "value": "1e+00",
810 },
811 },
812 "annotations": map[string]interface{}{
813 "summary": "High request latency",
814 },
815 "duration": 600,
816 "health": "ok",
817 "labels": map[string]interface{}{
818 "severity": "page",
819 },
820 "name": "HighRequestLatency",
821 "query": "job:request_latency_seconds:mean5m{job=\"myjob\"} > 0.5",
822 "type": "alerting",
823 "evaluationTime": 0.5,
824 "lastEvaluation": "2020-05-18T15:52:53.4503113Z",
825 "state": "firing",
826 },
827 {
828 "health": "ok",
829 "name": "job:http_inprogress_requests:sum",
830 "query": "sum(http_inprogress_requests) by (job)",
831 "type": "recording",
832 "evaluationTime": 0.3,
833 "lastEvaluation": "2020-05-18T15:52:53.4503113Z",
834 },
835 },
836 },
837 },
838 },
839 res: RulesResult{
840 Groups: []RuleGroup{
841 {
842 Name: "example",
843 File: "/rules.yaml",
844 Interval: 60,
845 Rules: []interface{}{
846 AlertingRule{
847 Alerts: []*Alert{
848 {
849 ActiveAt: testTime.UTC(),
850 Annotations: model.LabelSet{
851 "summary": "High request latency",
852 },
853 Labels: model.LabelSet{
854 "alertname": "HighRequestLatency",
855 "severity": "page",
856 },
857 State: AlertStateFiring,
858 Value: "1e+00",
859 },
860 },
861 Annotations: model.LabelSet{
862 "summary": "High request latency",
863 },
864 Labels: model.LabelSet{
865 "severity": "page",
866 },
867 Duration: 600,
868 Health: RuleHealthGood,
869 Name: "HighRequestLatency",
870 Query: "job:request_latency_seconds:mean5m{job=\"myjob\"} > 0.5",
871 LastError: "",
872 EvaluationTime: 0.5,
873 LastEvaluation: time.Date(2020, 5, 18, 15, 52, 53, 450311300, time.UTC),
874 State: "firing",
875 },
876 RecordingRule{
877 Health: RuleHealthGood,
878 Name: "job:http_inprogress_requests:sum",
879 Query: "sum(http_inprogress_requests) by (job)",
880 LastError: "",
881 EvaluationTime: 0.3,
882 LastEvaluation: time.Date(2020, 5, 18, 15, 52, 53, 450311300, time.UTC),
883 },
884 },
885 },
886 },
887 },
888 },
889
890 {
891 do: doRules(),
892 reqMethod: "GET",
893 reqPath: "/api/v1/rules",
894 inErr: errors.New("some error"),
895 err: errors.New("some error"),
896 },
897
898 {
899 do: doTargets(),
900 reqMethod: "GET",
901 reqPath: "/api/v1/targets",
902 inRes: map[string]interface{}{
903 "activeTargets": []map[string]interface{}{
904 {
905 "discoveredLabels": map[string]string{
906 "__address__": "127.0.0.1:9090",
907 "__metrics_path__": "/metrics",
908 "__scheme__": "http",
909 "job": "prometheus",
910 },
911 "labels": map[string]string{
912 "instance": "127.0.0.1:9090",
913 "job": "prometheus",
914 },
915 "scrapePool": "prometheus",
916 "scrapeUrl": "http://127.0.0.1:9090",
917 "globalUrl": "http://127.0.0.1:9090",
918 "lastError": "error while scraping target",
919 "lastScrape": testTime.UTC().Format(time.RFC3339Nano),
920 "lastScrapeDuration": 0.001146115,
921 "health": "up",
922 },
923 },
924 "droppedTargets": []map[string]interface{}{
925 {
926 "discoveredLabels": map[string]string{
927 "__address__": "127.0.0.1:9100",
928 "__metrics_path__": "/metrics",
929 "__scheme__": "http",
930 "job": "node",
931 },
932 },
933 },
934 },
935 res: TargetsResult{
936 Active: []ActiveTarget{
937 {
938 DiscoveredLabels: map[string]string{
939 "__address__": "127.0.0.1:9090",
940 "__metrics_path__": "/metrics",
941 "__scheme__": "http",
942 "job": "prometheus",
943 },
944 Labels: model.LabelSet{
945 "instance": "127.0.0.1:9090",
946 "job": "prometheus",
947 },
948 ScrapePool: "prometheus",
949 ScrapeURL: "http://127.0.0.1:9090",
950 GlobalURL: "http://127.0.0.1:9090",
951 LastError: "error while scraping target",
952 LastScrape: testTime.UTC(),
953 LastScrapeDuration: 0.001146115,
954 Health: HealthGood,
955 },
956 },
957 Dropped: []DroppedTarget{
958 {
959 DiscoveredLabels: map[string]string{
960 "__address__": "127.0.0.1:9100",
961 "__metrics_path__": "/metrics",
962 "__scheme__": "http",
963 "job": "node",
964 },
965 },
966 },
967 },
968 },
969
970 {
971 do: doTargets(),
972 reqMethod: "GET",
973 reqPath: "/api/v1/targets",
974 inErr: errors.New("some error"),
975 err: errors.New("some error"),
976 },
977
978 {
979 do: doTargetsMetadata("{job=\"prometheus\"}", "go_goroutines", "1"),
980 inRes: []map[string]interface{}{
981 {
982 "target": map[string]interface{}{
983 "instance": "127.0.0.1:9090",
984 "job": "prometheus",
985 },
986 "type": "gauge",
987 "help": "Number of goroutines that currently exist.",
988 "unit": "",
989 },
990 },
991 reqMethod: "GET",
992 reqPath: "/api/v1/targets/metadata",
993 res: []MetricMetadata{
994 {
995 Target: map[string]string{
996 "instance": "127.0.0.1:9090",
997 "job": "prometheus",
998 },
999 Type: "gauge",
1000 Help: "Number of goroutines that currently exist.",
1001 Unit: "",
1002 },
1003 },
1004 },
1005
1006 {
1007 do: doTargetsMetadata("{job=\"prometheus\"}", "go_goroutines", "1"),
1008 inErr: errors.New("some error"),
1009 reqMethod: "GET",
1010 reqPath: "/api/v1/targets/metadata",
1011 err: errors.New("some error"),
1012 },
1013
1014 {
1015 do: doMetadata("go_goroutines", "1"),
1016 inRes: map[string]interface{}{
1017 "go_goroutines": []map[string]interface{}{
1018 {
1019 "type": "gauge",
1020 "help": "Number of goroutines that currently exist.",
1021 "unit": "",
1022 },
1023 },
1024 },
1025 reqMethod: "GET",
1026 reqPath: "/api/v1/metadata",
1027 res: map[string][]Metadata{
1028 "go_goroutines": {
1029 {
1030 Type: "gauge",
1031 Help: "Number of goroutines that currently exist.",
1032 Unit: "",
1033 },
1034 },
1035 },
1036 },
1037
1038 {
1039 do: doMetadata("", "1"),
1040 inErr: errors.New("some error"),
1041 reqMethod: "GET",
1042 reqPath: "/api/v1/metadata",
1043 err: errors.New("some error"),
1044 },
1045
1046 {
1047 do: doTSDB(),
1048 reqMethod: "GET",
1049 reqPath: "/api/v1/status/tsdb",
1050 inErr: errors.New("some error"),
1051 err: errors.New("some error"),
1052 },
1053
1054 {
1055 do: doTSDB(),
1056 reqMethod: "GET",
1057 reqPath: "/api/v1/status/tsdb",
1058 inRes: map[string]interface{}{
1059 "headStats": map[string]interface{}{
1060 "numSeries": 18476,
1061 "numLabelPairs": 4301,
1062 "chunkCount": 72692,
•1063 "minTime": int64(1634644800304),
1064 "maxTime": int64(1634650590304),
1065 },
1066 "seriesCountByMetricName": []interface{}{
1067 map[string]interface{}{
1068 "name": "kubelet_http_requests_duration_seconds_bucket",
1069 "value": 1000,
1070 },
1071 },
1072 "labelValueCountByLabelName": []interface{}{
1073 map[string]interface{}{
1074 "name": "__name__",
1075 "value": 200,
1076 },
1077 },
1078 "memoryInBytesByLabelName": []interface{}{
1079 map[string]interface{}{
1080 "name": "id",
1081 "value": 4096,
1082 },
1083 },
1084 "seriesCountByLabelValuePair": []interface{}{
1085 map[string]interface{}{
1086 "name": "job=kubelet",
1087 "value": 30000,
1088 },
1089 },
1090 },
1091 res: TSDBResult{
1092 HeadStats: TSDBHeadStats{
1093 NumSeries: 18476,
1094 NumLabelPairs: 4301,
1095 ChunkCount: 72692,
1096 MinTime: 1634644800304,
1097 MaxTime: 1634650590304,
1098 },
1099 SeriesCountByMetricName: []Stat{
1100 {
1101 Name: "kubelet_http_requests_duration_seconds_bucket",
1102 Value: 1000,
1103 },
1104 },
1105 LabelValueCountByLabelName: []Stat{
1106 {
1107 Name: "__name__",
1108 Value: 200,
1109 },
1110 },
1111 MemoryInBytesByLabelName: []Stat{
1112 {
1113 Name: "id",
1114 Value: 4096,
1115 },
1116 },
1117 SeriesCountByLabelValuePair: []Stat{
1118 {
1119 Name: "job=kubelet",
1120 Value: 30000,
1121 },
1122 },
1123 },
1124 },
1125
1126 {
1127 do: doWalReply(),
1128 reqMethod: "GET",
1129 reqPath: "/api/v1/status/walreplay",
1130 inErr: errors.New("some error"),
1131 err: errors.New("some error"),
1132 },
1133
1134 {
1135 do: doWalReply(),
1136 reqMethod: "GET",
1137 reqPath: "/api/v1/status/walreplay",
1138 inRes: map[string]interface{}{
1139 "min": 2,
1140 "max": 5,
1141 "current": 40,
1142 },
1143 res: WalReplayStatus{
1144 Min: 2,
1145 Max: 5,
1146 Current: 40,
1147 },
1148 },
1149
1150 {
1151 do: doQueryExemplars("tns_request_duration_seconds_bucket", testTime.Add(-1*time.Minute), testTime),
1152 reqMethod: "POST",
1153 reqPath: "/api/v1/query_exemplars",
1154 inErr: errors.New("some error"),
1155 err: errors.New("some error"),
1156 },
1157
1158 {
1159 do: doQueryExemplars("tns_request_duration_seconds_bucket", testTime.Add(-1*time.Minute), testTime),
1160 reqMethod: "POST",
1161 reqPath: "/api/v1/query_exemplars",
1162 inRes: []interface{}{
1163 map[string]interface{}{
1164 "seriesLabels": map[string]interface{}{
1165 "__name__": "tns_request_duration_seconds_bucket",
1166 "instance": "app:80",
1167 "job": "tns/app",
1168 },
1169 "exemplars": []interface{}{
1170 map[string]interface{}{
1171 "labels": map[string]interface{}{
1172 "traceID": "19fd8c8a33975a23",
1173 },
1174 "value": "0.003863295",
1175 "timestamp": model.TimeFromUnixNano(testTime.UnixNano()),
1176 },
1177 map[string]interface{}{
1178 "labels": map[string]interface{}{
1179 "traceID": "67f743f07cc786b0",
1180 },
1181 "value": "0.001535405",
1182 "timestamp": model.TimeFromUnixNano(testTime.UnixNano()),
1183 },
1184 },
1185 },
1186 },
1187 res: []ExemplarQueryResult{
1188 {
1189 SeriesLabels: model.LabelSet{
1190 "__name__": "tns_request_duration_seconds_bucket",
1191 "instance": "app:80",
1192 "job": "tns/app",
1193 },
1194 Exemplars: []Exemplar{
1195 {
1196 Labels: model.LabelSet{"traceID": "19fd8c8a33975a23"},
1197 Value: 0.003863295,
1198 Timestamp: model.TimeFromUnixNano(testTime.UnixNano()),
1199 },
1200 {
1201 Labels: model.LabelSet{"traceID": "67f743f07cc786b0"},
1202 Value: 0.001535405,
1203 Timestamp: model.TimeFromUnixNano(testTime.UnixNano()),
1204 },
1205 },
1206 },
1207 },
1208 },
1209 }
1210
1211 var tests []apiTest
1212 tests = append(tests, queryTests...)
1213
1214 for i, test := range tests {
1215 t.Run(strconv.Itoa(i), func(t *testing.T) {
1216 tc.curTest = test
1217
1218 res, warnings, err := test.do()
1219
1220 if (test.inWarnings == nil) != (warnings == nil) && !reflect.DeepEqual(test.inWarnings, warnings) {
1221 t.Fatalf("mismatch in warnings expected=%v actual=%v", test.inWarnings, warnings)
1222 }
1223
1224 if test.err != nil {
1225 if err == nil {
1226 t.Fatalf("expected error %q but got none", test.err)
1227 }
1228 if err.Error() != test.err.Error() {
1229 t.Errorf("unexpected error: want %s, got %s", test.err, err)
1230 }
1231
1232 apiErr := &Error{}
1233 if ok := errors.As(err, &apiErr); ok {
1234 if apiErr.Detail != test.inRes {
1235 t.Errorf("%q should be %q", apiErr.Detail, test.inRes)
1236 }
1237 }
1238 return
1239 }
1240 if err != nil {
1241 t.Fatalf("unexpected error: %s", err)
1242 }
1243
1244 if !reflect.DeepEqual(res, test.res) {
1245 t.Errorf("unexpected result: want %v, got %v", test.res, res)
1246 }
1247 })
1248 }
1249 }
1250
1251 type testClient struct {
1252 *testing.T
1253
1254 ch chan apiClientTest
1255 req *http.Request
1256 }
1257
1258 type apiClientTest struct {
1259 code int
1260 response interface{}
1261 expectedBody string
1262 expectedErr *Error
1263 expectedWarnings Warnings
1264 }
1265
1266 func (c *testClient) URL(ep string, args map[string]string) *url.URL {
1267 return nil
1268 }
1269
1270 func (c *testClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
1271 if ctx == nil {
1272 c.Fatalf("context was not passed down")
1273 }
1274 if req != c.req {
1275 c.Fatalf("request was not passed down")
1276 }
1277
1278 test := <-c.ch
1279
1280 var b []byte
1281 var err error
1282
1283 switch v := test.response.(type) {
1284 case string:
1285 b = []byte(v)
1286 default:
1287 b, err = json.Marshal(v)
1288 if err != nil {
1289 c.Fatal(err)
1290 }
1291 }
1292
1293 resp := &http.Response{
1294 StatusCode: test.code,
1295 }
1296
1297 return resp, b, nil
1298 }
1299
1300 func TestAPIClientDo(t *testing.T) {
1301 tests := []apiClientTest{
1302 {
1303 code: http.StatusUnprocessableEntity,
1304 response: &apiResponse{
1305 Status: "error",
1306 Data: json.RawMessage(`null`),
1307 ErrorType: ErrBadData,
1308 Error: "failed",
1309 },
1310 expectedErr: &Error{
1311 Type: ErrBadData,
1312 Msg: "failed",
1313 },
1314 expectedBody: `null`,
1315 },
1316 {
1317 code: http.StatusUnprocessableEntity,
1318 response: &apiResponse{
1319 Status: "error",
1320 Data: json.RawMessage(`"test"`),
1321 ErrorType: ErrTimeout,
1322 Error: "timed out",
1323 },
1324 expectedErr: &Error{
1325 Type: ErrTimeout,
1326 Msg: "timed out",
1327 },
1328 expectedBody: `test`,
1329 },
1330 {
1331 code: http.StatusInternalServerError,
1332 response: "500 error details",
1333 expectedErr: &Error{
1334 Type: ErrServer,
1335 Msg: "server error: 500",
1336 Detail: "500 error details",
1337 },
1338 },
1339 {
1340 code: http.StatusNotFound,
1341 response: "404 error details",
1342 expectedErr: &Error{
1343 Type: ErrClient,
1344 Msg: "client error: 404",
1345 Detail: "404 error details",
1346 },
1347 },
1348 {
1349 code: http.StatusBadRequest,
1350 response: &apiResponse{
1351 Status: "error",
1352 Data: json.RawMessage(`null`),
1353 ErrorType: ErrBadData,
1354 Error: "end timestamp must not be before start time",
1355 },
1356 expectedErr: &Error{
1357 Type: ErrBadData,
1358 Msg: "end timestamp must not be before start time",
1359 },
1360 },
1361 {
1362 code: http.StatusUnprocessableEntity,
1363 response: "bad json",
1364 expectedErr: &Error{
1365 Type: ErrBadResponse,
1366 Msg: "readObjectStart: expect { or n, but found b, error found in #1 byte of ...|bad json|..., bigger context ...|bad json|...",
1367 },
1368 },
1369 {
1370 code: http.StatusUnprocessableEntity,
1371 response: &apiResponse{
1372 Status: "success",
1373 Data: json.RawMessage(`"test"`),
1374 },
1375 expectedErr: &Error{
1376 Type: ErrBadResponse,
1377 Msg: "inconsistent body for response code",
1378 },
1379 },
1380 {
1381 code: http.StatusUnprocessableEntity,
1382 response: &apiResponse{
1383 Status: "success",
1384 Data: json.RawMessage(`"test"`),
1385 ErrorType: ErrTimeout,
1386 Error: "timed out",
1387 },
1388 expectedErr: &Error{
1389 Type: ErrBadResponse,
1390 Msg: "inconsistent body for response code",
1391 },
1392 },
1393 {
1394 code: http.StatusOK,
1395 response: &apiResponse{
1396 Status: "error",
1397 Data: json.RawMessage(`"test"`),
1398 ErrorType: ErrTimeout,
1399 Error: "timed out",
1400 },
1401 expectedErr: &Error{
1402 Type: ErrTimeout,
1403 Msg: "timed out",
1404 },
1405 },
1406 {
1407 code: http.StatusOK,
1408 response: &apiResponse{
1409 Status: "error",
1410 Data: json.RawMessage(`"test"`),
1411 ErrorType: ErrTimeout,
1412 Error: "timed out",
1413 Warnings: []string{"a"},
1414 },
1415 expectedErr: &Error{
1416 Type: ErrTimeout,
1417 Msg: "timed out",
1418 },
1419 expectedWarnings: []string{"a"},
1420 },
1421 }
1422
1423 tc := &testClient{
1424 T: t,
1425 ch: make(chan apiClientTest, 1),
1426 req: &http.Request{},
1427 }
1428 client := &apiClientImpl{
1429 client: tc,
1430 }
1431
1432 for i, test := range tests {
1433 t.Run(strconv.Itoa(i), func(t *testing.T) {
1434 tc.ch <- test
1435
1436 _, body, warnings, err := client.Do(context.Background(), tc.req)
1437
1438 if test.expectedWarnings != nil {
1439 if !reflect.DeepEqual(test.expectedWarnings, warnings) {
1440 t.Fatalf("mismatch in warnings expected=%v actual=%v", test.expectedWarnings, warnings)
1441 }
1442 } else {
1443 if warnings != nil {
1444 t.Fatalf("unexpected warnings: %v", warnings)
1445 }
1446 }
1447
1448 if test.expectedErr != nil {
1449 if err == nil {
1450 t.Fatal("expected error, but got none")
1451 }
1452
1453 if test.expectedErr.Error() != err.Error() {
1454 t.Fatalf("expected error:%v, but got:%v", test.expectedErr.Error(), err.Error())
1455 }
1456
1457 if test.expectedErr.Detail != "" {
1458 apiErr := &Error{}
1459 if errors.As(err, &apiErr) {
1460 if apiErr.Detail != test.expectedErr.Detail {
1461 t.Fatalf("expected error detail :%v, but got:%v", apiErr.Detail, test.expectedErr.Detail)
1462 }
1463 } else {
1464 t.Fatalf("expected v1.Error instance, but got:%T", err)
1465 }
1466 }
1467
1468 return
1469 }
1470
1471 if err != nil {
1472 t.Fatalf("unexpected error:%v", err)
1473 }
1474 if test.expectedBody != string(body) {
1475 t.Fatalf("expected body :%v, but got:%v", test.expectedBody, string(body))
1476 }
1477 })
1478 }
1479 }
1480
1481 func TestSamplesJSONSerialization(t *testing.T) {
1482 tests := []struct {
1483 point model.SamplePair
1484 expected string
1485 }{
1486 {
1487 point: model.SamplePair{0, 0},
1488 expected: `[0,"0"]`,
1489 },
1490 {
1491 point: model.SamplePair{1, 20},
1492 expected: `[0.001,"20"]`,
1493 },
1494 {
1495 point: model.SamplePair{10, 20},
1496 expected: `[0.010,"20"]`,
1497 },
1498 {
1499 point: model.SamplePair{100, 20},
1500 expected: `[0.100,"20"]`,
1501 },
1502 {
1503 point: model.SamplePair{1001, 20},
1504 expected: `[1.001,"20"]`,
1505 },
1506 {
1507 point: model.SamplePair{1010, 20},
1508 expected: `[1.010,"20"]`,
1509 },
1510 {
1511 point: model.SamplePair{1100, 20},
1512 expected: `[1.100,"20"]`,
1513 },
1514 {
1515 point: model.SamplePair{12345678123456555, 20},
1516 expected: `[12345678123456.555,"20"]`,
1517 },
1518 {
1519 point: model.SamplePair{-1, 20},
1520 expected: `[-0.001,"20"]`,
1521 },
1522 {
1523 point: model.SamplePair{0, model.SampleValue(math.NaN())},
1524 expected: `[0,"NaN"]`,
1525 },
1526 {
1527 point: model.SamplePair{0, model.SampleValue(math.Inf(1))},
1528 expected: `[0,"+Inf"]`,
1529 },
1530 {
1531 point: model.SamplePair{0, model.SampleValue(math.Inf(-1))},
1532 expected: `[0,"-Inf"]`,
1533 },
1534 {
1535 point: model.SamplePair{0, model.SampleValue(1.2345678e6)},
1536 expected: `[0,"1234567.8"]`,
1537 },
1538 {
1539 point: model.SamplePair{0, 1.2345678e-6},
1540 expected: `[0,"0.0000012345678"]`,
1541 },
1542 {
1543 point: model.SamplePair{0, 1.2345678e-67},
1544 expected: `[0,"1.2345678e-67"]`,
1545 },
1546 }
1547
1548 for _, test := range tests {
1549 t.Run(test.expected, func(t *testing.T) {
1550 b, err := json.Marshal(test.point)
1551 if err != nil {
1552 t.Fatal(err)
1553 }
1554 if string(b) != test.expected {
1555 t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expected, string(b))
1556 }
1557
1558 // To test Unmarshal we will Unmarshal then re-Marshal this way we
1559 // can do a string compare, otherwise Nan values don't show equivalence
1560 // properly.
1561 var sp model.SamplePair
1562 if err = json.Unmarshal(b, &sp); err != nil {
1563 t.Fatal(err)
1564 }
1565
1566 b, err = json.Marshal(sp)
1567 if err != nil {
1568 t.Fatal(err)
1569 }
1570 if string(b) != test.expected {
1571 t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expected, string(b))
1572 }
1573 })
1574 }
1575 }
1576
1577 func TestHistogramJSONSerialization(t *testing.T) {
1578 tests := []struct {
1579 name string
1580 point model.SampleHistogramPair
1581 expected string
1582 }{
1583 {
1584 name: "empty histogram",
1585 point: model.SampleHistogramPair{
1586 Timestamp: 0,
1587 Histogram: &model.SampleHistogram{},
1588 },
1589 expected: `[0,{"count":"0","sum":"0"}]`,
1590 },
1591 {
1592 name: "histogram with NaN/Inf and no buckets",
1593 point: model.SampleHistogramPair{
1594 Timestamp: 0,
1595 Histogram: &model.SampleHistogram{
1596 Count: model.FloatString(math.NaN()),
1597 Sum: model.FloatString(math.Inf(1)),
1598 },
1599 },
1600 expected: `[0,{"count":"NaN","sum":"+Inf"}]`,
1601 },
1602 {
1603 name: "six-bucket histogram",
1604 point: model.SampleHistogramPair{
1605 Timestamp: 1,
1606 Histogram: &model.SampleHistogram{
1607 Count: 13.5,
1608 Sum: 3897.1,
1609 Buckets: model.HistogramBuckets{
1610 {
1611 Boundaries: 1,
1612 Lower: -4870.992343051145,
1613 Upper: -4466.7196729968955,
1614 Count: 1,
1615 },
1616 {
1617 Boundaries: 1,
1618 Lower: -861.0779292198035,
1619 Upper: -789.6119426088657,
1620 Count: 2,
1621 },
1622 {
1623 Boundaries: 1,
1624 Lower: -558.3399591246119,
1625 Upper: -512,
1626 Count: 3,
1627 },
1628 {
1629 Boundaries: 0,
1630 Lower: 2048,
1631 Upper: 2233.3598364984477,
1632 Count: 1.5,
1633 },
1634 {
1635 Boundaries: 0,
1636 Lower: 2896.3093757400984,
1637 Upper: 3158.4477704354626,
1638 Count: 2.5,
1639 },
1640 {
1641 Boundaries: 0,
1642 Lower: 4466.7196729968955,
1643 Upper: 4870.992343051145,
1644 Count: 3.5,
1645 },
1646 },
1647 },
1648 },
1649 expected: `[0.001,{"count":"13.5","sum":"3897.1","buckets":[[1,"-4870.992343051145","-4466.7196729968955","1"],[1,"-861.0779292198035","-789.6119426088657","2"],[1,"-558.3399591246119","-512","3"],[0,"2048","2233.3598364984477","1.5"],[0,"2896.3093757400984","3158.4477704354626","2.5"],[0,"4466.7196729968955","4870.992343051145","3.5"]]}]`,
1650 },
1651 }
1652
1653 for _, test := range tests {
1654 t.Run(test.name, func(t *testing.T) {
1655 b, err := json.Marshal(test.point)
1656 if err != nil {
1657 t.Fatal(err)
1658 }
1659 if string(b) != test.expected {
1660 t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expected, string(b))
1661 }
1662
1663 // To test Unmarshal we will Unmarshal then re-Marshal. This way we
1664 // can do a string compare, otherwise NaN values don't show equivalence
1665 // properly.
1666 var sp model.SampleHistogramPair
1667 if err = json.Unmarshal(b, &sp); err != nil {
1668 t.Fatal(err)
1669 }
1670
1671 b, err = json.Marshal(sp)
1672 if err != nil {
1673 t.Fatal(err)
1674 }
1675 if string(b) != test.expected {
1676 t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expected, string(b))
1677 }
1678 })
1679 }
1680 }
1681
1682 func TestSampleStreamJSONSerialization(t *testing.T) {
1683 floats, histograms := generateData(1, 5)
1684
1685 tests := []struct {
1686 name string
1687 stream model.SampleStream
1688 expectedJSON string
1689 }{
1690 {
1691 "floats",
1692 *floats[0],
1693 `{"metric":{"__name__":"timeseries_0","foo":"bar"},"values":[[1677587259.055,"1"],[1677587244.055,"2"],[1677587229.055,"3"],[1677587214.055,"4"],[1677587199.055,"5"]]}`,
1694 },
1695 {
1696 "histograms",
1697 *histograms[0],
1698 `{"metric":{"__name__":"timeseries_0","foo":"bar"},"histograms":[[1677587259.055,{"count":"13.5","sum":"0.1","buckets":[[1,"-4870.992343051145","-4466.7196729968955","1"],[1,"-861.0779292198035","-789.6119426088657","2"],[1,"-558.3399591246119","-512","3"],[0,"2048","2233.3598364984477","1.5"],[0,"2896.3093757400984","3158.4477704354626","2.5"],[0,"4466.7196729968955","4870.992343051145","3.5"]]}],[1677587244.055,{"count":"27","sum":"0.2","buckets":[[1,"-4870.992343051145","-4466.7196729968955","2"],[1,"-861.0779292198035","-789.6119426088657","4"],[1,"-558.3399591246119","-512","6"],[0,"2048","2233.3598364984477","3"],[0,"2896.3093757400984","3158.4477704354626","5"],[0,"4466.7196729968955","4870.992343051145","7"]]}],[1677587229.055,{"count":"40.5","sum":"0.30000000000000004","buckets":[[1,"-4870.992343051145","-4466.7196729968955","3"],[1,"-861.0779292198035","-789.6119426088657","6"],[1,"-558.3399591246119","-512","9"],[0,"2048","2233.3598364984477","4.5"],[0,"2896.3093757400984","3158.4477704354626","7.5"],[0,"4466.7196729968955","4870.992343051145","10.5"]]}],[1677587214.055,{"count":"54","sum":"0.4","buckets":[[1,"-4870.992343051145","-4466.7196729968955","4"],[1,"-861.0779292198035","-789.6119426088657","8"],[1,"-558.3399591246119","-512","12"],[0,"2048","2233.3598364984477","6"],[0,"2896.3093757400984","3158.4477704354626","10"],[0,"4466.7196729968955","4870.992343051145","14"]]}],[1677587199.055,{"count":"67.5","sum":"0.5","buckets":[[1,"-4870.992343051145","-4466.7196729968955","5"],[1,"-861.0779292198035","-789.6119426088657","10"],[1,"-558.3399591246119","-512","15"],[0,"2048","2233.3598364984477","7.5"],[0,"2896.3093757400984","3158.4477704354626","12.5"],[0,"4466.7196729968955","4870.992343051145","17.5"]]}]]}`,
1699 },
1700 {
1701 "both",
1702 model.SampleStream{
1703 Metric: floats[0].Metric,
1704 Values: floats[0].Values,
1705 Histograms: histograms[0].Histograms,
1706 },
1707 `{"metric":{"__name__":"timeseries_0","foo":"bar"},"values":[[1677587259.055,"1"],[1677587244.055,"2"],[1677587229.055,"3"],[1677587214.055,"4"],[1677587199.055,"5"]],"histograms":[[1677587259.055,{"count":"13.5","sum":"0.1","buckets":[[1,"-4870.992343051145","-4466.7196729968955","1"],[1,"-861.0779292198035","-789.6119426088657","2"],[1,"-558.3399591246119","-512","3"],[0,"2048","2233.3598364984477","1.5"],[0,"2896.3093757400984","3158.4477704354626","2.5"],[0,"4466.7196729968955","4870.992343051145","3.5"]]}],[1677587244.055,{"count":"27","sum":"0.2","buckets":[[1,"-4870.992343051145","-4466.7196729968955","2"],[1,"-861.0779292198035","-789.6119426088657","4"],[1,"-558.3399591246119","-512","6"],[0,"2048","2233.3598364984477","3"],[0,"2896.3093757400984","3158.4477704354626","5"],[0,"4466.7196729968955","4870.992343051145","7"]]}],[1677587229.055,{"count":"40.5","sum":"0.30000000000000004","buckets":[[1,"-4870.992343051145","-4466.7196729968955","3"],[1,"-861.0779292198035","-789.6119426088657","6"],[1,"-558.3399591246119","-512","9"],[0,"2048","2233.3598364984477","4.5"],[0,"2896.3093757400984","3158.4477704354626","7.5"],[0,"4466.7196729968955","4870.992343051145","10.5"]]}],[1677587214.055,{"count":"54","sum":"0.4","buckets":[[1,"-4870.992343051145","-4466.7196729968955","4"],[1,"-861.0779292198035","-789.6119426088657","8"],[1,"-558.3399591246119","-512","12"],[0,"2048","2233.3598364984477","6"],[0,"2896.3093757400984","3158.4477704354626","10"],[0,"4466.7196729968955","4870.992343051145","14"]]}],[1677587199.055,{"count":"67.5","sum":"0.5","buckets":[[1,"-4870.992343051145","-4466.7196729968955","5"],[1,"-861.0779292198035","-789.6119426088657","10"],[1,"-558.3399591246119","-512","15"],[0,"2048","2233.3598364984477","7.5"],[0,"2896.3093757400984","3158.4477704354626","12.5"],[0,"4466.7196729968955","4870.992343051145","17.5"]]}]]}`,
1708 },
1709 }
1710
1711 for _, test := range tests {
1712 t.Run(test.name, func(t *testing.T) {
1713 b, err := json.Marshal(test.stream)
1714 if err != nil {
1715 t.Fatal(err)
1716 }
1717 if string(b) != test.expectedJSON {
1718 t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expectedJSON, string(b))
1719 }
1720
1721 var stream model.SampleStream
1722 if err = json.Unmarshal(b, &stream); err != nil {
1723 t.Fatal(err)
1724 }
1725
1726 if !reflect.DeepEqual(test.stream, stream) {
1727 t.Fatalf("Mismatch after unmarshal expected=%#v actual=%#v", test.stream, stream)
1728 }
1729 })
1730 }
1731 }
1732
1733 type httpTestClient struct {
1734 client http.Client
1735 }
1736
1737 func (c *httpTestClient) URL(ep string, args map[string]string) *url.URL {
1738 return nil
1739 }
1740
1741 func (c *httpTestClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
1742 resp, err := c.client.Do(req)
1743 if err != nil {
1744 return nil, nil, err
1745 }
1746
1747 var body []byte
1748 done := make(chan struct{})
1749 go func() {
1750 body, err = io.ReadAll(resp.Body)
1751 close(done)
1752 }()
1753
1754 select {
1755 case <-ctx.Done():
1756 <-done
1757 err = resp.Body.Close()
1758 if err == nil {
1759 err = ctx.Err()
1760 }
1761 case <-done:
1762 }
1763
1764 return resp, body, err
1765 }
1766
1767 func TestDoGetFallback(t *testing.T) {
1768 v := url.Values{"a": []string{"1", "2"}}
1769
1770 type testResponse struct {
1771 Values string
1772 Method string
1773 }
1774
1775 // Start a local HTTP server.
1776 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
1777 req.ParseForm()
1778 testResp, _ := json.Marshal(&testResponse{
1779 Values: req.Form.Encode(),
1780 Method: req.Method,
1781 })
1782
1783 apiResp := &apiResponse{
1784 Data: testResp,
1785 }
1786
1787 body, _ := json.Marshal(apiResp)
1788
1789 if req.Method == http.MethodPost {
1790 if req.URL.Path == "/blockPost405" {
1791 http.Error(w, string(body), http.StatusMethodNotAllowed)
1792 return
1793 }
1794 }
1795
1796 if req.Method == http.MethodPost {
1797 if req.URL.Path == "/blockPost501" {
1798 http.Error(w, string(body), http.StatusNotImplemented)
1799 return
1800 }
1801 }
1802
1803 w.Write(body)
1804 }))
1805 // Close the server when test finishes.
1806 defer server.Close()
1807
1808 u, err := url.Parse(server.URL)
1809 if err != nil {
1810 t.Fatal(err)
1811 }
1812 client := &httpTestClient{client: *(server.Client())}
1813 api := &apiClientImpl{
1814 client: client,
1815 }
1816
1817 // Do a post, and ensure that the post succeeds.
1818 _, b, _, err := api.DoGetFallback(context.TODO(), u, v)
1819 if err != nil {
1820 t.Fatalf("Error doing local request: %v", err)
1821 }
1822 resp := &testResponse{}
1823 if err := json.Unmarshal(b, resp); err != nil {
1824 t.Fatal(err)
1825 }
1826 if resp.Method != http.MethodPost {
1827 t.Fatalf("Mismatch method")
1828 }
1829 if resp.Values != v.Encode() {
1830 t.Fatalf("Mismatch in values")
1831 }
1832
1833 // Do a fallback to a get on 405.
1834 u.Path = "/blockPost405"
1835 _, b, _, err = api.DoGetFallback(context.TODO(), u, v)
1836 if err != nil {
1837 t.Fatalf("Error doing local request: %v", err)
1838 }
1839 if err := json.Unmarshal(b, resp); err != nil {
1840 t.Fatal(err)
1841 }
1842 if resp.Method != http.MethodGet {
1843 t.Fatalf("Mismatch method")
1844 }
1845 if resp.Values != v.Encode() {
1846 t.Fatalf("Mismatch in values")
1847 }
1848
1849 // Do a fallback to a get on 501.
1850 u.Path = "/blockPost501"
1851 _, b, _, err = api.DoGetFallback(context.TODO(), u, v)
1852 if err != nil {
1853 t.Fatalf("Error doing local request: %v", err)
1854 }
1855 if err := json.Unmarshal(b, resp); err != nil {
1856 t.Fatal(err)
1857 }
1858 if resp.Method != http.MethodGet {
1859 t.Fatalf("Mismatch method")
1860 }
1861 if resp.Values != v.Encode() {
1862 t.Fatalf("Mismatch in values")
1863 }
1864 }