testsessionservice.go
Overview
testsessionservice.go implements a fake in-memory session service used primarily for testing purposes within the ADK framework. It provides a mock version of the session management functionality defined in the broader system, allowing tests to simulate session creation, retrieval, listing, deletion, and event appending without requiring a persistent backend. This helps isolate session-related logic in tests and supports deterministic behavior.
The file defines several types such as TestState, TestEvents, TestSession, and FakeSessionService, which collectively emulate real session behavior while storing data in simple Go maps and slices. It implements the session.Service interface, ensuring compatibility with the rest of the application that relies on session services.
Types and Their Responsibilities
TestState
Type: map[string]any
Purpose: Represents the session state as a key-value store, allowing arbitrary data to be stored and retrieved.
Methods:
Get(key string) (any, error): Returns the value for the specified key.Set(key string, val any) error: Sets the value for the specified key.All() iter.Seq2[string, any]: Returns an iterator over all key-value pairs in the state.
Usage: Used as the implementation of the
session.Stateinterface for session state management.
TestEvents
Type: []*session.Event
Purpose: Holds a slice of session events associated with a session.
Methods:
All() iter.Seq[*session.Event]: Returns an iterator over all stored events.Len() int: Returns the number of events.At(i int) *session.Event: Returns the event at a given index.
Usage: Implements the session.Events interface to provide event history for a session.
TestSession
Fields:
Id SessionKey: Uniquely identifies the session.SessionState TestState: Stores the session state.SessionEvents TestEvents: Stores the event history.UpdatedAt time.Time: Timestamp of the last update.
Methods: Implements the
session.Sessioninterface:ID() string: Returns the session ID.AppName() string: Returns the application name.UserID() string: Returns the user ID.State() session.State: Returns the session state.Events() session.Events: Returns the session events.LastUpdateTime() time.Time: Returns the last update timestamp.
Usage: Represents a full session object combining identity, state, and events.
SessionKey
Fields:
AppName stringUserID stringSessionID string
Purpose: Composite key used to uniquely identify sessions in the
FakeSessionServicemap.Usage: Used as map keys for storing and retrieving sessions.
FakeSessionService
Fields:
Sessions map[SessionKey]TestSession: In-memory storage of sessions keyed bySessionKey.
Implements: The
session.Serviceinterface.Purpose: Provides fake implementations of session service methods for testing.
Methods of FakeSessionService
Each method receives a context.Context and request objects from the session package, returning appropriate responses or errors.
Create
func (s *FakeSessionService) Create(ctx context.Context, req *session.CreateRequest) (*session.CreateResponse, error)
Purpose: Creates a new session with the provided application name, user ID, session ID (optional), and initial state.
Behavior:
Checks if a session with the same key already exists; returns an error if so.
If no session ID is provided, assigns
"testID".Constructs a
TestSessionwith the provided parameters and current time.Stores the session in
Sessionsmap.Returns the created session wrapped in
session.CreateResponse.
Errors: Returns an error if the session already exists.
Example:
resp, err := fakeService.Create(ctx, &session.CreateRequest{ AppName: "app1", UserID: "user1", SessionID: "", State: make(TestState), })
Get
func (s *FakeSessionService) Get(ctx context.Context, req *session.GetRequest) (*session.GetResponse, error)
Purpose: Retrieves a session by application name, user ID, and session ID.
Behavior: Looks up the session in the map; returns it if found.
Errors: Returns "not found" error if session does not exist.
Example:
resp, err := fakeService.Get(ctx, &session.GetRequest{ AppName: "app1", UserID: "user1", SessionID: "testID", })
List
func (s *FakeSessionService) List(ctx context.Context, req *session.ListRequest) (*session.ListResponse, error)
Purpose: Lists all sessions for a given application name and user ID.
Behavior: Iterates over all stored sessions, filters by
AppNameandUserID.Returns: A slice of sessions matching the criteria.
Example:
resp, err := fakeService.List(ctx, &session.ListRequest{ AppName: "app1", UserID: "user1", })
Delete
func (s *FakeSessionService) Delete(ctx context.Context, req *session.DeleteRequest) error
Purpose: Deletes a specific session identified by application name, user ID, and session ID.
Behavior: Removes the session from the map.
Errors: Returns "not found" error if session does not exist.
Example:
err := fakeService.Delete(ctx, &session.DeleteRequest{ AppName: "app1", UserID: "user1", SessionID: "testID", })
AppendEvent
func (s *FakeSessionService) AppendEvent(ctx context.Context, curSession session.Session, event *session.Event) error
Purpose: Appends a new event to the session's event list and updates the last update timestamp.
Behavior:
Converts the generic
session.Sessioninterface to*TestSession.Appends the event to
SessionEvents.Updates
UpdatedAtwith the event's timestamp.Stores the updated session back into the map.
Errors: Returns an error if the session type is invalid (not
*TestSession).Example:
err := fakeService.AppendEvent(ctx, testSession, newEvent)
Important Implementation Details
In-Memory Storage: Sessions are stored in a Go map keyed by
SessionKey, allowing fast retrieval and mutation.Session Identification: Uses a composite
SessionKeyconsisting of application name, user ID, and session ID to uniquely identify sessions.Event Handling: Events are appended to a slice, preserving order and allowing iteration via
TestEvents.State Interface Compliance:
TestStateimplements thesession.Stateinterface by providingGet,Set, andAllmethods.Session Interface Compliance:
TestSessionimplements thesession.Sessioninterface by exposing identity, state, events, and last update time methods.Type Safety in AppendEvent: The
AppendEventmethod requires the session to be a*TestSessionpointer to ensure safe mutation.
Interaction with Other System Components
Implements
session.Serviceinterface: This fake session service can be used wherever asession.Serviceis expected, allowing injection in tests.Works with
session.Session,session.State, andsession.Event: Uses these interfaces and types from thegoogle.golang.org/adk/sessionpackage.Supports Testing Workflows: Provides a lightweight alternative to persistent session services like database-backed implementations (
Database Session Service[80585]) or in-memory thread-safe implementations (In-Memory Session Service[80582]).Used in Testing Contexts: Facilitates testing of agent workflows, event processing, and session state management without external dependencies.
Usage Example
// Initialize fake service
fakeService := &FakeSessionService{
Sessions: make(map[SessionKey]TestSession),
}
// Create a session
createResp, err := fakeService.Create(context.Background(), &session.CreateRequest{
AppName: "TestApp",
UserID: "User1",
SessionID: "",
State: make(TestState),
})
// Retrieve the session
getResp, err := fakeService.Get(context.Background(), &session.GetRequest{
AppName: "TestApp",
UserID: "User1",
SessionID: "testID",
})
// Append an event
event := &session.Event{
Timestamp: time.Now(),
Name: "TestEvent",
Data: nil,
}
err = fakeService.AppendEvent(context.Background(), getResp.Session, event)
Diagram: Class and Type Structure
classDiagram
class TestState {
+Get()
+Set()
+All()
}
class TestEvents {
+All()
+Len()
+At()
}
class TestSession {
-Id: SessionKey
-SessionState: TestState
-SessionEvents: TestEvents
-UpdatedAt: time.Time
+ID()
+AppName()
+UserID()
+State()
+Events()
+LastUpdateTime()
}
class SessionKey {
-AppName: string
-UserID: string
-SessionID: string
}
class FakeSessionService {
-Sessions: map[SessionKey]TestSession
+Create()
+Get()
+List()
+Delete()
+AppendEvent()
}
FakeSessionService --> "1..*" TestSession : manages
TestSession --> TestState : contains
TestSession --> TestEvents : contains
TestSession --> SessionKey : identified by
References to Related Topics
See
Session Managementfor the design and interface of sessions and session services within the system.For implementations of persistent or other session service types, refer to
Database Session ServiceandIn-Memory Session Service.The session events and state interfaces used here are part of the core session abstractions in
Session Management.