github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/libnetwork/datastore/mockstore_test.go (about) 1 package datastore 2 3 import ( 4 "errors" 5 6 store "github.com/Prakhar-Agarwal-byte/moby/libnetwork/internal/kvstore" 7 "github.com/Prakhar-Agarwal-byte/moby/libnetwork/types" 8 ) 9 10 // MockData exported 11 type MockData struct { 12 Data []byte 13 Index uint64 14 } 15 16 // MockStore exported 17 type MockStore struct { 18 db map[string]*MockData 19 } 20 21 // NewMockStore creates a Map backed Datastore that is useful for mocking 22 func NewMockStore() *MockStore { 23 return &MockStore{db: make(map[string]*MockData)} 24 } 25 26 // Get the value at "key", returns the last modified index 27 // to use in conjunction to CAS calls 28 func (s *MockStore) Get(key string) (*store.KVPair, error) { 29 mData := s.db[key] 30 if mData == nil { 31 return nil, nil 32 } 33 return &store.KVPair{Value: mData.Data, LastIndex: mData.Index}, nil 34 } 35 36 // Put a value at "key" 37 func (s *MockStore) Put(key string, value []byte) error { 38 mData := s.db[key] 39 if mData == nil { 40 mData = &MockData{value, 0} 41 } 42 mData.Index = mData.Index + 1 43 s.db[key] = mData 44 return nil 45 } 46 47 // Exists checks that the key exists inside the store 48 func (s *MockStore) Exists(key string) (bool, error) { 49 _, ok := s.db[key] 50 return ok, nil 51 } 52 53 // List gets a range of values at "directory" 54 func (s *MockStore) List(prefix string) ([]*store.KVPair, error) { 55 return nil, errors.New("not implemented") 56 } 57 58 // AtomicPut put a value at "key" if the key has not been 59 // modified in the meantime, throws an error if this is the case 60 func (s *MockStore) AtomicPut(key string, newValue []byte, previous *store.KVPair) (*store.KVPair, error) { 61 mData := s.db[key] 62 63 if previous == nil { 64 if mData != nil { 65 return nil, types.InvalidParameterErrorf("atomic put failed because key exists") 66 } // Else OK. 67 } else { 68 if mData == nil { 69 return nil, types.InvalidParameterErrorf("atomic put failed because key exists") 70 } 71 if mData != nil && mData.Index != previous.LastIndex { 72 return nil, types.InvalidParameterErrorf("atomic put failed due to mismatched Index") 73 } // Else OK. 74 } 75 if err := s.Put(key, newValue); err != nil { 76 return nil, err 77 } 78 return &store.KVPair{Key: key, Value: newValue, LastIndex: s.db[key].Index}, nil 79 } 80 81 // AtomicDelete deletes a value at "key" if the key has not 82 // been modified in the meantime, throws an error if this is the case 83 func (s *MockStore) AtomicDelete(key string, previous *store.KVPair) error { 84 mData := s.db[key] 85 if mData != nil && mData.Index != previous.LastIndex { 86 return types.InvalidParameterErrorf("atomic delete failed due to mismatched Index") 87 } 88 delete(s.db, key) 89 return nil 90 } 91 92 // Close closes the client connection 93 func (s *MockStore) Close() { 94 }