From de8493db4b3e06921c3ee97fa0b200435a8a796d Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 6 Nov 2018 11:34:39 +0100 Subject: [PATCH] Added 100% coverage test for cancelableReader --- cancelable_reader_test.go | 63 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 cancelable_reader_test.go diff --git a/cancelable_reader_test.go b/cancelable_reader_test.go new file mode 100644 index 0000000..80e56fe --- /dev/null +++ b/cancelable_reader_test.go @@ -0,0 +1,63 @@ +package extract + +import ( + "bytes" + "context" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestCancelableReader(t *testing.T) { + var b [100000]byte + ctx, cancel := context.WithCancel(context.Background()) + reader := newCancelableReader(ctx, bytes.NewReader(b[:])) + defer cancel() + + var buff [1000]byte + readed := 0 + for { + n, err := reader.Read(buff[:]) + if err != nil { + fmt.Println("exit error:", err) + require.Equal(t, "EOF", err.Error()) + break + } + require.NotZero(t, n) + time.Sleep(10 * time.Millisecond) + readed += n + } + + fmt.Println("Readed", readed, "out of", len(b)) + require.Equal(t, len(b), readed) +} + +func TestCancelableReaderWithInterruption(t *testing.T) { + var b [100000]byte + ctx, cancel := context.WithCancel(context.Background()) + reader := newCancelableReader(ctx, bytes.NewReader(b[:])) + defer cancel() + + go func() { + time.Sleep(100 * time.Millisecond) + cancel() + }() + + var buff [1000]byte + readed := 0 + for { + n, err := reader.Read(buff[:]) + if err != nil { + fmt.Println("exit error:", err) + require.Equal(t, "interrupted", err.Error()) + break + } + require.NotZero(t, n) + time.Sleep(10 * time.Millisecond) + readed += n + } + fmt.Println("Readed", readed, "out of", len(b)) + require.True(t, readed < len(b)) +}