| 1 | package corehttp |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | |
| 8 | protocol "github.com/libp2p/go-libp2p/core/protocol" |
| 9 | "github.com/stretchr/testify/require" |
| 10 | ) |
| 11 | |
| 12 | type TestCase struct { |
| 13 | urlprefix string |
| 14 | target string |
| 15 | name string |
| 16 | path string |
| 17 | } |
| 18 | |
| 19 | var validtestCases = []TestCase{ |
| 20 | {"http://localhost:5001", "QmT8JtU54XSmC38xSb1XHFSMm775VuTeajg7LWWWTAwzxT", "/http", "path/to/index.txt"}, |
| 21 | {"http://localhost:5001", "QmT8JtU54XSmC38xSb1XHFSMm775VuTeajg7LWWWTAwzxT", "/x/custom/http", "path/to/index.txt"}, |
| 22 | {"http://localhost:5001", "QmT8JtU54XSmC38xSb1XHFSMm775VuTeajg7LWWWTAwzxT", "/x/custom/http", "http/path/to/index.txt"}, |
| 23 | } |
| 24 | |
| 25 | func TestParseRequest(t *testing.T) { |
| 26 | for _, tc := range validtestCases { |
| 27 | url := tc.urlprefix + "/p2p/" + tc.target + tc.name + "/" + tc.path |
| 28 | req, _ := http.NewRequest(http.MethodGet, url, strings.NewReader("")) |
| 29 | |
| 30 | parsed, err := parseRequest(req) |
| 31 | require.NoError(t, err) |
| 32 | require.Equal(t, tc.path, parsed.httpPath, "proxy request path") |
| 33 | require.Equal(t, protocol.ID(tc.name), parsed.name, "proxy request name") |
| 34 | require.Equal(t, tc.target, parsed.target, "proxy request peer-id") |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | var invalidtestCases = []string{ |
| 39 | "http://localhost:5001/p2p/http/foobar", |
| 40 | "http://localhost:5001/p2p/QmT8JtU54XSmC38xSb1XHFSMm775VuTeajg7LWWWTAwzxT/x/custom/foobar", |
| 41 | } |
| 42 | |
| 43 | func TestParseRequestInvalidPath(t *testing.T) { |
| 44 | for _, tc := range invalidtestCases { |
| 45 | url := tc |
| 46 | req, _ := http.NewRequest(http.MethodGet, url, strings.NewReader("")) |
| 47 | |
| 48 | _, err := parseRequest(req) |
| 49 | require.Error(t, err) |
| 50 | } |
| 51 | } |