executor_test.go
Overview
The executor_test.go file contains unit tests for the Executor component of the system, which is responsible for executing AI agent tasks and managing their lifecycle in the context of the Agent-To-Agent (A2A) protocol. The tests verify the behavior of the executor when processing tasks through the agent runtime, handling sessions, managing event queues, and dealing with cancellation requests.
The file primarily focuses on the following:
Testing the execution flow of tasks (Executor.Execute) including interaction with agents and sessions.
Testing cancellation logic (
Executor.Cancel).Validating session reuse behavior.
Simulating failures in session creation, agent execution, and event queue writes.
Ensuring correct event generation and error handling during execution.
This testing file interacts with components such as the agent.Agent interface, the session.Service for session management, and the eventqueue.Queue for event handling. It uses mock implementations and replay agents to simulate various scenarios and validate the executor's response.
Components and Key Elements
Types
testQueue
A test double implementing the eventqueue.Queue interface.
Fields:
events []a2a.Event– Stores events written to the queue.writeErr *eventIndex– If set, simulates a failure when writing an event at a particular index.
Method:
Write(ctx context.Context, e a2a.Event) error
Appends the event to the queue unless writeErr is triggered at the current event index, in which case it returns an error.
testSessionService
A test double wrapping the session.Service.
Fields:
createErr bool– If true, simulates a failure on session creation.
Method:
Create(ctx context.Context, req *session.CreateRequest) (*session.CreateResponse, error)
Either calls the underlying service or returns an error if createErr is set.
eventIndex
A simple struct representing an index position in the event queue to trigger failures.
Field:
i int– The event index at which to simulate failure.
Functions
newEventReplayAgent(events []*session.Event, failWith error) (agent.Agent, error)
Creates a mock agent.Agent which replays a predefined sequence of session events.
Parameters:
events []*session.Event– List of events to replay during agent execution.failWith error– Optional error to yield after replaying all events to simulate a failure.
Returns:
agent.Agent– Agent instance implementing a run function that yields the events.error– Returns an error if agent creation fails.
Usage:
Used to simulate agent execution by replaying a fixed event sequence and optionally injecting an error.
Test Functions
TestExecutor_Execute(t *testing.T)
Tests the Executor.Execute method's behavior across multiple scenarios defined as test cases.
Purpose:
Verifies the executor's handling of different input messages, session creation failures, agent run failures, queue write failures, and event generation correctness.Test Cases Include:
No message provided (expecting error).
Malformed message data (base64 error).
Session creation failure.
Successful execution for new and existing tasks.
Failures during queue writes and agent runs.
Handling of LLM-generated errors during agent execution.
Key Implementation Details:
Uses
newEventReplayAgentto simulate agent responses.Uses
testSessionServiceto simulate session service behavior.Uses
testQueueto capture and optionally fail event writes.Employs the
cmppackage with options to compare expected and actual events while ignoring non-critical fields such as IDs and timestamps.
Example Usage:
err = executor.Execute(ctx, reqCtx, queue) if err != nil { t.Fatalf("executor.Execute() error = %v, want nil", err) }
TestExecutor_Cancel(t *testing.T)
Tests the Executor.Cancel method.
Purpose:
Ensures that cancelling a task produces exactly one cancellation event with the appropriate state (TaskStateCanceled).Test Steps:
Creates a task and an executor instance.
Calls
Cancelon the executor with a request context and event queue.Asserts no error is returned.
Checks that a single cancellation event is emitted.
Usage Example:
err := executor.Cancel(ctx, reqCtx, queue) if err != nil { t.Fatalf("executor.Cancel() error = %v, want nil", err) }
TestExecutor_SessionReuse(t *testing.T)
Tests session reuse behavior across executions.
Purpose:
Validates that executing the same task multiple times reuses existing sessions, and that different context IDs result in different sessions.Implementation Details:
Uses an in-memory session service.
Executes the same request twice, expecting no errors.
Lists sessions to verify exactly one session exists for the same context.
Changes context ID to ensure a new session is created.
Usage:
Demonstrates session lifecycle management and reuse according to context identity.
Important Implementation Details and Algorithms
Event Replay Agent:
ThenewEventReplayAgentfunction constructs anagent.AgentwhoseRunmethod yields a fixed sequence of session events. This allows deterministic testing of the executor's handling of agent-generated events.Error Injection:
ThetestQueueandtestSessionServiceenable simulating failure modes such as write errors and session creation failures. This supports robust testing of executor error handling and event rollback.Event Comparison:
The test compares actual and expected events using thecmppackage with selective ignored fields (IDs, timestamps, metadata), focusing the test on meaningful event content and order.Task Event Flow:
The tests cover transitions through task states such asSubmitted,Working,Completed,Failed, andCanceled, verifying the executor emits the correct sequence of status and artifact events.
Interaction with Other System Components
Agent Interface (
agent.Agent):
The executor uses agents to process tasks, where agents produce session events representing responses or intermediate states.Session Service (
session.Service):
The executor relies on session services to create, retrieve, and manage sessions associated with tasks. Sessions store the state and event history of agent interactions.Event Queue (
eventqueue.Queue):
Events generated during execution (e.g., status updates, artifacts) are written to an event queue for downstream processing or client notification.Runner Configuration (
runner.Config):
The executor is configured with a runner that bundles the agent and session service, coordinating the execution environment.Request Context (
a2asrv.RequestContext):
Encapsulates the execution request details including task ID, context ID, and incoming message, providing context for execution and cancellation operations.
Diagram: Executor Test Structure and Workflow
flowchart TD
subgraph Test Setup
TC[Test Cases]
Agent[newEventReplayAgent]
Session[testSessionService]
Queue[testQueue]
end
subgraph Executor
Exec[Executor]
Runner[runner.Config]
end
TC -->|defines inputs| Agent
TC -->|sets failure flags| Session
TC -->|sets failure flags| Queue
Agent --> Exec
Session --> Exec
Queue --> Exec
Runner --> Exec
Exec -->|calls Execute/Cancel| Agent
Exec -->|uses| Session
Exec -->|writes events| Queue
Exec -->|generates events| Events[a2a.Events]
Events -->|compare| TC
click Agent href "80562" "LLM Integration and Agents"
click Session href "80559" "Session Management"
click Queue href "80591" "Event Conversion and Processing"
click Exec href "80589" "Executor and Server"
Usage Examples Extracted from Tests
1. Executing a task:
agent, _ := newEventReplayAgent(events, nil)
sessionService := &testSessionService{Service: session.InMemoryService()}
runnerConfig := runner.Config{AppName: agent.Name(), Agent: agent, SessionService: sessionService}
executor := NewExecutor(ExecutorConfig{RunnerConfig: runnerConfig})
queue := &testQueue{Queue: eventqueue.NewInMemoryQueue(10)}
reqCtx := &a2asrv.RequestContext{TaskID: task.ID, ContextID: task.ContextID, Message: request.Message}
err := executor.Execute(ctx, reqCtx, queue)
2. Cancelling a task:
executor := NewExecutor(ExecutorConfig{})
queue := &testQueue{Queue: eventqueue.NewInMemoryQueue(10)}
reqCtx := &a2asrv.RequestContext{TaskID: task.ID, ContextID: task.ContextID, StoredTask: task}
err := executor.Cancel(ctx, reqCtx, queue)
References to Related Topics
Executorand runner configuration is part of the Executor and Server topic.The agent interface and event replay relates closely to LLM Integration and Agents.
Session service mocking corresponds to Session Management.
Event queue handling ties in with Event Conversion and Processing.
Agent invocation context and lifecycle are discussed in Agent Invocation Context and Agent Lifecycle and Callbacks.
This documentation provides a detailed view of how the executor_test.go file exercises the Executor component, focusing on task execution, session handling, event generation, and error scenarios through comprehensive unit tests.