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