github.com/prebid/prebid-server/v2@v2.18.0/util/stringutil/stringutil_test.go (about)

     1  package stringutil
     2  
     3  import (
     4  	"strconv"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestStrToInt8Slice(t *testing.T) {
    11  	type testOutput struct {
    12  		arr []int8
    13  		err error
    14  	}
    15  	tests := []struct {
    16  		desc     string
    17  		in       string
    18  		expected testOutput
    19  	}{
    20  		{
    21  			desc: "empty string, expect nil output array",
    22  			in:   "",
    23  			expected: testOutput{
    24  				arr: nil,
    25  				err: nil,
    26  			},
    27  		},
    28  		{
    29  			desc: "string doesn't contain digits, expect nil output array",
    30  			in:   "malformed",
    31  			expected: testOutput{
    32  				arr: nil,
    33  				err: &strconv.NumError{Func: "ParseInt", Num: "malformed", Err: strconv.ErrSyntax},
    34  			},
    35  		},
    36  		{
    37  			desc: "string contains int8 digits and non-digits, expect array with a single int8 element",
    38  			in:   "malformed,2,malformed",
    39  			expected: testOutput{
    40  				arr: nil,
    41  				err: &strconv.NumError{Func: "ParseInt", Num: "malformed", Err: strconv.ErrSyntax},
    42  			},
    43  		},
    44  		{
    45  			desc: "string comes with single digit too big to fit into a signed int8, expect nil output array",
    46  			in:   "128",
    47  			expected: testOutput{
    48  				arr: nil,
    49  				err: &strconv.NumError{Func: "ParseInt", Num: "128", Err: strconv.ErrRange},
    50  			},
    51  		},
    52  		{
    53  			desc: "string comes with single digit that fits into 8 bits, expect array with a single int8 element",
    54  			in:   "127",
    55  			expected: testOutput{
    56  				arr: []int8{int8(127)},
    57  				err: nil,
    58  			},
    59  		},
    60  		{
    61  			desc: "string comes with multiple, comma-separated numbers that fit into 8 bits, expect array with int8 elements",
    62  			in:   "127,2,-127",
    63  			expected: testOutput{
    64  				arr: []int8{int8(127), int8(2), int8(-127)},
    65  				err: nil,
    66  			},
    67  		},
    68  	}
    69  
    70  	for _, tt := range tests {
    71  		t.Run(tt.desc, func(t *testing.T) {
    72  			outArr, outErr := StrToInt8Slice(tt.in)
    73  			assert.Equal(t, tt.expected.arr, outArr, tt.desc)
    74  			assert.Equal(t, tt.expected.err, outErr, tt.desc)
    75  		})
    76  	}
    77  }