forked from viamrobotics/goutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio_test.go
95 lines (77 loc) · 2.2 KB
/
io_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
package utils
import (
"context"
"testing"
"github.com/pkg/errors"
"go.viam.com/test"
)
func TestTryClose(t *testing.T) {
// not a closer
test.That(t, TryClose(context.Background(), 5), test.ShouldBeNil)
stc := &somethingToClose{}
test.That(t, TryClose(context.Background(), stc), test.ShouldBeNil)
test.That(t, stc.called, test.ShouldEqual, 1)
stc.err = true
err := TryClose(context.Background(), stc)
test.That(t, err, test.ShouldNotBeNil)
test.That(t, err.Error(), test.ShouldContainSubstring, "whoops")
test.That(t, stc.called, test.ShouldEqual, 2)
stcc := &somethingToCloseContext{}
test.That(t, TryClose(context.Background(), stcc), test.ShouldBeNil)
test.That(t, stcc.called, test.ShouldEqual, 1)
stcc.err = true
err = TryClose(context.Background(), stcc)
test.That(t, err, test.ShouldNotBeNil)
test.That(t, err.Error(), test.ShouldContainSubstring, "whoops")
test.That(t, stcc.called, test.ShouldEqual, 2)
stcs := &somethingToCloseSimple{}
test.That(t, TryClose(context.Background(), stcs), test.ShouldBeNil)
test.That(t, stcs.called, test.ShouldEqual, 1)
}
type somethingToClose struct {
called int
err bool
}
func (stc *somethingToClose) Close() error {
stc.called++
if stc.err {
return errors.New("whoops")
}
return nil
}
type somethingToCloseContext struct {
called int
err bool
}
func (stc *somethingToCloseContext) Close(ctx context.Context) error {
stc.called++
if stc.err {
return errors.New("whoops")
}
return nil
}
type somethingToCloseSimple struct {
called int
}
func (stc *somethingToCloseSimple) Close() {
stc.called++
}
func TestReadBytes(t *testing.T) {
x, err := ReadBytes(context.Background(), &dummyReader{}, 4)
test.That(t, err, test.ShouldBeNil)
test.That(t, len(x), test.ShouldEqual, 4)
test.That(t, x[0], test.ShouldEqual, 0x5)
test.That(t, x[1], test.ShouldEqual, 0x5)
test.That(t, x[2], test.ShouldEqual, 0x5)
test.That(t, x[3], test.ShouldEqual, 0x5)
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = ReadBytes(ctx, &dummyReader{}, 4)
test.That(t, err, test.ShouldBeError, context.Canceled)
}
type dummyReader struct{}
func (r *dummyReader) Read(buf []byte) (int, error) {
buf[0] = 0x5
buf[1] = 0x5
return 2, nil
}