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