github.com/splucs/witchcraft-go-server@v1.7.0/rest/rest_test.go (about)

     1  // Copyright (c) 2019 Palantir Technologies. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package rest_test
    16  
    17  import (
    18  	"io/ioutil"
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"testing"
    22  
    23  	werror "github.com/palantir/witchcraft-go-error"
    24  	"github.com/palantir/witchcraft-go-server/rest"
    25  	"github.com/stretchr/testify/require"
    26  )
    27  
    28  func TestWriteJSONResponse_Error(t *testing.T) {
    29  	for _, test := range []struct {
    30  		Name         string
    31  		Err          error
    32  		ExpectedCode int
    33  		ExpectedJSON string
    34  	}{
    35  		{
    36  			Name:         "standard werror",
    37  			Err:          werror.Error("bad things happened"),
    38  			ExpectedCode: 500,
    39  			ExpectedJSON: "\"bad things happened\"\n",
    40  		},
    41  		{
    42  			Name:         "rest.Error with code",
    43  			Err:          rest.NewError(werror.Error("bad things happened"), rest.StatusCode(400)),
    44  			ExpectedCode: 400,
    45  			ExpectedJSON: "\"witchcraft-server rest error: bad things happened\"\n",
    46  		},
    47  	} {
    48  		t.Run(test.Name, func(t *testing.T) {
    49  			server := httptest.NewServer(rest.NewJSONHandler(func(http.ResponseWriter, *http.Request) error {
    50  				return test.Err
    51  			}, rest.StatusCodeMapper, nil))
    52  			defer server.Close()
    53  
    54  			resp, err := server.Client().Get(server.URL)
    55  			require.NoError(t, err)
    56  			require.Equal(t, resp.StatusCode, test.ExpectedCode)
    57  			body, err := ioutil.ReadAll(resp.Body)
    58  			require.NoError(t, err)
    59  			require.Equal(t, test.ExpectedJSON, string(body))
    60  		})
    61  	}
    62  }