instruction_processor_test.go
Overview
This file contains comprehensive unit tests for the session state and artifact injection functionality within instruction templates, specifically testing the InjectSessionState function. The purpose of these tests is to verify that placeholders in instruction template strings are correctly replaced with values from session state or artifact contents, and that error handling behaves as expected in various scenarios.
These tests ensure the robustness of the dynamic instruction injection mechanism, which is a critical part of the Instruction Injection subtopic. This functionality supports the generation of context-aware prompts by embedding live session and artifact data into LLM instructions.
Detailed Explanation of Test Structure and Logic
Test Function: TestInjectSessionState
This is the sole exported test function in the file, defined using Go's testing package. It employs table-driven testing to cover multiple scenarios of template injection:
func TestInjectSessionState(t *testing.T) { ... }
Test Case Structure
Each test case is defined as a struct with the following fields:
Field Name | Type | Description |
|---|---|---|
|
| Identifier for the sub-test, describing the scenario. |
|
| Input instruction template string containing placeholders. |
|
| Initial session state key-value pairs to inject. |
|
| Artifacts keyed by filename, representing saved artifact data. |
|
| If |
|
| Expected resulting string after injection. |
|
| Whether an error is expected from injection. |
|
| Substring expected in the error message, for assertion. |
Test Case Examples
Successful state injection: Template
"Hello {user_name}, you are in {app_state} state."with session state providing"user_name": "Foo"and"app_state": "active"should produce"Hello Foo, you are in active state.".Successful artifact injection: Template with
{artifact.my_file}where"my_file"artifact contains"This is my artifact content."should inject the artifact text.Optional placeholders: Template with
{optional_value?}where the key is missing should replace the placeholder with an empty string without error.Error scenarios: Missing required session keys or artifacts produce errors with expected messages.
Invalid placeholder syntax: Placeholders with invalid characters or prefixes are left unmodified.
Complex templates: Combining multiple placeholders of different types including optional artifacts and session state variables.
Test Workflow
For each test case, the following steps occur:
Subtest Initialization with
t.Run
Each case runs as a subtest, isolating execution and improving output clarity.Session Service Setup
An in-memory session service is created (
session.InMemoryService()).A session is created with the test case state via
sessionService.Create.A mutable session wrapper is constructed (
sessioninternal.NewMutableSession).
Artifact Service Setup
If
expectNilServiceis false, an in-memory artifact service is initialized and wrapped.Artifacts from the test case are saved into the artifact service.
Invocation Context Creation
An
InvocationContextis constructed with the session and artifact services (icontext.NewInvocationContext).
Injection Execution
The function under test,
InjectSessionState(ctx, template), is called with the context and template.
Assertion
If an error is expected (
wantErr), asserts an error occurred and optionally checks error message content.Otherwise, asserts no error and that the output matches the expected string exactly.
Important Implementation Details and Algorithms Tested
Placeholder Parsing and Replacement:
The test cases exercise the functionality of identifying placeholders enclosed in{}and replacing them with appropriate values from session state or artifacts.Optional Placeholders Handling:
Placeholders suffixed with?should not cause an error if missing; instead, they are replaced with an empty string.Artifact Loading:
Placeholders with the prefixartifact.trigger artifact content loading. Errors are raised if the artifact service is nil or the artifact is missing.Validation of Placeholder Names:
Placeholders with invalid characters or prefixes are not replaced and remain as-is.Nil Values in State:
If a session state value isnil, it is replaced with an empty string.Error Scenarios:
Tests confirm that missing required keys/artifacts cause error returns with descriptive messages.Complex Templates:
The test suite verifies multi-line templates with mixed placeholders are fully and correctly injected.
Interaction with Other Parts of the System
This test file validates core behavior of the InjectSessionState function, which is part of the Instruction Template Processing subsystem (80563) and Instruction Injection (80568). Specifically:
It uses the Session Management (
80559) in-memory session service to simulate session state storage and retrieval.It uses the Artifact Management (
80557) in-memory artifact service to simulate artifact storage and loading.It creates an Invocation Context (
80572) combining session and artifact services, mimicking the environment in which agents operate.It tests the functionality that dynamically injects session and artifact data into LLM prompts, which is a key step before sending instructions to the LLM model.
Usage Example from Test Cases
template := "Hello {user_name}, you are in {app_state} state."
state := map[string]any{"user_name": "Foo", "app_state": "active"}
sessionService := session.InMemoryService()
createResp, err := sessionService.Create(ctx, &session.CreateRequest{
AppName: "testApp",
UserID: "testUser",
SessionID: "testSession",
State: state,
})
sess := sessioninternal.NewMutableSession(sessionService, createResp.Session)
artifacts := &artifactinternal.Artifacts{
Service: artifact.InMemoryService(),
AppName: "testApp",
UserID: "testUser",
SessionID: "testSession",
}
ctx := icontext.NewInvocationContext(context.Background(), icontext.InvocationContextParams{
Artifacts: artifacts,
Session: sess,
})
result, err := InjectSessionState(ctx, template)
// result should be "Hello Foo, you are in active state."
This example shows the setup of session and artifact services, creation of an invocation context, and execution of the injection function under test.
Mermaid Diagram: Test Structure and Workflow
flowchart TD
Start[TestInjectSessionState]
Start --> DefineTestCases[Test Cases Defined]
DefineTestCases --> ForEachTestCase[For Each Test Case]
ForEachTestCase --> SetupSessionService[Setup Session Service]
SetupSessionService --> SetupArtifactService[Setup Artifact Service]
SetupArtifactService --> CreateInvocationContext[Create Invocation Context]
CreateInvocationContext --> CallInjectSessionState[Call InjectSessionState]
CallInjectSessionState --> AssertResults[Assert Output or Error]
AssertResults --> NextTestCase{More Tests?}
NextTestCase -->|Yes| ForEachTestCase
NextTestCase -->|No| End[Test Complete]
Summary of Key Points
The file tests
InjectSessionState, which replaces placeholders in instruction templates using session state and artifacts.It covers success cases, error handling, optional placeholders, invalid syntax, and complex template scenarios.
The tests simulate real invocation contexts with in-memory session and artifact services.
This testing is crucial for ensuring the reliability of dynamic instruction generation in agents, as described in Instruction Injection.
The file directly interacts with and validates the integration of session state and artifact management subsystems via the invocation context.
This documentation references the following related topics for additional context:
Instruction Injection — Core mechanism tested here for embedding session and artifact data into instructions.
Session Management — Source of session state data used in injection.
Artifact Management — Source of artifact content loaded during injection.
Agent Invocation Context — Provides the context encapsulating session and artifact services for injection.
Instruction Template Processing — Broader processing of instruction templates related to this injection function.