inmemory_test.go
Overview
This file contains unit tests for the in-memory implementation of the memory.Service interface, specifically testing the Search functionality provided by the InMemoryService() from the memory package. The tests verify that the in-memory memory service correctly indexes, stores, and retrieves session events based on search queries, while enforcing proper scoping by application name and user ID.
The file defines a helper struct testSession which implements the session.Session interface, allowing the creation of mock sessions with lists of events for testing purposes. The test cases cover typical scenarios including matching events, absence of matches, and ensuring no data leakage across different apps or users.
The tests utilize external libraries such as go-cmp for deep comparison of expected and actual results, genai for generating content with roles, and Go standard libraries for time parsing and sorting.
Detailed Descriptions
Test_inMemoryService_SearchMemory
Purpose:
Tests the search functionality of the in-memory memory service to ensure it returns the correct events matching the search query within the correct app and user scope.Parameters:
t *testing.T- Standard Go testing handle.
Test Structure:
A table-driven test iterating over multiple scenarios defined in a slice of structs, each specifying:name(string): Name of the test case.initSessions ([]session.Session): Initial sessions to preload into the in-memory service.
req(*memory.SearchRequest): The search query input.wantResp (*memory.SearchResponse): The expected search results.
wantErr (bool): Indicates if an error is expected.
Function Flow:
Initialize the in-memory memory service via
memory.InMemoryService().Populate the service with pre-defined sessions using AddSession.
Call
Searchwith the test's search request.Verify errors against expectations.
Compare the returned memory entries with expected ones after sorting by timestamp.
Usage Example:
req := &memory.SearchRequest{
AppName: "app1",
UserID: "user1",
Query: "quick hello",
}
resp, err := s.Search(ctx, req)
if err != nil {
// handle error
}
// process resp.Memories
makeSession
Purpose:
Helper function to instantiate atestSessionimplementing thesession.Sessioninterface for use in tests.Parameters:
t *testing.T: Testing handle for helper marking.appName string: Application name associated with the session.userID string: User identifier for the session.sessionID string: Unique session ID.events []*session.Event: Slice of session events to associate with the session.
Returns:
session.Session: An instance oftestSessionconfigured with the provided parameters.
Usage Example:
sess := makeSession(t, "app1", "user1", "sess1", events)
testSession Struct and Methods
Purpose:
A mock implementation of thesession.Sessioninterface to simulate session behavior in tests.Fields:
appName stringuserID stringsessionID stringevents []*session.Event
Methods and Behavior:
Method
Description
ID()Returns the session's unique identifier.
AppName()Returns the application name associated with the session.
UserID()Returns the user ID associated with the session.
Events()Returns the session itself as it implements the
session.Eventsinterface.All()Returns a sequence of all events in the session (slice of pointers to
session.Event).Len()Returns the number of events in the session.
At(i int)Returns the event at the specified index.
State()Panics (not implemented), as state handling is not required for these tests.
LastUpdateTime()Panics (not implemented), not used in current tests.
sortMemories Transformer
Purpose:
Ago-cmptransformer function used in test assertions to sort theMemoriesslice by timestamp before comparison, ensuring order-independent equality checks.Input:
Pointer to
memory.SearchResponse.
Output:
Sorted pointer to
memory.SearchResponsewithMemoriessorted chronologically.
Sorting Logic:
Usesslices.SortFuncwith a comparator based onTimestamp.Compare.
must Helper Function
Purpose:
A generic helper to unwrap a value and error tuple, panicking if an error is present. Used primarily for simplifying time parsing calls in tests.Parameters:
v V: Value of any type.err error: Error to check.
Returns:
V: The value iferrisnil.
Behavior:
Panics on non-nil error; otherwise returns the value.Usage Example:
t := must(time.Parse(time.RFC3339, "2023-10-01T10:00:00Z"))
Important Implementation Details
The tests simulate realistic user sessions consisting of multiple
session.Eventobjects, each with an author, timestamp, and LLM response content.Search queries are tested against the combined content of events across sessions for a given app and user.
The in-memory service is expected to isolate results by
AppNameandUserID, preventing cross-app or cross-user data leakage.The test uses the
cmp.Difffunction with the custom sorter to verify that the returned memories exactly match the expected entries without order sensitivity.testSessionimplements thesession.Eventsinterface by returning itself, leveraging methods likeLen()andAt()to provide event iteration capabilities.Two methods in
testSession(State()andLastUpdateTime()) are unimplemented and will panic if called, indicating they are not relevant for these tests.
Interaction with Other System Components
memory.InMemoryService(): The core in-memory memory service under test, responsible for storing sessions and providing search capabilities.session.SessionInterface: The testSession mocks this interface to provide session data to the memory service.session.Event: Represents individual events within sessions, including user/model content and timestamps.model.LLMResponseandgenai.Content: Used to create content for events with role-based metadata (e.g., user or model).memory.SearchRequestandmemory.SearchResponse: Input and output types for the memory service's search API.cmpandslices: Utility libraries used for comparing and sorting test results.The tests simulate realistic usage scenarios that would interface with in-memory session and memory services as part of the larger system described in Session Management and In-Memory Session Service.
Mermaid Diagram: File Structure and Function Relationships
flowchart TD
A[Test_inMemoryService_SearchMemory]
B[makeSession]
C[testSession]
D[must]
E[sortMemories]
A --> B
A --> E
A --> C
B --> C
A --> D
Explanation:
Test_inMemoryService_SearchMemoryis the main test function coordinating the tests.It depends on
makeSessionto create session mocks.makeSessionreturns atestSessioninstance which implements the required interfaces.sortMemoriesis a helper used within the test to order results before comparison.mustis a utility function called inside the test andmakeSessionfor error handling convenience.