summaryrefslogtreecommitdiff
path: root/xenstoreclient/xenstore_test.go
blob: 6335e6b83c71e4af8ec96ff611b653a10467aff5 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package xenstoreclient

import (
	"bytes"
	"fmt"
	"io"
	"testing"
	"time"
)

type mockFile struct {
	r         io.Reader
	w         io.Writer
	watchKeys map[string]struct{}
	t         *testing.T
}

func NewMockFile(t *testing.T) io.ReadWriteCloser {
	var b bytes.Buffer

	return &mockFile{
		r:         &b,
		w:         &b,
		t:         t,
		watchKeys: make(map[string]struct{}),
	}
}

func (f *mockFile) Read(p []byte) (n int, err error) {
	for i := 0; i < 1; i++ {
		n, err = f.r.Read(p)
		if err == io.EOF {
			fmt.Printf("Read sleep %#v second\n", i)
			time.Sleep(1 * time.Second)
		} else {
			fmt.Printf("Read=%#v err %#v\n", n, err)
			return
		}
	}
	return 0, io.EOF
}

func (f *mockFile) Write(b []byte) (n int, err error) {
	n, err = f.w.Write(b)
	fmt.Printf("Write=%#v err %#v\n", n, err)
	return
}

func (f *mockFile) Close() error {
	f.t.Logf("Close()")
	return nil
}

func TestXenStore(t *testing.T) {
	xs, err := newXenstore(0, NewMockFile(t))
	if err != nil {
		t.Errorf("newXenstore error: %#v\n", err)
	}
	defer xs.Close()

	if err := xs.Write("foo", "bar"); err != nil {
		t.Errorf("xs.Write error: %#v\n", err)
	}

	if _, err := xs.Read("foo"); err != nil {
		t.Errorf("xs.Read error: %#v\n", err)
	}
}

func TestXenStoreWatch2(t *testing.T) {
	xs, err := newXenstore(0, NewMockFile(t))
	if err != nil {
		t.Errorf("newXenstore error: %#v\n", err)
	}
	defer xs.Close()

	go func() {
		time.Sleep(5 * time.Second)
		if err := xs.StopWatch(); err != nil {
			t.Errorf("xs.StopWatch error: %#v\n", err)
		}
	}()

	go func() {
		for i := 0; i < 5; i++ {
			xs.Write("foo", "bar")
			time.Sleep(1 * time.Second)
		}
	}()

	err = xs.Watch("foo", "test")
	if err != nil {
		t.Errorf("xs.Watch(\"foo\") error: %#v\n", err)
	}

	time.Sleep(6 * time.Second)
}