github.com/m3db/m3@v1.5.0/src/dbnode/network/server/httpjson/handlers_test.go (about)

     1  // Copyright (c) 2020 Uber Technologies, Inc.
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to deal
     5  // in the Software without restriction, including without limitation the rights
     6  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     7  // copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    18  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    19  // THE SOFTWARE.
    20  
    21  package httpjson
    22  
    23  import (
    24  	"bytes"
    25  	"encoding/json"
    26  	"errors"
    27  	"io/ioutil"
    28  	"net/http"
    29  	"net/http/httptest"
    30  	"strings"
    31  	"testing"
    32  
    33  	"github.com/m3db/m3/src/dbnode/client"
    34  	"github.com/m3db/m3/src/dbnode/network/server/tchannelthrift/cluster"
    35  	"github.com/m3db/m3/src/x/headers"
    36  	xjson "github.com/m3db/m3/src/x/json"
    37  	xtest "github.com/m3db/m3/src/x/test"
    38  
    39  	apachethrift "github.com/apache/thrift/lib/go/thrift"
    40  	"github.com/golang/mock/gomock"
    41  	"github.com/stretchr/testify/require"
    42  	"golang.org/x/net/context"
    43  )
    44  
    45  var (
    46  	// testClientOptions to not allocate multiple times.
    47  	testClientOptions = client.NewOptions()
    48  
    49  	errTestClientSessionError = errors.New("session test error")
    50  )
    51  
    52  func newTestClient(ctrl *gomock.Controller) *client.MockClient {
    53  	client := client.NewMockClient(ctrl)
    54  	client.EXPECT().Options().Return(testClientOptions).AnyTimes()
    55  	client.EXPECT().NewSessionWithOptions(gomock.Any()).Return(nil, errTestClientSessionError).AnyTimes()
    56  	return client
    57  }
    58  
    59  func TestRegisterHandlersRequestSimple(t *testing.T) {
    60  	ctrl := xtest.NewController(t)
    61  	defer ctrl.Finish()
    62  
    63  	mux := http.NewServeMux()
    64  
    65  	client := newTestClient(ctrl)
    66  	service := cluster.NewService(client)
    67  
    68  	opts := NewServerOptions()
    69  
    70  	err := RegisterHandlers(mux, service, opts)
    71  	require.NoError(t, err)
    72  
    73  	recorder := httptest.NewRecorder()
    74  	req := httptest.NewRequest(http.MethodGet, "/health", nil)
    75  	mux.ServeHTTP(recorder, req)
    76  
    77  	require.Equal(t, http.StatusOK, recorder.Code)
    78  }
    79  
    80  func TestRegisterHandlersRequestPostRequestFn(t *testing.T) {
    81  	ctrl := xtest.NewController(t)
    82  	defer ctrl.Finish()
    83  
    84  	mux := http.NewServeMux()
    85  
    86  	client := newTestClient(ctrl)
    87  	service := cluster.NewService(client)
    88  
    89  	calledPostRequestFn := 0
    90  	opts := NewServerOptions().
    91  		SetPostResponseFn(func(
    92  			_ context.Context,
    93  			method string,
    94  			_ apachethrift.TStruct,
    95  		) {
    96  			require.Equal(t, "Health", method)
    97  			calledPostRequestFn++
    98  		})
    99  
   100  	err := RegisterHandlers(mux, service, opts)
   101  	require.NoError(t, err)
   102  
   103  	recorder := httptest.NewRecorder()
   104  	req := httptest.NewRequest(http.MethodGet, "/health", nil)
   105  	mux.ServeHTTP(recorder, req)
   106  
   107  	require.Equal(t, http.StatusOK, recorder.Code)
   108  	require.Equal(t, 1, calledPostRequestFn)
   109  }
   110  
   111  func TestRegisterHandlersRequestUnknownFieldsBadRequestError(t *testing.T) {
   112  	ctrl := xtest.NewController(t)
   113  	defer ctrl.Finish()
   114  
   115  	mux := http.NewServeMux()
   116  
   117  	client := newTestClient(ctrl)
   118  	service := cluster.NewService(client)
   119  
   120  	opts := NewServerOptions()
   121  
   122  	err := RegisterHandlers(mux, service, opts)
   123  	require.NoError(t, err)
   124  
   125  	// Create a payload with unknown field.
   126  	payload := xjson.Map{"unknownFieldName": "unknownFieldValue"}
   127  
   128  	body := bytes.NewBuffer(nil)
   129  	require.NoError(t, json.NewEncoder(body).Encode(payload))
   130  
   131  	recorder := httptest.NewRecorder()
   132  	req := httptest.NewRequest(http.MethodPost, "/query", body)
   133  	mux.ServeHTTP(recorder, req)
   134  
   135  	require.Equal(t, http.StatusBadRequest, recorder.Code)
   136  
   137  	out, err := ioutil.ReadAll(recorder.Result().Body)
   138  	require.NoError(t, err)
   139  	str := string(out)
   140  	require.True(t, strings.Contains(str, "invalid request body:"))
   141  	require.True(t, strings.Contains(str, "unknown field"))
   142  }
   143  
   144  func TestRegisterHandlersRequestDisableUnknownFields(t *testing.T) {
   145  	ctrl := xtest.NewController(t)
   146  	defer ctrl.Finish()
   147  
   148  	mux := http.NewServeMux()
   149  
   150  	client := newTestClient(ctrl)
   151  	service := cluster.NewService(client)
   152  
   153  	opts := NewServerOptions()
   154  
   155  	err := RegisterHandlers(mux, service, opts)
   156  	require.NoError(t, err)
   157  
   158  	// Create a payload with unknown field.
   159  	payload := xjson.Map{"unknownFieldName": "unknownFieldValue"}
   160  
   161  	body := bytes.NewBuffer(nil)
   162  	require.NoError(t, json.NewEncoder(body).Encode(payload))
   163  
   164  	recorder := httptest.NewRecorder()
   165  	req := httptest.NewRequest(http.MethodPost, "/query", body)
   166  	req.Header.Set(headers.JSONDisableDisallowUnknownFields, "true")
   167  	mux.ServeHTTP(recorder, req)
   168  
   169  	// Make sure not bad request, but expected error.
   170  	require.Equal(t, http.StatusInternalServerError, recorder.Code)
   171  
   172  	out, err := ioutil.ReadAll(recorder.Result().Body)
   173  	require.NoError(t, err)
   174  	str := string(out)
   175  	require.True(t, strings.Contains(str, errTestClientSessionError.Error()))
   176  }