Merge "Add another parameter to the definition"
[multicloud/k8s.git] / src / k8splugin / db / testing.go
1 // +build unit
2
3 /*
4 Copyright 2018 Intel Corporation.
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
8     http://www.apache.org/licenses/LICENSE-2.0
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 package db
17
18 import (
19         "encoding/json"
20         pkgerrors "github.com/pkg/errors"
21 )
22
23 //Creating an embedded interface via anonymous variable
24 //This allows us to make mockDB satisfy the DatabaseConnection
25 //interface even if we are not implementing all the methods in it
26 type MockDB struct {
27         Store
28         Items map[string]map[string][]byte
29         Err   error
30 }
31
32 func (m *MockDB) Create(table, key, tag string, data interface{}) error {
33         return m.Err
34 }
35
36 // MockDB uses simple JSON and not BSON
37 func (m *MockDB) Unmarshal(inp []byte, out interface{}) error {
38         err := json.Unmarshal(inp, out)
39         if err != nil {
40                 return pkgerrors.Wrap(err, "Unmarshaling json")
41         }
42         return nil
43 }
44
45 func (m *MockDB) Read(table, key, tag string) ([]byte, error) {
46         if m.Err != nil {
47                 return nil, m.Err
48         }
49
50         for k, v := range m.Items {
51                 if k == key {
52                         return v[tag], nil
53                 }
54         }
55
56         return nil, m.Err
57 }
58
59 func (m *MockDB) Delete(table, key, tag string) error {
60         return m.Err
61 }
62
63 func (m *MockDB) ReadAll(table, tag string) (map[string][]byte, error) {
64         if m.Err != nil {
65                 return nil, m.Err
66         }
67
68         ret := make(map[string][]byte)
69
70         for k, v := range m.Items {
71                 for k1, v1 := range v {
72                         if k1 == tag {
73                                 ret[k] = v1
74                         }
75                 }
76         }
77
78         return ret, nil
79 }