forked from ipfs/go-ipfs-files
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwebfile_test.go
97 lines (83 loc) · 1.88 KB
/
webfile_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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package files
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
func TestWebFile(t *testing.T) {
const content = "Hello world!"
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, content)
}))
defer s.Close()
u, err := url.Parse(s.URL)
if err != nil {
t.Fatal(err)
}
wf := NewWebFile(u)
body, err := ioutil.ReadAll(wf)
if err != nil {
t.Fatal(err)
}
if string(body) != content {
t.Fatalf("expected %q but got %q", content, string(body))
}
}
func TestWebFile_notFound(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "File not found.", http.StatusNotFound)
}))
defer s.Close()
u, err := url.Parse(s.URL)
if err != nil {
t.Fatal(err)
}
wf := NewWebFile(u)
_, err = ioutil.ReadAll(wf)
if err == nil {
t.Fatal("expected error")
}
}
func TestWebFileSize(t *testing.T) {
body := "Hello world!"
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, body)
}))
defer s.Close()
u, err := url.Parse(s.URL)
if err != nil {
t.Fatal(err)
}
// Read size before reading file.
wf1 := NewWebFile(u)
if size, err := wf1.Size(); err != nil {
t.Error(err)
} else if int(size) != len(body) {
t.Errorf("expected size to be %d, got %d", len(body), size)
}
actual, err := ioutil.ReadAll(wf1)
if err != nil {
t.Fatal(err)
}
if string(actual) != body {
t.Fatal("should have read the web file")
}
wf1.Close()
// Read size after reading file.
wf2 := NewWebFile(u)
actual, err = ioutil.ReadAll(wf2)
if err != nil {
t.Fatal(err)
}
if string(actual) != body {
t.Fatal("should have read the web file")
}
if size, err := wf2.Size(); err != nil {
t.Error(err)
} else if int(size) != len(body) {
t.Errorf("expected size to be %d, got %d", len(body), size)
}
}