-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_test.go
81 lines (69 loc) · 1.61 KB
/
handler_test.go
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 metrica
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"sync"
"testing"
)
func TestHandlerCountFS_Sequential(t *testing.T) {
f, err := os.Create("test")
if err != nil {
t.Fatalf("error creating temp file: %v", err)
}
defer func() {
_ = os.Remove(f.Name())
}()
fs := NewFileStorage(&sync.Mutex{}, f.Name())
mux := Handler(fs)
for i := 0; i < 100; i++ {
req := httptest.NewRequest("GET", "/countfs", nil)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status OK; got %v", w.Code)
}
var gotRes countResponse
if err := json.NewDecoder(w.Body).Decode(&gotRes); err != nil {
t.Errorf("unable to decode body: %v", err)
}
wantCount := int64(i + 1)
assert(t, wantCount, gotRes.Count)
}
}
func TestHandlerCountFS_Concurrent(t *testing.T) {
f, err := os.Create("test")
if err != nil {
t.Fatalf("error creating temp file: %v", err)
}
defer func() {
_ = os.Remove(f.Name())
}()
fs := NewFileStorage(&sync.Mutex{}, f.Name())
mux := Handler(fs)
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
req := httptest.NewRequest("GET", "/countfs", nil)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status OK; got %v", w.Code)
}
defer wg.Done()
}()
}
wg.Wait()
got, err := fs.Read()
if err != nil {
t.Fatalf("error reading file: %v", err)
}
assert(t, int64(100), got.Count60sec())
}
func assert(t *testing.T, want interface{}, got interface{}) {
if want != got {
t.Errorf("expected %v; got %v", want, got)
}
}