summaryrefslogtreecommitdiff
path: root/internal/vote/vote_test.go
blob: 02c4af0a1a8f3c98d7ac0ecbe648264a98050ad2 (plain)
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
package vote

import (
	"os"
	"testing"
	"time"
)

func TestVote(t *testing.T) {
	v, _ := New([]string{"foo", "bar", "baz", "bay"})
	hostname, _ := os.Hostname()

	if v.FromID != hostname {
		t.Errorf("Expected vote to come from earth but came from %s", v.FromID)
	}

	if len(v.IDs) != 4 {
		t.Errorf("Expected vote length to be 4 but is %d", len(v.IDs))
	}

	if v.IDs[0] != "foo" {
		t.Errorf("Expected vote 1 to be foo but is %s", v.IDs[0])
	}

	if v.IDs[1] != "bar" {
		t.Errorf("Expected vote 2 to be bar but is %s", v.IDs[1])
	}
}

func TestVoteExpiry(t *testing.T) {
	v, _ := New([]string{"foo", "bar", "baz", "bay"})

	// Set expiry 1h into the future
	v.ExpiresAt = time.Now().Add(1 * time.Hour)
	if v.Expired() {
		t.Errorf("Didn't expect vote to be expired")
	}

	// Set expiry to now
	v.ExpiresAt = time.Now()
	if !v.Expired() {
		t.Errorf("Expected vote to be expired")
	}
}

func TestMarshalling(t *testing.T) {
	v, _ := New([]string{"foo", "bar", "baz", "bay"})
	bytes, err := v.ToJSON()
	if err != nil {
		t.Errorf("unable to serialize vote to json: %v", err)
	}

	v2, err := NewFromJSON(bytes)
	if err != nil {
		t.Errorf("unable to deserialize json to vote: %v", err)
	}

	if !v.Equal(v2) {
		t.Errorf("serialized %v and deserialized %v votes differ", v, v2)
	}
}