go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/data/embeddedkvs/kvs_test.go (about)

     1  // Copyright 2020 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     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  package embeddedkvs
    16  
    17  import (
    18  	"context"
    19  	"path/filepath"
    20  	"sort"
    21  	"sync"
    22  	"testing"
    23  
    24  	. "github.com/smartystreets/goconvey/convey"
    25  )
    26  
    27  func TestCache(t *testing.T) {
    28  	t.Parallel()
    29  
    30  	Convey("basic", t, func() {
    31  		path := filepath.Join(t.TempDir(), "db")
    32  		k, err := New(context.Background(), path)
    33  		So(err, ShouldBeNil)
    34  
    35  		So(k.Set("key1", []byte("value1")), ShouldBeNil)
    36  
    37  		So(k.SetMulti(func(set func(key string, value []byte) error) error {
    38  			So(set("key2", []byte("value2")), ShouldBeNil)
    39  			So(set("key3", []byte("value3")), ShouldBeNil)
    40  			return nil
    41  		}), ShouldBeNil)
    42  
    43  		var mu sync.Mutex
    44  		var keys []string
    45  		var values []string
    46  
    47  		So(k.GetMulti(context.Background(), []string{"key1", "key2", "key4"}, func(key string, value []byte) error {
    48  			mu.Lock()
    49  			keys = append(keys, key)
    50  			values = append(values, string(value))
    51  			mu.Unlock()
    52  			return nil
    53  		}), ShouldBeNil)
    54  
    55  		sort.Strings(keys)
    56  		sort.Strings(values)
    57  
    58  		So(keys, ShouldResemble, []string{"key1", "key2"})
    59  		So(values, ShouldResemble, []string{"value1", "value2"})
    60  
    61  		keys = nil
    62  		values = nil
    63  		k.ForEach(func(key string, value []byte) error {
    64  			keys = append(keys, key)
    65  			values = append(values, string(value))
    66  			return nil
    67  		})
    68  
    69  		So(keys, ShouldResemble, []string{"key1", "key2", "key3"})
    70  		So(values, ShouldResemble, []string{"value1", "value2", "value3"})
    71  
    72  		So(k.Close(), ShouldBeNil)
    73  	})
    74  }