github.com/wanliu/go-oauth2-server@v0.0.0-20180817021415-f928fa1580df/util/response/response_test.go (about)

     1  package response_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http/httptest"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/wanliu/go-oauth2-server/util/response"
    11  )
    12  
    13  func TestWriteJSON(t *testing.T) {
    14  	w := httptest.NewRecorder()
    15  	obj := map[string]interface{}{
    16  		"foo": "bar",
    17  		"qux": 1,
    18  	}
    19  	response.WriteJSON(w, obj, 201)
    20  
    21  	assert.Equal(t, 201, w.Code)
    22  	assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
    23  	expected, _ := json.Marshal(obj)
    24  	assert.Equal(t, string(expected), strings.TrimSpace(w.Body.String()))
    25  }
    26  
    27  func TestNoContent(t *testing.T) {
    28  	w := httptest.NewRecorder()
    29  	response.NoContent(w)
    30  
    31  	assert.Equal(t, 204, w.Code)
    32  	assert.Equal(t, "", strings.TrimSpace(w.Body.String()))
    33  }
    34  
    35  func TestError(t *testing.T) {
    36  	w := httptest.NewRecorder()
    37  	response.Error(w, "something went wrong", 500)
    38  
    39  	assert.Equal(t, 500, w.Code)
    40  	assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
    41  	expected := "{\"error\":\"something went wrong\"}"
    42  	assert.Equal(t, expected, strings.TrimSpace(w.Body.String()))
    43  }