pkg/common/test/server.go   A
last analyzed

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 36
dl 0
loc 62
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A test.NewTSLServerWithAssertion 0 7 1
A test.*ServerAssertion.At 0 5 1
A test.NewServerWithAssertion 0 6 1
A test.*ServerAssertion.Range 0 6 2
A test.*ServerAssertion.wrap 0 8 2
A test.*ServerAssertion.Len 0 5 1
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