8 _ "github.com/anacrolix/envpprof"
9 qt "github.com/frankban/quicktest"
12 func TestReserveOverMax(t *testing.T) {
14 l := &Limiter{Max: 10}
16 c.Assert(r.Wait(context.Background()), qt.IsNotNil)
19 func TestImmediateAllow(t *testing.T) {
21 l := &Limiter{Max: 10}
23 c.Assert(r.Wait(context.Background()), qt.IsNil)
26 func TestSimpleSequence(t *testing.T) {
28 l := &Limiter{Max: 10}
29 rs := make([]*Reservation, 0)
30 rs = append(rs, l.Reserve(6))
31 rs = append(rs, l.Reserve(5))
32 rs = append(rs, l.Reserve(5))
33 c.Assert(rs[0].Wait(context.Background()), qt.IsNil)
34 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Nanosecond))
35 c.Assert(rs[1].Wait(ctx), qt.Equals, context.DeadlineExceeded)
37 ctx, cancel = context.WithCancel(context.Background())
39 c.Assert(rs[2].Wait(ctx), qt.Equals, context.Canceled)
41 ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(time.Second))
42 c.Assert(rs[1].Wait(ctx), qt.IsNil)
44 c.Assert(rs[2].Wait(ctx), qt.IsNil)
49 c.Assert(l.Value(), qt.Equals, l.Max)
52 func TestSequenceWithCancel(t *testing.T) {
54 l := &Limiter{Max: 10}
55 rs := make([]*Reservation, 0)
56 rs = append(rs, l.Reserve(6))
57 rs = append(rs, l.Reserve(6))
58 rs = append(rs, l.Reserve(4))
59 rs = append(rs, l.Reserve(4))
60 c.Assert(rs[0].Cancel(), qt.IsFalse)
61 c.Assert(func() { rs[1].Release() }, qt.PanicMatches, "not resolved")
62 c.Assert(rs[1].Cancel(), qt.IsTrue)
63 c.Assert(rs[2].Wait(context.Background()), qt.IsNil)
65 c.Assert(rs[3].Wait(context.Background()), qt.IsNil)
66 c.Assert(l.Value(), qt.Equals, int64(2))
70 c.Assert(l.Value(), qt.Equals, l.Max)
73 func TestCancelWhileWaiting(t *testing.T) {
75 l := &Limiter{Max: 10}
76 rs := make([]*Reservation, 0)
77 rs = append(rs, l.Reserve(6))
78 rs = append(rs, l.Reserve(6))
79 rs = append(rs, l.Reserve(4))
80 rs = append(rs, l.Reserve(4))
82 err := rs[1].Wait(context.Background())
83 c.Assert(err, qt.IsNotNil)
84 err = rs[2].Wait(context.Background())
85 c.Assert(err, qt.IsNil)
86 ctx, cancel := context.WithCancel(context.Background())
89 c.Assert(err, qt.Equals, context.Canceled)
92 c.Assert(err, qt.IsNil)