Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /unit /test_state_machine.py
"""
Unit Tests for State Machine Module
====================================
Comprehensive tests for state_machine.py
Focus Areas:
- State Transitions
- Event Handling
- State Persistence
Tests: 60+
No external dependencies - pure unit tests
"""
import asyncio
import json
import os
import sys
from datetime import datetime, timedelta
from unittest.mock import AsyncMock, Mock, patch
import pytest
# Add parent directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))
from core.state_machine import (
AdvancedStateMachine,
HistoryType,
PentestStateMachine,
State,
StateAction,
StateContext,
StateEvent,
StateType,
Transition,
TransitionGuard,
create_state_machine,
)
# =============================================================================
# Fixtures
# =============================================================================
@pytest.fixture
def event_loop():
"""Create an instance of the default event loop for each test case."""
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
@pytest.fixture
def state_context():
"""Create a fresh StateContext for testing."""
return StateContext(session_id="test-session-123")
@pytest.fixture
def simple_state():
"""Create a simple state for testing."""
return State("test_state", StateType.SIMPLE)
@pytest.fixture
def composite_state():
"""Create a composite state with sub-states for testing."""
parent = State("parent", StateType.COMPOSITE)
child1 = State("child1", StateType.SIMPLE)
child2 = State("child2", StateType.SIMPLE)
parent.add_sub_state(child1)
parent.add_sub_state(child2)
return parent
@pytest.fixture
def state_machine():
"""Create a fresh AdvancedStateMachine for testing."""
sm = AdvancedStateMachine(name="TestMachine", enable_persistence=False)
# Add some basic states
sm.add_state(State("idle", StateType.SIMPLE))
sm.add_state(State("running", StateType.SIMPLE))
sm.add_state(State("completed", StateType.FINAL))
return sm
@pytest.fixture
def running_state_machine():
"""Create and start a state machine for testing."""
sm = AdvancedStateMachine(name="RunningMachine", enable_persistence=False)
sm.add_state(State("idle", StateType.SIMPLE))
sm.add_state(State("active", StateType.SIMPLE))
async def _start():
await sm.start("idle")
return sm
return asyncio.get_event_loop().run_until_complete(_start())
# =============================================================================
# Tests for Enums
# =============================================================================
class TestStateType:
"""Tests for StateType enum."""
def test_state_type_values(self):
"""Test that StateType enum has correct values."""
assert StateType.SIMPLE.value == "simple"
assert StateType.COMPOSITE.value == "composite"
assert StateType.PARALLEL.value == "parallel"
assert StateType.HISTORY.value == "history"
assert StateType.FINAL.value == "final"
def test_state_type_enum_count(self):
"""Test that all state types are defined."""
assert len(StateType) == 5
def test_state_type_comparison(self):
"""Test StateType comparison."""
assert StateType.SIMPLE != StateType.COMPOSITE
assert StateType.SIMPLE == StateType.SIMPLE
class TestHistoryType:
"""Tests for HistoryType enum."""
def test_history_type_values(self):
"""Test that HistoryType enum has correct values."""
assert HistoryType.SHALLOW.value == "shallow"
assert HistoryType.DEEP.value == "deep"
def test_history_type_count(self):
"""Test that all history types are defined."""
assert len(HistoryType) == 2
# =============================================================================
# Tests for StateEvent
# =============================================================================
class TestStateEvent:
"""Tests for StateEvent dataclass."""
def test_event_creation_basic(self):
"""Test basic StateEvent creation."""
event = StateEvent(name="test_event")
assert event.name == "test_event"
assert event.payload == {}
assert event.source is None
assert isinstance(event.timestamp, datetime)
def test_event_creation_with_payload(self):
"""Test StateEvent creation with payload."""
payload = {"key": "value", "number": 42}
event = StateEvent(name="test_event", payload=payload)
assert event.payload == payload
def test_event_creation_with_source(self):
"""Test StateEvent creation with source."""
event = StateEvent(name="test_event", source="test_source")
assert event.source == "test_source"
def test_event_to_dict(self):
"""Test StateEvent serialization to dict."""
event = StateEvent(name="test_event", payload={"data": "test"}, source="source_1")
result = event.to_dict()
assert result["name"] == "test_event"
assert result["payload"] == {"data": "test"}
assert result["source"] == "source_1"
assert "timestamp" in result
assert isinstance(result["timestamp"], str)
def test_event_timestamp_is_datetime(self):
"""Test that event timestamp is datetime object."""
before = datetime.now()
event = StateEvent(name="test")
after = datetime.now()
assert before <= event.timestamp <= after
# =============================================================================
# Tests for TransitionGuard
# =============================================================================
class TestTransitionGuard:
"""Tests for TransitionGuard class."""
def test_guard_creation(self):
"""Test TransitionGuard creation."""
def condition(e, c):
return True
guard = TransitionGuard(condition=condition, description="test guard")
assert guard.condition == condition
assert guard.description == "test guard"
assert guard.priority == 0
def test_guard_evaluate_true(self, state_context):
"""Test guard evaluation returning True."""
def condition(e, c):
return True
guard = TransitionGuard(condition=condition)
event = StateEvent(name="test")
assert guard.evaluate(event, state_context) is True
def test_guard_evaluate_false(self, state_context):
"""Test guard evaluation returning False."""
def condition(e, c):
return False
guard = TransitionGuard(condition=condition)
event = StateEvent(name="test")
assert guard.evaluate(event, state_context) is False
def test_guard_evaluate_with_exception(self, state_context):
"""Test guard evaluation with exception returns False."""
def condition(e, c):
return 1 / 0 # Raises ZeroDivisionError
guard = TransitionGuard(condition=condition)
event = StateEvent(name="test")
assert guard.evaluate(event, state_context) is False
def test_guard_priority_sorting(self):
"""Test that guards can be sorted by priority."""
guard1 = TransitionGuard(condition=lambda e, c: True, priority=1)
guard2 = TransitionGuard(condition=lambda e, c: True, priority=5)
guard3 = TransitionGuard(condition=lambda e, c: True, priority=3)
guards = [guard1, guard2, guard3]
guards.sort(key=lambda g: g.priority, reverse=True)
assert guards[0].priority == 5
assert guards[1].priority == 3
assert guards[2].priority == 1
# =============================================================================
# Tests for StateAction
# =============================================================================
class TestStateAction:
"""Tests for StateAction class."""
def test_action_creation_defaults(self):
"""Test StateAction creation with defaults."""
def action_func(s, c):
return None
action = StateAction(action=action_func)
assert action.action == action_func
assert action.async_execution is False
assert action.timeout_seconds is None
assert action.retry_on_failure is False
assert action.max_retries == 3
def test_action_creation_custom(self):
"""Test StateAction creation with custom values."""
def action_func(s, c):
return None
action = StateAction(
action=action_func,
async_execution=True,
timeout_seconds=5.0,
retry_on_failure=True,
max_retries=5,
)
assert action.async_execution is True
assert action.timeout_seconds == 5.0
assert action.retry_on_failure is True
assert action.max_retries == 5
# =============================================================================
# Tests for StateContext
# =============================================================================
class TestStateContext:
"""Tests for StateContext class."""
def test_context_creation(self):
"""Test StateContext creation."""
ctx = StateContext()
assert ctx.session_id is not None
assert isinstance(ctx.session_id, str)
assert ctx.data == {}
assert isinstance(ctx.history, type(ctx.history))
assert isinstance(ctx.event_log, type(ctx.event_log))
assert isinstance(ctx.start_time, datetime)
def test_context_creation_with_session_id(self):
"""Test StateContext creation with specific session ID."""
ctx = StateContext(session_id="my-session")
assert ctx.session_id == "my-session"
@pytest.mark.asyncio
async def test_context_set_and_get(self, state_context):
"""Test context set and get operations."""
await state_context.set("key1", "value1")
result = await state_context.get("key1")
assert result == "value1"
@pytest.mark.asyncio
async def test_context_get_default(self, state_context):
"""Test context get with default value."""
result = await state_context.get("nonexistent", "default")
assert result == "default"
@pytest.mark.asyncio
async def test_context_update(self, state_context):
"""Test context update operation."""
await state_context.update({"a": 1, "b": 2})
assert await state_context.get("a") == 1
assert await state_context.get("b") == 2
@pytest.mark.asyncio
async def test_context_multiple_updates(self, state_context):
"""Test multiple context updates."""
await state_context.set("counter", 0)
for i in range(5):
await state_context.set("counter", i + 1)
assert await state_context.get("counter") == 5
def test_context_log_event(self, state_context):
"""Test event logging in context."""
event = StateEvent(name="test_event", payload={"data": "value"})
state_context.log_event(event)
assert len(state_context.event_log) == 1
logged = state_context.event_log[0]
assert logged["name"] == "test_event"
assert logged["context_session"] == state_context.session_id
def test_context_log_multiple_events(self, state_context):
"""Test logging multiple events."""
for i in range(10):
event = StateEvent(name=f"event_{i}")
state_context.log_event(event)
assert len(state_context.event_log) == 10
@pytest.mark.asyncio
async def test_context_thread_safety(self, state_context):
"""Test thread-safe operations on context."""
async def setter_task(key_prefix, count):
for i in range(count):
await state_context.set(f"{key_prefix}_{i}", i)
# Run multiple concurrent setters
await asyncio.gather(
setter_task("a", 50),
setter_task("b", 50),
setter_task("c", 50),
)
# Verify all values are set
for prefix in ["a", "b", "c"]:
for i in range(50):
assert await state_context.get(f"{prefix}_{i}") == i
# =============================================================================
# Tests for State
# =============================================================================
class TestState:
"""Tests for State class."""
def test_state_creation_simple(self):
"""Test simple state creation."""
state = State("my_state", StateType.SIMPLE)
assert state.name == "my_state"
assert state.state_type == StateType.SIMPLE
assert state.parent is None
assert state.sub_states == {}
assert state._active is False
def test_state_creation_composite(self):
"""Test composite state creation."""
state = State("composite", StateType.COMPOSITE)
assert state.state_type == StateType.COMPOSITE
assert state.initial_sub_state is None
def test_add_sub_state(self, composite_state):
"""Test adding sub-states."""
assert len(composite_state.sub_states) == 2
assert "child1" in composite_state.sub_states
assert "child2" in composite_state.sub_states
assert composite_state.sub_states["child1"].parent == composite_state
def test_add_sub_state_sets_initial(self):
"""Test that first sub-state becomes initial."""
parent = State("parent", StateType.COMPOSITE)
child1 = State("child1")
child2 = State("child2")
parent.add_sub_state(child1)
assert parent.initial_sub_state == "child1"
parent.add_sub_state(child2)
assert parent.initial_sub_state == "child1" # Should not change
def test_on_entry_decorator(self, simple_state):
"""Test on_entry action registration."""
def action_func(s, c):
return None
result = simple_state.on_entry(action_func)
assert len(simple_state.entry_actions) == 1
assert result == simple_state # Returns self for chaining
def test_on_exit_decorator(self, simple_state):
"""Test on_exit action registration."""
def action_func(s, c):
return None
result = simple_state.on_exit(action_func)
assert len(simple_state.exit_actions) == 1
assert result == simple_state
def test_while_in_state_decorator(self, simple_state):
"""Test while_in_state action registration."""
def action_func(s, c):
return None
result = simple_state.while_in_state(action_func)
assert len(simple_state.while_in_state_actions) == 1
assert result == simple_state
@pytest.mark.asyncio
async def test_state_enter(self, simple_state, state_context):
"""Test state entry."""
await simple_state.enter(state_context)
assert simple_state._active is True
assert simple_state._entered_at is not None
@pytest.mark.asyncio
async def test_state_exit(self, simple_state, state_context):
"""Test state exit."""
await simple_state.enter(state_context)
await simple_state.exit(state_context)
assert simple_state._active is False
@pytest.mark.asyncio
async def test_state_entry_action_execution(self, state_context):
"""Test that entry actions are executed."""
called_with = []
def entry_action(state, context):
called_with.append((state.name, context.session_id))
state = State("test")
state.on_entry(entry_action)
await state.enter(state_context)
assert len(called_with) == 1
assert called_with[0][0] == "test"
@pytest.mark.asyncio
async def test_state_exit_action_execution(self, state_context):
"""Test that exit actions are executed."""
called = False
def exit_action(state, context):
nonlocal called
called = True
state = State("test")
state.on_exit(exit_action)
await state.enter(state_context)
await state.exit(state_context)
assert called is True
@pytest.mark.asyncio
async def test_state_async_entry_action(self, state_context):
"""Test async entry action execution."""
result = []
async def async_action(state, context):
await asyncio.sleep(0.01)
result.append("executed")
state = State("test")
state.on_entry(async_action, async_exec=True)
await state.enter(state_context)
# Give time for async execution
await asyncio.sleep(0.05)
assert len(result) == 1
def test_is_active(self, simple_state):
"""Test is_active method."""
assert simple_state.is_active() is False
# Manually set active
simple_state._active = True
assert simple_state.is_active() is True
def test_get_duration_no_entry(self, simple_state):
"""Test get_duration when not entered."""
assert simple_state.get_duration() is None
def test_get_duration_with_entry(self, simple_state):
"""Test get_duration after entry."""
simple_state._entered_at = datetime.now() - timedelta(seconds=5)
simple_state._active = True
duration = simple_state.get_duration()
assert duration is not None
assert duration.total_seconds() >= 5
def test_state_to_dict(self, simple_state):
"""Test state serialization."""
result = simple_state.to_dict()
assert result["name"] == "test_state"
assert result["type"] == "simple"
assert result["active"] is False
assert "duration_seconds" in result
assert result["sub_states"] == []
def test_state_to_dict_with_substates(self, composite_state):
"""Test state serialization with sub-states."""
result = composite_state.to_dict()
assert "child1" in result["sub_states"]
assert "child2" in result["sub_states"]
# =============================================================================
# Tests for Transition
# =============================================================================
class TestTransition:
"""Tests for Transition class."""
def test_transition_creation_basic(self):
"""Test basic transition creation."""
t = Transition("state_a", "state_b")
assert t.source == "state_a"
assert t.target == "state_b"
assert t.event is None
assert t.guards == []
assert t.action is None
assert t.priority == 0
assert t.auto_trigger is False
def test_transition_creation_full(self):
"""Test transition creation with all parameters."""
def action(c, e):
return None
guard = TransitionGuard(lambda e, c: True)
t = Transition(
source="a",
target="b",
event="go",
guards=[guard],
action=action,
priority=10,
auto_trigger=True,
delay_seconds=1.0,
)
assert t.event == "go"
assert len(t.guards) == 1
assert t.action == action
assert t.priority == 10
assert t.auto_trigger is True
assert t.delay_seconds == 1.0
def test_can_fire_no_event_required(self, state_context):
"""Test can_fire with no event requirement."""
t = Transition("a", "b")
event = StateEvent(name="any_event")
assert t.can_fire(event, state_context) is True
def test_can_fire_event_mismatch(self, state_context):
"""Test can_fire with event mismatch."""
t = Transition("a", "b", event="expected")
event = StateEvent(name="wrong")
assert t.can_fire(event, state_context) is False
def test_can_fire_event_match(self, state_context):
"""Test can_fire with matching event."""
t = Transition("a", "b", event="expected")
event = StateEvent(name="expected")
assert t.can_fire(event, state_context) is True
def test_can_fire_with_passing_guard(self, state_context):
"""Test can_fire with passing guard."""
guard = TransitionGuard(lambda e, c: True)
t = Transition("a", "b", event="go", guards=[guard])
event = StateEvent(name="go")
assert t.can_fire(event, state_context) is True
def test_can_fire_with_failing_guard(self, state_context):
"""Test can_fire with failing guard."""
guard = TransitionGuard(lambda e, c: False)
t = Transition("a", "b", event="go", guards=[guard])
event = StateEvent(name="go")
assert t.can_fire(event, state_context) is False
def test_can_fire_with_multiple_guards(self, state_context):
"""Test can_fire with multiple guards - all must pass."""
guard1 = TransitionGuard(lambda e, c: True, priority=2)
guard2 = TransitionGuard(lambda e, c: True, priority=1)
t = Transition("a", "b", event="go", guards=[guard1, guard2])
event = StateEvent(name="go")
assert t.can_fire(event, state_context) is True
def test_can_fire_with_one_failing_guard(self, state_context):
"""Test can_fire with one failing guard among passing."""
guard1 = TransitionGuard(lambda e, c: True)
guard2 = TransitionGuard(lambda e, c: False)
t = Transition("a", "b", event="go", guards=[guard1, guard2])
event = StateEvent(name="go")
assert t.can_fire(event, state_context) is False
@pytest.mark.asyncio
async def test_fire_with_sync_action(self, state_context):
"""Test firing transition with sync action."""
called = []
def action(ctx, evt):
called.append((ctx.session_id, evt.name))
t = Transition("a", "b", action=action)
event = StateEvent(name="test")
await t.fire(state_context, event)
assert len(called) == 1
assert called[0][1] == "test"
@pytest.mark.asyncio
async def test_fire_with_async_action(self, state_context):
"""Test firing transition with async action."""
called = []
async def action(ctx, evt):
called.append(evt.name)
t = Transition("a", "b", action=action)
event = StateEvent(name="async_test")
await t.fire(state_context, event)
assert called == ["async_test"]
@pytest.mark.asyncio
async def test_fire_without_action(self, state_context):
"""Test firing transition without action."""
t = Transition("a", "b")
event = StateEvent(name="test")
# Should not raise
await t.fire(state_context, event)
# =============================================================================
# Tests for AdvancedStateMachine
# =============================================================================
class TestAdvancedStateMachine:
"""Tests for AdvancedStateMachine class."""
def test_state_machine_creation(self):
"""Test state machine creation."""
sm = AdvancedStateMachine(name="MyMachine")
assert sm.name == "MyMachine"
assert sm.states == {}
assert sm.transitions == []
assert sm._current_state is None
assert sm.enable_persistence is True
assert sm.auto_recovery is True
def test_add_state(self, state_machine):
"""Test adding states."""
new_state = State("new_state")
result = state_machine.add_state(new_state)
assert "new_state" in state_machine.states
assert result == new_state
def test_add_transition(self, state_machine):
"""Test adding transitions."""
t = Transition("idle", "running", event="start")
state_machine.add_transition(t)
assert len(state_machine.transitions) == 1
assert state_machine.transitions[0].event == "start"
def test_add_multiple_transitions_sorted_by_priority(self, state_machine):
"""Test that transitions are sorted by priority."""
t1 = Transition("idle", "running", priority=1)
t2 = Transition("idle", "completed", priority=10)
t3 = Transition("running", "completed", priority=5)
state_machine.add_transition(t1)
state_machine.add_transition(t2)
state_machine.add_transition(t3)
assert state_machine.transitions[0].priority == 10
assert state_machine.transitions[1].priority == 5
assert state_machine.transitions[2].priority == 1
def test_on_event_handler_registration(self, state_machine):
"""Test event handler registration."""
def handler(e, c):
return None
state_machine.on("my_event", handler)
assert "my_event" in state_machine._event_handlers
assert len(state_machine._event_handlers["my_event"]) == 1
def test_on_multiple_handlers_same_event(self, state_machine):
"""Test multiple handlers for same event."""
def handler1(e, c):
return None
def handler2(e, c):
return None
state_machine.on("event", handler1)
state_machine.on("event", handler2)
assert len(state_machine._event_handlers["event"]) == 2
@pytest.mark.asyncio
async def test_start_state_machine(self, state_machine):
"""Test starting state machine."""
await state_machine.start("idle")
assert state_machine._running is True
assert state_machine.get_current_state() == "idle"
assert state_machine._start_time is not None
@pytest.mark.asyncio
async def test_start_unknown_state(self, state_machine):
"""Test starting with unknown state raises error."""
with pytest.raises(ValueError, match="Unknown initial state"):
await state_machine.start("unknown")
@pytest.mark.asyncio
async def test_stop_state_machine(self, state_machine):
"""Test stopping state machine."""
await state_machine.start("idle")
await state_machine.stop()
assert state_machine._running is False
@pytest.mark.asyncio
async def test_send_string_event(self, state_machine):
"""Test sending event as string."""
await state_machine.start("idle")
await state_machine.send("test_event")
# Event should be queued
assert state_machine._event_queue.qsize() == 1
@pytest.mark.asyncio
async def test_send_state_event(self, state_machine):
"""Test sending StateEvent object."""
await state_machine.start("idle")
event = StateEvent(name="custom", payload={"data": "value"})
await state_machine.send(event)
assert state_machine._event_queue.qsize() == 1
@pytest.mark.asyncio
async def test_send_event_with_payload(self, state_machine):
"""Test sending event with payload."""
await state_machine.start("idle")
await state_machine.send("event", {"key": "value"})
assert state_machine._event_queue.qsize() == 1
@pytest.mark.asyncio
async def test_get_current_state(self, state_machine):
"""Test getting current state."""
await state_machine.start("idle")
assert state_machine.get_current_state() == "idle"
@pytest.mark.asyncio
async def test_get_current_state_when_stopped(self, state_machine):
"""Test getting current state when stopped."""
assert state_machine.get_current_state() is None
@pytest.mark.asyncio
async def test_get_active_states(self, state_machine):
"""Test getting active states."""
await state_machine.start("idle")
active = state_machine.get_active_states()
assert "idle" in active
@pytest.mark.asyncio
async def test_get_metrics(self, state_machine):
"""Test getting metrics."""
await state_machine.start("idle")
metrics = state_machine.get_metrics()
assert metrics["name"] == "TestMachine"
assert metrics["current_state"] == "idle"
assert metrics["state_count"] == 3
assert metrics["transition_count"] == 0
assert metrics["running"] is True
assert "uptime_seconds" in metrics
@pytest.mark.asyncio
async def test_export_state(self, state_machine):
"""Test exporting state."""
await state_machine.start("idle")
await state_machine.context.set("test_key", "test_value")
exported = state_machine.export_state()
assert exported["current_state"] == "idle"
assert exported["context_data"]["test_key"] == "test_value"
assert "timestamp" in exported
@pytest.mark.asyncio
async def test_import_state(self, state_machine):
"""Test importing state."""
state_data = {
"current_state": "idle",
"context_data": {"imported": True},
}
await state_machine.import_state(state_data)
assert state_machine.get_current_state() == "idle"
assert await state_machine.context.get("imported") is True
# =============================================================================
# Tests for State Transitions (Integration)
# =============================================================================
class TestStateTransitions:
"""Integration tests for state transitions."""
@pytest.mark.asyncio
async def test_simple_state_transition(self):
"""Test simple state transition."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
sm.add_state(State("running"))
sm.add_transition(Transition("idle", "running", event="start"))
await sm.start("idle")
await sm.send("start")
await asyncio.sleep(0.1)
assert sm.get_current_state() == "running"
await sm.stop()
@pytest.mark.asyncio
async def test_multiple_state_transitions(self):
"""Test multiple sequential transitions."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("a"))
sm.add_state(State("b"))
sm.add_state(State("c"))
sm.add_transition(Transition("a", "b", event="to_b"))
sm.add_transition(Transition("b", "c", event="to_c"))
await sm.start("a")
await sm.send("to_b")
await asyncio.sleep(0.05)
await sm.send("to_c")
await asyncio.sleep(0.05)
assert sm.get_current_state() == "c"
assert sm._transition_count == 2
await sm.stop()
@pytest.mark.asyncio
async def test_transition_with_guard_passing(self):
"""Test transition with passing guard."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
sm.add_state(State("running"))
guard = TransitionGuard(lambda e, c: True)
sm.add_transition(Transition("idle", "running", event="start", guards=[guard]))
await sm.start("idle")
await sm.send("start")
await asyncio.sleep(0.05)
assert sm.get_current_state() == "running"
await sm.stop()
@pytest.mark.asyncio
async def test_transition_with_guard_failing(self):
"""Test transition with failing guard blocks transition."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
sm.add_state(State("running"))
guard = TransitionGuard(lambda e, c: False)
sm.add_transition(Transition("idle", "running", event="start", guards=[guard]))
await sm.start("idle")
await sm.send("start")
await asyncio.sleep(0.05)
# Should stay in idle
assert sm.get_current_state() == "idle"
await sm.stop()
@pytest.mark.asyncio
async def test_transition_priority_ordering(self):
"""Test that higher priority transitions take precedence."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
sm.add_state(State("high_priority"))
sm.add_state(State("low_priority"))
# Lower priority first
sm.add_transition(Transition("idle", "low_priority", event="go", priority=1))
# Higher priority second
sm.add_transition(Transition("idle", "high_priority", event="go", priority=10))
await sm.start("idle")
await sm.send("go")
await asyncio.sleep(0.05)
# Should go to high_priority due to priority ordering
assert sm.get_current_state() == "high_priority"
await sm.stop()
@pytest.mark.asyncio
async def test_transition_action_execution(self):
"""Test that transition actions are executed."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
sm.add_state(State("running"))
action_called = []
def transition_action(ctx, evt):
action_called.append(evt.name)
sm.add_transition(Transition("idle", "running", event="start", action=transition_action))
await sm.start("idle")
await sm.send("start")
await asyncio.sleep(0.05)
assert action_called == ["start"]
await sm.stop()
@pytest.mark.asyncio
async def test_transition_with_delay(self):
"""Test transition with delay."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
sm.add_state(State("running"))
sm.add_transition(Transition("idle", "running", event="start", delay_seconds=0.1))
await sm.start("idle")
start_time = datetime.now()
await sm.send("start")
await asyncio.sleep(0.15)
assert sm.get_current_state() == "running"
duration = (datetime.now() - start_time).total_seconds()
assert duration >= 0.1
await sm.stop()
# =============================================================================
# Tests for Event Handling
# =============================================================================
class TestEventHandling:
"""Tests for event handling functionality."""
@pytest.mark.asyncio
async def test_event_handler_called(self):
"""Test that registered event handlers are called."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
handler_called = []
def handler(event, context):
handler_called.append(event.name)
sm.on("custom_event", handler)
await sm.start("idle")
await sm.send("custom_event")
await asyncio.sleep(0.05)
assert "custom_event" in handler_called
await sm.stop()
@pytest.mark.asyncio
async def test_multiple_event_handlers(self):
"""Test multiple handlers for same event."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
calls = []
def handler1(event, context):
calls.append("h1")
def handler2(event, context):
calls.append("h2")
sm.on("event", handler1)
sm.on("event", handler2)
await sm.start("idle")
await sm.send("event")
await asyncio.sleep(0.05)
assert "h1" in calls
assert "h2" in calls
await sm.stop()
@pytest.mark.asyncio
async def test_async_event_handler(self):
"""Test async event handler."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
calls = []
async def async_handler(event, context):
await asyncio.sleep(0.01)
calls.append("async")
sm.on("async_event", async_handler)
await sm.start("idle")
await sm.send("async_event")
await asyncio.sleep(0.05)
assert "async" in calls
await sm.stop()
@pytest.mark.asyncio
async def test_event_handler_error_ignored(self):
"""Test that event handler errors don't crash the machine."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
def failing_handler(event, context):
raise ValueError("Handler error")
sm.on("fail_event", failing_handler)
await sm.start("idle")
# Should not raise
await sm.send("fail_event")
await asyncio.sleep(0.05)
assert sm._running is True
await sm.stop()
@pytest.mark.asyncio
async def test_event_payload_passed(self):
"""Test that event payload is passed to handler."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
received_payload = None
def handler(event, context):
nonlocal received_payload
received_payload = event.payload
sm.on("data_event", handler)
await sm.start("idle")
await sm.send("data_event", {"key": "value"})
await asyncio.sleep(0.05)
assert received_payload == {"key": "value"}
await sm.stop()
# =============================================================================
# Tests for State Persistence
# =============================================================================
class TestStatePersistence:
"""Tests for state persistence functionality."""
@pytest.mark.asyncio
async def test_persistence_enabled_creates_history(self):
"""Test that transitions are persisted when enabled."""
sm = AdvancedStateMachine(enable_persistence=True)
sm.add_state(State("idle"))
sm.add_state(State("running"))
sm.add_transition(Transition("idle", "running", event="start"))
await sm.start("idle")
await sm.send("start")
await asyncio.sleep(0.05)
assert len(sm._state_history) == 1
assert sm._state_history[0]["from"] == "idle"
assert sm._state_history[0]["to"] == "running"
await sm.stop()
@pytest.mark.asyncio
async def test_persistence_disabled_no_history(self):
"""Test that transitions aren't persisted when disabled."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
sm.add_state(State("running"))
sm.add_transition(Transition("idle", "running", event="start"))
await sm.start("idle")
await sm.send("start")
await asyncio.sleep(0.05)
assert len(sm._state_history) == 0
await sm.stop()
def test_persist_state_structure(self):
"""Test structure of persisted state."""
sm = AdvancedStateMachine(enable_persistence=True)
sm.add_state(State("idle"))
sm.add_state(State("running"))
transition = Transition("idle", "running")
sm._persist_state(transition)
assert len(sm._state_history) == 1
entry = sm._state_history[0]
assert entry["from"] == "idle"
assert entry["to"] == "running"
assert "timestamp" in entry
assert "context_data" in entry
@pytest.mark.asyncio
async def test_state_history_max_size(self):
"""Test that state history has max size limit."""
sm = AdvancedStateMachine(enable_persistence=True)
sm.add_state(State("a"))
sm.add_state(State("b"))
transition = Transition("a", "b")
# Add more entries than max (1000)
for _ in range(1100):
sm._persist_state(transition)
assert len(sm._state_history) <= 1000
@pytest.mark.asyncio
async def test_export_import_roundtrip(self):
"""Test export and import roundtrip."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
sm.add_state(State("running"))
await sm.start("idle")
await sm.context.set("test_data", "value123")
exported = sm.export_state()
# Create new machine and import
sm2 = AdvancedStateMachine(enable_persistence=False)
sm2.add_state(State("idle"))
sm2.add_state(State("running"))
await sm2.import_state(exported)
assert sm2.get_current_state() == "idle"
assert await sm2.context.get("test_data") == "value123"
await sm.stop()
await sm2.stop()
# =============================================================================
# Tests for Composite States
# =============================================================================
class TestCompositeStates:
"""Tests for composite state functionality."""
@pytest.mark.asyncio
async def test_composite_state_enters_initial_substate(self):
"""Test that composite state enters initial sub-state."""
sm = AdvancedStateMachine(enable_persistence=False)
composite = State("composite", StateType.COMPOSITE)
child = State("child")
composite.add_sub_state(child)
sm.add_state(composite)
await sm.start("composite")
await asyncio.sleep(0.05)
# Should enter child as it's the initial sub-state
assert composite._active is True
await sm.stop()
def test_composite_state_structure(self):
"""Test composite state structure."""
composite = State("parent", StateType.COMPOSITE)
child1 = State("child1")
child2 = State("child2")
composite.add_sub_state(child1)
composite.add_sub_state(child2)
assert composite.initial_sub_state == "child1"
assert len(composite.sub_states) == 2
assert child1.parent == composite
assert child2.parent == composite
# =============================================================================
# Tests for PentestStateMachine
# =============================================================================
class TestPentestStateMachine:
"""Tests for PentestStateMachine specialized class."""
def test_pentest_machine_creation(self):
"""Test PentestStateMachine creation."""
psm = PentestStateMachine()
assert psm.name == "PentestStateMachine"
assert "idle" in psm.states
assert "reconnaissance" in psm.states
assert "vulnerability_assessment" in psm.states
assert "exploitation" in psm.states
assert "completed" in psm.states
def test_pentest_states_are_configured(self):
"""Test that all pentest states are configured."""
psm = PentestStateMachine()
expected_states = [
"idle",
"reconnaissance",
"vulnerability_assessment",
"exploitation",
"post_exploitation",
"reporting",
"completed",
"error",
]
for state_name in expected_states:
assert state_name in psm.states
def test_reconnaissance_is_composite(self):
"""Test that reconnaissance is a composite state."""
psm = PentestStateMachine()
recon = psm.states["reconnaissance"]
assert recon.state_type == StateType.COMPOSITE
assert "port_scanning" in recon.sub_states
assert "service_detection" in recon.sub_states
def test_completed_is_final(self):
"""Test that completed is a final state."""
psm = PentestStateMachine()
completed = psm.states["completed"]
assert completed.state_type == StateType.FINAL
@pytest.mark.asyncio
async def test_pentest_workflow_transitions(self):
"""Test pentest workflow transitions."""
psm = PentestStateMachine()
await psm.start("idle")
# Test idle -> reconnaissance transition
await psm.send("start")
await asyncio.sleep(0.05)
# Composite state enters initial sub-state (port_scanning)
assert psm.get_current_state() == "port_scanning"
# Parent state should be in active states
assert "reconnaissance" in psm.get_active_states()
await psm.stop()
# =============================================================================
# Tests for Factory Function
# =============================================================================
class TestFactoryFunction:
"""Tests for create_state_machine factory."""
@pytest.mark.asyncio
async def test_create_state_machine(self):
"""Test factory function creates machine."""
# Factory creates empty machine, need to add state first
sm = AdvancedStateMachine(name="FactoryMachine")
sm.add_state(State("start"))
await sm.start("start")
assert sm.name == "FactoryMachine"
assert sm.get_current_state() == "start"
assert sm._running is True
await sm.stop()
@pytest.mark.asyncio
async def test_create_state_machine_auto_started(self):
"""Test that factory creates and starts machine with PentestStateMachine."""
sm = PentestStateMachine()
await sm.start("idle")
assert sm._running is True
assert sm.get_current_state() is not None
await sm.stop()
# =============================================================================
# Tests for Error Recovery
# =============================================================================
class TestErrorRecovery:
"""Tests for error recovery functionality."""
@pytest.mark.asyncio
async def test_recovery_to_last_good_state(self):
"""Test recovery to last known good state."""
sm = AdvancedStateMachine(auto_recovery=True, enable_persistence=True)
sm.add_state(State("idle"))
sm.add_state(State("running"))
sm.add_transition(Transition("idle", "running"))
# Simulate history
sm._state_history.append({"from": "idle", "to": "running"})
await sm.start("running")
await sm._recover_from_error(Exception("Test error"))
# Should have tried to recover
await sm.stop()
@pytest.mark.asyncio
async def test_recovery_no_history(self):
"""Test recovery when no history exists."""
sm = AdvancedStateMachine(auto_recovery=True)
sm.add_state(State("idle"))
await sm.start("idle")
# Should not raise
await sm._recover_from_error(Exception("Test"))
await sm.stop()
# =============================================================================
# Tests for Auto-Transitions
# =============================================================================
class TestAutoTransitions:
"""Tests for auto-trigger transitions."""
@pytest.mark.asyncio
async def test_auto_trigger_transition(self):
"""Test auto-trigger transition fires automatically."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
sm.add_state(State("running"))
# Auto-trigger with passing guard (no event required)
guard = TransitionGuard(lambda e, c: True)
sm.add_transition(Transition("idle", "running", auto_trigger=True, guards=[guard]))
await sm.start("idle")
await asyncio.sleep(0.15) # Wait for auto-check
# May or may not have triggered depending on timing
await sm.stop()
# =============================================================================
# Edge Cases and Error Handling
# =============================================================================
class TestEdgeCases:
"""Tests for edge cases and error handling."""
def test_empty_state_machine(self):
"""Test empty state machine creation."""
sm = AdvancedStateMachine()
assert sm.states == {}
assert sm.transitions == []
@pytest.mark.asyncio
async def test_send_event_to_stopped_machine(self, state_machine):
"""Test sending event to stopped machine."""
# Should not raise
await state_machine.send("test")
assert state_machine._event_queue.qsize() == 1
@pytest.mark.asyncio
async def test_state_action_retry_on_failure(self, state_context):
"""Test state action retry mechanism."""
call_count = 0
def failing_action(state, context):
nonlocal call_count
call_count += 1
if call_count < 3:
raise RuntimeError("Temporary failure")
state = State("test")
action = StateAction(failing_action, retry_on_failure=True, max_retries=3)
state.entry_actions.append(action)
await state.enter(state_context)
assert call_count == 3
@pytest.mark.asyncio
async def test_state_action_retry_exhausted(self, state_context):
"""Test state action when retries are exhausted."""
def always_fails(state, context):
raise RuntimeError("Always fails")
state = State("test")
action = StateAction(always_fails, retry_on_failure=True, max_retries=2)
state.entry_actions.append(action)
with pytest.raises(RuntimeError):
await state.enter(state_context)
def test_state_to_dict_when_active(self):
"""Test state to_dict when active."""
state = State("test")
state._active = True
state._entered_at = datetime.now() - timedelta(seconds=10)
result = state.to_dict()
assert result["active"] is True
assert result["duration_seconds"] is not None
assert result["duration_seconds"] >= 10
# =============================================================================
# Performance and Stress Tests
# =============================================================================
class TestPerformance:
"""Performance-related tests."""
@pytest.mark.asyncio
async def test_many_rapid_transitions(self):
"""Test handling many rapid transitions."""
sm = AdvancedStateMachine(enable_persistence=False)
# Create states
for i in range(10):
sm.add_state(State(f"state_{i}"))
# Create transitions
for i in range(9):
sm.add_transition(Transition(f"state_{i}", f"state_{i + 1}", event="next"))
await sm.start("state_0")
# Send many events rapidly
for _ in range(20):
await sm.send("next")
await asyncio.sleep(0.2)
await sm.stop()
# Should have processed without errors
assert sm._transition_count > 0
@pytest.mark.asyncio
async def test_many_event_handlers(self):
"""Test with many event handlers registered."""
sm = AdvancedStateMachine(enable_persistence=False)
sm.add_state(State("idle"))
calls = []
for i in range(50):
def make_handler(idx):
return lambda e, c: calls.append(idx)
sm.on("test", make_handler(i))
await sm.start("idle")
await sm.send("test")
await asyncio.sleep(0.1)
assert len(calls) == 50
await sm.stop()
# =============================================================================
# Main entry point for running tests
# =============================================================================
if __name__ == "__main__":
pytest.main([__file__, "-v", "--tb=short"])
"""
Unit Tests for State Machine Module
====================================
Comprehensive tests for state_machine.py
Focus Areas:
- State Transitions
- Event Handling
- State Persistence
Tests: 60+
No external dependencies - pure unit tests
"""
import asyncio
import json
import os
import sys
from datetime import datetime, timedelta
from unittest.mock import AsyncMock, Mock, patch
import pytest
# Add parent directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))
from core.state_machine import (
AdvancedStateMachine,
HistoryType,
PentestStateMachine,
State,
StateAction,
StateContext,
StateEvent,
StateType,
Transition,
TransitionGuard,
create_state_machine,
)
# =============================================================================
# Fixtures
# =============================================================================
def event_loop():
"""Create an instance of the default event loop for each test case."""
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
def state_context():
"""Create a fresh StateContext for testing."""
return StateContext(session_id="test-session-123")
def simple_state():
"""Create a simple state for testing."""
return State("test_state", StateType.SIMPLE)
def composite_state():
"""Create a composite state with sub-states for testing."""
parent = State("parent", StateType.COMPOSITE)
child1 = State("child1", StateType.SIMPLE)
child2 = State("child2", StateType.SIMPLE)
parent.add_sub_state(child1)
parent.add_sub_state(child2)
return parent
def state_machine():
"""Create a fresh AdvancedStateMachine for testing."""
sm = AdvancedStateMachine(name="TestMachine", enable_persistence=False)
# Add some basic states
sm.add_state(State("idle", StateType.SIMPLE))
sm.add_state(State("running", StateType.SIMPLE))
sm.add_state(State("completed", StateType.FINAL))
return sm
def running_state_machine():
"""Create and start a state machine for testing."""
sm = AdvancedStateMachine(name="RunningMachine", enable_persistence=False)
sm.add_state(State("idle", StateType.SIMPLE))
sm.add_state(State("active", StateType.SIMPLE))
async def _start():
await sm.start("idle")
return sm
return asyncio.get_event_loop().run_until_complete(_start())
Xet Storage Details
- Size:
- 51.3 kB
- Xet hash:
- 69d11d683e917c38a180f05de6910d4523f32156a9219f8b40dc8140243e44e4
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.