summaryrefslogtreecommitdiff
path: root/internal/worktime/integrity_test.go
blob: 8239d494f091cb985d077a4630f0d82c1c45b51e (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
package worktime

import (
	"testing"
	"time"
)

func TestCheckEntriesIntegrityDetectsIssues(t *testing.T) {
	entries := []Entry{
		{Action: "login", What: "work", Epoch: 100, Source: "host-a"},
		{Action: "login", What: "work", Epoch: 110, Source: "host-a"},  // double login
		{Action: "logout", What: "work", Epoch: 120, Source: "host-a"}, // matches first login
		{Action: "logout", What: "work", Epoch: 130, Source: "host-a"}, // logout without login
		{Action: "login", What: "off", Epoch: 200, Source: "host-b"},   // open session warning
		{Action: "login", What: "bank", Epoch: 300, Source: "host-c"},
		{Action: "logout", What: "bank", Epoch: 300 + int64((16*time.Hour)/time.Second), Source: "host-c"}, // too long
	}

	issues := CheckEntriesIntegrity(entries, DefaultMaxSessionSpan)
	if len(issues) != 3 {
		t.Fatalf("issues len = %d, want 3", len(issues))
	}

	kinds := map[string]bool{}
	for _, issue := range issues {
		kinds[issue.Kind] = true
	}
	for _, kind := range []string{
		"double-login",
		"logout-without-login",
		"session-too-long",
	} {
		if !kinds[kind] {
			t.Fatalf("missing expected issue kind %q", kind)
		}
	}
}

func TestOpenSessionsReturnsActiveLogins(t *testing.T) {
	entries := []Entry{
		{Action: "login", What: "work", Epoch: 100, Source: "host-a"},
		{Action: "logout", What: "work", Epoch: 200, Source: "host-a"},
		{Action: "login", What: "off", Epoch: 300, Source: "host-b"},
		{Action: "login", What: "bank", Epoch: 400, Source: "host-c"},
	}

	sessions := OpenSessions(entries)
	if len(sessions) != 2 {
		t.Fatalf("sessions len = %d, want 2", len(sessions))
	}

	if sessions[0].Category != "bank" || sessions[0].Login.Source != "host-c" {
		t.Fatalf("unexpected first session: %+v", sessions[0])
	}
	if sessions[1].Category != "off" || sessions[1].Login.Source != "host-b" {
		t.Fatalf("unexpected second session: %+v", sessions[1])
	}
}

func TestCheckEntriesIntegrityPassesValidFlow(t *testing.T) {
	entries := []Entry{
		{Action: "login", What: "work", Epoch: 100, Source: "host-a"},
		{Action: "logout", What: "work", Epoch: 200, Source: "host-a"},
		{Action: "add", What: "off", Epoch: 300, Source: "host-a", Value: 8 * 3600},
	}

	issues := CheckEntriesIntegrity(entries, DefaultMaxSessionSpan)
	if len(issues) != 0 {
		t.Fatalf("issues len = %d, want 0 (%v)", len(issues), issues)
	}
}

func TestCheckIntegrityValidation(t *testing.T) {
	if _, err := CheckIntegrity(t.TempDir(), 0); err == nil {
		t.Fatal("CheckIntegrity() with non-positive max span should fail")
	}
}