11package server
22
33import (
4+ "context"
45 "net/http"
56 "net/http/httptest"
7+ "sync"
68 "testing"
9+ "time"
710)
811
912func TestHeaderMW (t * testing.T ) {
@@ -23,3 +26,81 @@ func TestHeaderMW(t *testing.T) {
2326 t .Errorf ("expected *, got %s" , w .Header ().Get ("Content-Type" ))
2427 }
2528}
29+ func TestRequestValidationAndMetricsMW (t * testing.T ) {
30+ handler := http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {})
31+
32+ mp := & mockPublisher {}
33+ sut := RequestValidationAndMetricsMW (handler , mp )
34+
35+ w := httptest .NewRecorder ()
36+ r := httptest .NewRequest (http .MethodGet , "http://test.com/api/page?verbose=true" , nil )
37+ r .SetPathValue ("page" , "page" )
38+ sut .ServeHTTP (w , r )
39+
40+ ctx , cancel := context .WithTimeout (context .Background (), 5 * time .Second )
41+ defer cancel ()
42+
43+ loop:
44+ for {
45+ select {
46+ case <- ctx .Done ():
47+ t .Errorf ("timed out waiting for publish to be called" )
48+ default :
49+ if ! mp .getPublishedCalled () {
50+ time .Sleep (500 * time .Millisecond )
51+ continue
52+ }
53+ break loop
54+ }
55+ }
56+ }
57+
58+ func TestRequestValidationAndMetricsMWEmptyPage (t * testing.T ) {
59+ handler := http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {})
60+
61+ mp := & mockPublisher {}
62+ sut := RequestValidationAndMetricsMW (handler , mp )
63+
64+ w := httptest .NewRecorder ()
65+ r := httptest .NewRequest (http .MethodGet , "http://test.com/api?verbose=true" , nil )
66+ r .SetPathValue ("page" , "" )
67+ sut .ServeHTTP (w , r )
68+
69+ if w .Code != http .StatusBadRequest {
70+ t .Errorf ("expected %d, got %d" , http .StatusBadRequest , w .Code )
71+ }
72+ }
73+
74+ func TestRequestValidationAndMetricsMWBadParameter (t * testing.T ) {
75+ handler := http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {})
76+
77+ mp := & mockPublisher {}
78+ sut := RequestValidationAndMetricsMW (handler , mp )
79+
80+ w := httptest .NewRecorder ()
81+ r := httptest .NewRequest (http .MethodGet , "http://test.com/api/page?table=x" , nil )
82+ r .SetPathValue ("page" , "page" )
83+ sut .ServeHTTP (w , r )
84+
85+ if w .Code != http .StatusBadRequest {
86+ t .Errorf ("expected %d, got %d" , http .StatusBadRequest , w .Code )
87+ }
88+ }
89+
90+ type mockPublisher struct {
91+ publishCalled bool
92+ lock sync.Mutex
93+ }
94+
95+ func (m * mockPublisher ) Publish (code int , ip string , page string , lang string ) error {
96+ m .lock .Lock ()
97+ defer m .lock .Unlock ()
98+ m .publishCalled = true
99+ return nil
100+ }
101+
102+ func (m * mockPublisher ) getPublishedCalled () bool {
103+ m .lock .Lock ()
104+ defer m .lock .Unlock ()
105+ return m .publishCalled
106+ }
0 commit comments