prometheus
82 строки · 2.0 Кб
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
14package promql
15
16import (
17"errors"
18"testing"
19
20"github.com/go-kit/log"
21"github.com/stretchr/testify/require"
22
23"github.com/prometheus/prometheus/promql/parser"
24"github.com/prometheus/prometheus/util/annotations"
25)
26
27func TestRecoverEvaluatorRuntime(t *testing.T) {
28var output []interface{}
29logger := log.Logger(log.LoggerFunc(func(keyvals ...interface{}) error {
30output = append(output, keyvals...)
31return nil
32}))
33ev := &evaluator{logger: logger}
34
35expr, _ := parser.ParseExpr("sum(up)")
36
37var err error
38
39defer func() {
40require.EqualError(t, err, "unexpected error: runtime error: index out of range [123] with length 0")
41require.Contains(t, output, "sum(up)")
42}()
43defer ev.recover(expr, nil, &err)
44
45// Cause a runtime panic.
46var a []int
47a[123] = 1
48}
49
50func TestRecoverEvaluatorError(t *testing.T) {
51ev := &evaluator{logger: log.NewNopLogger()}
52var err error
53
54e := errors.New("custom error")
55
56defer func() {
57require.EqualError(t, err, e.Error())
58}()
59defer ev.recover(nil, nil, &err)
60
61panic(e)
62}
63
64func TestRecoverEvaluatorErrorWithWarnings(t *testing.T) {
65ev := &evaluator{logger: log.NewNopLogger()}
66var err error
67var ws annotations.Annotations
68
69warnings := annotations.New().Add(errors.New("custom warning"))
70e := errWithWarnings{
71err: errors.New("custom error"),
72warnings: warnings,
73}
74
75defer func() {
76require.EqualError(t, err, e.Error())
77require.Equal(t, warnings, ws, "wrong warning message")
78}()
79defer ev.recover(nil, &ws, &err)
80
81panic(e)
82}
83