github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmhttp/filetransport_test.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package gmhttp 6 7 import ( 8 "io" 9 "os" 10 "path/filepath" 11 "testing" 12 ) 13 14 func checker(t *testing.T) func(string, error) { 15 return func(call string, err error) { 16 if err == nil { 17 return 18 } 19 t.Fatalf("%s: %v", call, err) 20 } 21 } 22 23 func TestFileTransport(t *testing.T) { 24 check := checker(t) 25 26 dname := t.TempDir() 27 fname := filepath.Join(dname, "foo.txt") 28 err := os.WriteFile(fname, []byte("Bar"), 0644) 29 check("WriteFile", err) 30 defer os.Remove(fname) 31 32 tr := &Transport{} 33 tr.RegisterProtocol("file", NewFileTransport(Dir(dname))) 34 c := &Client{Transport: tr} 35 36 fooURLs := []string{"file:///foo.txt", "file://../foo.txt"} 37 for _, urlstr := range fooURLs { 38 res, err := c.Get(urlstr) 39 check("Get "+urlstr, err) 40 if res.StatusCode != 200 { 41 t.Errorf("for %s, StatusCode = %d, want 200", urlstr, res.StatusCode) 42 } 43 if res.ContentLength != -1 { 44 t.Errorf("for %s, ContentLength = %d, want -1", urlstr, res.ContentLength) 45 } 46 if res.Body == nil { 47 t.Fatalf("for %s, nil Body", urlstr) 48 } 49 slurp, err := io.ReadAll(res.Body) 50 res.Body.Close() 51 check("ReadAll "+urlstr, err) 52 if string(slurp) != "Bar" { 53 t.Errorf("for %s, got content %q, want %q", urlstr, string(slurp), "Bar") 54 } 55 } 56 57 const badURL = "file://../no-exist.txt" 58 res, err := c.Get(badURL) 59 check("Get "+badURL, err) 60 if res.StatusCode != 404 { 61 t.Errorf("for %s, StatusCode = %d, want 404", badURL, res.StatusCode) 62 } 63 res.Body.Close() 64 }