testutil

package
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package testutil provides fluent builders for creating complex test objects.

Package testutil provides centralized test mocks, fixtures, and helpers.

Package testutil provides centralized test mocks, fixtures, and helpers. All test files should import mocks from here instead of defining their own.

Index

Constants

View Source
const TestUserID int64 = 123

TestUserID is the default user ID for tests.

Variables

This section is empty.

Functions

func AssertContentType added in v0.6.1

func AssertContentType(t *testing.T, rr *httptest.ResponseRecorder, expected string)

AssertContentType asserts that the response has the expected Content-Type header.

func AssertErrorResponse added in v0.6.1

func AssertErrorResponse(t *testing.T, rr *httptest.ResponseRecorder, expectedStatus int, expectedContains string)

AssertErrorResponse asserts that the response is an error with the expected status code and optionally checks the error message contains the expected string.

func AssertFactContains added in v0.5.3

func AssertFactContains(t *testing.T, store *storage.SQLiteStore, userID int64, content string)

AssertFactContains asserts that a fact containing the given content exists.

func AssertFactCount added in v0.5.3

func AssertFactCount(t *testing.T, store *storage.SQLiteStore, userID int64, expected int)

AssertFactCount asserts the number of facts for a user.

func AssertFactExists added in v0.5.3

func AssertFactExists(t *testing.T, store *storage.SQLiteStore, userID int64, substr string) storage.Fact

AssertFactExists asserts that a fact containing the substring exists for the user. Returns the matching fact for further inspection.

func AssertJSONResponse added in v0.6.1

func AssertJSONResponse(t *testing.T, rr *httptest.ResponseRecorder, expectedStatus int, target interface{})

AssertJSONResponse asserts that the response has the expected status code and parses the JSON body into the target struct.

Example usage:

var resp struct { Success bool `json:"success"` }
testutil.AssertJSONResponse(t, rr, http.StatusOK, &resp)
assert.True(t, resp.Success)

func AssertLogContains added in v0.5.3

func AssertLogContains(t *testing.T, logs []LogEntry, level string, msg string)

AssertLogContains asserts that the log contains an entry with the given level and message.

func AssertLogHasField added in v0.5.3

func AssertLogHasField(t *testing.T, logs []LogEntry, key string, value interface{})

AssertLogHasField asserts that a log entry exists with the given field value.

func AssertMessageCount added in v0.5.3

func AssertMessageCount(t *testing.T, store *storage.SQLiteStore, userID int64, expected int)

AssertMessageCount asserts the number of messages for a user.

func AssertMessageExists added in v0.5.3

func AssertMessageExists(t *testing.T, store *storage.SQLiteStore, userID int64, substr string) storage.Message

AssertMessageExists asserts that a message containing the substring exists for the user.

func AssertMetricExists added in v0.5.3

func AssertMetricExists(t *testing.T, metrics, metricName string)

AssertMetricExists asserts that a metric exists in the metrics output.

func AssertMetricGreaterThan added in v0.5.3

func AssertMetricGreaterThan(t *testing.T, metrics, metricName string, threshold float64)

AssertMetricGreaterThan asserts that a metric value is greater than a threshold.

func AssertMetricIncremented added in v0.5.3

func AssertMetricIncremented(t *testing.T, before, after, metricName string)

AssertMetricIncremented asserts that a metric value increased between two scrapes. Useful for testing that a metric is incremented during an operation.

func AssertMetricValue added in v0.5.3

func AssertMetricValue(t *testing.T, metrics, metricName, expectedValue string, expectedLabels map[string]string)

AssertMetricValue asserts that a metric has a specific value (with optional label matching).

func AssertNoErrorLogs added in v0.5.3

func AssertNoErrorLogs(t *testing.T, logs []LogEntry)

AssertNoErrorLogs asserts that no ERROR level logs were captured.

func AssertPersonCount added in v0.5.3

func AssertPersonCount(t *testing.T, store *storage.SQLiteStore, userID int64, expected int)

AssertPersonCount asserts the number of people for a user.

func AssertPersonExists added in v0.5.3

func AssertPersonExists(t *testing.T, store *storage.SQLiteStore, userID int64, name string) storage.Person

AssertPersonExists asserts that a person with the given name exists for the user. Returns the matching person for further inspection.

func AssertPersonHasAlias added in v0.5.3

func AssertPersonHasAlias(t *testing.T, store *storage.SQLiteStore, userID int64, personName string, alias string)

AssertPersonHasAlias asserts that a person has a specific alias.

func AssertRedirect added in v0.6.1

func AssertRedirect(t *testing.T, rr *httptest.ResponseRecorder, expectedStatus int, expectedLocation string)

AssertRedirect asserts that the response is a redirect to the expected location.

func AssertSSEHeaders added in v0.6.1

func AssertSSEHeaders(t *testing.T, h SSEHeadersGetter)

AssertSSEHeaders asserts that the response has proper SSE headers. Accepts both *httptest.ResponseRecorder and *SSERecorder.

func AssertStatusCode added in v0.6.1

func AssertStatusCode(t *testing.T, rr *httptest.ResponseRecorder, expected int)

AssertStatusCode asserts that the response has the expected status code.

func AssertTopicCount added in v0.5.3

func AssertTopicCount(t *testing.T, store *storage.SQLiteStore, userID int64, expected int)

AssertTopicCount asserts the number of topics for a user.

func AssertTopicExists added in v0.5.3

func AssertTopicExists(t *testing.T, store *storage.SQLiteStore, userID int64, substr string) storage.Topic

AssertTopicExists asserts that a topic containing the substring exists for the user. Returns the matching topic for further inspection.

func CountSSEEvents added in v0.6.1

func CountSSEEvents(body string) int

CountSSEEvents counts the number of SSE events in the response body.

func ExecuteRequest added in v0.6.1

func ExecuteRequest(t *testing.T, handler http.Handler, req *http.Request) *httptest.ResponseRecorder

ExecuteRequest executes an HTTP request against a handler and returns the recorder. This is useful for testing individual handlers without a full server.

Example usage:

handler := http.HandlerFunc(myHandler)
req := testutil.NewTestRequest(t, "GET", "/api/stats", nil)
rr := testutil.ExecuteRequest(t, handler, req)
testutil.AssertStatusCode(t, rr, http.StatusOK)

func MockChatResponse added in v0.5.4

func MockChatResponse(content string) openrouter.ChatCompletionResponse

MockChatResponse creates a mock ChatCompletionResponse with the given content. Token counts are set to reasonable defaults (150/30/180).

func MockChatResponseWithTokens added in v0.5.4

func MockChatResponseWithTokens(content string, promptTokens, completionTokens int) openrouter.ChatCompletionResponse

MockChatResponseWithTokens creates a mock ChatCompletionResponse with the given content and token counts. TotalTokens is calculated automatically.

func MockChatResponseWithToolCalls added in v0.6.1

func MockChatResponseWithToolCalls(content string, toolCalls []openrouter.ToolCall) openrouter.ChatCompletionResponse

MockChatResponseWithToolCalls creates a mock ChatCompletionResponse with tool calls. Token counts are set to reasonable defaults (150/30/180).

func MockEmbeddingResponse added in v0.5.2

func MockEmbeddingResponse() *openrouter.EmbeddingResponse

MockEmbeddingResponse returns a mock embedding response for tests.

func MockToolCall added in v0.6.1

func MockToolCall(id, name, arguments string) openrouter.ToolCall

MockToolCall creates a mock ToolCall for testing.

func NewTestRequest added in v0.6.1

func NewTestRequest(t *testing.T, method, path string, body interface{}) *http.Request

NewTestRequest creates an HTTP request for testing handlers. For GET requests, body can be nil. For POST/PUT requests, body will be JSON-encoded if it's not nil and not already io.Reader.

Example usage:

req := testutil.NewTestRequest(t, "GET", "/api/stats?user_id=123", nil)
req := testutil.NewTestRequest(t, "POST", "/api/webhook", map[string]any{"key": "value"})

func NewTestRequestWithAuth added in v0.6.1

func NewTestRequestWithAuth(t *testing.T, method, path string, body interface{}, username, password string) *http.Request

NewTestRequestWithAuth creates an HTTP request with Basic Auth credentials.

func ParseMetricValue added in v0.5.3

func ParseMetricValue(metrics, metricName string) (string, map[string]string, error)

ParseMetricValue parses a single metric value from the metrics output. Returns the value and labels (if any) for the first matching metric.

func ProcessSessionForTest added in v0.5.3

func ProcessSessionForTest(t *testing.T, ctx context.Context, userID int64, store *storage.SQLiteStore) int64

ProcessSessionForTest processes the active session for testing purposes. This forces topic creation without waiting for timeout, but does NOT extract facts. For fact extraction, use the memory service or testbot with --process-session flag.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to the given value. Useful for optional fields.

func ReadJSONResponse added in v0.6.1

func ReadJSONResponse(t *testing.T, rr *httptest.ResponseRecorder, target interface{})

ReadJSONResponse reads the response body as JSON into the target struct. Unlike AssertJSONResponse, this doesn't make assertions about status or content type.

func ResponseBodyContains added in v0.6.1

func ResponseBodyContains(t *testing.T, rr *httptest.ResponseRecorder, expected string)

ResponseBodyContains checks if the response body contains the expected string.

func ResponseBodyEqual added in v0.6.1

func ResponseBodyEqual(t *testing.T, rr *httptest.ResponseRecorder, expected string)

ResponseBodyEqual checks if the response body exactly equals the expected string.

func SetupDefaultMocks

func SetupDefaultMocks(s *MockStorage)

SetupDefaultMocks configures mocks with safe defaults for background operations. Call this when testing code that may trigger background loops.

func TestAgentLog

func TestAgentLog() storage.AgentLog

TestAgentLog returns a sample agent log for testing.

func TestConfig

func TestConfig() *config.Config

TestConfig returns a config with sensible test defaults.

func TestConfigWithRAGDisabled

func TestConfigWithRAGDisabled() *config.Config

TestConfigWithRAGDisabled returns a test config with RAG disabled.

func TestDashboardStats

func TestDashboardStats() *storage.DashboardStats

TestDashboardStats returns sample dashboard stats for testing.

func TestEmbedding

func TestEmbedding() []float32

TestEmbedding returns a sample embedding vector for testing.

func TestFacts

func TestFacts() []storage.Fact

TestFacts returns sample facts for testing.

func TestLogger

func TestLogger() *slog.Logger

TestLogger returns a discarding logger for tests.

func TestMessage

func TestMessage() storage.Message

TestMessage returns a sample message for testing.

func TestMessages

func TestMessages() []storage.Message

TestMessages returns a conversation history for testing.

func TestPeople added in v0.5.3

func TestPeople() []storage.Person

TestPeople returns sample people for testing.

func TestProfileFacts

func TestProfileFacts() []storage.Fact

TestProfileFacts returns facts that would be included in a user profile.

func TestStat

func TestStat() storage.Stat

TestStat returns a sample stat for testing.

func TestTopic

func TestTopic() storage.Topic

TestTopic returns a sample topic for testing.

func TestTopics

func TestTopics() []storage.Topic

TestTopics returns multiple sample topics for testing.

func TestTranslator

func TestTranslator(t *testing.T) *i18n.Translator

TestTranslator creates a translator with minimal translations for tests. Use t.TempDir() automatically cleaned up after test.

func TestUser

func TestUser() storage.User

TestUser returns a standard test user.

func TestUsers

func TestUsers() []storage.User

TestUsers returns multiple test users.

Types

type LogCapture added in v0.5.3

type LogCapture struct {
	// contains filtered or unexported fields
}

LogCapture captures slog JSON output for testing.

func NewLogCapture added in v0.5.3

func NewLogCapture() *LogCapture

NewLogCapture creates a new log capture.

func (*LogCapture) Clear added in v0.5.3

func (lc *LogCapture) Clear()

Clear removes all captured entries.

func (*LogCapture) Entries added in v0.5.3

func (lc *LogCapture) Entries() []LogEntry

Entries returns all captured log entries.

func (*LogCapture) Find added in v0.5.3

func (lc *LogCapture) Find(level string, msgSubstring string) []LogEntry

Find returns entries matching the specified level and message substring.

func (*LogCapture) FindByField added in v0.5.3

func (lc *LogCapture) FindByField(key string, value interface{}) []LogEntry

FindByField returns entries containing the specified field value.

func (*LogCapture) Handler added in v0.5.3

func (lc *LogCapture) Handler() *slog.JSONHandler

Handler returns the slog.Handler for this capture.

func (*LogCapture) HasError added in v0.5.3

func (lc *LogCapture) HasError() bool

HasError returns true if any ERROR level entries were captured.

func (*LogCapture) Logger added in v0.5.3

func (lc *LogCapture) Logger() *slog.Logger

Logger returns the slog.Logger that writes to this capture.

func (*LogCapture) MultiWriter added in v0.5.3

func (lc *LogCapture) MultiWriter(w io.Writer) io.Writer

MultiWriter creates an io.Writer that writes to both LogCapture and another writer. Useful for writing logs to both a capture and stdout/stderr.

func (*LogCapture) ParseJSON added in v0.5.3

func (lc *LogCapture) ParseJSON(p []byte) LogEntry

ParseJSON parses a JSON log line into a LogEntry.

func (*LogCapture) Sync added in v0.5.3

func (lc *LogCapture) Sync() error

Sync is a no-op for compatibility.

func (*LogCapture) Write added in v0.5.3

func (lc *LogCapture) Write(p []byte) (n int, err error)

Write implements io.Writer for compatibility.

type LogEntry added in v0.5.3

type LogEntry struct {
	Level   string                 `json:"level"`
	Message string                 `json:"msg"`
	Time    time.Time              `json:"time"`
	Fields  map[string]interface{} `json:"-"`
}

LogEntry represents a parsed log entry.

type MetricsHelper added in v0.5.3

type MetricsHelper struct {
	// contains filtered or unexported fields
}

MetricsHelper provides helper functions for testing Prometheus metrics.

func NewMetricsHelper added in v0.5.3

func NewMetricsHelper(host string, port int) *MetricsHelper

NewMetricsHelper creates a new metrics helper.

func (*MetricsHelper) GetMetricValue added in v0.5.3

func (mh *MetricsHelper) GetMetricValue(metricName string) (string, map[string]string, error)

GetMetricValue is a convenience function that scrapes and parses a metric value.

func (*MetricsHelper) ScrapeMetrics added in v0.5.3

func (mh *MetricsHelper) ScrapeMetrics() (string, error)

ScrapeMetrics scrapes metrics from the metrics endpoint.

type MockAgentLogger added in v0.6.0

type MockAgentLogger struct {
	mock.Mock
}

MockAgentLogger implements agentlog.Logger for tests.

func NewMockAgentLogger added in v0.6.0

func NewMockAgentLogger() *MockAgentLogger

NewMockAgentLogger creates a new MockAgentLogger.

func (*MockAgentLogger) Log added in v0.6.0

func (m *MockAgentLogger) Log(ctx context.Context, entry interface{})

Log mock for agent log entry.

type MockBotAPI

type MockBotAPI struct {
	mock.Mock
}

MockBotAPI implements telegram.BotAPI for tests.

func (*MockBotAPI) GetFile

func (*MockBotAPI) GetToken

func (m *MockBotAPI) GetToken() string

func (*MockBotAPI) GetUpdates

func (*MockBotAPI) SendChatAction

func (m *MockBotAPI) SendChatAction(ctx context.Context, req telegram.SendChatActionRequest) error

func (*MockBotAPI) SendMessage

func (*MockBotAPI) SetMessageReaction

func (m *MockBotAPI) SetMessageReaction(ctx context.Context, req telegram.SetMessageReactionRequest) error

func (*MockBotAPI) SetMyCommands

func (m *MockBotAPI) SetMyCommands(ctx context.Context, req telegram.SetMyCommandsRequest) error

func (*MockBotAPI) SetWebhook

func (m *MockBotAPI) SetWebhook(ctx context.Context, req telegram.SetWebhookRequest) error

type MockFileDownloader

type MockFileDownloader struct {
	mock.Mock
}

MockFileDownloader implements telegram.FileDownloader for tests.

func (*MockFileDownloader) DownloadFile

func (m *MockFileDownloader) DownloadFile(ctx context.Context, fileID string) ([]byte, error)

func (*MockFileDownloader) DownloadFileAsBase64

func (m *MockFileDownloader) DownloadFileAsBase64(ctx context.Context, fileID string) (string, error)

type MockFileSaver added in v0.6.1

type MockFileSaver struct {
	mock.Mock
}

MockFileSaver implements files.FileSaver for tests.

func (*MockFileSaver) SaveFile added in v0.6.1

func (m *MockFileSaver) SaveFile(ctx context.Context, userID int64, messageID int64, fileType string, originalName string, mimeType string, reader io.Reader, messageText string) (*int64, error)

type MockOpenRouterClient

type MockOpenRouterClient struct {
	mock.Mock
}

MockOpenRouterClient implements openrouter.Client for tests.

func (*MockOpenRouterClient) CreateChatCompletion

func (*MockOpenRouterClient) CreateEmbeddings

type MockRetriever added in v0.6.1

type MockRetriever struct {
	mock.Mock
}

MockRetriever is a mock for testing code that needs rag.Retriever. Due to import cycle constraints (rag tests import testutil), this mock cannot directly implement rag.Retriever.

For laplace package tests that need rag.Retriever, use this approach:

// In laplace_context_test.go - define a thin wrapper that casts types:
type ragRetrieverAdapter struct {
	*testutil.MockRetriever
}

func (a *ragRetrieverAdapter) Retrieve(ctx context.Context, userID int64, query string, opts *rag.RetrievalOptions) (*rag.RetrievalResult, *rag.RetrievalDebugInfo, error) {
	result, debugInfo, err := a.MockRetriever.Retrieve(ctx, userID, query, opts)
	return result.(*rag.RetrievalResult), debugInfo.(*rag.RetrievalDebugInfo), err
}

For now, laplace_context_test.go keeps its inline mockRetriever which directly implements the interface. This is acceptable for a single file.

func (*MockRetriever) GetRecentTopics added in v0.6.1

func (m *MockRetriever) GetRecentTopics(userID int64, limit int) ([]storage.TopicExtended, error)

GetRecentTopics returns the N most recent topics for a user with message counts.

func (*MockRetriever) Retrieve added in v0.6.1

func (m *MockRetriever) Retrieve(ctx context.Context, userID int64, query string, opts interface{}) (interface{}, interface{}, error)

Retrieve performs RAG retrieval for a query. Returns (result interface{}, debugInfo interface{}, error). Caller is responsible for type assertions to *rag.RetrievalResult and *rag.RetrievalDebugInfo.

type MockStorage

type MockStorage struct {
	mock.Mock
}

MockStorage implements all storage repository interfaces for tests. This is a composite mock that covers MessageRepository, UserRepository, TopicRepository, FactRepository, FactHistoryRepository, StatsRepository, MemoryBankRepository, MaintenanceRepository, and AgentLogRepository.

func (*MockStorage) AddAgentLog

func (m *MockStorage) AddAgentLog(log storage.AgentLog) error

func (*MockStorage) AddArtifact added in v0.6.0

func (m *MockStorage) AddArtifact(artifact storage.Artifact) (int64, error)

func (*MockStorage) AddFact

func (m *MockStorage) AddFact(fact storage.Fact) (int64, error)

func (*MockStorage) AddFactHistory

func (m *MockStorage) AddFactHistory(history storage.FactHistory) error

func (*MockStorage) AddMessageToHistory

func (m *MockStorage) AddMessageToHistory(userID int64, message storage.Message) error

func (*MockStorage) AddPerson added in v0.5.1

func (m *MockStorage) AddPerson(person storage.Person) (int64, error)

func (*MockStorage) AddStat

func (m *MockStorage) AddStat(stat storage.Stat) error

func (*MockStorage) AddTopic

func (m *MockStorage) AddTopic(topic storage.Topic) (int64, error)

func (*MockStorage) AddTopicWithoutMessageUpdate

func (m *MockStorage) AddTopicWithoutMessageUpdate(topic storage.Topic) (int64, error)

func (*MockStorage) Checkpoint

func (m *MockStorage) Checkpoint() error

func (*MockStorage) CleanupAgentLogs

func (m *MockStorage) CleanupAgentLogs(keepPerUserPerAgent int) (int64, error)

func (*MockStorage) CleanupFactHistory

func (m *MockStorage) CleanupFactHistory(keepPerUser int) (int64, error)

func (*MockStorage) ClearHistory

func (m *MockStorage) ClearHistory(userID int64) error

func (*MockStorage) CountAgentLogs

func (m *MockStorage) CountAgentLogs() (int64, error)

func (*MockStorage) CountContaminatedTopics

func (m *MockStorage) CountContaminatedTopics(userID int64) (int, error)

func (*MockStorage) CountFactHistory

func (m *MockStorage) CountFactHistory() (int64, error)

func (*MockStorage) CountFactsOnOrphanedTopics

func (m *MockStorage) CountFactsOnOrphanedTopics(userID int64) (int, error)

func (*MockStorage) CountOrphanedTopics

func (m *MockStorage) CountOrphanedTopics(userID int64) (int, error)

func (*MockStorage) CountOverlappingTopics

func (m *MockStorage) CountOverlappingTopics(userID int64) (int, error)

func (*MockStorage) CountPeopleWithoutEmbedding added in v0.5.1

func (m *MockStorage) CountPeopleWithoutEmbedding(userID int64) (int, error)

func (*MockStorage) CreateTopic

func (m *MockStorage) CreateTopic(topic storage.Topic) (int64, error)

func (*MockStorage) DeleteFact

func (m *MockStorage) DeleteFact(userID, id int64) error

func (*MockStorage) DeletePerson added in v0.5.1

func (m *MockStorage) DeletePerson(userID, personID int64) error

func (*MockStorage) DeleteTopic

func (m *MockStorage) DeleteTopic(userID int64, id int64) error

func (*MockStorage) DeleteTopicCascade

func (m *MockStorage) DeleteTopicCascade(userID int64, id int64) error

func (*MockStorage) FindPersonByAlias added in v0.5.1

func (m *MockStorage) FindPersonByAlias(userID int64, alias string) ([]storage.Person, error)

func (*MockStorage) FindPersonByName added in v0.5.1

func (m *MockStorage) FindPersonByName(userID int64, name string) (*storage.Person, error)

func (*MockStorage) FindPersonByTelegramID added in v0.5.1

func (m *MockStorage) FindPersonByTelegramID(userID, telegramID int64) (*storage.Person, error)

func (*MockStorage) FindPersonByUsername added in v0.5.1

func (m *MockStorage) FindPersonByUsername(userID int64, username string) (*storage.Person, error)

func (*MockStorage) FixContaminatedTopics

func (m *MockStorage) FixContaminatedTopics(userID int64) (int64, error)

func (*MockStorage) GetAgentLogFull added in v0.6.0

func (m *MockStorage) GetAgentLogFull(ctx context.Context, id int64, userID int64) (*storage.AgentLog, error)

func (*MockStorage) GetAgentLogs

func (m *MockStorage) GetAgentLogs(agentType string, userID int64, limit int) ([]storage.AgentLog, error)

func (*MockStorage) GetAgentLogsExtended

func (m *MockStorage) GetAgentLogsExtended(filter storage.AgentLogFilter, limit, offset int) (storage.AgentLogResult, error)

func (*MockStorage) GetAllFacts

func (m *MockStorage) GetAllFacts() ([]storage.Fact, error)

func (*MockStorage) GetAllPeople added in v0.5.1

func (m *MockStorage) GetAllPeople() ([]storage.Person, error)

func (*MockStorage) GetAllTopics

func (m *MockStorage) GetAllTopics() ([]storage.Topic, error)

func (*MockStorage) GetAllUsers

func (m *MockStorage) GetAllUsers() ([]storage.User, error)

func (*MockStorage) GetArtifact added in v0.6.0

func (m *MockStorage) GetArtifact(userID, artifactID int64) (*storage.Artifact, error)

func (*MockStorage) GetArtifacts added in v0.6.0

func (m *MockStorage) GetArtifacts(filter storage.ArtifactFilter, limit, offset int) ([]storage.Artifact, int64, error)

func (*MockStorage) GetArtifactsByIDs added in v0.6.0

func (m *MockStorage) GetArtifactsByIDs(userID int64, artifactIDs []int64) ([]storage.Artifact, error)

func (*MockStorage) GetByHash added in v0.6.0

func (m *MockStorage) GetByHash(userID int64, contentHash string) (*storage.Artifact, error)

func (*MockStorage) GetContaminatedTopics

func (m *MockStorage) GetContaminatedTopics(userID int64) ([]storage.ContaminatedTopic, error)

func (*MockStorage) GetDBSize

func (m *MockStorage) GetDBSize() (int64, error)

func (*MockStorage) GetDashboardStats

func (m *MockStorage) GetDashboardStats(userID int64) (*storage.DashboardStats, error)

func (*MockStorage) GetFactHistory

func (m *MockStorage) GetFactHistory(userID int64, limit int) ([]storage.FactHistory, error)

func (*MockStorage) GetFactHistoryExtended

func (m *MockStorage) GetFactHistoryExtended(filter storage.FactHistoryFilter, limit, offset int, sortBy, sortDir string) (storage.FactHistoryResult, error)

func (*MockStorage) GetFactStats

func (m *MockStorage) GetFactStats() (storage.FactStats, error)

func (*MockStorage) GetFactStatsByUser

func (m *MockStorage) GetFactStatsByUser(userID int64) (storage.FactStats, error)

func (*MockStorage) GetFacts

func (m *MockStorage) GetFacts(userID int64) ([]storage.Fact, error)

func (*MockStorage) GetFactsAfterID

func (m *MockStorage) GetFactsAfterID(minID int64) ([]storage.Fact, error)

func (*MockStorage) GetFactsByIDs

func (m *MockStorage) GetFactsByIDs(userID int64, ids []int64) ([]storage.Fact, error)

func (*MockStorage) GetFactsByTopicID

func (m *MockStorage) GetFactsByTopicID(userID int64, topicID int64) ([]storage.Fact, error)

func (*MockStorage) GetLastTopicEndMessageID

func (m *MockStorage) GetLastTopicEndMessageID(userID int64) (int64, error)

func (*MockStorage) GetMemoryBank

func (m *MockStorage) GetMemoryBank(userID int64) (string, error)

func (*MockStorage) GetMergeCandidates

func (m *MockStorage) GetMergeCandidates(userID int64) ([]storage.MergeCandidate, error)

func (*MockStorage) GetMessagesByIDs

func (m *MockStorage) GetMessagesByIDs(userID int64, ids []int64) ([]storage.Message, error)

func (*MockStorage) GetMessagesByTopicID

func (m *MockStorage) GetMessagesByTopicID(ctx context.Context, topicID int64) ([]storage.Message, error)

func (*MockStorage) GetMessagesInRange

func (m *MockStorage) GetMessagesInRange(ctx context.Context, userID int64, startID, endID int64) ([]storage.Message, error)

func (*MockStorage) GetOrphanedTopicIDs

func (m *MockStorage) GetOrphanedTopicIDs(userID int64) ([]int64, error)

func (*MockStorage) GetOverlappingTopics

func (m *MockStorage) GetOverlappingTopics(userID int64) ([]storage.OverlappingPair, error)

func (*MockStorage) GetPendingArtifacts added in v0.6.0

func (m *MockStorage) GetPendingArtifacts(userID int64, maxRetries int) ([]storage.Artifact, error)

func (*MockStorage) GetPeople added in v0.5.1

func (m *MockStorage) GetPeople(userID int64) ([]storage.Person, error)

func (*MockStorage) GetPeopleAfterID added in v0.5.1

func (m *MockStorage) GetPeopleAfterID(minID int64) ([]storage.Person, error)

func (*MockStorage) GetPeopleByIDs added in v0.5.1

func (m *MockStorage) GetPeopleByIDs(userID int64, ids []int64) ([]storage.Person, error)

func (*MockStorage) GetPeopleExtended added in v0.5.1

func (m *MockStorage) GetPeopleExtended(filter storage.PersonFilter, limit, offset int, sortBy, sortDir string) (storage.PersonResult, error)

func (*MockStorage) GetPeopleWithoutEmbedding added in v0.5.1

func (m *MockStorage) GetPeopleWithoutEmbedding(userID int64) ([]storage.Person, error)

func (*MockStorage) GetPerson added in v0.5.1

func (m *MockStorage) GetPerson(userID, personID int64) (*storage.Person, error)

func (*MockStorage) GetRecentHistory

func (m *MockStorage) GetRecentHistory(userID int64, limit int) ([]storage.Message, error)

func (*MockStorage) GetRecentSessionMessages added in v0.6.0

func (m *MockStorage) GetRecentSessionMessages(ctx context.Context, userID int64, limit int, excludeIDs []int64) ([]storage.Message, error)

func (*MockStorage) GetStats

func (m *MockStorage) GetStats() (map[int64]storage.Stat, error)

func (*MockStorage) GetTableSizes

func (m *MockStorage) GetTableSizes() ([]storage.TableSize, error)

func (*MockStorage) GetTopics

func (m *MockStorage) GetTopics(userID int64) ([]storage.Topic, error)

func (*MockStorage) GetTopicsAfterID

func (m *MockStorage) GetTopicsAfterID(minID int64) ([]storage.Topic, error)

func (*MockStorage) GetTopicsByIDs

func (m *MockStorage) GetTopicsByIDs(userID int64, ids []int64) ([]storage.Topic, error)

func (*MockStorage) GetTopicsExtended

func (m *MockStorage) GetTopicsExtended(filter storage.TopicFilter, limit, offset int, sortBy, sortDir string) (storage.TopicResult, error)

func (*MockStorage) GetTopicsPendingFacts

func (m *MockStorage) GetTopicsPendingFacts(userID int64) ([]storage.Topic, error)

func (*MockStorage) GetUnprocessedMessages

func (m *MockStorage) GetUnprocessedMessages(userID int64) ([]storage.Message, error)

func (*MockStorage) ImportMessage

func (m *MockStorage) ImportMessage(userID int64, message storage.Message) error

func (*MockStorage) IncrementContextLoadCount added in v0.6.0

func (m *MockStorage) IncrementContextLoadCount(userID int64, artifactIDs []int64) error

func (*MockStorage) MergePeople added in v0.5.1

func (m *MockStorage) MergePeople(userID, targetID, sourceID int64, newBio string, newAliases []string, newUsername *string, newTelegramID *int64) error

func (*MockStorage) RecalculateTopicRanges

func (m *MockStorage) RecalculateTopicRanges(userID int64) (int, error)

func (*MockStorage) RecalculateTopicSizes

func (m *MockStorage) RecalculateTopicSizes(userID int64) (int, error)

func (*MockStorage) RecoverArtifactStates added in v0.6.0

func (m *MockStorage) RecoverArtifactStates(threshold time.Duration) error

func (*MockStorage) ResetUserData

func (m *MockStorage) ResetUserData(userID int64) error

func (*MockStorage) SetTopicConsolidationChecked

func (m *MockStorage) SetTopicConsolidationChecked(userID int64, topicID int64, checked bool) error

func (*MockStorage) SetTopicFactsExtracted

func (m *MockStorage) SetTopicFactsExtracted(userID int64, topicID int64, extracted bool) error

func (*MockStorage) UpdateArtifact added in v0.6.0

func (m *MockStorage) UpdateArtifact(artifact storage.Artifact) error

func (*MockStorage) UpdateFact

func (m *MockStorage) UpdateFact(fact storage.Fact) error

func (*MockStorage) UpdateFactHistoryTopic

func (m *MockStorage) UpdateFactHistoryTopic(oldTopicID, newTopicID int64) error

func (*MockStorage) UpdateFactsTopic added in v0.5.4

func (m *MockStorage) UpdateFactsTopic(userID int64, oldTopicID, newTopicID int64) error

func (*MockStorage) UpdateMemoryBank

func (m *MockStorage) UpdateMemoryBank(userID int64, content string) error

func (*MockStorage) UpdateMessageID added in v0.6.0

func (m *MockStorage) UpdateMessageID(userID, artifactID, messageID int64) error

func (*MockStorage) UpdateMessageTopic

func (m *MockStorage) UpdateMessageTopic(userID int64, messageID, topicID int64) error

func (*MockStorage) UpdateMessagesTopicInRange

func (m *MockStorage) UpdateMessagesTopicInRange(ctx context.Context, userID, startMsgID, endMsgID, topicID int64) error

func (*MockStorage) UpdatePerson added in v0.5.1

func (m *MockStorage) UpdatePerson(person storage.Person) error

func (*MockStorage) UpsertUser

func (m *MockStorage) UpsertUser(user storage.User) error

type MockToolHandler added in v0.6.0

type MockToolHandler struct {
	mock.Mock
}

MockToolHandler implements laplace.ToolHandler for tests.

func (*MockToolHandler) ExecuteToolCall added in v0.6.0

func (m *MockToolHandler) ExecuteToolCall(toolName string, arguments string) (string, error)

ExecuteToolCall executes a tool call and returns the result.

type MockVectorSearcher

type MockVectorSearcher struct {
	mock.Mock
}

MockVectorSearcher implements rag.VectorSearcher for tests.

func (*MockVectorSearcher) FindSimilarFacts

func (m *MockVectorSearcher) FindSimilarFacts(ctx context.Context, userID int64, embedding []float32, threshold float32) ([]storage.Fact, error)

type SSEEvent added in v0.6.1

type SSEEvent struct {
	Data string
}

SSEEvent represents a single Server-Sent Event.

func ParseSSEEvents added in v0.6.1

func ParseSSEEvents(t *testing.T, body string) []SSEEvent

ParseSSEEvents parses SSE formatted response body into individual events. Each SSE event has the format "data: <json>\n\n".

type SSEHeadersGetter added in v0.6.1

type SSEHeadersGetter interface {
	Header() http.Header
}

SSEHeadersGetter is an interface for getting HTTP headers.

type SSERecorder added in v0.6.1

type SSERecorder struct {
	*httptest.ResponseRecorder
	// contains filtered or unexported fields
}

SSERecorder is a test response recorder that supports Server-Sent Events (SSE) by implementing the http.Flusher interface. Use this for testing handlers that stream responses via SSE.

Example usage:

mockBot.On("ForceCloseSessionWithProgress", ...).Run(func(args mock.Arguments) {
    onProgress := args.Get(2).(rag.ProgressCallback)
    onProgress(rag.ProgressEvent{Stage: "processing", Complete: false})
    onProgress(rag.ProgressEvent{Stage: "done", Complete: true})
}).Return(&rag.ProcessingStats{}, nil)

req := testutil.NewTestRequest(t, "GET", "/ui/debug/sessions/process?user_id=123", nil)
sseRecorder := testutil.NewSSERecorder()
handler(sseRecorder, req)

assert.Equal(t, http.StatusOK, sseRecorder.Code)
events := testutil.ParseSSEEvents(t, sseRecorder.Body.String())
assert.Len(t, events, 2)

func NewSSERecorder added in v0.6.1

func NewSSERecorder() *SSERecorder

NewSSERecorder creates a new SSE-capable response recorder.

func (*SSERecorder) Flush added in v0.6.1

func (r *SSERecorder) Flush()

Flush implements http.Flusher for SSE support.

func (*SSERecorder) FlushCount added in v0.6.1

func (r *SSERecorder) FlushCount() int

FlushCount returns the number of times Flush was called.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL