test.*ServerAssertion.At   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
package test
2
3
import (
4
	"net/http"
5
	"net/http/httptest"
6
	"sync"
7
)
8
9
func NewServerWithAssertion(handler http.HandlerFunc) (*httptest.Server, *ServerAssertion) {
10
	serverAssertion := &ServerAssertion{}
11
12
	server := httptest.NewServer(serverAssertion.wrap(handler))
13
14
	return server, serverAssertion
15
}
16
17
func NewTSLServerWithAssertion(handler http.HandlerFunc) (*httptest.Server, *ServerAssertion) {
18
	serverAssertion := &ServerAssertion{}
19
20
	server := httptest.NewUnstartedServer(serverAssertion.wrap(handler))
21
	server.StartTLS()
22
23
	return server, serverAssertion
24
}
25
26
type ServerAssertion struct {
27
	requests   []http.Request
28
	requestsMx sync.RWMutex
29
}
30
31
func (s *ServerAssertion) wrap(handler http.HandlerFunc) http.HandlerFunc {
32
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
33
		handler(w, r)
34
35
		s.requestsMx.Lock()
36
		defer s.requestsMx.Unlock()
37
38
		s.requests = append(s.requests, *r)
39
	})
40
}
41
42
func (s *ServerAssertion) Range(fn func(index int, r http.Request)) {
43
	s.requestsMx.RLock()
44
	defer s.requestsMx.RUnlock()
45
46
	for i, r := range s.requests {
47
		fn(i, r)
48
	}
49
}
50
51
func (s *ServerAssertion) At(index int, fn func(r http.Request)) {
52
	s.requestsMx.RLock()
53
	defer s.requestsMx.RUnlock()
54
55
	fn(s.requests[index])
56
}
57
58
func (s *ServerAssertion) Len() int {
59
	s.requestsMx.RLock()
60
	defer s.requestsMx.RUnlock()
61
62
	return len(s.requests)
63
}
64