OSDN Git Service

265a3b903e94b975ded227d5f753678f7d883ffc
[pf3gnuchains/gcc-fork.git] / libgo / go / net / http / filetransport_test.go
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_test
6
7 import (
8         "io/ioutil"
9         "net/http"
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
32         tr := &http.Transport{}
33         tr.RegisterProtocol("file", http.NewFileTransport(http.Dir(dname)))
34         c := &http.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 := ioutil.ReadAll(res.Body)
50                 check("ReadAll "+urlstr, err)
51                 if string(slurp) != "Bar" {
52                         t.Errorf("for %s, got content %q, want %q", urlstr, string(slurp), "Bar")
53                 }
54         }
55
56         const badURL = "file://../no-exist.txt"
57         res, err := c.Get(badURL)
58         check("Get "+badURL, err)
59         if res.StatusCode != 404 {
60                 t.Errorf("for %s, StatusCode = %d, want 404", badURL, res.StatusCode)
61         }
62 }