istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/util/hash/hash_test.go (about)

     1  // Copyright Istio 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 hash
    16  
    17  import (
    18  	"testing"
    19  )
    20  
    21  func TestFactory(t *testing.T) {
    22  	testCases := []struct {
    23  		name                   string
    24  		str                    string
    25  		wantSum                []byte
    26  		wantStr                string
    27  		wantUint64             uint64
    28  		wantLittleEndianUint64 uint64
    29  	}{
    30  		{
    31  			name: "foo",
    32  			str:  "foo",
    33  			// note: Different hash implementation may get different hash value
    34  			wantStr:    "33bf00a859c4ba3f",
    35  			wantUint64: 3728699739546630719,
    36  		},
    37  	}
    38  
    39  	for _, tt := range testCases {
    40  		t.Run(tt.name, func(t *testing.T) {
    41  			h := New()
    42  			h.Write([]byte(tt.str))
    43  			if gotStr := h.Sum(); tt.wantStr != gotStr {
    44  				t.Errorf("wantStr %v, but got %v", tt.wantStr, gotStr)
    45  			}
    46  			if gotUint64 := h.Sum64(); tt.wantUint64 != gotUint64 {
    47  				t.Errorf("wantUint64 %v, but got %v", tt.wantUint64, gotUint64)
    48  			}
    49  		})
    50  	}
    51  }
    52  
    53  func TestFactoryWriteString(t *testing.T) {
    54  	testCases := []struct {
    55  		name                   string
    56  		str                    string
    57  		wantSum                []byte
    58  		wantStr                string
    59  		wantUint64             uint64
    60  		wantLittleEndianUint64 uint64
    61  	}{
    62  		{
    63  			name: "foo",
    64  			str:  "foo",
    65  			// note: Different hash implementation may get different hash value
    66  			wantStr:    "33bf00a859c4ba3f",
    67  			wantUint64: 3728699739546630719,
    68  		},
    69  	}
    70  
    71  	for _, tt := range testCases {
    72  		t.Run(tt.name, func(t *testing.T) {
    73  			h := New()
    74  			h.WriteString(tt.str)
    75  			if gotStr := h.Sum(); tt.wantStr != gotStr {
    76  				t.Errorf("wantStr %v, but got %v", tt.wantStr, gotStr)
    77  			}
    78  			if gotUint64 := h.Sum64(); tt.wantUint64 != gotUint64 {
    79  				t.Errorf("wantUint64 %v, but got %v", tt.wantUint64, gotUint64)
    80  			}
    81  		})
    82  	}
    83  }