github.com/cavaliergopher/grab/v3@v3.0.1/grab_test.go (about) 1 package grab 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "log" 7 "os" 8 "testing" 9 10 "github.com/cavaliergopher/grab/v3/pkg/grabtest" 11 ) 12 13 func TestMain(m *testing.M) { 14 os.Exit(func() int { 15 // chdir to temp so test files downloaded to pwd are isolated and cleaned up 16 cwd, err := os.Getwd() 17 if err != nil { 18 panic(err) 19 } 20 tmpDir, err := ioutil.TempDir("", "grab-") 21 if err != nil { 22 panic(err) 23 } 24 if err := os.Chdir(tmpDir); err != nil { 25 panic(err) 26 } 27 defer func() { 28 os.Chdir(cwd) 29 if err := os.RemoveAll(tmpDir); err != nil { 30 panic(err) 31 } 32 }() 33 return m.Run() 34 }()) 35 } 36 37 // TestGet tests grab.Get 38 func TestGet(t *testing.T) { 39 filename := ".testGet" 40 defer os.Remove(filename) 41 grabtest.WithTestServer(t, func(url string) { 42 resp, err := Get(filename, url) 43 if err != nil { 44 t.Fatalf("error in Get(): %v", err) 45 } 46 testComplete(t, resp) 47 }) 48 } 49 50 func ExampleGet() { 51 // download a file to /tmp 52 resp, err := Get("/tmp", "http://example.com/example.zip") 53 if err != nil { 54 log.Fatal(err) 55 } 56 57 fmt.Println("Download saved to", resp.Filename) 58 } 59 60 func mustNewRequest(dst, urlStr string) *Request { 61 req, err := NewRequest(dst, urlStr) 62 if err != nil { 63 panic(err) 64 } 65 return req 66 } 67 68 func mustDo(req *Request) *Response { 69 resp := DefaultClient.Do(req) 70 if err := resp.Err(); err != nil { 71 panic(err) 72 } 73 return resp 74 }