Debian Codegraph @

backend/mock/mock.go

raw
1 package mock
2
3 import (
4 "errors"
5 "path"
6 "strings"
7 "time"
8
9 "github.com/xordataexchange/crypt/backend"
10 )
11
12 var mockedStore map[string][]byte
13
14 type Client struct{}
15
16 func New(machines []string) (*Client, error) {
17 if mockedStore == nil {
18 mockedStore = make(map[string][]byte, 2)
19 }
20 return &Client{}, nil
21 }
22
23 func (c *Client) Get(key string) ([]byte, error) {
24 if v, ok := mockedStore[key]; ok {
25 return v, nil
26 }
27 err := errors.New("Could not find key: " + key)
28 return nil, err
29 }
30
31 func (c *Client) List(key string) (backend.KVPairs, error) {
32 var list backend.KVPairs
33 dir := path.Clean(key) + "/"
34 for k, v := range mockedStore {
35 if strings.HasPrefix(k, dir) {
36 list = append(list, &backend.KVPair{Key: k, Value: v})
37 }
38 }
39 return list, nil
40 }
41
42 func (c *Client) Set(key string, value []byte) error {
43 mockedStore[key] = value
44 return nil
45 }
46
47 func (c *Client) Watch(key string, stop chan bool) <-chan *backend.Response {
48 respChan := make(chan *backend.Response, 0)
49 go func() {
50 for {
51 b, err := c.Get(key)
52 if err != nil {
53 respChan <- &backend.Response{nil, err}
54 time.Sleep(time.Second * 5)
55 continue
56 }
57 respChan <- &backend.Response{b, nil}
58 }
59 }()
60 return respChan
61 }