internal/packlimit/watch_test.go

v1.40.1
gitbay/internal/packlimit/watch_test.go history · blame · raw

75 lines · 1574 bytes

 1package packlimit
 2
 3import (
 4	"io"
 5	"strings"
 6	"testing"
 7	"time"
 8)
 9
10func TestWatchStalls(t *testing.T) {
11	old := StallDeadline
12	StallDeadline = 100 * time.Millisecond
13	t.Cleanup(func() { StallDeadline = old })
14	l := New(1, 0, 0, time.Second)
15	w, stalled, stop := l.Watch(io.Discard)
16	defer stop()
17	// Writes keep it alive past the deadline.
18	for range 6 {
19		time.Sleep(40 * time.Millisecond)
20		w.Write([]byte("x"))
21		select {
22		case <-stalled:
23			t.Fatal("stalled while writing")
24		default:
25		}
26	}
27	select {
28	case <-stalled:
29	case <-time.After(2 * time.Second):
30		t.Fatal("no stall after writes stopped")
31	}
32}
33
34func TestWatchWithoutLimit(t *testing.T) {
35	var l *Limiter
36	w, stalled, stop := l.Watch(io.Discard)
37	defer stop()
38	if w != io.Discard || stalled != nil {
39		t.Fatal("a nil limiter watched")
40	}
41}
42
43// Bytes either way keep an armed Idle watch alive; silence both ways
44// ends it. Before arm, silence ends nothing.
45func TestIdleCountsBothDirections(t *testing.T) {
46	src := strings.NewReader(strings.Repeat("x", 16))
47	r, w, idle, arm, stop := Idle(src, io.Discard, 100*time.Millisecond)
48	defer stop()
49	time.Sleep(300 * time.Millisecond)
50	select {
51	case <-idle:
52		t.Fatal("idle before arm")
53	default:
54	}
55	arm()
56	buf := make([]byte, 1)
57	for i := range 8 {
58		time.Sleep(40 * time.Millisecond)
59		if i%2 == 0 {
60			r.Read(buf)
61		} else {
62			w.Write(buf)
63		}
64		select {
65		case <-idle:
66			t.Fatalf("idle at step %d while bytes moved", i)
67		default:
68		}
69	}
70	select {
71	case <-idle:
72	case <-time.After(2 * time.Second):
73		t.Fatal("not idle after both directions went quiet")
74	}
75}