github.com/peterdeka/grab@v2.0.0+incompatible/util_test.go (about) 1 package grab 2 3 import ( 4 "fmt" 5 "net/http" 6 "net/url" 7 "testing" 8 ) 9 10 func TestURLFilenames(t *testing.T) { 11 t.Run("Valid", func(t *testing.T) { 12 expect := "filename" 13 testCases := []string{ 14 "http://test.com/filename", 15 "http://test.com/path/filename", 16 "http://test.com/deep/path/filename", 17 "http://test.com/filename?with=args", 18 "http://test.com/filename#with-fragment", 19 } 20 21 for _, tc := range testCases { 22 req, _ := http.NewRequest("GET", tc, nil) 23 resp := &http.Response{ 24 Request: req, 25 } 26 actual, err := guessFilename(resp) 27 if err != nil { 28 t.Errorf("%v", err) 29 } 30 31 if actual != expect { 32 t.Errorf("expected '%v', got '%v'", expect, actual) 33 } 34 } 35 }) 36 37 t.Run("Invalid", func(t *testing.T) { 38 testCases := []string{ 39 "http://test.com", 40 "http://test.com/", 41 "http://test.com/filename/", 42 "http://test.com/filename/?with=args", 43 "http://test.com/filename/#with-fragment", 44 "http://test.com/filename\x00", 45 } 46 47 for _, tc := range testCases { 48 req, _ := http.NewRequest("GET", tc, nil) 49 resp := &http.Response{ 50 Request: req, 51 } 52 53 _, err := guessFilename(resp) 54 if err != ErrNoFilename { 55 t.Errorf("expected '%v', got '%v'", ErrNoFilename, err) 56 } 57 } 58 }) 59 } 60 61 func TestHeaderFilenames(t *testing.T) { 62 u, _ := url.ParseRequestURI("http://test.com/badfilename") 63 resp := &http.Response{ 64 Request: &http.Request{ 65 URL: u, 66 }, 67 Header: http.Header{}, 68 } 69 70 setFilename := func(resp *http.Response, filename string) { 71 resp.Header.Set("Content-Disposition", fmt.Sprintf("attachment;filename=\"%s\"", filename)) 72 } 73 74 t.Run("Valid", func(t *testing.T) { 75 expect := "filename" 76 testCases := []string{ 77 "filename", 78 "path/filename", 79 "/path/filename", 80 "../../filename", 81 "/path/../../filename", 82 "/../../././///filename", 83 } 84 85 for _, tc := range testCases { 86 setFilename(resp, tc) 87 actual, err := guessFilename(resp) 88 if err != nil { 89 t.Errorf("error (%v): %v", tc, err) 90 } 91 92 if actual != expect { 93 t.Errorf("expected '%v' (%v), got '%v'", expect, tc, actual) 94 } 95 } 96 }) 97 98 t.Run("Invalid", func(t *testing.T) { 99 testCases := []string{ 100 "", 101 "/", 102 ".", 103 "/.", 104 "/./", 105 "..", 106 "../", 107 "/../", 108 "/path/", 109 "../path/", 110 "filename\x00", 111 "filename/", 112 "filename//", 113 "filename/..", 114 } 115 116 for _, tc := range testCases { 117 setFilename(resp, tc) 118 if actual, err := guessFilename(resp); err != ErrNoFilename { 119 t.Errorf("expected: %v (%v), got: %v (%v)", ErrNoFilename, tc, err, actual) 120 } 121 } 122 }) 123 }