github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/net/http/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 http
     6  
     7  import (
     8  	"io/ioutil"
     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, err := ioutil.TempDir("", "")
    27  	check("TempDir", err)
    28  	fname := filepath.Join(dname, "foo.txt")
    29  	err = ioutil.WriteFile(fname, []byte("Bar"), 0644)
    30  	check("WriteFile", err)
    31  	defer os.Remove(dname)
    32  	defer os.Remove(fname)
    33  
    34  	tr := &Transport{}
    35  	tr.RegisterProtocol("file", NewFileTransport(Dir(dname)))
    36  	c := &Client{Transport: tr}
    37  
    38  	fooURLs := []string{"file:///foo.txt", "file://../foo.txt"}
    39  	for _, urlstr := range fooURLs {
    40  		res, err := c.Get(urlstr)
    41  		check("Get "+urlstr, err)
    42  		if res.StatusCode != 200 {
    43  			t.Errorf("for %s, StatusCode = %d, want 200", urlstr, res.StatusCode)
    44  		}
    45  		if res.ContentLength != -1 {
    46  			t.Errorf("for %s, ContentLength = %d, want -1", urlstr, res.ContentLength)
    47  		}
    48  		if res.Body == nil {
    49  			t.Fatalf("for %s, nil Body", urlstr)
    50  		}
    51  		slurp, err := ioutil.ReadAll(res.Body)
    52  		res.Body.Close()
    53  		check("ReadAll "+urlstr, err)
    54  		if string(slurp) != "Bar" {
    55  			t.Errorf("for %s, got content %q, want %q", urlstr, string(slurp), "Bar")
    56  		}
    57  	}
    58  
    59  	const badURL = "file://../no-exist.txt"
    60  	res, err := c.Get(badURL)
    61  	check("Get "+badURL, err)
    62  	if res.StatusCode != 404 {
    63  		t.Errorf("for %s, StatusCode = %d, want 404", badURL, res.StatusCode)
    64  	}
    65  	res.Body.Close()
    66  }