...

Source file src/github.com/go-chi/chi/context_test.go

Documentation: github.com/go-chi/chi

     1  package chi
     2  
     3  import "testing"
     4  
     5  // TestRoutePattern tests correct in-the-middle wildcard removals.
     6  // If user organizes a router like this:
     7  //
     8  // (router.go)
     9  // r.Route("/v1", func(r chi.Router) {
    10  // 	r.Mount("/resources", resourcesController{}.Router())
    11  // }
    12  //
    13  // (resources_controller.go)
    14  // r.Route("/", func(r chi.Router) {
    15  // 	r.Get("/{resource_id}", getResource())
    16  // 	other routes...
    17  // }
    18  //
    19  // This test checks how the route pattern is calculated
    20  // "/v1/resources/{resource_id}" (right)
    21  // "/v1/resources/*/{resource_id}" (wrong)
    22  func TestRoutePattern(t *testing.T) {
    23  	routePatterns := []string{
    24  		"/v1/*",
    25  		"/resources/*",
    26  		"/{resource_id}",
    27  	}
    28  
    29  	x := &Context{
    30  		RoutePatterns: routePatterns,
    31  	}
    32  
    33  	if p := x.RoutePattern(); p != "/v1/resources/{resource_id}" {
    34  		t.Fatal("unexpected route pattern: " + p)
    35  	}
    36  
    37  	x.RoutePatterns = []string{
    38  		"/v1/*",
    39  		"/resources/*",
    40  		// Additional wildcard, depending on the router structure of the user
    41  		"/*",
    42  		"/{resource_id}",
    43  	}
    44  
    45  	// Correctly removes in-the-middle wildcards instead of "/v1/resources/*/{resource_id}"
    46  	if p := x.RoutePattern(); p != "/v1/resources/{resource_id}" {
    47  		t.Fatal("unexpected route pattern: " + p)
    48  	}
    49  
    50  	x.RoutePatterns = []string{
    51  		"/v1/*",
    52  		"/resources/*",
    53  		// Even with many wildcards
    54  		"/*",
    55  		"/*",
    56  		"/*",
    57  		"/{resource_id}/*", // Keeping trailing wildcard
    58  	}
    59  
    60  	// Correctly removes in-the-middle wildcards instead of "/v1/resources/*/*/{resource_id}/*"
    61  	if p := x.RoutePattern(); p != "/v1/resources/{resource_id}/*" {
    62  		t.Fatal("unexpected route pattern: " + p)
    63  	}
    64  
    65  	x.RoutePatterns = []string{
    66  		"/v1/*",
    67  		"/resources/*",
    68  		// And respects asterisks as part of the paths
    69  		"/*special_path/*",
    70  		"/with_asterisks*/*",
    71  		"/{resource_id}",
    72  	}
    73  
    74  	// Correctly removes in-the-middle wildcards instead of "/v1/resourcesspecial_path/with_asterisks{resource_id}"
    75  	if p := x.RoutePattern(); p != "/v1/resources/*special_path/with_asterisks*/{resource_id}" {
    76  		t.Fatal("unexpected route pattern: " + p)
    77  	}
    78  }
    79  

View as plain text