go.chromium.org/luci@v0.0.0-20250314024836-d9a61d0730e6/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  	"go.chromium.org/luci/common/testing/ftt"
    22  	"go.chromium.org/luci/common/testing/truth/assert"
    23  	"go.chromium.org/luci/common/testing/truth/should"
    24  )
    25  
    26  func TestShards(t *testing.T) {
    27  	ftt.Run("Build shards, serialize and deserialize", t, func(t *ftt.Test) {
    28  		// Build sharded set of 500 strings.
    29  		set := make(Set, 10)
    30  		for i := 0; i < 500; i++ {
    31  			set.Insert([]byte(fmt.Sprintf("blob #%d", i)))
    32  		}
    33  
    34  		// Read same strings. Should be noop, they are already in the set.
    35  		for i := 0; i < 500; i++ {
    36  			set.Insert([]byte(fmt.Sprintf("blob #%d", i)))
    37  		}
    38  
    39  		// Make sure shards are balanced, and all data is there.
    40  		totalLen := 0
    41  		for _, shard := range set {
    42  			assert.Loosely(t, len(shard), should.BeGreaterThan(45))
    43  			assert.Loosely(t, len(shard), should.BeLessThan(55))
    44  			totalLen += len(shard)
    45  		}
    46  		assert.Loosely(t, totalLen, should.Equal(500))
    47  
    48  		// Serialize and deserialize first shard, should be left unchanged.
    49  		shard, err := ParseShard(set[0].Serialize())
    50  		assert.Loosely(t, err, should.BeNil)
    51  		assert.Loosely(t, shard, should.Match(set[0]))
    52  	})
    53  
    54  	ftt.Run("Empty shards serialization", t, func(t *ftt.Test) {
    55  		var shard Shard
    56  		deserialized, err := ParseShard(shard.Serialize())
    57  		assert.Loosely(t, err, should.BeNil)
    58  		assert.Loosely(t, len(deserialized), should.BeZero)
    59  	})
    60  
    61  	ftt.Run("Deserialize garbage", t, func(t *ftt.Test) {
    62  		_, err := ParseShard([]byte("blah"))
    63  		assert.Loosely(t, err, should.NotBeNil)
    64  	})
    65  }