Source file src/cmd/go/internal/cache/hash_test.go

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package cache
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  	"testing"
    11  )
    12  
    13  func TestHash(t *testing.T) {
    14  	oldSalt := hashSalt
    15  	hashSalt = nil
    16  	defer func() {
    17  		hashSalt = oldSalt
    18  	}()
    19  
    20  	h := NewHash("alice")
    21  	h.Write([]byte("hello world"))
    22  	sum := fmt.Sprintf("%x", h.Sum())
    23  	want := "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
    24  	if sum != want {
    25  		t.Errorf("hash(hello world) = %v, want %v", sum, want)
    26  	}
    27  }
    28  
    29  func TestHashFile(t *testing.T) {
    30  	f, err := os.CreateTemp("", "cmd-go-test-")
    31  	if err != nil {
    32  		t.Fatal(err)
    33  	}
    34  	name := f.Name()
    35  	fmt.Fprintf(f, "hello world")
    36  	defer os.Remove(name)
    37  	if err := f.Close(); err != nil {
    38  		t.Fatal(err)
    39  	}
    40  
    41  	var h ActionID // make sure hash result is assignable to ActionID
    42  	h, err = FileHash(name)
    43  	if err != nil {
    44  		t.Fatal(err)
    45  	}
    46  	sum := fmt.Sprintf("%x", h)
    47  	want := "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
    48  	if sum != want {
    49  		t.Errorf("hash(hello world) = %v, want %v", sum, want)
    50  	}
    51  }
    52  

View as plain text