master
go 133 lines 2.27 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package filepersister
4
5 import (
6 "context"
7 "errors"
8 "os"
9 "path"
10 "strings"
11 "testing"
12 "time"
13
14 "github.com/stretchr/testify/assert"
15 "github.com/stretchr/testify/require"
16 )
17
18 func TestNew(t *testing.T) {
19 tests := map[string]struct {
20 path string
21 wantErr bool
22 }{
23 "empty filepath": {
24 wantErr: true,
25 path: "",
26 },
27 "not empty filepath": {
28 wantErr: false,
29 path: "testdata/test.json",
30 },
31 }
32
33 for name, test := range tests {
34 t.Run(name, func(t *testing.T) {
35 p := New(test.path)
36 require.NotNil(t, p)
37 })
38 }
39 }
40
41 func TestPersister_Run(t *testing.T) {
42 tests := map[string]struct {
43 wantErr bool
44 wantFile string
45 }{
46 "no save because data bytes error": {
47 wantErr: true,
48 },
49 "successful save": {
50 wantErr: false,
51 wantFile: `
52 {
53 "module1": {
54 "name1:17896517344060997937": "ok"
55 },
56 "module2": {
57 "name2:14519194242031159283": "ok"
58 }
59 }
60 `,
61 },
62 }
63
64 for name, test := range tests {
65 t.Run(name, func(t *testing.T) {
66 dir, err := os.MkdirTemp(os.TempDir(), "netdata-go.d-test-filepersister-run")
67 require.NoError(t, err)
68 defer func() { assert.NoError(t, os.RemoveAll(dir)) }()
69
70 filename := path.Join(dir, "filestatus")
71
72 p := New(filename)
73
74 data := newMockData(test.wantFile)
75 data.wantError = test.wantErr
76
77 ctx, cancel := context.WithCancel(context.Background())
78 done := make(chan struct{})
79 go func() {
80 defer close(done)
81 p.Run(ctx, data)
82 }()
83
84 cancel()
85
86 timeout := time.Second * 5
87 tk := time.NewTimer(timeout)
88 defer tk.Stop()
89
90 select {
91 case <-done:
92 case <-tk.C:
93 t.Errorf("timed out after %s", timeout)
94 }
95
96 bs, err := os.ReadFile(filename)
97
98 if test.wantErr {
99 require.Error(t, err)
100 } else {
101 require.NoError(t, err)
102 assert.Equal(t, strings.TrimSpace(test.wantFile), strings.TrimSpace(string(bs)))
103 }
104 })
105 }
106 }
107
108 func newMockData(s string) *mockData {
109 m := &mockData{
110 data: s,
111 ch: make(chan struct{}, 1),
112 }
113 m.ch <- struct{}{}
114
115 return m
116 }
117
118 type mockData struct {
119 data string
120 ch chan struct{}
121 wantError bool
122 }
123
124 func (m *mockData) Bytes() ([]byte, error) {
125 if m.wantError {
126 return nil, errors.New("mockData.Bytes() mock error")
127 }
128 return []byte(m.data), nil
129 }
130
131 func (m *mockData) Updated() <-chan struct{} {
132 return m.ch
133 }