github.com/silveraid/fabric-ca@v1.1.0-preview.0.20180127000700-71974f53ab08/lib/serverendpoint_test.go (about)

     1  /*
     2  Copyright IBM Corp. 2017 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8                   http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package lib
    18  
    19  import (
    20  	"encoding/json"
    21  	"io/ioutil"
    22  	"net/http"
    23  	"net/http/httptest"
    24  	"testing"
    25  
    26  	"github.com/cloudflare/cfssl/api"
    27  	"github.com/stretchr/testify/assert"
    28  )
    29  
    30  var handlerError error
    31  
    32  func TestServerEndpoint(t *testing.T) {
    33  	// Positive tests
    34  	url := "http://localhost:7054/api/v1/enroll"
    35  	handlerError = nil
    36  	testEndpoint(t, "HEAD", url, 200, 0)
    37  	testEndpoint(t, "GET", url, 200, 0)
    38  	testEndpoint(t, "POST", url, 200, 0)
    39  	// Negative tests
    40  	testEndpoint(t, "DELETE", url, 405, ErrMethodNotAllowed)
    41  	handlerError = newAuthErr(ErrInvalidToken, "Invalid token")
    42  	testEndpoint(t, "GET", url, 401, ErrAuthFailure)
    43  }
    44  
    45  func testEndpoint(t *testing.T, method, url string, scode, rcode int) {
    46  	se := &serverEndpoint{
    47  		Methods: []string{"GET", "POST", "HEAD"},
    48  		Handler: testEndpointHandler,
    49  	}
    50  	r, err := http.NewRequest(method, url, nil)
    51  	assert.NoError(t, err)
    52  	w := httptest.NewRecorder()
    53  	se.ServeHTTP(w, r)
    54  	resp := w.Result()
    55  	assert.True(t, resp.StatusCode == scode)
    56  	buf, err := ioutil.ReadAll(resp.Body)
    57  	assert.NoError(t, err)
    58  	if method != "HEAD" {
    59  		var body api.Response
    60  		err = json.Unmarshal(buf, &body)
    61  		assert.NoError(t, err)
    62  		if rcode == 0 {
    63  			assert.True(t, len(body.Errors) == 0)
    64  		} else {
    65  			assert.True(t, body.Errors[0].Code == rcode)
    66  		}
    67  	} else {
    68  		// No response body
    69  		assert.True(t, len(buf) == 0)
    70  	}
    71  }
    72  
    73  func testEndpointHandler(ctx *serverRequestContext) (interface{}, error) {
    74  	return "result", handlerError
    75  }