Debian Codegraph @

launcher/internal/healthmonitoring/nodeproblemdetector/systemstats_config_test.go

raw
1 package nodeproblemdetector
2
3 import (
4 "bytes"
5 "encoding/json"
6 "io"
7 "os"
8 "path"
9 "testing"
10 "time"
11
12 "github.com/google/go-cmp/cmp"
13 )
14
15 func TestEnableHealthMonitoringConfig(t *testing.T) {
16 tmpDir := t.TempDir()
17 systemStatsFilePath = path.Join(tmpDir, "system-stats-monitor.json")
18
19 wantBytes, err := json.Marshal(allConfig)
20 if err != nil {
21 t.Fatalf("Error marshaling expected config: %v", err)
22 }
23
24 EnableAllConfig()
25
26 file, err := os.OpenFile(systemStatsFilePath, os.O_RDONLY, 0)
27 if err != nil {
28 t.Fatalf("failed to open file %s: %v", systemStatsFilePath, err)
29 }
30
31 gotBytes, err := io.ReadAll(file)
32 if err != nil {
33 t.Fatalf("failed to read from file %s: %v", systemStatsFilePath, err)
34 }
35
36 if !bytes.Equal(gotBytes, wantBytes) {
37 t.Errorf("WriteFile() did not write expected contents, got %s, want %s", gotBytes, wantBytes)
38 }
39 }
40
41 func TestEnableMemoryBytesUsed(t *testing.T) {
42 got := NewSystemStatsConfig()
43 got.EnableMemoryBytesUsed()
44
45 want := SystemStatsConfig{
46 Memory: &statsConfig{
47 MetricsConfigs: map[string]metricConfig{
48 "memory/bytes_used": {DisplayName: "memory/bytes_used"},
49 },
50 },
51 InvokeInterval: defaultInvokeIntervalString,
52 }
53 if !cmp.Equal(got, want) {
54 t.Errorf("EnableMemoryBytesUsed() failed, got: %v, want: %v", got, want)
55 }
56 }
57
58 func TestWithInvokeInterval(t *testing.T) {
59 got := SystemStatsConfig{}
60 got.WithInvokeInterval(2 * time.Second)
61
62 want := SystemStatsConfig{InvokeInterval: (2 * time.Second).String()}
63 if !cmp.Equal(got, want) {
64 t.Errorf("WithInvokeInterval() failed, got: %v, want: %v", got, want)
65 }
66 }
67
68 func TestWriteFile(t *testing.T) {
69 tmpDir := t.TempDir()
70 tmpConfigFile := path.Join(tmpDir, "system-stats-monitor.json")
71
72 config := NewSystemStatsConfig()
73 config.EnableMemoryBytesUsed()
74 if err := config.WriteFile(tmpConfigFile); err != nil {
75 t.Fatalf("WriteFile() failed: %v", err)
76 }
77
78 file, err := os.OpenFile(tmpConfigFile, os.O_RDONLY, 0)
79 if err != nil {
80 t.Fatalf("failed to open file %s: %v", tmpConfigFile, err)
81 }
82
83 gotBytes, err := io.ReadAll(file)
84 if err != nil {
85 t.Fatalf("failed to read from file %s: %v", tmpConfigFile, err)
86 }
87
88 wantBytes := []byte(`{"memory":{"metricsConfigs":{"memory/bytes_used":{"displayName":"memory/bytes_used"}}},"invokeInterval":"1m0s"}`)
89 if !bytes.Equal(gotBytes, wantBytes) {
90 t.Errorf("WriteFile() did not write expected contents, got %s, want %s", gotBytes, wantBytes)
91 }
92 }