summaryrefslogtreecommitdiff
path: root/internal/peer_test.go
blob: 2cada608dc499b39fb456c1e231d6a0634270543 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package internal

import (
	"context"
	"errors"
	"testing"
	"time"
)

func TestPeerActiveAtStale(t *testing.T) {
	now := time.Date(2023, 1, 1, 12, 0, 0, 0, time.UTC)
	conf := config{
		PeerURL:             "https://peer.example/gogios/index.json",
		PeerStaleThresholdS: 600,
		PeerPrimaryName:     "primary",
		PeerSecondaryName:   "secondary",
	}

	lastUpdated := now.Add(-11 * time.Minute)
	active, _ := peerActiveAt(context.Background(), conf, now, "secondary",
		func(context.Context, string) (time.Time, error) {
			return lastUpdated, nil
		})

	if !active {
		t.Fatalf("expected active when peer is stale")
	}
}

func TestPeerActiveAtFreshStandby(t *testing.T) {
	now := time.Date(2023, 1, 1, 12, 0, 0, 0, time.UTC)
	conf := config{
		PeerURL:             "https://peer.example/gogios/index.json",
		PeerStaleThresholdS: 600,
		PeerPrimaryName:     "primary",
		PeerSecondaryName:   "secondary",
	}

	lastUpdated := now.Add(-1 * time.Minute)
	active, _ := peerActiveAt(context.Background(), conf, now, "secondary",
		func(context.Context, string) (time.Time, error) {
			return lastUpdated, nil
		})

	if active {
		t.Fatalf("expected passive when peer is healthy and local is standby")
	}
}

func TestPeerActiveAtFetchError(t *testing.T) {
	now := time.Date(2023, 1, 1, 12, 0, 0, 0, time.UTC)
	conf := config{
		PeerURL:             "https://peer.example/gogios/index.json",
		PeerStaleThresholdS: 600,
		PeerPrimaryName:     "primary",
		PeerSecondaryName:   "secondary",
	}

	active, _ := peerActiveAt(context.Background(), conf, now, "secondary",
		func(context.Context, string) (time.Time, error) {
			return time.Time{}, errors.New("boom")
		})

	if !active {
		t.Fatalf("expected active on peer fetch error")
	}
}

func TestScheduledMasterWeekParity(t *testing.T) {
	primary := "primary"
	secondary := "secondary"

	weekOne := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC) // Sunday
	weekTwo := time.Date(2023, 1, 8, 0, 0, 0, 0, time.UTC) // Next Sunday

	if master := scheduledMaster(primary, secondary, weekOne); master != primary {
		t.Fatalf("expected primary to be master in week 1, got %s", master)
	}

	if master := scheduledMaster(primary, secondary, weekTwo); master != secondary {
		t.Fatalf("expected secondary to be master in week 2, got %s", master)
	}
}