package main

import (
	"sync"
	"testing"
)

func TestStaleRefill(t *testing.T) {
	d, c := staleRefill()
	if d != 2 || c != 1 {
		t.Fatal(d, c)
	}
}
func TestGuardedRefill(t *testing.T) {
	ok, d, hit, next := guardedRefill()
	if ok || d != 2 || hit || next != 2 {
		t.Fatal(ok, d, hit, next)
	}
}
func TestWriteBehindLoss(t *testing.T) {
	ack, d := lostWriteBehind()
	if ack != 2 || d != 1 {
		t.Fatal(ack, d)
	}
}
func TestGenerationRejectsOldFills(t *testing.T) {
	c := &Cache{}
	old := c.Begin()
	c.Invalidate()
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if c.Fill(old, Value{1, "old"}) {
				t.Error("accepted stale generation")
			}
		}()
	}
	wg.Wait()
	if _, ok := c.Get(); ok {
		t.Fatal("stale value present")
	}
}
