|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/stretchr/testify/require" |
| 7 | +) |
| 8 | + |
| 9 | +func TestOurByteBuffer_Table(t *testing.T) { |
| 10 | + for name, tc := range map[string]struct { |
| 11 | + initialContent string |
| 12 | + operations []operation |
| 13 | + }{ |
| 14 | + "read_initial_bytes": { |
| 15 | + initialContent: "hello", |
| 16 | + operations: []operation{ |
| 17 | + &bytesOperation{ |
| 18 | + wantValue: "hello", |
| 19 | + }, |
| 20 | + }, |
| 21 | + }, |
| 22 | + "subsequent_writes_are_appended": { |
| 23 | + initialContent: "hello", |
| 24 | + operations: []operation{ |
| 25 | + &writeOperation{ |
| 26 | + value: " world", |
| 27 | + }, |
| 28 | + &bytesOperation{ |
| 29 | + wantValue: "hello world", |
| 30 | + }, |
| 31 | + }, |
| 32 | + }, |
| 33 | + "read_oversized_slice": { |
| 34 | + initialContent: "hello world", |
| 35 | + operations: []operation{ |
| 36 | + &readOperation{ |
| 37 | + bufferSize: 50, |
| 38 | + wantValue: "hello world", |
| 39 | + }, |
| 40 | + }, |
| 41 | + }, |
| 42 | + "read_undersized_slices": { |
| 43 | + initialContent: "hello world", |
| 44 | + operations: []operation{ |
| 45 | + &readOperation{ |
| 46 | + bufferSize: 6, |
| 47 | + wantValue: "hello ", |
| 48 | + }, |
| 49 | + &readOperation{ |
| 50 | + bufferSize: 5, |
| 51 | + wantValue: "world", |
| 52 | + }, |
| 53 | + }, |
| 54 | + }, |
| 55 | + } { |
| 56 | + t.Run(name, func(t *testing.T) { |
| 57 | + b := NewBufferString(tc.initialContent) |
| 58 | + for _, operation := range tc.operations { |
| 59 | + operation.Do(t, &b) |
| 60 | + } |
| 61 | + }) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +type operation interface { |
| 66 | + Do(t *testing.T, b *OurByteBuffer) |
| 67 | +} |
| 68 | + |
| 69 | +type readOperation struct { |
| 70 | + bufferSize int |
| 71 | + wantValue string |
| 72 | +} |
| 73 | + |
| 74 | +func (o *readOperation) Do(t *testing.T, b *OurByteBuffer) { |
| 75 | + t.Helper() |
| 76 | + buf := make([]byte, o.bufferSize) |
| 77 | + n, err := b.Read(buf) |
| 78 | + require.NoError(t, err) |
| 79 | + require.Equal(t, len(o.wantValue), n) |
| 80 | + require.Equal(t, o.wantValue, string(buf[:n])) |
| 81 | +} |
| 82 | + |
| 83 | +type writeOperation struct { |
| 84 | + value string |
| 85 | +} |
| 86 | + |
| 87 | +func (o *writeOperation) Do(t *testing.T, b *OurByteBuffer) { |
| 88 | + t.Helper() |
| 89 | + n, err := b.Write([]byte(o.value)) |
| 90 | + require.NoError(t, err) |
| 91 | + require.Equal(t, len(o.value), n) |
| 92 | +} |
| 93 | + |
| 94 | +type bytesOperation struct { |
| 95 | + wantValue string |
| 96 | +} |
| 97 | + |
| 98 | +func (o *bytesOperation) Do(t *testing.T, b *OurByteBuffer) { |
| 99 | + t.Helper() |
| 100 | + got := string(b.Bytes()) |
| 101 | + require.Equal(t, o.wantValue, got) |
| 102 | +} |
0 commit comments