state/state_test.go (view raw)
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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 | package state
import (
"bytes"
"context"
"fmt"
"log"
"sync"
"testing"
"time"
)
// MockCommand implements the command.Command interface for testing
type MockCommand struct {
mu sync.Mutex
startCalled bool
stopCalled bool
waitCalled bool
startErr error
waitErr error
stopErr error
waitChan chan struct{}
started bool
}
func NewMockCommand() *MockCommand {
return &MockCommand{
waitChan: make(chan struct{}),
}
}
func (m *MockCommand) Start() error {
m.mu.Lock()
defer m.mu.Unlock()
m.startCalled = true
m.started = true
return m.startErr
}
func (m *MockCommand) Wait() error {
m.mu.Lock()
m.waitCalled = true
m.mu.Unlock()
// Wait for signal to simulate command completion
<-m.waitChan
return m.waitErr
}
func (m *MockCommand) Stop(_ context.Context) error {
m.mu.Lock()
defer m.mu.Unlock()
m.stopCalled = true
m.started = false
// Add small delay to allow tests to observe Stopping state
go func() {
time.Sleep(20 * time.Millisecond)
// Signal Wait to return
select {
case m.waitChan <- struct{}{}:
default:
}
}()
return m.stopErr
}
func (m *MockCommand) SimulateExit() {
m.mu.Lock()
m.started = false
m.mu.Unlock()
// Signal Wait to return
select {
case m.waitChan <- struct{}{}:
default:
}
}
func (m *MockCommand) WasStartCalled() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.startCalled
}
func (m *MockCommand) WasStopCalled() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.stopCalled
}
func (m *MockCommand) WasWaitCalled() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.waitCalled
}
func (m *MockCommand) SetStartError(err error) {
m.mu.Lock()
defer m.mu.Unlock()
m.startErr = err
}
func (m *MockCommand) SetWaitError(err error) {
m.mu.Lock()
defer m.mu.Unlock()
m.waitErr = err
}
func (m *MockCommand) SetStopError(err error) {
m.mu.Lock()
defer m.mu.Unlock()
m.stopErr = err
}
func (m *MockCommand) Reset() {
m.mu.Lock()
defer m.mu.Unlock()
m.startCalled = false
m.stopCalled = false
m.waitCalled = false
m.startErr = nil
m.waitErr = nil
m.stopErr = nil
m.started = false
// Signal any waiting goroutines before creating new channel
select {
case m.waitChan <- struct{}{}:
default:
}
m.waitChan = make(chan struct{})
}
func (m *MockCommand) ClearCallCounts() {
m.mu.Lock()
defer m.mu.Unlock()
m.startCalled = false
m.stopCalled = false
m.waitCalled = false
}
func createTestStateMachine() (*StateMachine, *MockCommand, *bytes.Buffer) {
mockCmd := NewMockCommand()
var buf bytes.Buffer
logger := log.New(&buf, "", 0)
sm := New(mockCmd, Options{
Logger: logger,
})
return sm, mockCmd, &buf
}
func TestStateString(t *testing.T) {
t.Parallel()
tests := []struct {
state State
expected string
}{
{NotStarted, "NotStarted"},
{Running, "Running"},
{Stopping, "Stopping"},
{Exited, "Exited"},
{State(99), "Unknown"},
}
for _, tt := range tests {
if got := tt.state.String(); got != tt.expected {
t.Errorf("State.String() = %v, want %v", got, tt.expected)
}
}
}
func TestEventString(t *testing.T) {
t.Parallel()
tests := []struct {
event Event
expected string
}{
{Start, "Start"},
{Shutdown, "Shutdown"},
{Exit, "Stopped"},
{Restart, "Restart"},
{Event(99), "Unknown"},
}
for _, tt := range tests {
if got := tt.event.String(); got != tt.expected {
t.Errorf("Event.String() = %v, want %v", got, tt.expected)
}
}
}
func TestNewStateMachine(t *testing.T) {
t.Parallel()
sm, _, _ := createTestStateMachine()
if sm.currentState != NotStarted {
t.Errorf("Initial state should be NotStarted, got %v", sm.currentState)
}
}
func TestStartTransition(t *testing.T) {
t.Parallel()
sm, mockCmd, _ := createTestStateMachine()
// Send Start event
sm.SendEvent(Start)
// Give some time for goroutine to start
time.Sleep(10 * time.Millisecond)
if sm.currentState != Running {
t.Errorf("State should be Running after Start event, got %v", sm.currentState)
}
if !mockCmd.WasStartCalled() {
t.Error("Start should have been called on command")
}
if !mockCmd.WasWaitCalled() {
t.Error("Wait should have been called on command")
}
}
func TestShutdownTransition(t *testing.T) {
t.Parallel()
sm, mockCmd, _ := createTestStateMachine()
// Start the state machine
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
// Clear call counts to track shutdown calls
mockCmd.ClearCallCounts()
// Send Shutdown event
sm.SendEvent(Shutdown)
time.Sleep(10 * time.Millisecond)
if sm.currentState != Stopping {
t.Errorf(
"State should be Stopping after Shutdown event from Running, got %v",
sm.currentState,
)
}
if !mockCmd.WasStopCalled() {
t.Error("Stop should have been called on command")
}
// Simulate command exit to complete transition to Exited
mockCmd.SimulateExit()
time.Sleep(10 * time.Millisecond)
if sm.currentState != Exited {
t.Errorf("State should be Exited after command exit, got %v", sm.currentState)
}
}
func TestExitTransition(t *testing.T) {
t.Parallel()
sm, mockCmd, _ := createTestStateMachine()
// Start the state machine
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
// Simulate command exit
mockCmd.SimulateExit()
time.Sleep(10 * time.Millisecond)
if sm.currentState != Exited {
t.Errorf("State should be Exited after Exit event, got %v", sm.currentState)
}
}
func TestRestartFromRunning(t *testing.T) {
t.Parallel()
sm, mockCmd, _ := createTestStateMachine()
// Start the state machine
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
// Clear call counts to track restart calls
mockCmd.ClearCallCounts()
// Send Restart event
sm.SendEvent(Restart)
time.Sleep(50 * time.Millisecond) // Give more time for restart sequence
if sm.currentState != Running {
t.Errorf("State should be Running after Restart event, got %v", sm.currentState)
}
if !mockCmd.WasStopCalled() {
t.Error("Stop should have been called during restart")
}
if !mockCmd.WasStartCalled() {
t.Error("Start should have been called during restart")
}
}
func TestRestartFromExited(t *testing.T) {
t.Parallel()
sm, mockCmd, _ := createTestStateMachine()
// Start and then exit
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
mockCmd.SimulateExit()
time.Sleep(10 * time.Millisecond)
// Reset mock
mockCmd.Reset()
// Send Restart event from Exited state
sm.SendEvent(Restart)
time.Sleep(10 * time.Millisecond)
if sm.currentState != Running {
t.Errorf("State should be Running after Restart from Exited, got %v", sm.currentState)
}
if !mockCmd.WasStartCalled() {
t.Error("Start should have been called during restart from Exited")
}
}
func TestStartFromExited(t *testing.T) {
t.Parallel()
sm, mockCmd, _ := createTestStateMachine()
// Start and then exit
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
mockCmd.SimulateExit()
time.Sleep(10 * time.Millisecond)
// Reset mock
mockCmd.Reset()
// Send Start event from Exited state
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
if sm.currentState != Running {
t.Errorf("State should be Running after Start from Exited, got %v", sm.currentState)
}
if !mockCmd.WasStartCalled() {
t.Error("Start should have been called")
}
}
func TestInvalidTransitions(t *testing.T) {
t.Parallel()
sm, _, buf := createTestStateMachine()
tests := []struct {
initialState State
event Event
description string
}{
{NotStarted, Shutdown, "Shutdown from NotStarted"},
{NotStarted, Exit, "Exit from NotStarted"},
{NotStarted, Restart, "Restart from NotStarted"},
{Stopping, Start, "Start from Stopping"},
{Stopping, Restart, "Restart from Stopping"},
{Exited, Shutdown, "Shutdown from Exited"},
{Exited, Exit, "Exit from Exited"},
}
for _, tt := range tests {
// Reset state machine to initial state
sm.currentState = tt.initialState
buf.Reset()
sm.SendEvent(tt.event)
if sm.currentState != tt.initialState {
t.Errorf(
"%s: state should remain %v, got %v",
tt.description,
tt.initialState,
sm.currentState,
)
}
logOutput := buf.String()
if logOutput != "" {
t.Errorf("%s: should not log invalid transition", tt.description)
}
}
}
func TestCommandStartError(t *testing.T) {
t.Parallel()
sm, mockCmd, buf := createTestStateMachine()
// Set start to return an error
mockCmd.SetStartError(fmt.Errorf("test error"))
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
// Should still transition to Running state even if start fails
if sm.currentState != Running {
t.Errorf("State should be Running even if Start fails, got %v", sm.currentState)
}
logOutput := buf.String()
if logOutput == "" {
t.Error("Should have logged start message")
}
}
func TestCommandStopError(t *testing.T) {
t.Parallel()
sm, mockCmd, buf := createTestStateMachine()
// Start first
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
// Set stop to return an error
mockCmd.SetStopError(fmt.Errorf("stop error"))
buf.Reset()
// Clear call counts to track stop calls
mockCmd.ClearCallCounts()
sm.SendEvent(Shutdown)
time.Sleep(10 * time.Millisecond)
if sm.currentState != Stopping {
t.Errorf("State should be Stopping even if Stop fails, got %v", sm.currentState)
}
// Complete the transition by simulating command exit
mockCmd.SimulateExit()
time.Sleep(10 * time.Millisecond)
if sm.currentState != Exited {
t.Errorf("State should be Exited after command exit, got %v", sm.currentState)
}
logOutput := buf.String()
if logOutput == "" {
t.Error("Should have logged stop message")
}
}
func TestConcurrentEvents(t *testing.T) {
t.Parallel()
sm, mockCmd, _ := createTestStateMachine()
// Send multiple events concurrently
go sm.SendEvent(Start)
go sm.SendEvent(Start)
go sm.SendEvent(Start)
time.Sleep(50 * time.Millisecond)
if sm.currentState != Running {
t.Errorf("State should be Running after concurrent Start events, got %v", sm.currentState)
}
if !mockCmd.WasStartCalled() {
t.Error("Start should have been called")
}
}
func TestCompleteLifecycle(t *testing.T) {
t.Parallel()
sm, mockCmd, _ := createTestStateMachine()
// Complete lifecycle: NotStarted -> Running -> Exited -> Running -> Exited
// Start
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
if sm.currentState != Running {
t.Errorf("Expected Running, got %v", sm.currentState)
}
// Shutdown to stop
sm.SendEvent(Shutdown)
time.Sleep(10 * time.Millisecond)
if sm.currentState != Stopping {
t.Errorf("Expected Stopping, got %v", sm.currentState)
}
// Complete shutdown by simulating command exit
mockCmd.SimulateExit()
time.Sleep(10 * time.Millisecond)
if sm.currentState != Exited {
t.Errorf("Expected Exited, got %v", sm.currentState)
}
// Start again
mockCmd.ClearCallCounts()
sm.SendEvent(Start)
time.Sleep(10 * time.Millisecond)
if sm.currentState != Running {
t.Errorf("Expected Running after restart, got %v", sm.currentState)
}
// Exit naturally
mockCmd.SimulateExit()
time.Sleep(10 * time.Millisecond)
if sm.currentState != Exited {
t.Errorf("Expected Exited after natural exit, got %v", sm.currentState)
}
}
|