1// Copyright (C) 2013-2015 Sören Tempel 2// 3// This program is free software: you can redistribute it and/or modify 4// it under the terms of the GNU General Public License as published by 5// the Free Software Foundation, either version 3 of the License, or 6// (at your option) any later version. 7// 8// This program is distributed in the hope that it will be useful, 9// but WITHOUT ANY WARRANTY; without even the implied warranty of 10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11// GNU General Public License for more details. 12// 13// You should have received a copy of the GNU General Public License 14// along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16package util 17 18import ( 19 "fmt" 20 "io/ioutil" 21 "net/http" 22 "net/http/httptest" 23 "os" 24 "testing" 25) 26 27type testpair struct { 28 inputData string 29 expected string 30} 31 32func TestFilename(t *testing.T) { 33 testpairs := []testpair{ 34 {"http://example.com/foo/bar/foo/bar/foo.mp3", "foo.mp3"}, 35 {"http://example.com/bar.opus?foo=bar&bar=foo", "bar.opus"}, 36 {"http://example.org/foobar ", "foobar"}, 37 {"http://example.com/", "unnamed"}, 38 {"http://example.com", "unnamed"}, 39 {"", "unnamed"}, 40 } 41 42 for _, p := range testpairs { 43 f, err := filename(p.inputData) 44 if err != nil { 45 t.Fatal(err) 46 } 47 48 if f != p.expected { 49 t.Fatalf("Expected %q - got %q", p.expected, f) 50 } 51 } 52} 53 54func TestGet(t *testing.T) { 55 expected := "Success\n" 56 th := func(w http.ResponseWriter, r *http.Request) { 57 fmt.Fprintf(w, expected) 58 } 59 60 ts := httptest.NewServer(http.HandlerFunc(th)) 61 defer ts.Close() 62 63 resp, err := Get(ts.URL) 64 if err != nil { 65 t.Fatal(err) 66 } 67 defer resp.Body.Close() 68 69 data, err := ioutil.ReadAll(resp.Body) 70 if err != nil { 71 t.Fatal(err) 72 } 73 74 result := string(data) 75 if result != expected { 76 t.Fatalf("Expected %q - got %q", expected, result) 77 } 78} 79 80func TestGetFile1(t *testing.T) { 81 expected := "Hello World!\n" 82 th := func(w http.ResponseWriter, r *http.Request) { 83 fmt.Fprintf(w, expected) 84 } 85 86 ts := httptest.NewServer(http.HandlerFunc(th)) 87 defer ts.Close() 88 89 fp, err := GetFile(ts.URL, os.TempDir()) 90 if err != nil { 91 t.Fatal(err) 92 } 93 defer os.Remove(fp) 94 95 data, err := ioutil.ReadFile(fp) 96 if err != nil { 97 t.Fatal(err) 98 } 99100 result := string(data)101 if result != expected {102 t.Fatalf("Expected %q - got %q", expected, result)103 }104}