github.com/pion/dtls/v2@v2.2.12/pkg/crypto/fingerprint/hash_test.go (about)

     1  // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
     2  // SPDX-License-Identifier: MIT
     3  
     4  package fingerprint
     5  
     6  import (
     7  	"crypto"
     8  	"errors"
     9  	"testing"
    10  )
    11  
    12  func TestHashFromString(t *testing.T) {
    13  	t.Run("InvalidHashAlgorithm", func(t *testing.T) {
    14  		_, err := HashFromString("invalid-hash-algorithm")
    15  		if !errors.Is(err, errInvalidHashAlgorithm) {
    16  			t.Errorf("Expected error '%v' for invalid hash name, got '%v'", errInvalidHashAlgorithm, err)
    17  		}
    18  	})
    19  	t.Run("ValidHashAlgorithm", func(t *testing.T) {
    20  		h, err := HashFromString("sha-512")
    21  		if err != nil {
    22  			t.Fatalf("Unexpected error for valid hash name, got '%v'", err)
    23  		}
    24  		if h != crypto.SHA512 {
    25  			t.Errorf("Expected hash ID of %d, got %d", int(crypto.SHA512), int(h))
    26  		}
    27  	})
    28  	t.Run("ValidCaseInsensitiveHashAlgorithm", func(t *testing.T) {
    29  		h, err := HashFromString("SHA-512")
    30  		if err != nil {
    31  			t.Fatalf("Unexpected error for valid hash name, got '%v'", err)
    32  		}
    33  		if h != crypto.SHA512 {
    34  			t.Errorf("Expected hash ID of %d, got %d", int(crypto.SHA512), int(h))
    35  		}
    36  	})
    37  }
    38  
    39  func TestStringFromHash_Roundtrip(t *testing.T) {
    40  	for _, h := range nameToHash() {
    41  		s, err := StringFromHash(h)
    42  		if err != nil {
    43  			t.Fatalf("Unexpected error for valid hash algorithm, got '%v'", err)
    44  		}
    45  		h2, err := HashFromString(s)
    46  		if err != nil {
    47  			t.Fatalf("Unexpected error for valid hash name, got '%v'", err)
    48  		}
    49  		if h != h2 {
    50  			t.Errorf("Hash value doesn't match, expected: 0x%x, got 0x%x", h, h2)
    51  		}
    52  	}
    53  }