gitlab.com/ignitionrobotics/web/ign-go@v1.0.0-rc4/testhelpers/router_test_helpers.go (about)

     1  package igntest
     2  
     3  // Important note: functions in this module should not include
     4  // references to parent package 'ign', to avoid circular dependencies.
     5  // These functions should be independent.
     6  
     7  import (
     8  	"encoding/json"
     9  	"github.com/stretchr/testify/assert"
    10  	"net/http"
    11  	"os"
    12  	"regexp"
    13  	"testing"
    14  )
    15  
    16  // Generic Router tests helper functions. To be invoked from
    17  // projects that defines the routes.
    18  
    19  // InvalidRouteTestHelper is a helper test function that just invokes
    20  // an invalid route
    21  func InvalidRouteTestHelper(t *testing.T) {
    22  	uri := "/1.0/invalidroute/"
    23  	myJWT := os.Getenv("IGN_TEST_JWT")
    24  	AssertRouteMultipleArgs("GET", uri, nil, http.StatusNotFound, &myJWT, "text/plain; charset=utf-8", t)
    25  	t.Log("InvalidRouteTestHelper run")
    26  }
    27  
    28  // OptionsTestHelper is a helper function to test the autogenerated OPTIONS
    29  // urls, given a set of Routes' URIs. This function should be called from each specific
    30  // project that defines routes.
    31  func OptionsTestHelper(uris []string, routenames []string, t *testing.T) {
    32  
    33  	for idx, uri := range uris {
    34  		// Create a valid url. We look for routes containing {path:[a-zA-Z0-9=\\-\\_\\/\\.\\+]+},
    35  		// and only keep the first part (ie. path)
    36  		re := regexp.MustCompile("{([^/]+)?:.+?}")
    37  		uri = re.ReplaceAllString(uri, "$1")
    38  		body, ok := AssertRoute("OPTIONS", uri, http.StatusOK, t)
    39  		t.Log("Detected uri:", uri)
    40  
    41  		var parsed map[string]interface{}
    42  		json.Unmarshal(*body, &parsed)
    43  		assert.True(t, ok, "OPTIONS %s request failed", uri)
    44  		assert.Equal(t, routenames[idx], parsed["name"],
    45  			"OPTIONS %s request returned invalid name. Exp: [%s], got: [%s]", uri,
    46  			routenames[idx], parsed["name"])
    47  	}
    48  }