github.com/rclone/rclone@v1.66.1-0.20240517100346-7b89735ae726/lib/rest/url_test.go (about)

     1  package rest
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestURLJoin(t *testing.T) {
    13  	for i, test := range []struct {
    14  		base   string
    15  		path   string
    16  		wantOK bool
    17  		want   string
    18  	}{
    19  		{"http://example.com/", "potato", true, "http://example.com/potato"},
    20  		{"http://example.com/dir/", "potato", true, "http://example.com/dir/potato"},
    21  		{"http://example.com/dir/", "../dir/potato", true, "http://example.com/dir/potato"},
    22  		{"http://example.com/dir/", "..", true, "http://example.com/"},
    23  		{"http://example.com/dir/", "http://example.com/", true, "http://example.com/"},
    24  		{"http://example.com/dir/", "http://example.com/dir/", true, "http://example.com/dir/"},
    25  		{"http://example.com/dir/", "http://example.com/dir/potato", true, "http://example.com/dir/potato"},
    26  		{"http://example.com/dir/", "/dir/", true, "http://example.com/dir/"},
    27  		{"http://example.com/dir/", "/dir/potato", true, "http://example.com/dir/potato"},
    28  		{"http://example.com/dir/", "subdir/potato", true, "http://example.com/dir/subdir/potato"},
    29  		{"http://example.com/dir/", "With percent %25.txt", true, "http://example.com/dir/With%20percent%20%25.txt"},
    30  		{"http://example.com/dir/", "With colon :", false, ""},
    31  		{"http://example.com/dir/", URLPathEscape("With colon :"), true, "http://example.com/dir/With%20colon%20:"},
    32  	} {
    33  		u, err := url.Parse(test.base)
    34  		require.NoError(t, err)
    35  		got, err := URLJoin(u, test.path)
    36  		gotOK := err == nil
    37  		what := fmt.Sprintf("test %d base=%q, val=%q", i, test.base, test.path)
    38  		assert.Equal(t, test.wantOK, gotOK, what)
    39  		var gotString string
    40  		if gotOK {
    41  			gotString = got.String()
    42  		}
    43  		assert.Equal(t, test.want, gotString, what)
    44  	}
    45  }
    46  
    47  func TestURLPathEscape(t *testing.T) {
    48  	for i, test := range []struct {
    49  		path string
    50  		want string
    51  	}{
    52  		{"", ""},
    53  		{"/hello.txt", "/hello.txt"},
    54  		{"With Space", "With%20Space"},
    55  		{"With Colon:", "./With%20Colon:"},
    56  		{"With Percent%", "With%20Percent%25"},
    57  	} {
    58  		got := URLPathEscape(test.path)
    59  		assert.Equal(t, test.want, got, fmt.Sprintf("Test %d path = %q", i, test.path))
    60  	}
    61  }