|
| 1 | +package io |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/stretchr/testify/assert" |
| 10 | + "github.com/stretchr/testify/require" |
| 11 | +) |
| 12 | + |
| 13 | +func TestCopy(t *testing.T) { |
| 14 | + t.Run("successful copy", func(t *testing.T) { |
| 15 | + ctx := t.Context() |
| 16 | + src := strings.NewReader("hello world") |
| 17 | + dst := &bytes.Buffer{} |
| 18 | + |
| 19 | + n, err := Copy(ctx, dst, src) |
| 20 | + require.NoError(t, err) |
| 21 | + assert.Equal(t, int64(11), n) |
| 22 | + assert.Equal(t, "hello world", dst.String()) |
| 23 | + }) |
| 24 | + |
| 25 | + t.Run("context canceled before read", func(t *testing.T) { |
| 26 | + ctx, cancel := context.WithCancel(t.Context()) |
| 27 | + cancel() // Cancel immediately |
| 28 | + |
| 29 | + src := strings.NewReader("hello world") |
| 30 | + dst := &bytes.Buffer{} |
| 31 | + |
| 32 | + n, err := Copy(ctx, dst, src) |
| 33 | + require.ErrorIs(t, err, context.Canceled) |
| 34 | + assert.Equal(t, int64(0), n) |
| 35 | + assert.Empty(t, dst.String()) |
| 36 | + }) |
| 37 | + |
| 38 | + t.Run("context canceled during read", func(t *testing.T) { |
| 39 | + ctx, cancel := context.WithCancel(t.Context()) |
| 40 | + |
| 41 | + // Create a reader that will be canceled after first read |
| 42 | + reader := &dummyReader{ |
| 43 | + cancel: cancel, // Cancel after first read |
| 44 | + } |
| 45 | + dst := &bytes.Buffer{} |
| 46 | + |
| 47 | + n, err := Copy(ctx, dst, reader) |
| 48 | + require.ErrorIs(t, err, context.Canceled) |
| 49 | + // Should have written first chunk before cancellation |
| 50 | + assert.Equal(t, int64(5), n) |
| 51 | + assert.Equal(t, "dummy", dst.String()) |
| 52 | + }) |
| 53 | +} |
| 54 | + |
| 55 | +// dummyReader returns the same data on every Read call |
| 56 | +type dummyReader struct { |
| 57 | + cancel context.CancelFunc |
| 58 | +} |
| 59 | + |
| 60 | +func (r *dummyReader) Read(p []byte) (int, error) { |
| 61 | + n := copy(p, "dummy") |
| 62 | + if r.cancel != nil { |
| 63 | + r.cancel() // Simulate cancellation after first read |
| 64 | + } |
| 65 | + return n, nil |
| 66 | +} |
0 commit comments