package cache

import (
	"testing"
	"time"
)

func TestNewWithLimit(t *testing.T) {
	c := NewWithLimit(time.Minute, 2)
	c.Set("a", []byte("1"))
	c.Set("b", []byte("2"))
	c.Set("c", []byte("3")) // full: not added
	if _, ok := c.Get("c"); ok {
		t.Error("a third key was added to a cache of 2")
	}
	c.Set("a", []byte("4")) // an existing key is still updated
	if got, _ := c.Get("a"); string(got) != "4" {
		t.Errorf("a = %q, want 4", got)
	}

	expiring := NewWithLimit(time.Nanosecond, 1)
	expiring.Set("a", []byte("1"))
	time.Sleep(time.Millisecond)
	expiring.Set("b", []byte("2")) // the expired entry makes room
	// b expires at once too, so look at what is stored rather than Get it.
	expiring.mu.RLock()
	_, stored := expiring.entries["b"]
	expiring.mu.RUnlock()
	if !stored {
		t.Error("an expired entry didn't make room for a new key")
	}

	unlimited := New(time.Minute)
	for _, key := range []string{"a", "b", "c"} {
		unlimited.Set(key, nil)
	}
	if _, ok := unlimited.Get("c"); !ok {
		t.Error("New has a cap")
	}
}
