package metrics

import "testing"

func TestRecentLatencyByKeyTracksBoundedP99PerKey(t *testing.T) {
	tracker := NewRecentLatencyByKey(3)

	p99, samples := tracker.Observe("a", 10)
	if p99 != 10 || samples != 1 {
		t.Fatalf("first p99=%v samples=%d", p99, samples)
	}
	tracker.Observe("a", 20)
	p99, samples = tracker.Observe("a", 30)
	if p99 != 30 || samples != 3 {
		t.Fatalf("filled p99=%v samples=%d", p99, samples)
	}
	p99, samples = tracker.Observe("a", 5)
	if p99 != 30 || samples != 3 {
		t.Fatalf("bounded p99=%v samples=%d", p99, samples)
	}
	p99, samples = tracker.Observe("b", 7)
	if p99 != 7 || samples != 1 {
		t.Fatalf("second key p99=%v samples=%d", p99, samples)
	}
}

func TestRecentLatencyByKeySanitizesBadValues(t *testing.T) {
	tracker := NewRecentLatencyByKey(2)

	p99, samples := tracker.Observe("", -10)
	if p99 != 0 || samples != 1 {
		t.Fatalf("p99=%v samples=%d", p99, samples)
	}
}
