|
| 1 | +package mode |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/prometheus/common/model" |
| 7 | +) |
| 8 | + |
| 9 | +func TestExpandAlias(t *testing.T) { |
| 10 | + tests := []struct { |
| 11 | + name string |
| 12 | + alias string |
| 13 | + labels model.Metric |
| 14 | + value float64 |
| 15 | + expected string |
| 16 | + }{ |
| 17 | + { |
| 18 | + name: "simple template with label", |
| 19 | + alias: "Hostname: {{.hostname}}", |
| 20 | + labels: model.Metric{"hostname": "server01"}, |
| 21 | + value: 42.0, |
| 22 | + expected: "Hostname: server01", |
| 23 | + }, |
| 24 | + { |
| 25 | + name: "template with multiple labels", |
| 26 | + alias: "Host: {{.hostname}} Job: {{.job}}", |
| 27 | + labels: model.Metric{"hostname": "server01", "job": "prometheus"}, |
| 28 | + value: 1.0, |
| 29 | + expected: "Host: server01 Job: prometheus", |
| 30 | + }, |
| 31 | + { |
| 32 | + name: "template with xvalue", |
| 33 | + alias: "Value: {{.xvalue}}", |
| 34 | + labels: model.Metric{"hostname": "server01"}, |
| 35 | + value: 123.45, |
| 36 | + expected: "Value: 123.45", |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "template with if-else condition", |
| 40 | + alias: "Status: {{if eq .xvalue \"1\"}}UP{{else}}DOWN{{end}}", |
| 41 | + labels: model.Metric{"hostname": "server01"}, |
| 42 | + value: 1.0, |
| 43 | + expected: "Status: UP", |
| 44 | + }, |
| 45 | + { |
| 46 | + name: "template with if-else condition false", |
| 47 | + alias: "Status: {{if eq .xvalue \"1\"}}UP{{else}}DOWN{{end}}", |
| 48 | + labels: model.Metric{"hostname": "server01"}, |
| 49 | + value: 0.0, |
| 50 | + expected: "Status: DOWN", |
| 51 | + }, |
| 52 | + { |
| 53 | + name: "invalid template fallback", |
| 54 | + alias: "{{invalid template", |
| 55 | + labels: model.Metric{"hostname": "server01"}, |
| 56 | + value: 42.0, |
| 57 | + expected: "{{invalid template", |
| 58 | + }, |
| 59 | + { |
| 60 | + name: "empty alias", |
| 61 | + alias: "", |
| 62 | + labels: model.Metric{"hostname": "server01"}, |
| 63 | + value: 42.0, |
| 64 | + expected: "", |
| 65 | + }, |
| 66 | + } |
| 67 | + |
| 68 | + for _, tt := range tests { |
| 69 | + t.Run(tt.name, func(t *testing.T) { |
| 70 | + result := expandAlias(tt.alias, tt.labels, tt.value) |
| 71 | + if result != tt.expected { |
| 72 | + t.Errorf("expandAlias(%q, ...) = %q, want %q", tt.alias, result, tt.expected) |
| 73 | + } |
| 74 | + }) |
| 75 | + } |
| 76 | +} |
| 77 | + |
0 commit comments