github.com/mailgun/holster/v4@v4.20.0/random/random_test.go (about)

     1  package random
     2  
     3  import (
     4  	"fmt"
     5  	"math/rand"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestString(t *testing.T) {
    13  	rand.Seed(time.Now().UnixNano())
    14  	for _, tc := range []struct {
    15  		msg            string
    16  		prefix         string
    17  		length         int
    18  		contains       string
    19  		expectedLength int
    20  	}{{
    21  		msg:            "only made of alpha and numeric characters",
    22  		prefix:         "",
    23  		length:         10,
    24  		contains:       AlphaRunes + NumericRunes,
    25  		expectedLength: 10,
    26  	}, {
    27  		msg:            "with prefix and add to length",
    28  		prefix:         "abc",
    29  		length:         5,
    30  		contains:       AlphaRunes + NumericRunes,
    31  		expectedLength: 5 + 3, // = len("abc")
    32  	}} {
    33  		t.Run(tc.msg, func(t *testing.T) {
    34  			res := String(tc.prefix, tc.length)
    35  			assert.Equal(t, tc.expectedLength, len(res))
    36  			assert.Contains(t, res, tc.prefix)
    37  			for _, ch := range res {
    38  				assert.Contains(t, tc.contains, fmt.Sprintf("%c", ch))
    39  			}
    40  		})
    41  	}
    42  }
    43  
    44  func TestAlpha(t *testing.T) {
    45  	rand.Seed(time.Now().UnixNano())
    46  	for _, tc := range []struct {
    47  		msg            string
    48  		prefix         string
    49  		length         int
    50  		contains       string
    51  		expectedLength int
    52  	}{{
    53  		msg:            "only made of alpha characters",
    54  		prefix:         "",
    55  		length:         10,
    56  		contains:       AlphaRunes,
    57  		expectedLength: 10,
    58  	}, {
    59  		msg:            "with prefix and add to length",
    60  		prefix:         "abc",
    61  		length:         5,
    62  		contains:       AlphaRunes,
    63  		expectedLength: 5 + 3, // = len("abc")
    64  	}} {
    65  		t.Run(tc.msg, func(t *testing.T) {
    66  			res := Alpha(tc.prefix, tc.length)
    67  			assert.Equal(t, tc.expectedLength, len(res))
    68  			assert.Contains(t, res, tc.prefix)
    69  			for _, ch := range res {
    70  				assert.Contains(t, tc.contains, fmt.Sprintf("%c", ch))
    71  			}
    72  		})
    73  	}
    74  }
    75  
    76  func TestItem(t *testing.T) {
    77  	rand.Seed(time.Now().UnixNano())
    78  	for _, tc := range []struct {
    79  		msg      string
    80  		items    []string
    81  		expected string
    82  	}{{
    83  		msg:   "one of the given list",
    84  		items: []string{"com", "net", "org"},
    85  	}} {
    86  		t.Run(tc.msg, func(t *testing.T) {
    87  			res := Item(tc.items...)
    88  			assert.Contains(t, tc.items, res)
    89  		})
    90  	}
    91  }