gitee.com/zhaochuninhefei/fabric-ca-gm@v0.0.2/lib/serverendpoint_test.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package lib 8 9 import ( 10 "encoding/json" 11 "io/ioutil" 12 "testing" 13 14 "gitee.com/zhaochuninhefei/gmgo/gmhttp/httptest" 15 16 http "gitee.com/zhaochuninhefei/gmgo/gmhttp" 17 18 "gitee.com/zhaochuninhefei/cfssl-gm/api" 19 "gitee.com/zhaochuninhefei/fabric-ca-gm/lib/caerrors" 20 "github.com/stretchr/testify/assert" 21 ) 22 23 var handlerError error 24 25 func TestServerEndpoint(t *testing.T) { 26 // Positive tests 27 url := "http://localhost:7054/api/v1/enroll" 28 handlerError = nil 29 testEndpoint(t, "HEAD", url, 200, 0) 30 testEndpoint(t, "GET", url, 200, 0) 31 testEndpoint(t, "POST", url, 200, 0) 32 // Negative tests 33 testEndpoint(t, "DELETE", url, 405, caerrors.ErrMethodNotAllowed) 34 handlerError = caerrors.NewAuthenticationErr(caerrors.ErrInvalidToken, "Invalid token") 35 testEndpoint(t, "GET", url, 401, caerrors.ErrAuthenticationFailure) 36 } 37 38 func testEndpoint(t *testing.T, method, url string, scode, rcode int) { 39 se := &serverEndpoint{ 40 Methods: []string{"GET", "POST", "HEAD"}, 41 Handler: testEndpointHandler, 42 } 43 r, err := http.NewRequest(method, url, nil) 44 assert.NoError(t, err) 45 w := httptest.NewRecorder() 46 se.ServeHTTP(w, r) 47 resp := w.Result() 48 assert.True(t, resp.StatusCode == scode) 49 buf, err := ioutil.ReadAll(resp.Body) 50 assert.NoError(t, err) 51 if method != "HEAD" { 52 var body api.Response 53 err = json.Unmarshal(buf, &body) 54 assert.NoError(t, err) 55 if rcode == 0 { 56 assert.True(t, len(body.Errors) == 0) 57 } else { 58 assert.True(t, body.Errors[0].Code == rcode) 59 } 60 } else { 61 // No response body 62 assert.True(t, len(buf) == 0) 63 } 64 } 65 66 func testEndpointHandler(ctx *serverRequestContextImpl) (interface{}, error) { 67 return "result", handlerError 68 }