github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/shuffle/shuffle_test.go (about)

     1  // Copyright 2016 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package shuffle
    12  
    13  import (
    14  	"math/rand"
    15  	"reflect"
    16  	"testing"
    17  
    18  	"github.com/cockroachdb/cockroach/pkg/util/leaktest"
    19  )
    20  
    21  type testSlice []int
    22  
    23  // testSlice implements shuffle.Interface.
    24  func (ts testSlice) Len() int      { return len(ts) }
    25  func (ts testSlice) Swap(i, j int) { ts[i], ts[j] = ts[j], ts[i] }
    26  
    27  func TestShuffle(t *testing.T) {
    28  	defer leaktest.AfterTest(t)()
    29  	rand.Seed(0)
    30  
    31  	verify := func(original, expected testSlice) {
    32  		Shuffle(original)
    33  		if !reflect.DeepEqual(original, expected) {
    34  			t.Errorf("expected %v, got %v", expected, original)
    35  		}
    36  	}
    37  
    38  	ts := testSlice{}
    39  	verify(ts, testSlice{})
    40  	verify(ts, testSlice{})
    41  
    42  	ts = testSlice{1}
    43  	verify(ts, testSlice{1})
    44  	verify(ts, testSlice{1})
    45  
    46  	ts = testSlice{1, 2}
    47  	verify(ts, testSlice{2, 1})
    48  	verify(ts, testSlice{1, 2})
    49  
    50  	ts = testSlice{1, 2, 3}
    51  	verify(ts, testSlice{1, 3, 2})
    52  	verify(ts, testSlice{1, 2, 3})
    53  	verify(ts, testSlice{1, 2, 3})
    54  	verify(ts, testSlice{3, 1, 2})
    55  
    56  	ts = testSlice{1, 2, 3, 4, 5}
    57  	verify(ts, testSlice{2, 1, 3, 5, 4})
    58  	verify(ts, testSlice{4, 2, 1, 5, 3})
    59  	verify(ts, testSlice{1, 4, 2, 3, 5})
    60  	verify(ts, testSlice{2, 5, 4, 1, 3})
    61  	verify(ts, testSlice{4, 2, 3, 1, 5})
    62  
    63  	verify(ts[2:2], testSlice{})
    64  	verify(ts[0:0], testSlice{})
    65  	verify(ts[5:5], testSlice{})
    66  	verify(ts[3:5], testSlice{1, 5})
    67  	verify(ts[3:5], testSlice{5, 1})
    68  	verify(ts[0:2], testSlice{4, 2})
    69  	verify(ts[0:2], testSlice{2, 4})
    70  	verify(ts[1:4], testSlice{3, 5, 4})
    71  	verify(ts[1:4], testSlice{5, 4, 3})
    72  	verify(ts[0:4], testSlice{4, 5, 2, 3})
    73  	verify(ts[0:4], testSlice{2, 4, 3, 5})
    74  
    75  	verify(ts, testSlice{1, 3, 4, 2, 5})
    76  }