1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package v1
16
17 import (
18 "encoding/json"
19 "strconv"
20 "strings"
21 "testing"
22 )
23
24 func TestGoodHashes(t *testing.T) {
25 good := []string{
26 "sha256:deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
27 "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
28 }
29
30 for _, s := range good {
31 h, err := NewHash(s)
32 if err != nil {
33 t.Error("Unexpected error parsing hash:", err)
34 }
35 if got, want := h.String(), s; got != want {
36 t.Errorf("String(); got %q, want %q", got, want)
37 }
38 bytes, err := json.Marshal(h)
39 if err != nil {
40 t.Error("Unexpected error json.Marshaling hash:", err)
41 }
42 if got, want := string(bytes), strconv.Quote(h.String()); got != want {
43 t.Errorf("json.Marshal(); got %q, want %q", got, want)
44 }
45 }
46 }
47
48 func TestBadHashes(t *testing.T) {
49 bad := []string{
50
51 "sha256:deadbeef",
52
53 "sha256:o123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
54
55 "md5:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
56
57 "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
58
59 "md5:sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
60 }
61
62 for _, s := range bad {
63 h, err := NewHash(s)
64 if err == nil {
65 t.Error("Expected error, got:", h)
66 }
67 }
68 }
69
70 func TestSHA256(t *testing.T) {
71 input := "asdf"
72 h, n, err := SHA256(strings.NewReader(input))
73 if err != nil {
74 t.Error("SHA256(asdf) =", err)
75 }
76 if got, want := h.Algorithm, "sha256"; got != want {
77 t.Errorf("Algorithm; got %v, want %v", got, want)
78 }
79 if got, want := h.Hex, "f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b"; got != want {
80 t.Errorf("Hex; got %v, want %v", got, want)
81 }
82 if got, want := n, int64(len(input)); got != want {
83 t.Errorf("n; got %v, want %v", got, want)
84 }
85 }
86
87
88
89 func TestTextMarshalling(t *testing.T) {
90 foo := make(map[Hash]string)
91 b, err := json.Marshal(foo)
92 if err != nil {
93 t.Fatal("could not marshal:", err)
94 }
95 if err := json.Unmarshal(b, &foo); err != nil {
96 t.Error("could not unmarshal:", err)
97 }
98
99 h := &Hash{
100 Algorithm: "sha256",
101 Hex: strings.Repeat("a", 64),
102 }
103 g := &Hash{}
104 text, err := h.MarshalText()
105 if err != nil {
106 t.Fatal(err)
107 }
108 if err := g.UnmarshalText(text); err != nil {
109 t.Fatal(err)
110 }
111
112 if h.String() != g.String() {
113 t.Errorf("mismatched hash: %s != %s", h, g)
114 }
115 }
116
View as plain text