github.com/nextlinux/gosbom@v0.81.1-0.20230627115839-1ff50c281391/gosbom/formats/common/util/h_digest_test.go (about) 1 package util 2 3 import ( 4 "fmt" 5 "strings" 6 "testing" 7 8 "github.com/stretchr/testify/require" 9 ) 10 11 func Test_HDigestToSHA(t *testing.T) { 12 tests := []struct { 13 name string 14 hDigest string 15 expected string 16 error bool 17 }{ 18 { 19 name: "valid h1digest", 20 hDigest: "h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=", 21 expected: "sha256:f10a9c0e0ceb52a9546ff1b63d04d68ae786a33b91d7cf3881d74ccb093a88b5", 22 error: false, 23 }, 24 { 25 name: "other valid h1digest", 26 hDigest: "h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=", 27 expected: "sha256:4933fc0ef0f273f748e5bf13e61b21b648d2f84e364e7cac34250f7637221a16", 28 error: false, 29 }, 30 { 31 name: "invalid h1digest", 32 hDigest: "h12:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=", 33 expected: "", 34 error: true, 35 }, 36 } 37 38 for _, test := range tests { 39 t.Run(test.name, func(t *testing.T) { 40 algo, digest, err := HDigestToSHA(test.hDigest) 41 if test.error { 42 require.Error(t, err) 43 return 44 } else { 45 require.NoError(t, err) 46 } 47 got := fmt.Sprintf("%s:%s", algo, digest) 48 require.Equal(t, test.expected, got) 49 }) 50 } 51 } 52 53 func Test_HDigestFromSHA(t *testing.T) { 54 tests := []struct { 55 name string 56 sha string 57 expected string 58 error bool 59 }{ 60 { 61 name: "valid sha", 62 sha: "sha256:f10a9c0e0ceb52a9546ff1b63d04d68ae786a33b91d7cf3881d74ccb093a88b5", 63 expected: "h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=", 64 error: false, 65 }, 66 { 67 name: "other valid sha", 68 sha: "sha256:4933fc0ef0f273f748e5bf13e61b21b648d2f84e364e7cac34250f7637221a16", 69 expected: "h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=", 70 error: false, 71 }, 72 { 73 name: "invalid sha", 74 expected: "h12:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=", 75 sha: "sha256:f10a9c0e0zzzzceb52a99968ae786a33b91d7cf3881d74ccb093a88b5", 76 error: true, 77 }, 78 { 79 name: "invalid algorithm", 80 expected: "h12:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=", 81 sha: "sha1:f10a9c0e0ceb52a9546ff1b63d04d68ae786a33b91d7cf3881d74ccb093a88b5", 82 error: true, 83 }, 84 { 85 name: "empty sha", 86 expected: "", 87 sha: "sha256:", 88 error: true, 89 }, 90 } 91 92 for _, test := range tests { 93 t.Run(test.name, func(t *testing.T) { 94 parts := strings.Split(test.sha, ":") 95 algo := parts[0] 96 digest := parts[1] 97 got, err := HDigestFromSHA(algo, digest) 98 if test.error { 99 require.Error(t, err) 100 return 101 } else { 102 require.NoError(t, err) 103 } 104 require.Equal(t, test.expected, got) 105 }) 106 } 107 }