-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemaphore_test.go
More file actions
81 lines (68 loc) · 1.86 KB
/
semaphore_test.go
File metadata and controls
81 lines (68 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package ghratelimit
import (
"context"
"testing"
"time"
)
func TestSemaphoreAcquire(t *testing.T) {
sem := newSemaphore(1)
// Test acquiring a slot
ctx := context.Background()
err := sem.Acquire(ctx)
if err != nil {
t.Fatalf("expected to acquire a slot, got error: %v", err)
}
// Test acquiring a slot with a full semaphore
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
err = sem.Acquire(ctx)
if err == nil {
t.Fatal("expected timeout error, got nil")
}
}
func TestSemaphoreRelease(t *testing.T) {
sem := newSemaphore(1)
// Acquire a slot and then release it
ctx := context.Background()
err := sem.Acquire(ctx)
if err != nil {
t.Fatalf("expected to acquire a slot, got error: %v", err)
}
sem.Release()
// Acquire again to ensure the slot was released
err = sem.Acquire(ctx)
if err != nil {
t.Fatalf("expected to acquire a slot after release, got error: %v", err)
}
}
func TestSemaphoreWithContextTimeout(t *testing.T) {
sem := newSemaphore(1)
// Acquire the slot to fill the semaphore
ctx := context.Background()
err := sem.Acquire(ctx)
if err != nil {
t.Fatalf("expected to acquire a slot, got error: %v", err)
}
// Try to acquire another slot, expect timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
err = sem.Acquire(ctx)
if err == nil {
t.Fatal("expected timeout error, got nil")
}
if err != context.DeadlineExceeded {
t.Fatalf("expected DeadlineExceeded error, got: %v", err)
}
}
func TestSemaphoreAcquireAfterRelease(t *testing.T) {
sem := newSemaphore(1)
// Acquire and release multiple times to ensure proper functioning
for i := 0; i < 3; i++ {
ctx := context.Background()
err := sem.Acquire(ctx)
if err != nil {
t.Fatalf("expected to acquire a slot on iteration %d, got error: %v", i, err)
}
sem.Release()
}
}