...
1 package reaper
2
3 import (
4 "context"
5 "testing"
6
7 "github.com/cybertec-postgresql/pgwatch/v3/internal/metrics"
8 "github.com/cybertec-postgresql/pgwatch/v3/internal/sources"
9 "github.com/stretchr/testify/assert"
10 )
11
12 var (
13 initialMetricDefs = metrics.MetricDefs{
14 "metric1": metrics.Metric{Description: "metric1"},
15 }
16 initialPresetDefs = metrics.PresetDefs{
17 "preset1": metrics.Preset{Description: "preset1", Metrics: map[string]float64{"metric1": 1.0}},
18 }
19
20 newMetricDefs = metrics.MetricDefs{
21 "metric2": metrics.Metric{Description: "metric2"},
22 }
23 newPresetDefs = metrics.PresetDefs{
24 "preset2": metrics.Preset{Description: "preset2", Metrics: map[string]float64{"metric2": 2.0}},
25 }
26 )
27
28 func TestReaper_FetchStatsDirectlyFromOS(t *testing.T) {
29 a := assert.New(t)
30 r := &Reaper{}
31 md := &sources.SourceConn{}
32 for _, m := range directlyFetchableOSMetrics {
33 a.True(IsDirectlyFetchableMetric(m), "Expected %s to be directly fetchable", m)
34 a.NotPanics(func() {
35 _, _ = r.FetchStatsDirectlyFromOS(context.Background(), md, m)
36 })
37 }
38 }
39
40 func TestConcurrentMetricDefs_Assign(t *testing.T) {
41 concurrentDefs := NewConcurrentMetricDefs()
42 concurrentDefs.Assign(&metrics.Metrics{
43 MetricDefs: initialMetricDefs,
44 PresetDefs: initialPresetDefs,
45 })
46
47 concurrentDefs.Assign(&metrics.Metrics{
48 MetricDefs: newMetricDefs,
49 PresetDefs: newPresetDefs,
50 })
51
52 assert.Equal(t, newMetricDefs, concurrentDefs.MetricDefs, "MetricDefs should be updated")
53 assert.Equal(t, newPresetDefs, concurrentDefs.PresetDefs, "PresetDefs should be updated")
54 }
55
56 func TestConcurrentMetricDefs_RandomAccess(t *testing.T) {
57 a := assert.New(t)
58
59 concurrentDefs := NewConcurrentMetricDefs()
60 concurrentDefs.Assign(&metrics.Metrics{
61 MetricDefs: initialMetricDefs,
62 PresetDefs: initialPresetDefs,
63 })
64
65 go a.NotPanics(func() {
66 for range 1000 {
67 _, ok1 := concurrentDefs.GetMetricDef("metric1")
68 _, ok2 := concurrentDefs.GetMetricDef("metric2")
69 a.True(ok1 || ok2, "Expected metric1 or metric3 to exist at any time")
70 _, ok1 = concurrentDefs.GetPresetDef("preset1")
71 _, ok2 = concurrentDefs.GetPresetDef("preset2")
72 a.True(ok1 || ok2, "Expected preset1 or preset2 to exist at any time")
73 m1 := concurrentDefs.GetPresetMetrics("preset1")
74 m2 := concurrentDefs.GetPresetMetrics("preset2")
75 a.True(m1 != nil || m2 != nil, "Expected preset1 or preset2 metrics to be non-empty")
76 }
77 })
78
79 go a.NotPanics(func() {
80 for range 1000 {
81 concurrentDefs.Assign(&metrics.Metrics{
82 MetricDefs: newMetricDefs,
83 PresetDefs: newPresetDefs,
84 })
85 }
86 })
87 }
88