-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
256 lines (209 loc) · 6.26 KB
/
main_test.go
File metadata and controls
256 lines (209 loc) · 6.26 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package main
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"sync"
"testing"
"testing/synctest"
"time"
)
// Test helpers and mocks
type MockGCPAPI struct {
suspendCalled bool
mu sync.Mutex
}
func (m *MockGCPAPI) WasSuspendCalled() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.suspendCalled
}
func (m *MockGCPAPI) Reset() {
m.mu.Lock()
defer m.mu.Unlock()
m.suspendCalled = false
}
// Mock the GCP API calls
var mockGCP = &MockGCPAPI{}
func setupTestConfig() *Config {
return &Config{
Port: "8808",
InactivityTimeout: 90 * time.Second,
LogLevel: "ERROR",
GoogleProjectID: "test-project",
GCEZone: "test-zone",
GCEInstance: "test-instance",
LibOpsKeepOnline: "",
}
}
func setupTestEnvironment() func() {
// Save original globals
origConfig := config
origTracker := tracker
origShutdownTimer := shutdownTimer
origServerShutdown := serverShutdown
origSuspendFunc := suspendFunc
// Set test config and tracker
config = setupTestConfig()
tracker = &ActivityTracker{
lastPing: time.Now(),
}
shutdownTimer = nil
serverShutdown = make(chan struct{})
suspendFunc = mockSuspendInstance
mockGCP.Reset()
// Setup test logging (suppress output)
opts := &slog.HandlerOptions{Level: slog.LevelError}
handler := slog.New(slog.NewTextHandler(io.Discard, opts))
slog.SetDefault(handler)
// Return cleanup function
return func() {
// Stop any running shutdown timer first
stopShutdownTimer()
// Protect global variable assignments with mutex to prevent race condition
shutdownMutex.Lock()
config = origConfig
tracker = origTracker
shutdownTimer = origShutdownTimer
serverShutdown = origServerShutdown
suspendFunc = origSuspendFunc
shutdownMutex.Unlock()
}
}
// Mock suspend function for testing
func mockSuspendInstance() error {
mockGCP.mu.Lock()
mockGCP.suspendCalled = true
mockGCP.mu.Unlock()
return nil
}
func TestSuspensionAfterInactivityTimeout(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
cleanup := setupTestEnvironment()
defer cleanup()
// Start the shutdown timer
resetShutdownTimer()
// Verify suspension hasn't been called yet
if mockGCP.WasSuspendCalled() {
t.Fatal("Suspension should not be called immediately")
}
// Advance time by the inactivity timeout period using fake clock
time.Sleep(config.InactivityTimeout + 100*time.Millisecond)
// Verify suspension was called
if !mockGCP.WasSuspendCalled() {
t.Fatal("Suspension should have been called after inactivity timeout")
}
})
}
func TestTimerResetOnPingRequest(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
cleanup := setupTestEnvironment()
defer cleanup()
// Start the shutdown timer
resetShutdownTimer()
// Wait for almost the timeout period
time.Sleep(config.InactivityTimeout - 1*time.Second)
// Make a ping request to reset the timer
req := httptest.NewRequest("GET", "/ping", nil)
w := httptest.NewRecorder()
pingHandler(w, req)
// Verify the response
if w.Code != http.StatusOK {
t.Fatalf("Expected status 200, got %d", w.Code)
}
if w.Body.String() != "pong" {
t.Fatalf("Expected 'pong', got %s", w.Body.String())
}
// Wait for the original timeout period (timer should have reset)
time.Sleep(2 * time.Second)
// Suspension should NOT have been called yet
if mockGCP.WasSuspendCalled() {
t.Fatal("Suspension should not be called after ping reset timer")
}
// Wait for the full timeout period after the ping
time.Sleep(config.InactivityTimeout)
// Now suspension should be called
if !mockGCP.WasSuspendCalled() {
t.Fatal("Suspension should be called after timeout following ping")
}
})
}
func TestMultiplePingsKeepMachineAlive(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
cleanup := setupTestEnvironment()
defer cleanup()
// Start the shutdown timer
resetShutdownTimer()
// Make multiple ping requests within the timeout period
for i := 0; i < 5; i++ {
// Wait for part of the timeout period
time.Sleep(config.InactivityTimeout / 2)
// Make a ping request
req := httptest.NewRequest("GET", "/ping", nil)
w := httptest.NewRecorder()
pingHandler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Ping %d: Expected status 200, got %d", i, w.Code)
}
// Suspension should not be called
if mockGCP.WasSuspendCalled() {
t.Fatalf("Suspension should not be called after ping %d", i)
}
}
// Finally, wait for the full timeout without any pings
time.Sleep(config.InactivityTimeout + 100*time.Millisecond)
// Now suspension should be called
if !mockGCP.WasSuspendCalled() {
t.Fatal("Suspension should be called after final timeout")
}
})
}
func TestKeepOnlineDisablesSuspension(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
cleanup := setupTestEnvironment()
defer cleanup()
// Set keep online flag
config.LibOpsKeepOnline = "yes"
// Don't start the timer at all when keep online is enabled
// This simulates the main() function logic that checks LibOpsKeepOnline != "yes"
if config.LibOpsKeepOnline != "yes" {
resetShutdownTimer()
}
// Wait for longer than the timeout period
time.Sleep(config.InactivityTimeout * 2)
// Suspension should NOT be called
if mockGCP.WasSuspendCalled() {
t.Fatal("Suspension should not be called when keep online is enabled")
}
})
}
func TestHealthEndpoint(t *testing.T) {
cleanup := setupTestEnvironment()
defer cleanup()
req := httptest.NewRequest("GET", "/healthcheck", nil)
w := httptest.NewRecorder()
healthHandler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Expected status 200, got %d", w.Code)
}
if w.Header().Get("Content-Type") != "text/plain" {
t.Fatalf("Expected Content-Type 'text/plain', got '%s'", w.Header().Get("Content-Type"))
}
}
func TestTimerResetBeforeSuspension(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
cleanup := setupTestEnvironment()
defer cleanup()
// Start timer
resetShutdownTimer()
// Wait for timeout to trigger suspension
time.Sleep(config.InactivityTimeout + 100*time.Millisecond)
// Verify suspension was called
// The resetShutdownTimer call before suspension is tested implicitly
// since suspendInstance calls resetShutdownTimer internally
if !mockGCP.WasSuspendCalled() {
t.Fatal("Suspension should have been called")
}
})
}