testutil

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package testutil provides testing utilities for Cortex tests.

This package contains helpers for creating test databases, fixtures, and custom assertions to simplify writing tests.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertConflictError

func AssertConflictError(t *testing.T, err error)

AssertConflictError asserts that an error is a ConflictError.

func AssertContains

func AssertContains[T comparable](t *testing.T, slice []T, element T)

AssertContains asserts that a slice contains an element.

func AssertEdgeEqual

func AssertEdgeEqual(t *testing.T, expected, actual *domain.Edge)

AssertEdgeEqual asserts that two edges are equal.

func AssertEdgeListEqual

func AssertEdgeListEqual(t *testing.T, expected, actual []*domain.Edge)

AssertEdgeListEqual asserts that two edge slices are equal.

func AssertEqual

func AssertEqual(t *testing.T, expected, actual any)

AssertEqual asserts that two values are equal using reflect.DeepEqual.

func AssertError

func AssertError(t *testing.T, err error)

AssertError fails the test if err is nil.

func AssertErrorAs

func AssertErrorAs(t *testing.T, err error, target any)

AssertErrorAs asserts that err can be unwrapped to the target type.

func AssertErrorIs

func AssertErrorIs(t *testing.T, err error, target error)

AssertErrorIs asserts that err wraps the target error.

func AssertFalse

func AssertFalse(t *testing.T, condition bool, message ...string)

AssertFalse asserts that a condition is false.

func AssertImportanceScoreEqual

func AssertImportanceScoreEqual(t *testing.T, expected, actual *domain.ImportanceScore)

AssertImportanceScoreEqual asserts that two importance scores are equal.

func AssertLen

func AssertLen(t *testing.T, value any, expectedLen int)

AssertLen asserts that a slice, map, or string has the expected length.

func AssertNil

func AssertNil(t *testing.T, value any)

AssertNil asserts that a value is nil.

func AssertNoError

func AssertNoError(t *testing.T, err error)

AssertNoError fails the test if err is not nil.

func AssertNotContains

func AssertNotContains[T comparable](t *testing.T, slice []T, element T)

AssertNotContains asserts that a slice does not contain an element.

func AssertNotEqual

func AssertNotEqual(t *testing.T, expected, actual any)

AssertNotEqual asserts that two values are not equal.

func AssertNotFoundError

func AssertNotFoundError(t *testing.T, err error, expectedType string, expectedID interface{})

AssertNotFoundError asserts that an error is a NotFoundError with the expected type and ID.

func AssertNotNil

func AssertNotNil(t *testing.T, value any)

AssertNotNil asserts that a value is not nil.

func AssertObservationEqual

func AssertObservationEqual(t *testing.T, expected, actual *domain.Observation)

AssertObservationEqual asserts that two observations are equal. It compares all fields except CreatedAt and UpdatedAt which are compared with a tolerance of 1 second to handle timing differences.

func AssertObservationIDs

func AssertObservationIDs(t *testing.T, observations []*domain.Observation, expectedIDs ...int64)

AssertObservationIDs asserts that observations have the expected IDs in order.

func AssertObservationListEqual

func AssertObservationListEqual(t *testing.T, expected, actual []*domain.Observation)

AssertObservationListEqual asserts that two observation slices are equal.

func AssertObservationTypes

func AssertObservationTypes(t *testing.T, observations []*domain.Observation, expectedTypes ...string)

AssertObservationTypes asserts that observations have the expected types.

func AssertPanics

func AssertPanics(t *testing.T, fn func())

AssertPanics asserts that a function panics.

func AssertPromptEqual

func AssertPromptEqual(t *testing.T, expected, actual *domain.Prompt)

AssertPromptEqual asserts that two prompts are equal.

func AssertPromptListEqual

func AssertPromptListEqual(t *testing.T, expected, actual []*domain.Prompt)

AssertPromptListEqual asserts that two prompt slices are equal.

func AssertSessionEqual

func AssertSessionEqual(t *testing.T, expected, actual *domain.Session)

AssertSessionEqual asserts that two sessions are equal.

func AssertSessionIDs

func AssertSessionIDs(t *testing.T, sessions []*domain.Session, expectedIDs ...string)

AssertSessionIDs asserts that sessions have the expected IDs in order.

func AssertTrue

func AssertTrue(t *testing.T, condition bool, message ...string)

AssertTrue asserts that a condition is true.

func AssertValidationError

func AssertValidationError(t *testing.T, err error, expectedField string)

AssertValidationError asserts that an error is a ValidationError with the expected field.

func AssertWithinDuration

func AssertWithinDuration(t *testing.T, expected, actual time.Time, delta time.Duration)

AssertWithinDuration asserts that two times are within the specified duration of each other.

func PanicRecovered

func PanicRecovered(t *testing.T, fn func()) interface{}

PanicRecovered asserts that a function panics and returns the recovered value. Returns nil if the function does not panic.

Example:

recovered := testutil.PanicRecovered(t, func() {
    panic("test panic")
})
if recovered != "test panic" {
    t.Errorf("expected 'test panic', got %v", recovered)
}

func RequireNoError

func RequireNoError(t *testing.T, err error)

RequireNoError fails immediately if err is not nil. This is similar to AssertNoError but uses Fatalf which stops test execution.

Types

type Fixtures

type Fixtures struct{}

Fixtures provides test data factories for creating domain objects. It uses the functional options pattern to allow overriding default values.

Example:

fixtures := &testutil.Fixtures{}

// Create observation with defaults
obs := fixtures.Observation()

// Create observation with custom title
obs := fixtures.Observation(func(o *domain.Observation) {
    o.Title = "Custom Title"
    o.Project = "my-project"
})

func NewFixtures

func NewFixtures() *Fixtures

NewFixtures creates a new Fixtures instance.

func (*Fixtures) Edge

func (f *Fixtures) Edge(fromID, toID int64, overrides ...func(*domain.Edge)) *domain.Edge

Edge creates a test edge with sensible defaults. Override any field by passing functional options.

Default values:

  • ID: 1
  • FromObsID: fromID parameter
  • ToObsID: toID parameter
  • RelationType: "references"
  • Weight: 0.8
  • CreatedAt: time.Now()

func (*Fixtures) EdgeContradicts

func (f *Fixtures) EdgeContradicts(fromID, toID int64, overrides ...func(*domain.Edge)) *domain.Edge

EdgeContradicts creates an edge with "contradicts" relation type.

func (*Fixtures) EdgeFollows

func (f *Fixtures) EdgeFollows(fromID, toID int64, overrides ...func(*domain.Edge)) *domain.Edge

EdgeFollows creates an edge with "follows" relation type.

func (*Fixtures) EdgeList

func (f *Fixtures) EdgeList(count int, overrides ...func(*domain.Edge, int)) []*domain.Edge

EdgeList creates multiple test edges between consecutive observations.

func (*Fixtures) EdgeRelatesTo

func (f *Fixtures) EdgeRelatesTo(fromID, toID int64, overrides ...func(*domain.Edge)) *domain.Edge

EdgeRelatesTo creates an edge with "relates_to" relation type.

func (*Fixtures) EdgeSupersedes

func (f *Fixtures) EdgeSupersedes(fromID, toID int64, overrides ...func(*domain.Edge)) *domain.Edge

EdgeSupersedes creates an edge with "supersedes" relation type.

func (*Fixtures) ImportanceScore

func (f *Fixtures) ImportanceScore(obsID int64, overrides ...func(*domain.ImportanceScore)) *domain.ImportanceScore

ImportanceScore creates a test importance score with sensible defaults. Override any field by passing functional options.

Default values:

  • ObservationID: obsID parameter
  • Score: 0.75
  • AccessCount: 5
  • LastAccessed: time.Now()
  • UpdatedAt: time.Now()

func (*Fixtures) Observation

func (f *Fixtures) Observation(overrides ...func(*domain.Observation)) *domain.Observation

Observation creates a test observation with sensible defaults. Override any field by passing functional options.

Default values:

  • ID: 1
  • Title: "Test Observation"
  • Content: "Test content for observation"
  • Type: "manual"
  • Project: "test-project"
  • Scope: "project"
  • SessionID: "test-session-123"
  • CreatedAt/UpdatedAt: time.Now()

func (*Fixtures) ObservationBugfix

func (f *Fixtures) ObservationBugfix(overrides ...func(*domain.Observation)) *domain.Observation

ObservationBugfix creates a test observation with type "bugfix".

func (*Fixtures) ObservationConfig

func (f *Fixtures) ObservationConfig(overrides ...func(*domain.Observation)) *domain.Observation

ObservationConfig creates a test observation with type "config".

func (*Fixtures) ObservationDecision

func (f *Fixtures) ObservationDecision(overrides ...func(*domain.Observation)) *domain.Observation

ObservationDecision creates a test observation with type "decision".

func (*Fixtures) ObservationDiscovery

func (f *Fixtures) ObservationDiscovery(overrides ...func(*domain.Observation)) *domain.Observation

ObservationDiscovery creates a test observation with type "discovery".

func (*Fixtures) ObservationFilter

func (f *Fixtures) ObservationFilter(overrides ...func(*domain.ObservationFilter)) *domain.ObservationFilter

ObservationFilter creates a test observation filter with defaults.

func (*Fixtures) ObservationLearning

func (f *Fixtures) ObservationLearning(overrides ...func(*domain.Observation)) *domain.Observation

ObservationLearning creates a test observation with type "learning".

func (*Fixtures) ObservationList

func (f *Fixtures) ObservationList(count int, overrides ...func(*domain.Observation, int)) []*domain.Observation

ObservationList creates multiple test observations. The count parameter specifies how many observations to create.

func (*Fixtures) ObservationPattern

func (f *Fixtures) ObservationPattern(overrides ...func(*domain.Observation)) *domain.Observation

ObservationPattern creates a test observation with type "pattern".

func (*Fixtures) ObservationPersonal

func (f *Fixtures) ObservationPersonal(overrides ...func(*domain.Observation)) *domain.Observation

ObservationPersonal creates a test observation with personal scope.

func (*Fixtures) ObservationToolUse

func (f *Fixtures) ObservationToolUse(overrides ...func(*domain.Observation)) *domain.Observation

ObservationToolUse creates a test observation with type "tool_use".

func (*Fixtures) Prompt

func (f *Fixtures) Prompt(overrides ...func(*domain.Prompt)) *domain.Prompt

Prompt creates a test prompt with sensible defaults. Override any field by passing functional options.

Default values:

  • ID: 1
  • Content: "Test prompt content"
  • Project: "test-project"
  • SessionID: "test-session-123"
  • CreatedAt: time.Now()

func (*Fixtures) PromptWithContent

func (f *Fixtures) PromptWithContent(content string, overrides ...func(*domain.Prompt)) *domain.Prompt

PromptWithContent creates a prompt with custom content.

func (*Fixtures) SearchOptions

func (f *Fixtures) SearchOptions(overrides ...func(*domain.SearchOptions)) *domain.SearchOptions

SearchOptions creates test search options with defaults.

func (*Fixtures) SearchResult

func (f *Fixtures) SearchResult(overrides ...func(*domain.SearchResult)) *domain.SearchResult

SearchResult creates a test search result with defaults.

func (*Fixtures) Session

func (f *Fixtures) Session(overrides ...func(*domain.Session)) *domain.Session

Session creates a test session with sensible defaults. Override any field by passing functional options.

Default values:

  • ID: "test-session-123"
  • Project: "test-project"
  • Directory: "/tmp/test-project"
  • StartedAt: time.Now()
  • EndedAt: nil
  • Summary: ""

func (*Fixtures) SessionEnded

func (f *Fixtures) SessionEnded(overrides ...func(*domain.Session)) *domain.Session

SessionEnded creates a test session that has already ended.

func (*Fixtures) SessionWithSummary

func (f *Fixtures) SessionWithSummary(summary string, overrides ...func(*domain.Session)) *domain.Session

SessionWithSummary creates a test session with a summary.

type TestDB

type TestDB struct {
	*database.Manager
	// contains filtered or unexported fields
}

TestDB wraps a test database with automatic cleanup and migration support. It provides an in-memory SQLite database that is automatically cleaned up when the test completes.

func NewTestDB

func NewTestDB(t *testing.T) *TestDB

NewTestDB creates an in-memory test database. The database is automatically cleaned up via t.Cleanup when the test completes.

Example:

func TestSomething(t *testing.T) {
    db := testutil.NewTestDB(t)
    // Use db.DB() for queries
}

func NewTestDBWithMigrations

func NewTestDBWithMigrations(t *testing.T, registry *migration.Registry) *TestDB

NewTestDBWithMigrations creates an in-memory test database with migrations applied. It registers all migrations from the provided registry and applies them.

Example:

func TestWithMigrations(t *testing.T) {
    registry := migration.NewRegistry()
    registry.Register(migration.Migration{
        Version: 1,
        Name:    "init",
        UpSQL:   "CREATE TABLE test (id INTEGER PRIMARY KEY);",
        DownSQL: "DROP TABLE test;",
    })
    db := testutil.NewTestDBWithMigrations(t, registry)
}

func (*TestDB) Cleanup

func (db *TestDB) Cleanup()

Cleanup closes the database connection and removes test resources. It is automatically called via t.Cleanup when using NewTestDB. It is safe to call multiple times.

func (*TestDB) CountRows

func (db *TestDB) CountRows(table string) int

CountRows returns the number of rows in the specified table.

func (*TestDB) Exec

func (db *TestDB) Exec(query string, args ...any) sql.Result

Exec executes a SQL statement with the given arguments. It fails the test if the execution fails.

func (*TestDB) Migrator

func (db *TestDB) Migrator() *migration.Migrator

Migrator returns the migrator for this test database. Returns nil if NewTestDBWithMigrations was not used.

func (*TestDB) MustExec

func (db *TestDB) MustExec(query string, args ...any) sql.Result

MustExec executes a SQL statement and panics if it fails. Use this for setup code where you want to panic on failure.

func (*TestDB) Query

func (db *TestDB) Query(query string, args ...any) *sql.Rows

Query executes a query that returns multiple rows. It fails the test if the query fails.

func (*TestDB) QueryRow

func (db *TestDB) QueryRow(query string, args ...any) *sql.Row

QueryRow executes a query that returns at most one row. It fails the test if the query fails.

func (*TestDB) TableExists

func (db *TestDB) TableExists(name string) bool

TableExists returns true if the specified table exists in the database.

func (*TestDB) WithTransaction

func (db *TestDB) WithTransaction(ctx context.Context, fn func(tx *sql.Tx) error) error

WithTransaction runs fn in a transaction that is automatically rolled back. This is useful for tests that need to verify database operations without persisting changes.

Example:

err := db.WithTransaction(ctx, func(tx *sql.Tx) error {
    _, err := tx.Exec("INSERT INTO observations (title) VALUES (?)", "test")
    return err
})
// Transaction is rolled back, changes are not persisted

func (*TestDB) WithTransactionCommit

func (db *TestDB) WithTransactionCommit(ctx context.Context, fn func(tx *sql.Tx) error) error

WithTransactionCommit runs fn in a transaction that is committed if fn succeeds. This is useful for tests that need to verify the committed state.

Jump to

Keyboard shortcuts

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