Browse Source

Add FakeResponseWriter

Volodymyr Tkach 2 years ago
parent
commit
1c1069190e
2 changed files with 54 additions and 0 deletions
  1. 35 0
      utils/http/helpers/helpers.go
  2. 19 0
      utils/http/helpers/helpers_test.go

+ 35 - 0
utils/http/helpers/helpers.go

@@ -228,3 +228,38 @@ func SetLanguageCookie(w http.ResponseWriter, r *http.Request) error {
 	}
 	return nil
 }
+
+// -----------------------------------------------------------------------------
+
+// For funcs which write some data to http.ResponseWriter
+//
+// Example: w = NewFakeResponseWriter()
+//
+// w.Body, w.Headers, w.StatusCode
+type FakeResponseWriter struct {
+	Body       []byte
+	Headers    http.Header
+	StatusCode int
+}
+
+func (w *FakeResponseWriter) Header() http.Header {
+	return w.Headers
+}
+
+func (w *FakeResponseWriter) Write(b []byte) (int, error) {
+	w.Body = append(w.Body, b...)
+	return len(b), nil
+}
+
+func (w *FakeResponseWriter) WriteHeader(statusCode int) {
+	w.StatusCode = statusCode
+}
+
+// Create fake http.ResponseWriter for using in tests
+func NewFakeResponseWriter() *FakeResponseWriter {
+	return &FakeResponseWriter{
+		Body:       []byte{},
+		Headers:    http.Header{},
+		StatusCode: http.StatusOK,
+	}
+}

+ 19 - 0
utils/http/helpers/helpers_test.go

@@ -375,6 +375,25 @@ var _ = Describe("helpers", func() {
 			`)).To(Equal(`<div><b>Contacts:</b> <a href="#">Link 1</a>, <a href="#">Link 2</a></div>`))
 		})
 	})
+
+	Context("FakeResponseWriter", func() {
+		It("write data to fake response writer", func() {
+			var someHandleFunc = func(w http.ResponseWriter) {
+				w.Header().Set("Content-Type", "application/json")
+				w.WriteHeader(http.StatusNotFound)
+				_, _ = w.Write([]byte("body"))
+			}
+
+			writer := helpers.NewFakeResponseWriter()
+			someHandleFunc(writer)
+
+			Expect(writer.Body).To(Equal([]byte("body")))
+			Expect(writer.Headers).To(Equal(http.Header{
+				"Content-Type": []string{"application/json"},
+			}))
+			Expect(writer.StatusCode).To(Equal(http.StatusNotFound))
+		})
+	})
 })
 
 func TestSuite(t *testing.T) {