| 1 | // Copyright (c) The EfficientGo Authors. |
| 2 | // Licensed under the Apache License 2.0. |
| 3 | |
| 4 | // Initially copied from Thanos |
| 5 | // |
| 6 | // Copyright (c) The Thanos Authors. |
| 7 | // Licensed under the Apache License 2.0. |
| 8 | |
| 9 | package logerrcapture |
| 10 | |
| 11 | import ( |
| 12 | "io" |
| 13 | "os" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | |
| 17 | "github.com/efficientgo/core/errors" |
| 18 | "github.com/efficientgo/core/testutil" |
| 19 | ) |
| 20 | |
| 21 | type loggerCapturer struct { |
| 22 | // WasCalled is true if the Log() function has been called. |
| 23 | WasCalled bool |
| 24 | } |
| 25 | |
| 26 | func (lc *loggerCapturer) Log(keyvals ...interface{}) error { |
| 27 | lc.WasCalled = true |
| 28 | return nil |
| 29 | } |
| 30 | |
| 31 | type emulatedCloser struct { |
| 32 | io.Reader |
| 33 | |
| 34 | calls int |
| 35 | } |
| 36 | |
| 37 | func (e *emulatedCloser) Close() error { |
| 38 | e.calls++ |
| 39 | if e.calls == 1 { |
| 40 | return nil |
| 41 | } |
| 42 | if e.calls == 2 { |
| 43 | return errors.Wrap(os.ErrClosed, "can even be a wrapped one") |
| 44 | } |
| 45 | return errors.New("something very bad happened") |
| 46 | } |
| 47 | |
| 48 | // newEmulatedCloser returns a ReadCloser with a Close method |
| 49 | // that at first returns success but then returns that |
| 50 | // it has been closed already. After that, it returns that |
| 51 | // something very bad had happened. |
| 52 | func newEmulatedCloser(r io.Reader) io.ReadCloser { |
| 53 | return &emulatedCloser{Reader: r} |
| 54 | } |
| 55 | |
| 56 | func TestCloseMoreThanOnce(t *testing.T) { |
| 57 | lc := &loggerCapturer{} |
| 58 | r := newEmulatedCloser(strings.NewReader("somestring")) |
| 59 | |
| 60 | Do(lc, r.Close, "should not be called") |
| 61 | Do(lc, r.Close, "should not be called") |
| 62 | testutil.Equals(t, false, lc.WasCalled) |
| 63 | |
| 64 | Do(lc, r.Close, "should be called") |
| 65 | testutil.Equals(t, true, lc.WasCalled) |
| 66 | } |