github.com/msales/pkg/v3@v3.24.0/bytes/buffer_test.go (about)

     1  package bytes_test
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/msales/pkg/v3/bytes"
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestPool(t *testing.T) {
    13  	const dummyData = "dummy data"
    14  
    15  	p := bytes.NewPool(512)
    16  
    17  	var wg sync.WaitGroup
    18  	for i := 0; i < 10; i++ {
    19  		wg.Add(1)
    20  		go func() {
    21  			defer wg.Done()
    22  
    23  			for i := 0; i < 100; i++ {
    24  				buf := p.Get()
    25  				assert.Zero(t, buf.Len(), "Expected truncated buffer")
    26  				assert.NotZero(t, buf.Cap(), "Expected non-zero capacity")
    27  
    28  				buf.WriteString(dummyData)
    29  
    30  				assert.Equal(t, buf.Len(), len(dummyData), "Expected buffer to contain dummy data")
    31  
    32  				p.Put(buf)
    33  			}
    34  		}()
    35  	}
    36  
    37  	wg.Wait()
    38  }
    39  
    40  func TestBuffer(t *testing.T) {
    41  	buf := bytes.NewPool(512).Get()
    42  
    43  	tests := []struct {
    44  		name string
    45  		fn   func()
    46  		want string
    47  	}{
    48  		{
    49  			name: "WriteByte",
    50  			fn:   func() { buf.WriteByte('v') },
    51  			want: "v",
    52  		},
    53  		{
    54  			name: "WriteString",
    55  			fn:   func() { buf.WriteString("foo") },
    56  			want: "foo",
    57  		},
    58  		{
    59  			name: "Write",
    60  			fn:   func() { buf.Write([]byte("foo")) },
    61  			want: "foo",
    62  		},
    63  		{
    64  			name: "AppendIntPositive",
    65  			fn:   func() { buf.AppendInt(42) }, want: "42",
    66  		},
    67  		{
    68  			name: "AppendIntNegative",
    69  			fn:   func() { buf.AppendInt(-42) }, want: "-42",
    70  		},
    71  		{
    72  			name: "AppendUint",
    73  			fn:   func() { buf.AppendUint(42) }, want: "42",
    74  		},
    75  		{
    76  			name: "AppendBool",
    77  			fn:   func() { buf.AppendBool(true) }, want: "true",
    78  		},
    79  		{
    80  			name: "AppendFloat64",
    81  			fn:   func() { buf.AppendFloat(3.14, 'f', 3, 64) },
    82  			want: "3.140",
    83  		},
    84  		{
    85  			name: "AppendTime",
    86  			fn:   func() { buf.AppendTime(time.Unix(1541573670, 0).UTC(), time.RFC3339) },
    87  			want: "2018-11-07T06:54:30Z",
    88  		},
    89  	}
    90  
    91  	assert.Equal(t, 512, buf.Cap())
    92  
    93  	for _, tt := range tests {
    94  		t.Run(tt.name, func(t *testing.T) {
    95  			buf.Reset()
    96  
    97  			tt.fn()
    98  
    99  			assert.Equal(t, tt.want, buf.String())
   100  			assert.Equal(t, tt.want, string(buf.Bytes()))
   101  			assert.Equal(t, len(tt.want), buf.Len())
   102  		})
   103  	}
   104  }