testutil

package
v0.0.0-...-04478d6 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Overview

Package testutil provides shared test helper functions for unit testing.

For integration tests requiring database access, use test/dbhelpers instead. This package provides lightweight helpers for unit tests without external dependencies.

Package testutil provides email testing utilities using MailHog.

Package testutil provides shared test utilities and mocks for unit testing.

Index

Constants

This section is empty.

Variables

View Source
var ErrMockObjectNotFound = errors.New("object not found")

ErrMockObjectNotFound is returned when an object is not found in mock storage

Functions

func AssertErrorContains

func AssertErrorContains(t *testing.T, err error, substring string)

AssertErrorContains asserts that an error's message contains a substring.

func AssertErrorIs

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

AssertErrorIs asserts that an error is of a specific type.

func AssertJSONContains

func AssertJSONContains(t *testing.T, expected, actual string)

AssertJSONContains asserts that the actual JSON contains all fields from expected JSON.

func AssertJSONEqual

func AssertJSONEqual(t *testing.T, expected, actual string)

AssertJSONEqual asserts that two JSON strings represent equal objects.

func CleanupTestDB

func CleanupTestDB(t *testing.T, db *pgxpool.Pool)

CleanupTestDB cleans up a test database connection.

func CreateTestTable

func CreateTestTable(t *testing.T, db *pgxpool.Pool, schema, table string, columns []Column)

CreateTestTable creates a test table with the specified columns.

Example:

testutil.CreateTestTable(t, db, "public", "test_products",
	[]testutil.Column{{Name: "id", Type: "serial PRIMARY KEY"}, {Name: "name", Type: "text"}})

func CreateTestUser

func CreateTestUser(t *testing.T, db *pgxpool.Pool, email string) string

CreateTestUser creates a test user in the database. Returns the user ID.

Uses the auth.users table schema with password_hash column.

func DeleteAllMailHogMessages

func DeleteAllMailHogMessages(t *testing.T)

DeleteAllMailHogMessages deletes all messages from MailHog. Use this before tests to ensure a clean state.

func DropTestTable

func DropTestTable(t *testing.T, db *pgxpool.Pool, schema, table string)

DropTestTable drops a test table.

func ExtractEmailVerificationToken

func ExtractEmailVerificationToken(t *testing.T, emailBody string) string

ExtractEmailVerificationToken extracts an email verification token from an email body.

func ExtractMagicLinkToken

func ExtractMagicLinkToken(t *testing.T, emailBody string) string

ExtractMagicLinkToken extracts a magic link token from an email body. It looks for patterns like: - /auth/verify?token=<token> - token=<token>

func ExtractPasswordResetToken

func ExtractPasswordResetToken(t *testing.T, emailBody string) string

ExtractPasswordResetToken extracts a password reset token from an email body. It looks for patterns like: - /auth/reset-password?token=<token> - /reset-password?token=<token> - token=<token>

func GetMailHogBaseURL

func GetMailHogBaseURL() string

GetMailHogBaseURL returns the MailHog base URL for the current environment. It checks the MAILHOG_HOST environment variable, defaulting to localhost.

func IntPtr

func IntPtr(i int) *int

IntPtr creates an int pointer.

func NullInt

func NullInt(i *int) sql.NullInt64

NullInt creates a sql.NullInt64 from an int pointer.

func NullString

func NullString(s *string) sql.NullString

NullString creates a sql.NullString from a string pointer.

func ReadBody

func ReadBody(t *testing.T, r io.ReadCloser) string

ReadBody reads the entire body into a string.

func SetupTestDB

func SetupTestDB(t *testing.T) *pgxpool.Pool

SetupTestDB creates a test database connection.

This function connects to the test database using environment variables or default config. For integration tests, consider using test/dbhelpers.NewDBTestContext() instead, which provides additional features like connection pooling and test table setup.

Example:

db := testutil.SetupTestDB(t)
defer testutil.CleanupTestDB(t, db)

func SetupTestServer

func SetupTestServer(t *testing.T) *fiber.App

SetupTestServer creates a test Fiber server with common middleware.

Example:

app := testutil.SetupTestServer(t)
// Register routes and test

func StringPtr

func StringPtr(s string) *string

StringPtr creates a string pointer.

func TruncateTable

func TruncateTable(t *testing.T, db *pgxpool.Pool, schema, table string)

TruncateTable truncates a table (removes all data but keeps structure).

func WaitForCondition

func WaitForCondition(t *testing.T, condition func() bool, timeout time.Duration, msg string)

WaitForCondition polls until a condition is met or timeout expires.

Example:

testutil.WaitForCondition(t, func() bool {
    return db.Ping(context.Background()) == nil
}, 5*time.Second, "database to become available")

Types

type Column

type Column struct {
	Name string
	Type string
}

Column represents a table column definition.

type MailHogMessage

type MailHogMessage struct {
	ID   string `json:"ID"`
	From struct {
		Mailbox string `json:"Mailbox"`
		Domain  string `json:"Domain"`
	} `json:"From"`
	To []struct {
		Mailbox string `json:"Mailbox"`
		Domain  string `json:"Domain"`
	} `json:"To"`
	Content struct {
		Headers map[string][]string `json:"Headers"`
		Body    string              `json:"body"`
	} `json:"Content"`
	Created time.Time `json:"Created"`
}

MailHogMessage represents an email message from MailHog API

func FindEmailTo

func FindEmailTo(t *testing.T, emailAddress string) *MailHogMessage

FindEmailTo finds an email sent to a specific recipient.

func FindEmailWithSubject

func FindEmailWithSubject(t *testing.T, subject string) *MailHogMessage

FindEmailWithSubject finds an email with a specific subject line.

func GetAllMailHogMessages

func GetAllMailHogMessages(t *testing.T) []MailHogMessage

GetAllMailHogMessages fetches all messages from MailHog.

func WaitForEmail

func WaitForEmail(t *testing.T, timeout time.Duration, checkFn func(MailHogMessage) bool) *MailHogMessage

WaitForEmail waits for an email to arrive in MailHog matching a filter function. It polls every 100ms until the timeout is reached.

Example:

msg := testutil.WaitForEmail(t, 5*time.Second, func(m testutil.MailHogMessage) bool {
    return len(m.To) > 0 && m.To[0].Mailbox == "user" && m.To[0].Domain == "example.com"
})
require.NotNil(t, msg, "Email not received within timeout")

type MailHogMessages

type MailHogMessages struct {
	Total int              `json:"total"`
	Count int              `json:"count"`
	Start int              `json:"start"`
	Items []MailHogMessage `json:"items"`
}

MailHogMessages represents the response from MailHog messages API

type MockAzureClient

type MockAzureClient struct {
	*MockOpenAIClient
}

MockAzureClient is similar to MockOpenAIClient for Azure OpenAI

func NewMockAzureClient

func NewMockAzureClient() *MockAzureClient

NewMockAzureClient creates a new mock Azure client

type MockOAuthProvider

type MockOAuthProvider struct {
	// Callbacks for custom behavior
	AuthURLFunc  func(state string) string
	ExchangeFunc func(token string) (*OAuthToken, error)
	GetUserFunc  func(token *OAuthToken) (*OAuthUser, error)

	// State tracking
	StateToken   string // Expected state for validation
	UserInfo     *OAuthUser
	TokenInfo    *OAuthToken
	ShouldError  bool
	ErrorMessage string
}

MockOAuthProvider implements OAuth provider functionality for testing

func NewMockOAuthProvider

func NewMockOAuthProvider() *MockOAuthProvider

NewMockOAuthProvider creates a new mock OAuth provider

func (*MockOAuthProvider) AuthURL

func (m *MockOAuthProvider) AuthURL(state string) string

AuthURL generates an authorization URL for testing

func (*MockOAuthProvider) Exchange

func (m *MockOAuthProvider) Exchange(code string) (*OAuthToken, error)

Exchange exchanges an authorization code for a token

func (*MockOAuthProvider) GetUser

func (m *MockOAuthProvider) GetUser(token *OAuthToken) (*OAuthUser, error)

GetUser gets user information from the OAuth provider

type MockOCRProvider

type MockOCRProvider struct {
	// Callbacks for custom behavior
	ExtractPDFFunc   func(ctx context.Context, data []byte, languages []string) (string, error)
	ExtractImageFunc func(ctx context.Context, data []byte, languages []string) (string, error)
	IsAvailableFunc  func() bool

	// State tracking
	Text         string
	IsAvailable  bool
	ShouldError  bool
	ErrorMessage string
}

MockOCRProvider implements OCR for testing

func NewMockOCRProvider

func NewMockOCRProvider() *MockOCRProvider

NewMockOCRProvider creates a new mock OCR provider

func (*MockOCRProvider) Available

func (m *MockOCRProvider) Available() bool

Available returns whether the OCR provider is available

func (*MockOCRProvider) ExtractImage

func (m *MockOCRProvider) ExtractImage(ctx context.Context, data []byte, languages []string) (string, error)

ExtractImage extracts text from an image

func (*MockOCRProvider) ExtractPDF

func (m *MockOCRProvider) ExtractPDF(ctx context.Context, data []byte, languages []string) (string, error)

ExtractPDF extracts text from a PDF

type MockOllamaClient

type MockOllamaClient struct {
	*MockOpenAIClient
}

MockOllamaClient is similar to MockOpenAIClient for Ollama

func NewMockOllamaClient

func NewMockOllamaClient() *MockOllamaClient

NewMockOllamaClient creates a new mock Ollama client

type MockOpenAIClient

type MockOpenAIClient struct {
	// Callbacks for custom behavior
	ChatCompletionFunc func(ctx context.Context, messages []interface{}, opts map[string]interface{}) (string, error)
	EmbeddingFunc      func(ctx context.Context, texts []string) ([][]float32, error)

	// State tracking
	Response     string
	Embeddings   [][]float32
	ShouldError  bool
	ErrorMessage string
}

MockOpenAIClient implements OpenAI client for testing

func NewMockOpenAIClient

func NewMockOpenAIClient() *MockOpenAIClient

NewMockOpenAIClient creates a new mock OpenAI client

func (*MockOpenAIClient) ChatCompletion

func (m *MockOpenAIClient) ChatCompletion(ctx context.Context, messages []interface{}, opts map[string]interface{}) (string, error)

ChatCompletion performs a chat completion

func (*MockOpenAIClient) Embedding

func (m *MockOpenAIClient) Embedding(ctx context.Context, texts []string) ([][]float32, error)

Embedding generates embeddings for texts

type MockPubSub

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

MockPubSub implements pubsub.PubSub for testing

func NewMockPubSub

func NewMockPubSub() *MockPubSub

NewMockPubSub creates a new mock pubsub

func (*MockPubSub) Close

func (m *MockPubSub) Close() error

func (*MockPubSub) GetPublishedMessages

func (m *MockPubSub) GetPublishedMessages() []PublishedMessage

GetPublishedMessages returns all published messages for testing

func (*MockPubSub) Name

func (m *MockPubSub) Name() string

func (*MockPubSub) Publish

func (m *MockPubSub) Publish(ctx context.Context, channel string, payload []byte) error

func (*MockPubSub) Subscribe

func (m *MockPubSub) Subscribe(ctx context.Context, channel string) (<-chan []byte, error)

func (*MockPubSub) Unsubscribe

func (m *MockPubSub) Unsubscribe(ctx context.Context, channel string) error

type MockRateLimiter

type MockRateLimiter struct {

	// Callbacks for custom behavior
	CheckFunc  func(key string) (bool, time.Duration, error)
	RecordFunc func(key string) error
	ResetFunc  func(key string) error

	// State tracking
	Attempts     map[string]int
	Locked       map[string]bool
	Limit        int
	Window       time.Duration
	ShouldError  bool
	ErrorMessage string
	// contains filtered or unexported fields
}

MockRateLimiter implements rate limiting for testing

func NewMockRateLimiter

func NewMockRateLimiter(limit int, window time.Duration) *MockRateLimiter

NewMockRateLimiter creates a new mock rate limiter

func (*MockRateLimiter) Check

func (m *MockRateLimiter) Check(key string) (bool, time.Duration, error)

Check checks if a key is rate limited

func (*MockRateLimiter) Record

func (m *MockRateLimiter) Record(key string) error

Record records an attempt for a key

func (*MockRateLimiter) Reset

func (m *MockRateLimiter) Reset(key string) error

Reset resets rate limiting for a key

type MockRuntime

type MockRuntime struct {
	// Callbacks for custom behavior
	ExecuteFunc func(code string, env map[string]string) (string, error)
	BundleFunc  func(entryPoint string) (string, []byte, error)

	// State tracking
	Output       string
	BundledCode  string
	SourceMap    []byte
	ShouldError  bool
	ErrorMessage string
}

MockRuntime implements Deno runtime for testing

func NewMockRuntime

func NewMockRuntime() *MockRuntime

NewMockRuntime creates a new mock runtime

func (*MockRuntime) Bundle

func (m *MockRuntime) Bundle(entryPoint string) (string, []byte, error)

Bundle bundles Deno code

func (*MockRuntime) Execute

func (m *MockRuntime) Execute(code string, env map[string]string) (string, error)

Execute executes Deno code

type MockSAMLService

type MockSAMLService struct {

	// Callbacks for custom behavior
	OnInitiateLogin  func(ctx context.Context, providerName, relayState string) (redirectURL string, err error)
	OnHandleCallback func(ctx context.Context, samlResponse, relayState string, providerName string) (nameID, email string, attributes map[string][]string, err error)
	OnGetProviders   func(ctx context.Context) ([]interface{}, error)
	OnLogout         func(ctx context.Context, sessionID string) error

	// State tracking for assertions
	Providers      map[string]bool   // provider name -> enabled
	Sessions       map[string]string // session ID -> user ID
	UsedAssertions map[string]bool   // assertion ID -> used (for replay detection)
	// contains filtered or unexported fields
}

MockSAMLService provides a mock for auth.SAMLService for testing

func NewMockSAMLService

func NewMockSAMLService() *MockSAMLService

NewMockSAMLService creates a new mock SAML service

func (*MockSAMLService) AddProvider

func (m *MockSAMLService) AddProvider(name string, enabled bool)

AddProvider adds a provider to the mock for testing

func (*MockSAMLService) HandleCallback

func (m *MockSAMLService) HandleCallback(ctx context.Context, samlResponse, relayState, providerName string) (nameID, email string, attributes map[string][]string, err error)

HandleCallback mocks SAML callback processing

func (*MockSAMLService) InitiateLogin

func (m *MockSAMLService) InitiateLogin(ctx context.Context, providerName, relayState string) (string, error)

InitiateLogin mocks SAML login initiation

func (*MockSAMLService) MarkAssertionUsed

func (m *MockSAMLService) MarkAssertionUsed(assertionID string)

MarkAssertionUsed marks an assertion as used for replay detection testing

type MockSettingsCache

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

MockSettingsCache provides a mock for auth.SettingsCache

func NewMockSettingsCache

func NewMockSettingsCache() *MockSettingsCache

NewMockSettingsCache creates a new mock settings cache

func (*MockSettingsCache) GetBool

func (m *MockSettingsCache) GetBool(ctx context.Context, key string, defaultValue bool) bool

GetBool retrieves a boolean value (mimics SettingsCache.GetBool interface)

func (*MockSettingsCache) GetInt

func (m *MockSettingsCache) GetInt(ctx context.Context, key string, defaultValue int) int

GetInt retrieves an integer value

func (*MockSettingsCache) GetString

func (m *MockSettingsCache) GetString(ctx context.Context, key string, defaultValue string) string

GetString retrieves a string value

func (*MockSettingsCache) SetBool

func (m *MockSettingsCache) SetBool(key string, value bool)

SetBool sets a boolean value for testing

func (*MockSettingsCache) SetInt

func (m *MockSettingsCache) SetInt(key string, value int)

SetInt sets an integer value for testing

func (*MockSettingsCache) SetString

func (m *MockSettingsCache) SetString(key string, value string)

SetString sets a string value for testing

type MockStorageProvider

type MockStorageProvider struct {

	// Callbacks for custom behavior
	OnUpload   func(ctx context.Context, bucket, key string, data io.Reader, size int64) error
	OnDownload func(ctx context.Context, bucket, key string) (io.ReadCloser, *storage.Object, error)
	OnDelete   func(ctx context.Context, bucket, key string) error
	// contains filtered or unexported fields
}

MockStorageProvider implements storage.Provider for testing

func NewMockStorageProvider

func NewMockStorageProvider() *MockStorageProvider

NewMockStorageProvider creates a new mock storage provider

func (*MockStorageProvider) BucketExists

func (m *MockStorageProvider) BucketExists(ctx context.Context, bucket string) (bool, error)

func (*MockStorageProvider) CopyObject

func (m *MockStorageProvider) CopyObject(ctx context.Context, srcBucket, srcKey, destBucket, destKey string) error

func (*MockStorageProvider) CreateBucket

func (m *MockStorageProvider) CreateBucket(ctx context.Context, bucket string) error

func (*MockStorageProvider) Delete

func (m *MockStorageProvider) Delete(ctx context.Context, bucket, key string) error

func (*MockStorageProvider) DeleteBucket

func (m *MockStorageProvider) DeleteBucket(ctx context.Context, bucket string) error

func (*MockStorageProvider) Download

func (m *MockStorageProvider) Download(ctx context.Context, bucket, key string, opts *storage.DownloadOptions) (io.ReadCloser, *storage.Object, error)

func (*MockStorageProvider) Exists

func (m *MockStorageProvider) Exists(ctx context.Context, bucket, key string) (bool, error)

func (*MockStorageProvider) GenerateSignedURL

func (m *MockStorageProvider) GenerateSignedURL(ctx context.Context, bucket, key string, opts *storage.SignedURLOptions) (string, error)

func (*MockStorageProvider) GetObject

func (m *MockStorageProvider) GetObject(ctx context.Context, bucket, key string) (*storage.Object, error)

func (*MockStorageProvider) Health

func (m *MockStorageProvider) Health(ctx context.Context) error

func (*MockStorageProvider) List

func (*MockStorageProvider) ListBuckets

func (m *MockStorageProvider) ListBuckets(ctx context.Context) ([]string, error)

func (*MockStorageProvider) MoveObject

func (m *MockStorageProvider) MoveObject(ctx context.Context, srcBucket, srcKey, destBucket, destKey string) error

func (*MockStorageProvider) Name

func (m *MockStorageProvider) Name() string

func (*MockStorageProvider) Upload

func (m *MockStorageProvider) Upload(ctx context.Context, bucket, key string, data io.Reader, size int64, opts *storage.UploadOptions) (*storage.Object, error)

type MockSubscriptionDB

type MockSubscriptionDB struct {

	// EnabledTables maps "schema.table" to enabled status
	EnabledTables map[string]bool

	// RLSResults maps "schema.table.recordID" to access result
	RLSResults map[string]bool

	// OwnershipResults maps execution ID to (isOwner, exists)
	OwnershipResults map[uuid.UUID]struct {
		IsOwner bool
		Exists  bool
	}
	// contains filtered or unexported fields
}

MockSubscriptionDB implements realtime.SubscriptionDB for testing. It allows configuring which tables are enabled for realtime and controlling RLS/ownership check results.

func NewMockSubscriptionDB

func NewMockSubscriptionDB() *MockSubscriptionDB

NewMockSubscriptionDB creates a new mock subscription database

func (*MockSubscriptionDB) CheckFunctionOwnership

func (m *MockSubscriptionDB) CheckFunctionOwnership(ctx context.Context, execID, userID uuid.UUID) (bool, bool, error)

CheckFunctionOwnership implements SubscriptionDB

func (*MockSubscriptionDB) CheckJobOwnership

func (m *MockSubscriptionDB) CheckJobOwnership(ctx context.Context, execID, userID uuid.UUID) (bool, bool, error)

CheckJobOwnership implements SubscriptionDB

func (*MockSubscriptionDB) CheckRLSAccess

func (m *MockSubscriptionDB) CheckRLSAccess(ctx context.Context, schema, table, role string, claims map[string]interface{}, recordID interface{}) (bool, error)

CheckRLSAccess implements SubscriptionDB

func (*MockSubscriptionDB) CheckRPCOwnership

func (m *MockSubscriptionDB) CheckRPCOwnership(ctx context.Context, execID, userID uuid.UUID) (bool, bool, error)

CheckRPCOwnership implements SubscriptionDB

func (*MockSubscriptionDB) EnableTable

func (m *MockSubscriptionDB) EnableTable(schema, table string)

EnableTable marks a table as enabled for realtime

func (*MockSubscriptionDB) IsTableRealtimeEnabled

func (m *MockSubscriptionDB) IsTableRealtimeEnabled(ctx context.Context, schema, table string) (bool, error)

IsTableRealtimeEnabled implements SubscriptionDB

type MockTOTPValidator

type MockTOTPValidator struct {

	// Callbacks for custom behavior
	ValidateFunc func(secret, code string) bool
	GenerateFunc func() (secret string, qrCode []byte, err error)

	// State tracking
	ValidCodes   map[string][]string // secret -> valid codes
	Secret       string
	ShouldError  bool
	ErrorMessage string
	CodeIsValid  bool // Override for validation result
	// contains filtered or unexported fields
}

MockTOTPValidator implements TOTP validation for testing

func NewMockTOTPValidator

func NewMockTOTPValidator() *MockTOTPValidator

NewMockTOTPValidator creates a new mock TOTP validator

func (*MockTOTPValidator) AddValidCode

func (m *MockTOTPValidator) AddValidCode(secret, code string)

AddValidCode adds a valid code for a secret (for testing)

func (*MockTOTPValidator) Generate

func (m *MockTOTPValidator) Generate() (string, []byte, error)

Generate generates a new TOTP secret for testing

func (*MockTOTPValidator) Validate

func (m *MockTOTPValidator) Validate(secret, code string) bool

Validate validates a TOTP code for testing

type MockTime

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

MockTime is a helper for time-sensitive tests. It allows you to control the current time in tests.

func NewMockTime

func NewMockTime() *MockTime

NewMockTime creates a new mock time helper.

func (*MockTime) Add

func (m *MockTime) Add(d time.Duration)

Add adds a duration to the current time.

func (*MockTime) Freeze

func (m *MockTime) Freeze()

Freeze freezes time at the current moment.

func (*MockTime) Now

func (m *MockTime) Now() time.Time

Now returns the current (mock) time.

func (*MockTime) Set

func (m *MockTime) Set(t time.Time)

Set sets the current time to a specific value.

func (*MockTime) Unfreeze

func (m *MockTime) Unfreeze()

Unfreeze unfreezes time.

type MockVectorDatabase

type MockVectorDatabase struct {

	// Callbacks for custom behavior
	InsertFunc func(vectors []Vector) error
	SearchFunc func(query Vector, limit int, filters map[string]string) ([]VectorSearchResult, error)
	DeleteFunc func(ids []string) error

	// State tracking
	Vectors      map[string]Vector // id -> vector
	ShouldError  bool
	ErrorMessage string
	// contains filtered or unexported fields
}

MockVectorDatabase implements vector database operations for testing

func NewMockVectorDatabase

func NewMockVectorDatabase() *MockVectorDatabase

NewMockVectorDatabase creates a new mock vector database

func (*MockVectorDatabase) Delete

func (m *MockVectorDatabase) Delete(ids []string) error

Delete deletes vectors by IDs

func (*MockVectorDatabase) Insert

func (m *MockVectorDatabase) Insert(vectors []Vector) error

Insert inserts vectors into the mock database

func (*MockVectorDatabase) Search

func (m *MockVectorDatabase) Search(query Vector, limit int, filters map[string]string) ([]VectorSearchResult, error)

Search searches for similar vectors

type OAuthToken

type OAuthToken struct {
	AccessToken  string
	RefreshToken string
	Expiry       time.Time
	TokenType    string
}

OAuthToken represents an OAuth token for testing

type OAuthUser

type OAuthUser struct {
	ID       string
	Email    string
	Name     string
	Picture  string
	Provider string
}

OAuthUser represents an OAuth user for testing

type PublishedMessage

type PublishedMessage struct {
	Channel string
	Payload []byte
}

PublishedMessage records a published message for testing

type Vector

type Vector struct {
	ID       string
	Values   []float32
	Metadata map[string]interface{}
}

Vector represents a vector with metadata

type VectorSearchResult

type VectorSearchResult struct {
	Vector     Vector
	Similarity float32
}

VectorSearchResult represents a vector search result

Jump to

Keyboard shortcuts

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