mutablesession_test.go
Overview
The mutablesession_test.go file contains unit tests for the MutableSession type provided by the sessioninternal package. This file validates the core functionality of mutable session objects, which represent user sessions capable of storing and modifying arbitrary key-value state data. These tests ensure the correctness of session state mutation, retrieval, and the passthrough of session metadata methods.
This test suite interacts primarily with:
The
sessioninternal.MutableSessionstruct, responsible for encapsulating session state and operations.The
session.Serviceinterface and its in-memory implementation, which simulate session creation and storage.The underlying session model and interface definitions from the google.golang.org/adk/session package.
The file's tests verify:
Setting and getting individual state entries.
Retrieving all session state data as a map.
Correct propagation of session metadata through passthrough accessor methods.
Detailed Explanations
Helper Function: createMutableSession
func createMutableSession(ctx context.Context, t *testing.T, sessionID string, initialData map[string]any) (*sessioninternal.MutableSession, session.Service)
Purpose: Creates a new mutable session with initial state data using an in-memory session service.
Parameters:
ctx: Context for request scoping and cancellation.t: Testing handle for error reporting.sessionID: Unique identifier for the session to be created.initialData: Initial key-value map to populate the session state.
Returns:
A pointer to a
MutableSessioninitialized with the created session.The
session.Serviceinstance used (in-memory implementation).
Details:
Uses
session.InMemoryService()to simulate a session storage backend.Constructs a
session.CreateRequestwith fixed app and user identifiers and the provided session ID and initial state.Calls
service.Createto create a new session, failing the test if this operation returns an error.Wraps the created session in a
MutableSessionusingsessioninternal.NewMutableSession.
Usage Example:
ms, svc := createMutableSession(ctx, t, "session123", map[string]any{"foo": "bar"})
Test: TestMutableSession_SetGet
func TestMutableSession_SetGet(t *testing.T)
Purpose: Verifies that individual state keys can be set and retrieved correctly.
Test Cases:
Setting string, integer, and boolean values.
Overwriting an existing key.
Adding a new key to a session with pre-existing state.
Workflow:
For each test case, a new mutable session is created with optional initial state.
The
Setmethod ofMutableSessionis called to update the session state.The
Getmethod is then used to retrieve the stored value.The retrieved value is compared to the expected value using
cmp.Difffrom thego-cmppackage.
Failure Handling: The test fails if
SetorGetreturns an error or if the retrieved value differs from the expected one.
Test: TestMutableSession_All
func TestMutableSession_All(t *testing.T)
Purpose: Confirms that the
Allmethod returns the complete session state as a map.Test Cases:
Session initialized with multiple key-value pairs.
Session with empty or nil initial state.
Workflow:
For each test case, a new mutable session is created.
The
Allmethod is called, which returns an iterator of key-value pairs.The iterator is converted to a map using
maps.Collect.The resulting map is compared to the expected initial state (or empty map if nil).
Validation: Uses
cmp.Diffto detect differences and reports errors if any mismatch is found.
Test: TestMutableSession_PassthroughMethods
func TestMutableSession_PassthroughMethods(t *testing.T)
Purpose: Tests that the
MutableSessioncorrectly exposes session metadata and passthrough methods.Methods Tested:
ID() string— Returns the session ID.AppName() string— Returns the application name.UserID() string— Returns the user ID.LastUpdateTime() time.Time— Returns the last update timestamp.Events() []Event— Returns the event history associated with the session.State() any— Returns the underlying session state object.
Workflow:
Creates a session via the
session.InMemoryService.Constructs a mutable session wrapper.
Calls each passthrough method and verifies the returned values against expected values from the original session.
Validates non-nil and type correctness for
EventsandState.
Validation: Uses
reflect.DeepEqualand other checks to ensure correctness.
Important Implementation Details
Testing Approach: The tests rely on an in-memory session service implementation (
session.InMemoryService) which provides a lightweight, thread-safe storage backend for sessions, facilitating quick and isolated unit tests.State Representation: Session state is represented as a map of string keys to arbitrary values (
map[string]any), allowing flexible data storage.Comparison Tool: The
google/go-cmppackage is used for deep comparison of values to detect subtle mismatches in expected vs. actual session contents.Error Handling: Tests use
t.Fatalfandt.Errorfto report failures early and provide detailed diagnostics.Session Wrapper: The
MutableSessionis a wrapper around a session state object and the service, exposing methods to mutate and access session data while maintaining metadata consistency.
Interaction with Other Components
sessioninternal.MutableSession: The primary subject under test, this type encapsulates session state and exposes mutation and access methods.session.Service: The interface used to create and manage session lifecycle, represented here by an in-memory implementation suitable for testing.session.CreateRequestandsession.CreateResponse: Used to initiate sessions with initial state and metadata.session.Session: The core session interface containing metadata and state, wrapped byMutableSession.Testing Framework: Uses Go's standard
testingpackage with helper functions for streamlined test setup.Utility Packages: Uses
mapsfrom the standard library for iterator collection andcmpfor value comparison.
This file is part of the broader session management system described in Session Management, focusing on verifying mutable session behavior.
Structure Diagram
flowchart TD
A[createMutableSession] --> B[session.InMemoryService]
A --> C[session.CreateRequest]
A --> D[sessioninternal.NewMutableSession]
subgraph TestMutableSession_SetGet
E[MutableSession.Set]
F[MutableSession.Get]
end
subgraph TestMutableSession_All
G[MutableSession.All]
H[maps.Collect]
end
subgraph TestMutableSession_PassthroughMethods
I[MutableSession.ID]
J[MutableSession.AppName]
K[MutableSession.UserID]
L[MutableSession.LastUpdateTime]
M[MutableSession.Events]
N[MutableSession.State]
end
D --> E
D --> F
D --> G
D --> I
D --> J
D --> K
D --> L
D --> M
D --> N
Summary of Key Functions and Methods
Function/Method | Description | Parameters | Returns |
|---|---|---|---|
| Helper to create a mutable session with initial state | context, testing.T, sessionID, initial map | *MutableSession, |
Sets a key-value pair in the session state | key string, value any | error | |
Retrieves a value for a given key | key string | value any, error | |
Returns an iterator over all key-value pairs in the session | none | iterator of key-value pairs | |
Returns the session ID | none | string | |
Returns the application name associated with the session | none | string | |
Returns the user ID associated with the session | none | string | |
Returns the last update time of the session | none | time.Time | |
Returns the list of events associated with the session | none | slice of events | |
Returns the underlying session state object | none | any |
This documentation focuses exclusively on the testing and verification of the MutableSession functionalities, which are a core part of the session management subsystem as described in Session Management.