github.com/iotexproject/iotex-core@v1.14.1-rc1/api/http_test.go (about) 1 package api 2 3 import ( 4 "context" 5 "io" 6 "net/http" 7 "net/http/httptest" 8 "strings" 9 "testing" 10 "time" 11 12 "github.com/golang/mock/gomock" 13 "github.com/stretchr/testify/require" 14 15 "github.com/iotexproject/iotex-core/test/mock/mock_web3server" 16 "github.com/iotexproject/iotex-core/testutil" 17 ) 18 19 func TestServeHTTP(t *testing.T) { 20 require := require.New(t) 21 ctrl := gomock.NewController(t) 22 defer ctrl.Finish() 23 handler := mock_web3server.NewMockWeb3Handler(ctrl) 24 handler.EXPECT().HandlePOSTReq(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) 25 svr := newHTTPHandler(handler) 26 27 t.Run("WrongHTTPMethod", func(t *testing.T) { 28 req, _ := http.NewRequest(http.MethodGet, "http://url.com", nil) 29 req.Header.Set("Content-Type", "application/json") 30 resp := httptest.NewRecorder() 31 svr.ServeHTTP(resp, req) 32 require.Equal(http.StatusOK, resp.Result().StatusCode) 33 bytes, _ := io.ReadAll(resp.Result().Body) 34 require.Equal("IoTeX RPC endpoint is ready.", string(bytes)) 35 }) 36 37 t.Run("Success", func(t *testing.T) { 38 req, _ := http.NewRequest(http.MethodPost, "http://url.com", strings.NewReader(`{}`)) 39 req.Header.Set("Content-Type", "application/json") 40 resp := httptest.NewRecorder() 41 svr.ServeHTTP(resp, req) 42 require.Equal(http.StatusOK, resp.Result().StatusCode) 43 }) 44 } 45 46 func TestServerStartStop(t *testing.T) { 47 require := require.New(t) 48 ctrl := gomock.NewController(t) 49 defer ctrl.Finish() 50 handler := mock_web3server.NewMockWeb3Handler(ctrl) 51 svr := NewHTTPServer("", testutil.RandomPort(), newHTTPHandler(handler)) 52 53 err := svr.Start(context.Background()) 54 require.NoError(err) 55 err = testutil.WaitUntil(100*time.Millisecond, 3*time.Second, func() (bool, error) { 56 err = svr.Stop(context.Background()) 57 return err == nil, err 58 }) 59 require.NoError(err) 60 }