github.com/maypok86/otter@v1.2.1/entry_test.go (about) 1 // Copyright (c) 2024 Alexey Mayshev. All rights reserved. 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 otter 16 17 import ( 18 "testing" 19 "time" 20 ) 21 22 func TestEntry(t *testing.T) { 23 k := 2 24 v := 3 25 exp := int64(0) 26 c := uint32(5) 27 e := Entry[int, int]{ 28 key: k, 29 value: v, 30 expiration: exp, 31 cost: c, 32 } 33 34 if e.Key() != k { 35 t.Fatalf("not valid key. want %d, got %d", k, e.Key()) 36 } 37 if e.Value() != v { 38 t.Fatalf("not valid value. want %d, got %d", v, e.Value()) 39 } 40 if e.Cost() != c { 41 t.Fatalf("not valid cost. want %d, got %d", c, e.Cost()) 42 } 43 if e.Expiration() != exp { 44 t.Fatalf("not valid expiration. want %d, got %d", exp, e.Expiration()) 45 } 46 if ttl := e.TTL(); ttl != -1 { 47 t.Fatalf("not valid ttl. want -1, got %d", ttl) 48 } 49 if e.HasExpired() { 50 t.Fatal("entry should not be expire") 51 } 52 53 newTTL := int64(10) 54 e.expiration = time.Now().Unix() + newTTL 55 if ttl := e.TTL(); ttl <= 0 || ttl > time.Duration(newTTL)*time.Second { 56 t.Fatalf("ttl should be in the range (0, %d] seconds, but got %d seconds", newTTL, ttl/time.Second) 57 } 58 if e.HasExpired() { 59 t.Fatal("entry should not be expire") 60 } 61 62 e.expiration -= 2 * newTTL 63 if ttl := e.TTL(); ttl != 0 { 64 t.Fatalf("ttl should be 0 seconds, but got %d seconds", ttl/time.Second) 65 } 66 if !e.HasExpired() { 67 t.Fatalf("entry should have expired") 68 } 69 }