refactor(oohelperd): improve tests implementation (#835)
After this diff has landed, we have addressed all the points originally published at https://github.com/ooni/probe/issues/2134.
This commit is contained in:
@@ -40,3 +40,26 @@ func (txp *HTTPClient) Do(req *http.Request) (*http.Response, error) {
|
||||
func (txp *HTTPClient) CloseIdleConnections() {
|
||||
txp.MockCloseIdleConnections()
|
||||
}
|
||||
|
||||
// HTTPResponseWriter allows mocking http.ResponseWriter.
|
||||
type HTTPResponseWriter struct {
|
||||
MockHeader func() http.Header
|
||||
|
||||
MockWrite func(b []byte) (int, error)
|
||||
|
||||
MockWriteHeader func(statusCode int)
|
||||
}
|
||||
|
||||
var _ http.ResponseWriter = &HTTPResponseWriter{}
|
||||
|
||||
func (w *HTTPResponseWriter) Header() http.Header {
|
||||
return w.MockHeader()
|
||||
}
|
||||
|
||||
func (w *HTTPResponseWriter) Write(b []byte) (int, error) {
|
||||
return w.MockWrite(b)
|
||||
}
|
||||
|
||||
func (w *HTTPResponseWriter) WriteHeader(statusCode int) {
|
||||
w.MockWriteHeader(statusCode)
|
||||
}
|
||||
|
||||
@@ -81,3 +81,49 @@ func TestHTTPClient(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHTTPResponseWriter(t *testing.T) {
|
||||
t.Run("Header", func(t *testing.T) {
|
||||
expect := http.Header{}
|
||||
w := &HTTPResponseWriter{
|
||||
MockHeader: func() http.Header {
|
||||
return expect
|
||||
},
|
||||
}
|
||||
got := w.Header()
|
||||
got.Set("Content-Type", "text/plain")
|
||||
if expect.Get("Content-Type") != "text/plain" {
|
||||
t.Fatal("we didn't get the expected header value")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Write", func(t *testing.T) {
|
||||
expected := errors.New("mocked error")
|
||||
w := &HTTPResponseWriter{
|
||||
MockWrite: func(b []byte) (int, error) {
|
||||
return 0, expected
|
||||
},
|
||||
}
|
||||
buffer := make([]byte, 16)
|
||||
count, err := w.Write(buffer)
|
||||
if count != 0 {
|
||||
t.Fatal("invalid count")
|
||||
}
|
||||
if !errors.Is(err, expected) {
|
||||
t.Fatal("unexpected err", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("WriteHeader", func(t *testing.T) {
|
||||
var called bool
|
||||
w := &HTTPResponseWriter{
|
||||
MockWriteHeader: func(statusCode int) {
|
||||
called = true
|
||||
},
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
if !called {
|
||||
t.Fatal("not called")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user