Codebase list golang-github-vbauerster-mpb / 7ddc3ae
ProxyReader tests Vladimir Bauer 9 years ago
1 changed file(s) with 88 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 package mpb_test
1
2 import (
3 "bytes"
4 "io"
5 "io/ioutil"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10
11 "github.com/vbauerster/mpb"
12 )
13
14 const content = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
15 eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
16 veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
17 commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
18 esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
19 cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
20 est laborum.`
21
22 func TestProxyReader(t *testing.T) {
23 var buf bytes.Buffer
24 p := mpb.New().SetOut(&buf)
25
26 reader := strings.NewReader(content)
27
28 total := int64(len(content))
29 bar := p.AddBar(total).TrimLeftSpace().TrimRightSpace()
30 preader := bar.ProxyReader(reader)
31
32 written, err := io.Copy(ioutil.Discard, preader)
33 if err != nil {
34 t.Errorf("Error copying from reader: %+v\n", err)
35 }
36
37 p.Stop()
38
39 if written != total {
40 t.Errorf("Expected written: %d, got: %d\n", total, written)
41 }
42
43 // underlying reader is not Closer
44 err = preader.Close()
45 if err != nil {
46 t.Errorf("Expected nil error, got: %+v\n", err)
47 }
48 }
49
50 func TestProxyReaderCloser(t *testing.T) {
51 var buf bytes.Buffer
52 p := mpb.New().SetOut(&buf)
53
54 ts := setupTestHttpServer(content)
55 defer ts.Close()
56
57 url := ts.URL + "/test"
58 resp, err := http.Get(url)
59 if err != nil {
60 t.Errorf("Test server get failure: %s\n", url)
61 }
62
63 total := resp.ContentLength
64 bar := p.AddBar(total).TrimLeftSpace().TrimRightSpace()
65 reader := bar.ProxyReader(resp.Body)
66
67 // calling reader.Close() will call resp.Body.Close() implicitly
68 err = reader.Close()
69 if err != nil {
70 t.Logf("Error closing resp.Body over reader.Close: %+v\n", err)
71 t.FailNow()
72 }
73
74 // reading from closed resp.Body
75 _, err = io.Copy(ioutil.Discard, reader)
76 if err == nil {
77 t.Error("Expected read on closed response body error!")
78 }
79 }
80
81 func setupTestHttpServer(content string) *httptest.Server {
82 mux := http.NewServeMux()
83 mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
84 io.WriteString(w, content)
85 })
86 return httptest.NewServer(mux)
87 }