Skip to content
quarry Artifact [cae15f8ca1]
Login

Artifact [cae15f8ca1]

Artifact cae15f8ca10f88f1d0978f2ac41f974aaffc4dc0d9dbdd7990001a4c7242124c:


package events

import (
	"sync"
	"testing"
)

func TestCounterAddsUp(t *testing.T) {
	s := testServer(t)
	if n, err := s.Total("alpha", "clone"); err != nil || n != 0 {
		t.Fatalf("an untouched counter = %d, %v; want 0, nil — never counted is an answer", n, err)
	}
	for i := 0; i < 3; i++ {
		if err := s.Count("alpha", "clone", 1); err != nil {
			t.Fatal(err)
		}
	}
	if n, err := s.Total("alpha", "clone"); err != nil || n != 3 {
		t.Fatalf("total = %d, %v; want 3", n, err)
	}
	// Counters are per repo and per name; neither may bleed.
	if n, _ := s.Total("beta", "clone"); n != 0 {
		t.Errorf("beta's clone counter = %d; repos share a stream, not a tally", n)
	}
	if n, _ := s.Total("alpha", "fetch"); n != 0 {
		t.Errorf("alpha's fetch counter = %d; names share a stream, not a tally", n)
	}
}

// The reason this is a counter stream and not an UPDATE: concurrent
// increments converge. A read-modify-write would lose some of these.
func TestConcurrentIncrementsAllLand(t *testing.T) {
	s := testServer(t)
	var wg sync.WaitGroup
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if err := s.Count("alpha", "fetch", 1); err != nil {
				t.Errorf("count: %v", err)
			}
		}()
	}
	wg.Wait()
	if n, err := s.Total("alpha", "fetch"); err != nil || n != 50 {
		t.Fatalf("total = %d, %v; want 50 — increments were lost", n, err)
	}
}

func TestCounterRefusesAnUnnamedTally(t *testing.T) {
	s := testServer(t)
	if err := s.Count("", "clone", 1); err == nil {
		t.Error("counted against no repo")
	}
	if err := s.Count("alpha", "", 1); err == nil {
		t.Error("counted against no name")
	}
}