github.com/zak-blake/goa@v1.4.1/middleware/log_response_test.go (about)

     1  package middleware_test
     2  
     3  import (
     4  	"net/http"
     5  	"net/url"
     6  	"strings"
     7  
     8  	"context"
     9  
    10  	"github.com/goadesign/goa"
    11  	"github.com/goadesign/goa/middleware"
    12  	. "github.com/onsi/ginkgo"
    13  	. "github.com/onsi/gomega"
    14  )
    15  
    16  var _ = Describe("LogResponse", func() {
    17  	var logger *testLogger
    18  	var ctx context.Context
    19  	var req *http.Request
    20  	var rw http.ResponseWriter
    21  	var params url.Values
    22  	responseText := "some response data to be logged"
    23  
    24  	BeforeEach(func() {
    25  		logger = new(testLogger)
    26  		service := newService(logger)
    27  
    28  		var err error
    29  		req, err = http.NewRequest("POST", "/goo", strings.NewReader(`{"payload":42}`))
    30  		Ω(err).ShouldNot(HaveOccurred())
    31  		rw = new(testResponseWriter)
    32  		params = url.Values{"query": []string{"value"}}
    33  		ctx = newContext(service, rw, req, params)
    34  	})
    35  
    36  	It("logs responses", func() {
    37  		h := func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
    38  			goa.ContextResponse(ctx).WriteHeader(200)
    39  			goa.ContextResponse(ctx).Write([]byte(responseText))
    40  			return nil
    41  		}
    42  		lg := middleware.LogResponse()(h)
    43  		Ω(lg(ctx, rw, req)).ShouldNot(HaveOccurred())
    44  		Ω(logger.InfoEntries).Should(HaveLen(1))
    45  
    46  		Ω(logger.InfoEntries[0].Data).Should(HaveLen(2))
    47  		Ω(logger.InfoEntries[0].Data[0]).Should(Equal("body"))
    48  		Ω(logger.InfoEntries[0].Data[1]).Should(Equal(responseText))
    49  	})
    50  })