File: set_test.go

package info (click to toggle)
golang-github-multiformats-go-multihash 0.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 376 kB
  • sloc: sh: 138; makefile: 39
file content (86 lines) | stat: -rw-r--r-- 1,269 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package multihash

import (
	"crypto/rand"
	"errors"
	"testing"
)

func makeRandomMultihash(t *testing.T) Multihash {
	t.Helper()

	p := make([]byte, 256)
	_, err := rand.Read(p)
	if err != nil {
		t.Fatal(err)
	}

	m, err := Sum(p, SHA3, 4)
	if err != nil {
		t.Fatal(err)
	}
	return m
}

func TestSet(t *testing.T) {
	mhSet := NewSet()

	total := 10
	for i := 0; i < total; i++ {
		mhSet.Add(makeRandomMultihash(t))
	}

	m0 := makeRandomMultihash(t)

	if mhSet.Len() != total {
		t.Error("bad length")
	}

	if mhSet.Has(m0) {
		t.Error("m0 should not be in set")
	}

	mhSet.Add(m0)

	if !mhSet.Has(m0) {
		t.Error("m0 should be in set")
	}

	i := 0
	f := func(m Multihash) error {
		i++
		if i == 3 {
			return errors.New("3")
		}
		return nil
	}

	mhSet.ForEach(f)
	if i != 3 {
		t.Error("forEach should have run 3 times")
	}

	mhSet.Remove(m0)

	if mhSet.Len() != total {
		t.Error("an element should have been removed")
	}

	if mhSet.Has(m0) {
		t.Error("m0 should not be in set")
	}

	if !mhSet.Visit(m0) {
		t.Error("Visit() should return true when new element added")
	}

	all := mhSet.All()
	if len(all) != mhSet.Len() {
		t.Error("All() should return all")
	}
	for _, mh := range all {
		if !mhSet.Has(mh) {
			t.Error("element in All() not in set")
		}
	}
}