github.com/0chain/gosdk@v1.17.11/core/common/math_test.go (about)

     1  package common
     2  
     3  import (
     4  	"math"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  func TestMathAddInt(t *testing.T) {
    11  	a := math.MaxInt
    12  	b := 1
    13  
    14  	_, err := TryAddInt(a, b)
    15  	require.NotNil(t, err)
    16  
    17  	tests := []struct {
    18  		name    string
    19  		a       int
    20  		b       int
    21  		result  int
    22  		wantErr bool
    23  	}{
    24  		{
    25  			name:    "greater than MaxInt must be overflow",
    26  			a:       math.MaxInt,
    27  			b:       1,
    28  			wantErr: true,
    29  		},
    30  		{
    31  			name:   "equal to MaxInt must not be overflow",
    32  			a:      math.MaxInt - 1,
    33  			b:      1,
    34  			result: math.MaxInt,
    35  		},
    36  		{
    37  			name:   "less than MaxInt must not be overflow",
    38  			a:      math.MaxInt - 2,
    39  			b:      1,
    40  			result: math.MaxInt - 1,
    41  		},
    42  		{
    43  			name:   "greater than MinInt must not be underflow",
    44  			a:      math.MinInt,
    45  			b:      1,
    46  			result: math.MinInt + 1,
    47  		},
    48  		{
    49  			name:   "equal to MinInt should not be underflow",
    50  			a:      math.MinInt + 1,
    51  			b:      -1,
    52  			result: math.MinInt,
    53  		},
    54  		{
    55  			name:    "less than MinInt must be underflow",
    56  			a:       math.MinInt,
    57  			b:       -1,
    58  			wantErr: true,
    59  		},
    60  	}
    61  
    62  	for _, test := range tests {
    63  
    64  		t.Run(test.name, func(t *testing.T) {
    65  
    66  			i, err := TryAddInt(test.a, test.b)
    67  			if test.wantErr {
    68  				require.NotNil(t, err)
    69  			}
    70  
    71  			require.Equal(t, test.result, i)
    72  
    73  		})
    74  
    75  	}
    76  
    77  }