-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemkeep_test.go
78 lines (65 loc) · 1.6 KB
/
memkeep_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package jsonmemkeep
import (
"encoding/json"
"github.com/stretchr/testify/assert"
"io/ioutil"
"os"
"sync"
"testing"
"time"
)
const TestFileName = "test.json"
type TestStruct struct {
Count int `json:"count"`
}
func TestWatcher(t *testing.T) {
resetFile(TestFileName)
assrt := assert.New(t)
listener := NewListener(TestFileName, new(TestStruct))
defer listener.Close()
listener.Run()
testStruct := listener.Fetch().(*TestStruct)
assrt.Equal(0, testStruct.Count)
incrementCounter(TestFileName)
time.Sleep(1 * time.Second)
testStruct = listener.Fetch().(*TestStruct)
assrt.Equal(1, testStruct.Count)
// CONCURRENT READ-WRITE TEST
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
for i := 0; i < 1000000; i++ {
testStruct = listener.Fetch().(*TestStruct)
}
wg.Done()
}()
wg.Add(1)
go func() {
for i := 0; i < 1000; i++ {
incrementCounter(TestFileName)
}
wg.Done()
}()
wg.Wait()
assrt.Equal(1001, testStruct.Count)
}
func incrementCounter(fileName string) {
var testStruct = new(TestStruct)
jsonFile, _ := os.OpenFile(fileName, os.O_RDWR, 0644)
defer jsonFile.Close()
bytes, _ := ioutil.ReadAll(jsonFile)
json.Unmarshal(bytes, &testStruct)
testStruct.Count++
newJson, _ := json.Marshal(testStruct)
result := string(newJson) + " "
jsonFile.WriteAt([]byte(result), 0)
}
func resetFile(fileName string) {
var testStruct = new(TestStruct)
jsonFile, _ := os.OpenFile(fileName, os.O_RDWR, 0644)
defer jsonFile.Close()
testStruct.Count = 0
newJson, _ := json.Marshal(testStruct)
result := string(newJson) + " "
jsonFile.WriteAt([]byte(result), 0)
}