improve render code coverage (#3525)
This commit is contained in:
parent
eac2daac64
commit
6a0556ed5a
@ -15,6 +15,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin/internal/json"
|
||||||
testdata "github.com/gin-gonic/gin/testdata/protoexample"
|
testdata "github.com/gin-gonic/gin/testdata/protoexample"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"google.golang.org/protobuf/proto"
|
"google.golang.org/protobuf/proto"
|
||||||
@ -136,6 +137,51 @@ func TestRenderJsonpJSON(t *testing.T) {
|
|||||||
assert.Equal(t, "application/javascript; charset=utf-8", w2.Header().Get("Content-Type"))
|
assert.Equal(t, "application/javascript; charset=utf-8", w2.Header().Get("Content-Type"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type errorWriter struct {
|
||||||
|
bufString string
|
||||||
|
*httptest.ResponseRecorder
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ http.ResponseWriter = (*errorWriter)(nil)
|
||||||
|
|
||||||
|
func (w *errorWriter) Write(buf []byte) (int, error) {
|
||||||
|
if string(buf) == w.bufString {
|
||||||
|
return 0, errors.New(`write "` + w.bufString + `" error`)
|
||||||
|
}
|
||||||
|
return w.ResponseRecorder.Write(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderJsonpJSONError(t *testing.T) {
|
||||||
|
ew := &errorWriter{
|
||||||
|
ResponseRecorder: httptest.NewRecorder(),
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonpJSON := JsonpJSON{
|
||||||
|
Callback: "foo",
|
||||||
|
Data: map[string]string{
|
||||||
|
"foo": "bar",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
cb := template.JSEscapeString(jsonpJSON.Callback)
|
||||||
|
ew.bufString = cb
|
||||||
|
err := jsonpJSON.Render(ew) // error was returned while writing callback
|
||||||
|
assert.Equal(t, `write "`+cb+`" error`, err.Error())
|
||||||
|
|
||||||
|
ew.bufString = `(`
|
||||||
|
err = jsonpJSON.Render(ew)
|
||||||
|
assert.Equal(t, `write "`+`(`+`" error`, err.Error())
|
||||||
|
|
||||||
|
data, _ := json.Marshal(jsonpJSON.Data) // error was returned while writing data
|
||||||
|
ew.bufString = string(data)
|
||||||
|
err = jsonpJSON.Render(ew)
|
||||||
|
assert.Equal(t, `write "`+string(data)+`" error`, err.Error())
|
||||||
|
|
||||||
|
ew.bufString = `);`
|
||||||
|
err = jsonpJSON.Render(ew)
|
||||||
|
assert.Equal(t, `write "`+`);`+`" error`, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
func TestRenderJsonpJSONError2(t *testing.T) {
|
func TestRenderJsonpJSONError2(t *testing.T) {
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
data := map[string]any{
|
data := map[string]any{
|
||||||
|
Loading…
Reference in New Issue
Block a user