go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/tokenserver/appengine/impl/utils/shards/shards_test.go (about)

     1  // Copyright 2016 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package shards
    16  
    17  import (
    18  	"fmt"
    19  	"testing"
    20  
    21  	. "github.com/smartystreets/goconvey/convey"
    22  )
    23  
    24  func TestShards(t *testing.T) {
    25  	Convey("Build shards, serialize and deserialize", t, func() {
    26  		// Build sharded set of 500 strings.
    27  		set := make(Set, 10)
    28  		for i := 0; i < 500; i++ {
    29  			set.Insert([]byte(fmt.Sprintf("blob #%d", i)))
    30  		}
    31  
    32  		// Read same strings. Should be noop, they are already in the set.
    33  		for i := 0; i < 500; i++ {
    34  			set.Insert([]byte(fmt.Sprintf("blob #%d", i)))
    35  		}
    36  
    37  		// Make sure shards are balanced, and all data is there.
    38  		totalLen := 0
    39  		for _, shard := range set {
    40  			So(len(shard), ShouldBeGreaterThan, 45)
    41  			So(len(shard), ShouldBeLessThan, 55)
    42  			totalLen += len(shard)
    43  		}
    44  		So(totalLen, ShouldEqual, 500)
    45  
    46  		// Serialize and deserialize first shard, should be left unchanged.
    47  		shard, err := ParseShard(set[0].Serialize())
    48  		So(err, ShouldBeNil)
    49  		So(shard, ShouldResemble, set[0])
    50  	})
    51  
    52  	Convey("Empty shards serialization", t, func() {
    53  		var shard Shard
    54  		deserialized, err := ParseShard(shard.Serialize())
    55  		So(err, ShouldBeNil)
    56  		So(len(deserialized), ShouldEqual, 0)
    57  	})
    58  
    59  	Convey("Deserialize garbage", t, func() {
    60  		_, err := ParseShard([]byte("blah"))
    61  		So(err, ShouldNotBeNil)
    62  	})
    63  }