go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/data/caching/cache/lru_test.go (about) 1 // Copyright 2019 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 cache 16 17 import ( 18 "crypto" 19 "math" 20 "reflect" 21 "testing" 22 "time" 23 ) 24 25 func TestEntryJSON(t *testing.T) { 26 for _, e := range []entry{ 27 { 28 key: "da39a3ee5e6b4b0d3255bfef95601890afd80709", 29 value: 0, 30 lastAccess: time.Now().Unix(), 31 }, 32 { 33 key: "46c5964fc9911cf02d6353d04ddff98aebb56ced", 34 value: math.MaxInt32 + 1, 35 lastAccess: time.Now().Unix(), 36 }, 37 } { 38 got, err := e.MarshalJSON() 39 if err != nil { 40 t.Errorf("entry.MarshalJSON() = _, %v, want nil", err) 41 } 42 43 var unmarshal entry 44 if err := unmarshal.UnmarshalJSON(got); err != nil { 45 t.Errorf("entry.UnmarshalJSON() = %v; want nil", err) 46 } 47 48 if !reflect.DeepEqual(unmarshal, e) { 49 t.Errorf("%#v != UnMarshalJSON(%#v.MarshalJSON())", unmarshal, e) 50 } 51 } 52 } 53 54 func TestEntryUnmarshal(t *testing.T) { 55 for _, data := range []string{ 56 `["key", [1, 1]]`, 57 `["key", [1.0, 1.0]]`, 58 } { 59 var e entry 60 if err := e.UnmarshalJSON([]byte(data)); err != nil { 61 t.Fatalf("failed to unmarshal `%s`: %v", data, err) 62 } 63 64 if e.key != "key" { 65 t.Errorf("got %s for key, expected `key`", e.key) 66 } 67 if e.value != 1 { 68 t.Errorf("got %d for value, expected 1.0", e.value) 69 } 70 if e.lastAccess != 1 { 71 t.Errorf("got %d for lastAccess, expected 1.0", e.lastAccess) 72 } 73 } 74 } 75 76 func TestLRU(t *testing.T) { 77 t.Parallel() 78 79 h := crypto.SHA1 80 l := makeLRUDict(h) 81 82 empty := HashBytes(h, nil) 83 if got, want := l.touch(empty), false; got != want { 84 t.Errorf("l.touch(...)=%v; want %v", got, want) 85 } 86 87 l.pushFront(empty, 0) 88 89 if got, want := l.touch(empty), true; got != want { 90 t.Errorf("l.touch(...)=%v; want %v", got, want) 91 } 92 }