ccache/bucket_test.go
Karl Seguin 890bb18dbf The cache can now do reference counting so that the LRU algorithm is aware of
long-lived objects and won't clean them up. Oftentimes, the value returned
from a cache hit is short-lived. As a silly example:

	func GetUser(http.responseWrite) {
		user := cache.Get("user:1")
		response.Write(serialize(user))
	}

It's fine if the cache's GC cleans up "user:1" while the user variable has a reference to the
object..the cache's reference is removed and the real GC will clean it up
at some point after the user variable falls out of scope.

However, what if user is long-lived? Possibly stored as a reference to another
cached object? Normally (without this commit) the next time you call
cache.Get("user:1"), you'll get a miss and will need to refetch the object; even
though the original user object is still somewhere in memory - you just lost
your reference to it from the cache.

By enabling the Track() configuration flag, and calling TrackingGet() (instead
of Get), the cache will track that the object is in-use and won't GC it (even
if there's great memory pressure (what's the point? something else is holding on
to it anyways). Calling item.Release() will decrement the number of references.
When the count is 0, the item can be pruned from the cache.

The returned value is a TrackedItem which exposes:

- Value() interface{} (to get the actual cached value)
- Release() to release the item back in the cache
2014-02-28 20:10:42 +08:00

64 lines
1.4 KiB
Go

package ccache
import (
"github.com/karlseguin/gspec"
"testing"
"time"
)
func TestGetMissFromBucket(t *testing.T) {
bucket := testBucket()
gspec.New(t).Expect(bucket.get("invalid")).ToBeNil()
}
func TestGetHitFromBucket(t *testing.T) {
bucket := testBucket()
item := bucket.get("power")
assertValue(t, item, "9000")
}
func TestDeleteItemFromBucket(t *testing.T) {
bucket := testBucket()
bucket.delete("power")
gspec.New(t).Expect(bucket.get("power")).ToBeNil()
}
func TestSetsANewBucketItem(t *testing.T) {
spec := gspec.New(t)
bucket := testBucket()
item, new := bucket.set("spice", TestValue("flow"), time.Minute)
assertValue(t, item, "flow")
item = bucket.get("spice")
assertValue(t, item, "flow")
spec.Expect(new).ToEqual(true)
}
func TestSetsAnExistingItem(t *testing.T) {
spec := gspec.New(t)
bucket := testBucket()
item, new := bucket.set("power", TestValue("9002"), time.Minute)
assertValue(t, item, "9002")
item = bucket.get("power")
assertValue(t, item, "9002")
spec.Expect(new).ToEqual(false)
}
func testBucket() *Bucket {
b := &Bucket{lookup: make(map[string]*Item)}
b.lookup["power"] = &Item{
key: "power",
value: TestValue("9000"),
}
return b
}
func assertValue(t *testing.T, item *Item, expected string) {
value := item.value.(TestValue)
gspec.New(t).Expect(value).ToEqual(TestValue(expected))
}
type TestValue string
func (v TestValue) Expires() time.Time {
return time.Now()
}