Skip to content

Commit

Permalink
Merge branch 'master' into bugfix
Browse files Browse the repository at this point in the history
  • Loading branch information
appleboy authored Aug 6, 2018
2 parents 772f671 + 9b7e7bd commit 9c686f0
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
36 changes: 36 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/gin-gonic/gin/binding"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
"io"
)

var _ context.Context = &Context{}
Expand Down Expand Up @@ -1558,3 +1559,38 @@ func TestContextRenderDataFromReader(t *testing.T) {
assert.Equal(t, fmt.Sprintf("%d", contentLength), w.HeaderMap.Get("Content-Length"))
assert.Equal(t, extraHeaders["Content-Disposition"], w.HeaderMap.Get("Content-Disposition"))
}

func TestContextStream(t *testing.T) {
w := CreateTestResponseRecorder()
c, _ := CreateTestContext(w)

stopStream := true
c.Stream(func(w io.Writer) bool {
defer func() {
stopStream = false
}()

w.Write([]byte("test"))

return stopStream
})

assert.Equal(t, "testtest", w.Body.String())
}

func TestContextStreamWithClientGone(t *testing.T) {
w := CreateTestResponseRecorder()
c, _ := CreateTestContext(w)

c.Stream(func(writer io.Writer) bool {
defer func() {
w.closeClient()
}()

writer.Write([]byte("test"))

return true
})

assert.Equal(t, "test", w.Body.String())
}
21 changes: 21 additions & 0 deletions test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package gin

import (
"net/http"
"net/http/httptest"
)

// CreateTestContext returns a fresh engine and context for testing purposes
Expand All @@ -16,3 +17,23 @@ func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {
c.writermem.reset(w)
return
}

type TestResponseRecorder struct {
*httptest.ResponseRecorder
closeChannel chan bool
}

func (r *TestResponseRecorder) CloseNotify() <-chan bool {
return r.closeChannel
}

func (r *TestResponseRecorder) closeClient() {
r.closeChannel <- true
}

func CreateTestResponseRecorder() *TestResponseRecorder {
return &TestResponseRecorder{
httptest.NewRecorder(),
make(chan bool, 1),
}
}

0 comments on commit 9c686f0

Please sign in to comment.