Merge branch 'master' into 2798-go-keep-client
[arvados.git] / sdk / go / src / arvados.org / keepclient / hashcheck_test.go
1 package keepclient
2
3 import (
4         "bytes"
5         "crypto/md5"
6         "fmt"
7         . "gopkg.in/check.v1"
8         "io"
9         "io/ioutil"
10 )
11
12 type HashcheckSuiteSuite struct{}
13
14 // Gocheck boilerplate
15 var _ = Suite(&HashcheckSuiteSuite{})
16
17 func (h *HashcheckSuiteSuite) TestRead(c *C) {
18         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
19
20         {
21                 r, w := io.Pipe()
22                 hcr := HashCheckingReader{r, md5.New(), hash}
23                 go func() {
24                         w.Write([]byte("foo"))
25                         w.Close()
26                 }()
27                 p, err := ioutil.ReadAll(hcr)
28                 c.Check(len(p), Equals, 3)
29                 c.Check(err, Equals, nil)
30         }
31
32         {
33                 r, w := io.Pipe()
34                 hcr := HashCheckingReader{r, md5.New(), hash}
35                 go func() {
36                         w.Write([]byte("bar"))
37                         w.Close()
38                 }()
39                 p, err := ioutil.ReadAll(hcr)
40                 c.Check(len(p), Equals, 3)
41                 c.Check(err, Equals, BadChecksum)
42         }
43 }
44
45 func (h *HashcheckSuiteSuite) TestWriteTo(c *C) {
46         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
47
48         {
49                 bb := bytes.NewBufferString("foo")
50                 hcr := HashCheckingReader{bb, md5.New(), hash}
51                 r, w := io.Pipe()
52                 done := make(chan bool)
53                 go func() {
54                         p, err := ioutil.ReadAll(r)
55                         c.Check(len(p), Equals, 3)
56                         c.Check(err, Equals, nil)
57                         done <- true
58                 }()
59
60                 n, err := hcr.WriteTo(w)
61                 w.Close()
62                 c.Check(n, Equals, int64(3))
63                 c.Check(err, Equals, nil)
64                 <-done
65         }
66
67         {
68                 bb := bytes.NewBufferString("bar")
69                 hcr := HashCheckingReader{bb, md5.New(), hash}
70                 r, w := io.Pipe()
71                 done := make(chan bool)
72                 go func() {
73                         p, err := ioutil.ReadAll(r)
74                         c.Check(len(p), Equals, 3)
75                         c.Check(err, Equals, nil)
76                         done <- true
77                 }()
78
79                 n, err := hcr.WriteTo(w)
80                 w.Close()
81                 c.Check(n, Equals, int64(3))
82                 c.Check(err, Equals, BadChecksum)
83                 <-done
84         }
85 }