testutil

package
v0.0.0-...-8a0222f Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2026 License: AGPL-3.0, GPL-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertEventuallyTrue

func AssertEventuallyTrue(t *testing.T, condition func() bool, timeout time.Duration, message string)

AssertEventuallyTrue asserts that a condition becomes true within a timeout

func AssertNeverTrue

func AssertNeverTrue(t *testing.T, condition func() bool, duration time.Duration, message string)

AssertNeverTrue asserts that a condition never becomes true within a duration

func CheckMailpitForRecipients

func CheckMailpitForRecipients(t *testing.T, subject string, expectedRecipients []string, timeout time.Duration) (map[string]bool, error)

CheckMailpitForRecipients checks if an email was sent to all expected recipients via Mailpit Returns a map of recipient email addresses to whether they received the email

func CleanupAllTasks

func CleanupAllTasks(t *testing.T, client *APIClient, workspaceID string) error

CleanupAllTasks deletes all tasks for a workspace This is useful for cleaning up evergreen tasks between tests

func CleanupAllTestConnections

func CleanupAllTestConnections() error

CleanupAllTestConnections cleans up the global connection pool This should be called at the end of test runs to ensure no connections leak

func CleanupGlobalTestPool

func CleanupGlobalTestPool() error

CleanupGlobalTestPool cleans up the global test pool This should be called at the end of test runs to ensure no connections leak

func CleanupTestEnvironment

func CleanupTestEnvironment()

CleanupTestEnvironment cleans up test environment variables and connections

func CleanupTestWorkspaces

func CleanupTestWorkspaces(t *testing.T, pool *TestConnectionPool, workspaceIDs []string)

CleanupTestWorkspaces removes test workspaces

func ClearMailpitMessages

func ClearMailpitMessages(t *testing.T) error

ClearMailpitMessages deletes all messages from Mailpit

func CreateTestEmailQueueEntry

func CreateTestEmailQueueEntry(integrationID, contactEmail, sourceID string, sourceType domain.EmailQueueSourceType) *domain.EmailQueueEntry

CreateTestEmailQueueEntry creates a test email queue entry with sensible defaults

func CreateTestLogger

func CreateTestLogger() logger.Logger

CreateTestLogger creates a logger for testing

func CreateTestWorkspaces

func CreateTestWorkspaces(t *testing.T, pool *TestConnectionPool, count int) []string

CreateTestWorkspaces creates N test workspaces and returns their IDs

func FindAvailablePort

func FindAvailablePort(t *testing.T) int

FindAvailablePort finds an available TCP port for testing

func GenerateRandomString

func GenerateRandomString(length int) string

GenerateRandomString generates a random string of specified length

func GenerateTestEmail

func GenerateTestEmail() string

GenerateTestEmail generates a test email address

func GetActiveConnectionCount

func GetActiveConnectionCount(t *testing.T, systemDB *sql.DB, user string) int

GetActiveConnectionCount returns current connection count for a user

func GetAllMailpitRecipients

func GetAllMailpitRecipients(t *testing.T, subject string) (map[string]bool, error)

GetAllMailpitRecipients returns all unique recipient email addresses for messages matching a subject This is the primary verification function for Issue #157 - ensures no recipients are skipped

func GetDatabaseConnectionStats

func GetDatabaseConnectionStats(t *testing.T, systemDB *sql.DB, dbName string) (int, error)

GetDatabaseConnectionStats returns detailed connection statistics for a database

func GetGlobalPoolConnectionCount

func GetGlobalPoolConnectionCount() int

GetGlobalPoolConnectionCount returns the connection count from the global pool

func GetMailpitMessageCount

func GetMailpitMessageCount(t *testing.T, subject string) (int, error)

GetMailpitMessageCount returns the total count of messages matching a subject substring This is useful for verifying broadcast delivery to large recipient lists

func GetTestConnectionCount

func GetTestConnectionCount() int

GetTestConnectionCount returns the current number of active test connections

func GetTestDatabaseConfig

func GetTestDatabaseConfig() *config.DatabaseConfig

GetTestDatabaseConfig returns a database config for testing

func MeasureOperationTime

func MeasureOperationTime(t *testing.T, operation string, fn func()) time.Duration

MeasureOperationTime measures and returns operation duration

func RequireEnvironmentVar

func RequireEnvironmentVar(t *testing.T, envVar string) string

RequireEnvironmentVar requires an environment variable to be set

func SetupTestEnvironment

func SetupTestEnvironment()

SetupTestEnvironment sets up environment variables for testing

func SkipIfShort

func SkipIfShort(t *testing.T)

SkipIfShort skips the test if running in short mode

func TerminateAllConnections

func TerminateAllConnections(t *testing.T, systemDB *sql.DB, dbName string) error

TerminateAllConnections terminates all connections to a database (for testing)

func VerifyBroadcastWinnerTemplate

func VerifyBroadcastWinnerTemplate(client *APIClient, broadcastID, expectedTemplateID string) error

VerifyBroadcastWinnerTemplate checks that a broadcast has the expected winning template

func VerifyNoLeakedConnections

func VerifyNoLeakedConnections(t *testing.T, systemDB *sql.DB, testUser string)

VerifyNoLeakedConnections queries PostgreSQL for leaked connections This should be called after cleaning up a test to ensure no connections remain

func VerifyTasksProcessed

func VerifyTasksProcessed(t *testing.T, client *APIClient, workspaceID string, taskIDs []string, timeout time.Duration) map[string]string

VerifyTasksProcessed checks that tasks in the given list were attempted to be processed Returns a map of task IDs to their final status

func WaitAndExecuteTasks

func WaitAndExecuteTasks(client *APIClient, rounds int, delayBetweenRounds time.Duration) error

WaitAndExecuteTasks is a helper method for A/B testing integration tests It executes pending tasks multiple times with delays to simulate real task execution

func WaitForBroadcastCompletion

func WaitForBroadcastCompletion(t *testing.T, client *APIClient, broadcastID string, timeout time.Duration) (string, error)

WaitForBroadcastCompletion waits for a broadcast to reach a terminal state Returns the final broadcast status or error if timeout/failure occurs

func WaitForBroadcastStatus

func WaitForBroadcastStatus(t *testing.T, client *APIClient, broadcastID string, acceptableStatuses []string, timeout time.Duration) (string, error)

WaitForBroadcastStatus polls a broadcast until it reaches one of the expected statuses This is useful for A/B testing scenarios where we need to wait for phase transitions Returns the actual status reached, or error if timeout or failure occurs

func WaitForBroadcastStatusWithExecution

func WaitForBroadcastStatusWithExecution(t *testing.T, client *APIClient, broadcastID string, acceptableStatuses []string, timeout time.Duration) (string, error)

WaitForBroadcastStatusWithExecution waits for a broadcast to reach one of the acceptable statuses while continuously executing pending tasks. This is the recommended helper for A/B testing flows that require task orchestration to complete.

This function differs from WaitForBroadcastStatus by actively executing tasks during the wait, which is necessary for broadcasts that need continuous task processing to transition through phases.

Parameters:

  • t: testing context for logging
  • client: API client for making requests
  • broadcastID: ID of the broadcast to monitor
  • acceptableStatuses: list of statuses that indicate success
  • timeout: maximum time to wait

Returns the final status reached or an error if timeout occurs.

func WaitForBuildTaskCreated

func WaitForBuildTaskCreated(t *testing.T, client *APIClient, workspaceID, segmentID string, afterTime time.Time, timeout time.Duration) (string, error)

WaitForBuildTaskCreated waits for a build_segment task to be created for a specific segment Returns the task ID or error if timeout occurs

func WaitForCondition

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

WaitForCondition waits for a condition to be true within a timeout

func WaitForConditionWithContext

func WaitForConditionWithContext(ctx context.Context, t *testing.T, condition func() bool, checkInterval time.Duration, message string) error

WaitForConditionWithContext waits for a condition to be true within a timeout

func WaitForConnectionClose

func WaitForConnectionClose(t *testing.T, systemDB *sql.DB, timeout time.Duration)

WaitForConnectionClose waits for a connection to be closed with timeout

func WaitForDatabaseReady

func WaitForDatabaseReady(t *testing.T, db *sql.DB, timeout time.Duration) error

WaitForDatabaseReady waits for a database to be ready for connections

func WaitForMailpitMessages

func WaitForMailpitMessages(t *testing.T, subject string, expectedCount int, timeout time.Duration) error

WaitForMailpitMessages waits until the expected count of messages arrive in Mailpit This is useful when testing async broadcast delivery to many recipients

func WaitForQueueEmpty

func WaitForQueueEmpty(t *testing.T, queueRepo domain.EmailQueueRepository, workspaceID string, timeout time.Duration) error

WaitForQueueEmpty waits for the email queue to be empty (no pending or processing entries)

func WaitForQueueProcessed

func WaitForQueueProcessed(t *testing.T, queueRepo domain.EmailQueueRepository, workspaceID string,
	expectedTotal int64, timeout time.Duration) (*domain.EmailQueueStats, error)

WaitForQueueProcessed waits for all pending entries to be processed (either sent or failed) Note: Sent entries are deleted immediately, so we wait until the queue is empty

func WaitForQueueStats

func WaitForQueueStats(t *testing.T, queueRepo domain.EmailQueueRepository, workspaceID string,
	expectedSent, expectedFailed int64, timeout time.Duration) error

WaitForQueueStats waits for the email queue to reach specific stats Note: Since sent entries are deleted immediately, this only waits for failed count and empty queue

func WaitForSegmentBuilt

func WaitForSegmentBuilt(t *testing.T, client *APIClient, workspaceID, segmentID string, timeout time.Duration) (string, error)

WaitForSegmentBuilt waits for a segment to reach "built" status Returns the final status or error if timeout/failure occurs

func WaitForTaskCompletion

func WaitForTaskCompletion(t *testing.T, client *APIClient, workspaceID, taskID string, timeout time.Duration) (string, error)

WaitForTaskCompletion waits for a task to reach a terminal state (completed, failed, or cancelled) Returns the final task status and any error that occurred

Types

type APIClient

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

APIClient provides HTTP client functionality for integration tests

func NewAPIClient

func NewAPIClient(baseURL string) *APIClient

NewAPIClient creates a new API client for testing

func NewAPIClientNoRedirect

func NewAPIClientNoRedirect(baseURL string) *APIClient

NewAPIClientNoRedirect creates an API client that does NOT follow redirects This is useful for testing redirect behavior itself

func (*APIClient) ActivateAutomation

func (c *APIClient) ActivateAutomation(request map[string]interface{}) (*http.Response, error)

ActivateAutomation activates an automation (creates DB trigger)

func (*APIClient) BatchImportContacts

func (c *APIClient) BatchImportContacts(contacts []map[string]interface{}, listIDs []string) (*http.Response, error)

func (*APIClient) CancelBroadcast

func (c *APIClient) CancelBroadcast(request map[string]interface{}) (*http.Response, error)

CancelBroadcast cancels a scheduled broadcast

func (*APIClient) CompileTemplate

func (c *APIClient) CompileTemplate(compileReq map[string]interface{}) (*http.Response, error)

func (*APIClient) CreateAutomation

func (c *APIClient) CreateAutomation(automation map[string]interface{}) (*http.Response, error)

CreateAutomation creates a new automation

func (*APIClient) CreateBlogCategory

func (c *APIClient) CreateBlogCategory(category map[string]interface{}) (*http.Response, error)

CreateBlogCategory creates a new blog category

func (*APIClient) CreateBlogPost

func (c *APIClient) CreateBlogPost(post map[string]interface{}) (*http.Response, error)

CreateBlogPost creates a new blog post

func (*APIClient) CreateBlogTheme

func (c *APIClient) CreateBlogTheme(theme map[string]interface{}) (*http.Response, error)

CreateBlogTheme creates a new blog theme

func (*APIClient) CreateBroadcast

func (c *APIClient) CreateBroadcast(broadcast map[string]interface{}) (*http.Response, error)

Broadcast API helpers

func (*APIClient) CreateContact

func (c *APIClient) CreateContact(contact map[string]interface{}) (*http.Response, error)

Contact API helpers

func (*APIClient) CreateList

func (c *APIClient) CreateList(list map[string]interface{}) (*http.Response, error)

List API helpers

func (*APIClient) CreateTask

func (c *APIClient) CreateTask(request map[string]interface{}) (*http.Response, error)

CreateTask creates a new task

func (*APIClient) CreateTemplate

func (c *APIClient) CreateTemplate(template map[string]interface{}) (*http.Response, error)

Template API helpers

func (*APIClient) CreateTransactionalNotification

func (c *APIClient) CreateTransactionalNotification(notification map[string]interface{}) (*http.Response, error)

CreateTransactionalNotification creates a transactional notification

func (*APIClient) CreateWorkspace

func (c *APIClient) CreateWorkspace(workspace map[string]interface{}) (*http.Response, error)

Workspace API helpers

func (*APIClient) DecodeJSON

func (c *APIClient) DecodeJSON(resp *http.Response, result interface{}) error

DecodeJSON decodes response body as JSON

func (*APIClient) Delete

func (c *APIClient) Delete(endpoint string, params ...map[string]string) (*http.Response, error)

Delete makes a DELETE request

func (*APIClient) DeleteAutomation

func (c *APIClient) DeleteAutomation(request map[string]interface{}) (*http.Response, error)

DeleteAutomation deletes an automation (soft delete)

func (*APIClient) DeleteBlogCategory

func (c *APIClient) DeleteBlogCategory(request map[string]interface{}) (*http.Response, error)

DeleteBlogCategory deletes a blog category

func (*APIClient) DeleteBlogPost

func (c *APIClient) DeleteBlogPost(request map[string]interface{}) (*http.Response, error)

DeleteBlogPost deletes a blog post

func (*APIClient) DeleteBroadcast

func (c *APIClient) DeleteBroadcast(request map[string]interface{}) (*http.Response, error)

DeleteBroadcast deletes a broadcast

func (*APIClient) DeleteTask

func (c *APIClient) DeleteTask(workspaceID, taskID string) (*http.Response, error)

DeleteTask deletes a task

func (*APIClient) DeleteTemplate

func (c *APIClient) DeleteTemplate(workspaceID, templateID string) (*http.Response, error)

func (*APIClient) DeleteTransactionalNotification

func (c *APIClient) DeleteTransactionalNotification(notificationID string) (*http.Response, error)

DeleteTransactionalNotification deletes a transactional notification

func (*APIClient) ExecutePendingTasks

func (c *APIClient) ExecutePendingTasks(maxTasks int) (*http.Response, error)

ExecutePendingTasks executes pending tasks

func (*APIClient) ExecuteTask

func (c *APIClient) ExecuteTask(request map[string]interface{}) (*http.Response, error)

ExecuteTask executes a specific task

func (*APIClient) ExpectStatus

func (c *APIClient) ExpectStatus(resp *http.Response, expectedStatus int) error

ExpectStatus checks if response has expected status code

func (*APIClient) Get

func (c *APIClient) Get(endpoint string, params ...map[string]string) (*http.Response, error)

Get makes a GET request

func (*APIClient) GetAutomation

func (c *APIClient) GetAutomation(automationID string) (*http.Response, error)

GetAutomation retrieves an automation by ID

func (*APIClient) GetBlogCategory

func (c *APIClient) GetBlogCategory(params map[string]string) (*http.Response, error)

GetBlogCategory retrieves a blog category by ID or slug

func (*APIClient) GetBlogPost

func (c *APIClient) GetBlogPost(params map[string]string) (*http.Response, error)

GetBlogPost retrieves a blog post by ID, slug, or category+slug

func (*APIClient) GetBlogTheme

func (c *APIClient) GetBlogTheme(params map[string]string) (*http.Response, error)

GetBlogTheme retrieves a blog theme by version

func (*APIClient) GetBroadcast

func (c *APIClient) GetBroadcast(broadcastID string) (*http.Response, error)

func (*APIClient) GetBroadcastTestResults

func (c *APIClient) GetBroadcastTestResults(workspaceID, broadcastID string) (*http.Response, error)

GetBroadcastTestResults retrieves A/B test results for a broadcast

func (*APIClient) GetContactByEmail

func (c *APIClient) GetContactByEmail(email string) (*http.Response, error)

func (*APIClient) GetContactListByIDs

func (c *APIClient) GetContactListByIDs(workspaceID, email, listID string) (*http.Response, error)

ContactList API methods

func (*APIClient) GetContactNodeExecutions

func (c *APIClient) GetContactNodeExecutions(automationID, email string) (*http.Response, error)

GetContactNodeExecutions retrieves a contact's node execution history for an automation

func (*APIClient) GetContactsByList

func (c *APIClient) GetContactsByList(workspaceID, listID string) (*http.Response, error)

func (*APIClient) GetJSON

func (c *APIClient) GetJSON(endpoint string, result interface{}, params ...map[string]string) error

GetJSON makes a GET request and decodes JSON response

func (*APIClient) GetList

func (c *APIClient) GetList(listID string) (*http.Response, error)

func (*APIClient) GetListsByContact

func (c *APIClient) GetListsByContact(workspaceID, email string) (*http.Response, error)

func (*APIClient) GetPublishedBlogTheme

func (c *APIClient) GetPublishedBlogTheme(params ...map[string]string) (*http.Response, error)

GetPublishedBlogTheme retrieves the currently published blog theme

func (*APIClient) GetTask

func (c *APIClient) GetTask(workspaceID, taskID string) (*http.Response, error)

GetTask retrieves a task by ID

func (*APIClient) GetTemplate

func (c *APIClient) GetTemplate(templateID string) (*http.Response, error)

func (*APIClient) GetToken

func (c *APIClient) GetToken() string

GetToken returns the current authentication token

func (*APIClient) GetTransactionalNotification

func (c *APIClient) GetTransactionalNotification(notificationID string) (*http.Response, error)

GetTransactionalNotification gets a transactional notification by ID

func (*APIClient) GetWebhookStatus

func (c *APIClient) GetWebhookStatus(workspaceID, integrationID string) (*http.Response, error)

GetWebhookStatus gets the status of webhooks for an email provider

func (*APIClient) GetWorkspace

func (c *APIClient) GetWorkspace(workspaceID string) (*http.Response, error)

func (*APIClient) GetWorkspaceID

func (c *APIClient) GetWorkspaceID() string

GetWorkspaceID returns the current workspace ID

func (*APIClient) ListAutomations

func (c *APIClient) ListAutomations(params map[string]string) (*http.Response, error)

ListAutomations lists automations with optional filtering

func (*APIClient) ListBlogCategories

func (c *APIClient) ListBlogCategories(params ...map[string]string) (*http.Response, error)

ListBlogCategories lists all blog categories

func (*APIClient) ListBlogPosts

func (c *APIClient) ListBlogPosts(params map[string]string) (*http.Response, error)

ListBlogPosts lists blog posts with optional filtering

func (*APIClient) ListBlogThemes

func (c *APIClient) ListBlogThemes(params ...map[string]string) (*http.Response, error)

ListBlogThemes lists all blog themes

func (*APIClient) ListBroadcasts

func (c *APIClient) ListBroadcasts(params map[string]string) (*http.Response, error)

func (*APIClient) ListContacts

func (c *APIClient) ListContacts(params map[string]string) (*http.Response, error)

func (*APIClient) ListLists

func (c *APIClient) ListLists(params map[string]string) (*http.Response, error)

func (*APIClient) ListTasks

func (c *APIClient) ListTasks(params map[string]string) (*http.Response, error)

ListTasks retrieves tasks with optional filtering

func (*APIClient) ListTemplates

func (c *APIClient) ListTemplates(params map[string]string) (*http.Response, error)

func (*APIClient) ListTransactionalNotifications

func (c *APIClient) ListTransactionalNotifications(params map[string]string) (*http.Response, error)

ListTransactionalNotifications lists transactional notifications

func (*APIClient) Login

func (c *APIClient) Login(email, password string) error

Login authenticates using the magic code flow and sets the token

func (*APIClient) MakeRequestWithHost

func (c *APIClient) MakeRequestWithHost(method, endpoint, host string, body interface{}, params ...map[string]string) (*http.Response, error)

MakeRequestWithHost makes an HTTP request with a custom Host header This is useful for testing blog routing logic that depends on the Host header

func (*APIClient) PauseAutomation

func (c *APIClient) PauseAutomation(request map[string]interface{}) (*http.Response, error)

PauseAutomation pauses an automation

func (*APIClient) PauseBroadcast

func (c *APIClient) PauseBroadcast(request map[string]interface{}) (*http.Response, error)

PauseBroadcast pauses a sending broadcast

func (*APIClient) Post

func (c *APIClient) Post(endpoint string, body interface{}, params ...map[string]string) (*http.Response, error)

Post makes a POST request

func (*APIClient) PostJSON

func (c *APIClient) PostJSON(endpoint string, reqBody interface{}, result interface{}, params ...map[string]string) error

PostJSON makes a POST request and decodes JSON response

func (*APIClient) PostRaw

func (c *APIClient) PostRaw(endpoint string, rawBody string) (*http.Response, error)

PostRaw makes a POST request with raw string body (no JSON encoding)

func (*APIClient) PublishBlogPost

func (c *APIClient) PublishBlogPost(request map[string]interface{}) (*http.Response, error)

PublishBlogPost publishes a blog post

func (*APIClient) PublishBlogTheme

func (c *APIClient) PublishBlogTheme(request map[string]interface{}) (*http.Response, error)

PublishBlogTheme publishes a blog theme

func (*APIClient) Put

func (c *APIClient) Put(endpoint string, body interface{}, params ...map[string]string) (*http.Response, error)

Put makes a PUT request

func (*APIClient) ReadBody

func (c *APIClient) ReadBody(resp *http.Response) (string, error)

ReadBody reads and returns response body as string

func (*APIClient) RegisterWebhooks

func (c *APIClient) RegisterWebhooks(request map[string]interface{}) (*http.Response, error)

RegisterWebhooks registers webhooks with an email provider

func (*APIClient) RemoveContactFromList

func (c *APIClient) RemoveContactFromList(workspaceID, email, listID string) (*http.Response, error)

func (*APIClient) ResumeBroadcast

func (c *APIClient) ResumeBroadcast(request map[string]interface{}) (*http.Response, error)

ResumeBroadcast resumes a paused broadcast

func (*APIClient) ScheduleBroadcast

func (c *APIClient) ScheduleBroadcast(request map[string]interface{}) (*http.Response, error)

ScheduleBroadcast schedules a broadcast for sending

func (*APIClient) SelectBroadcastWinner

func (c *APIClient) SelectBroadcastWinner(request map[string]interface{}) (*http.Response, error)

SelectBroadcastWinner manually selects the winning variation for an A/B test

func (*APIClient) SendBroadcastToIndividual

func (c *APIClient) SendBroadcastToIndividual(request map[string]interface{}) (*http.Response, error)

SendBroadcastToIndividual sends a broadcast to an individual recipient

func (*APIClient) SendTransactionalNotification

func (c *APIClient) SendTransactionalNotification(notification map[string]interface{}) (*http.Response, error)

SendTransactionalNotification sends a transactional notification

func (*APIClient) SetToken

func (c *APIClient) SetToken(token string)

SetToken sets the authentication token

func (*APIClient) SetWorkspaceID

func (c *APIClient) SetWorkspaceID(workspaceID string)

SetWorkspaceID sets the default workspace ID for requests

func (*APIClient) TestTransactionalTemplate

func (c *APIClient) TestTransactionalTemplate(request map[string]interface{}) (*http.Response, error)

TestTransactionalTemplate tests a transactional template

func (*APIClient) UnpublishBlogPost

func (c *APIClient) UnpublishBlogPost(request map[string]interface{}) (*http.Response, error)

UnpublishBlogPost unpublishes a blog post

func (*APIClient) UpdateAutomation

func (c *APIClient) UpdateAutomation(automation map[string]interface{}) (*http.Response, error)

UpdateAutomation updates an existing automation

func (*APIClient) UpdateBlogCategory

func (c *APIClient) UpdateBlogCategory(category map[string]interface{}) (*http.Response, error)

UpdateBlogCategory updates a blog category

func (*APIClient) UpdateBlogPost

func (c *APIClient) UpdateBlogPost(post map[string]interface{}) (*http.Response, error)

UpdateBlogPost updates a blog post

func (*APIClient) UpdateBlogTheme

func (c *APIClient) UpdateBlogTheme(theme map[string]interface{}) (*http.Response, error)

UpdateBlogTheme updates a blog theme

func (*APIClient) UpdateBroadcast

func (c *APIClient) UpdateBroadcast(broadcast map[string]interface{}) (*http.Response, error)

UpdateBroadcast updates an existing broadcast

func (*APIClient) UpdateContactListStatus

func (c *APIClient) UpdateContactListStatus(workspaceID, email, listID, status string) (*http.Response, error)

func (*APIClient) UpdateTemplate

func (c *APIClient) UpdateTemplate(template map[string]interface{}) (*http.Response, error)

func (*APIClient) UpdateTransactionalNotification

func (c *APIClient) UpdateTransactionalNotification(notificationID string, updates map[string]interface{}) (*http.Response, error)

UpdateTransactionalNotification updates a transactional notification

type AppInterface

type AppInterface interface {
	Initialize() error
	Start() error
	Shutdown(ctx context.Context) error
	GetConfig() *config.Config
	GetLogger() logger.Logger
	GetMux() *http.ServeMux

	// Repository getters for testing
	GetUserRepository() domain.UserRepository
	GetWorkspaceRepository() domain.WorkspaceRepository
	GetContactRepository() domain.ContactRepository
	GetListRepository() domain.ListRepository
	GetTemplateRepository() domain.TemplateRepository
	GetBroadcastRepository() domain.BroadcastRepository
	GetMessageHistoryRepository() domain.MessageHistoryRepository
	GetContactListRepository() domain.ContactListRepository
	GetTransactionalNotificationRepository() domain.TransactionalNotificationRepository
	GetEmailQueueRepository() domain.EmailQueueRepository

	// Service getters for testing
	GetAuthService() interface{} // Returns *service.AuthService but defined as interface{} to avoid import cycle
	GetTransactionalNotificationService() domain.TransactionalNotificationService
	GetEmailQueueWorker() *queue.EmailQueueWorker
	GetAutomationScheduler() *service.AutomationScheduler
}

AppInterface defines the interface for the App (to avoid circular imports)

type AutomationNodeOption

type AutomationNodeOption func(*domain.AutomationNode)

AutomationNodeOption defines options for creating automation nodes

func WithNodeAutomationID

func WithNodeAutomationID(automationID string) AutomationNodeOption

func WithNodeConfig

func WithNodeConfig(config map[string]interface{}) AutomationNodeOption

func WithNodeID

func WithNodeID(id string) AutomationNodeOption

Node options

func WithNodeNextNodeID

func WithNodeNextNodeID(nextNodeID string) AutomationNodeOption

func WithNodePosition

func WithNodePosition(x, y float64) AutomationNodeOption

func WithNodeType

func WithNodeType(nodeType domain.NodeType) AutomationNodeOption

type AutomationOption

type AutomationOption func(*domain.Automation)

AutomationOption defines options for creating automations

func WithAutomationID

func WithAutomationID(id string) AutomationOption

func WithAutomationListID

func WithAutomationListID(listID string) AutomationOption

func WithAutomationName

func WithAutomationName(name string) AutomationOption

Automation options

func WithAutomationNodes

func WithAutomationNodes(nodes []*domain.AutomationNode) AutomationOption

func WithAutomationRootNodeID

func WithAutomationRootNodeID(nodeID string) AutomationOption

func WithAutomationStatus

func WithAutomationStatus(status domain.AutomationStatus) AutomationOption

func WithAutomationTrigger

func WithAutomationTrigger(trigger *domain.TimelineTriggerConfig) AutomationOption

type BlogCategoryOption

type BlogCategoryOption func(*domain.BlogCategory)

Blog option types

func WithCategoryDescription

func WithCategoryDescription(description string) BlogCategoryOption

func WithCategoryName

func WithCategoryName(name string) BlogCategoryOption

Blog category options

func WithCategorySlug

func WithCategorySlug(slug string) BlogCategoryOption

type BlogPostOption

type BlogPostOption func(*domain.BlogPost)

func WithPostAuthors

func WithPostAuthors(authors []domain.BlogAuthor) BlogPostOption

func WithPostExcerpt

func WithPostExcerpt(excerpt string) BlogPostOption

func WithPostPublished

func WithPostPublished(published bool) BlogPostOption

func WithPostSlug

func WithPostSlug(slug string) BlogPostOption

func WithPostTemplate

func WithPostTemplate(templateID string, version int) BlogPostOption

func WithPostTitle

func WithPostTitle(title string) BlogPostOption

Blog post options

type BlogThemeOption

type BlogThemeOption func(*domain.BlogTheme)

func WithThemeFiles

func WithThemeFiles(files domain.BlogThemeFiles) BlogThemeOption

func WithThemePublished

func WithThemePublished(published bool) BlogThemeOption

func WithThemeVersion

func WithThemeVersion(version int) BlogThemeOption

Blog theme options

type BroadcastOption

type BroadcastOption func(*domain.Broadcast)

func WithBroadcastABTesting

func WithBroadcastABTesting(templateIDs []string) BroadcastOption

func WithBroadcastAudience

func WithBroadcastAudience(audience domain.AudienceSettings) BroadcastOption

func WithBroadcastName

func WithBroadcastName(name string) BroadcastOption

Broadcast options

func WithBroadcastStatus

func WithBroadcastStatus(status domain.BroadcastStatus) BroadcastOption

type CapturedSMTPMessage

type CapturedSMTPMessage struct {
	From       string
	Recipients []string
	Data       []byte
	Timestamp  time.Time
}

CapturedSMTPMessage stores a captured email message

type ConnectionPoolMetrics

type ConnectionPoolMetrics struct {
	TestName           string
	InitialConnections int
	PeakConnections    int
	FinalConnections   int
	LeakedConnections  int
	PoolCreations      int
	PoolDestructions   int
	Duration           time.Duration
	StartTime          time.Time
}

ConnectionPoolMetrics tracks connection pool usage during tests

func NewConnectionPoolMetrics

func NewConnectionPoolMetrics(testName string, initialConnections int) *ConnectionPoolMetrics

NewConnectionPoolMetrics creates a new metrics tracker

func (*ConnectionPoolMetrics) Finalize

func (m *ConnectionPoolMetrics) Finalize(finalConnections int)

Finalize finalizes the metrics

func (*ConnectionPoolMetrics) HasLeaks

func (m *ConnectionPoolMetrics) HasLeaks() bool

HasLeaks returns true if connections were leaked

func (*ConnectionPoolMetrics) RecordPoolCreation

func (m *ConnectionPoolMetrics) RecordPoolCreation()

RecordPoolCreation records a pool creation

func (*ConnectionPoolMetrics) RecordPoolDestruction

func (m *ConnectionPoolMetrics) RecordPoolDestruction()

RecordPoolDestruction records a pool destruction

func (*ConnectionPoolMetrics) Report

func (m *ConnectionPoolMetrics) Report(logFunc func(format string, args ...interface{}))

Report logs the metrics (for testing.T)

func (*ConnectionPoolMetrics) UpdateConnections

func (m *ConnectionPoolMetrics) UpdateConnections(current int)

UpdateConnections updates connection counts

type ContactListOption

type ContactListOption func(*domain.ContactList)

func WithContactListEmail

func WithContactListEmail(email string) ContactListOption

ContactList options

func WithContactListListID

func WithContactListListID(listID string) ContactListOption

func WithContactListStatus

func WithContactListStatus(status domain.ContactListStatus) ContactListOption

type ContactOption

type ContactOption func(*domain.Contact)

func WithContactCountry

func WithContactCountry(country string) ContactOption

func WithContactCustomNumber1

func WithContactCustomNumber1(value float64) ContactOption

func WithContactEmail

func WithContactEmail(email string) ContactOption

Contact options

func WithContactExternalID

func WithContactExternalID(externalID string) ContactOption

func WithContactName

func WithContactName(firstName, lastName string) ContactOption

type DatabaseManager

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

DatabaseManager manages test database lifecycle

func NewDatabaseManager

func NewDatabaseManager() *DatabaseManager

NewDatabaseManager creates a new database manager for testing

func (*DatabaseManager) Cleanup

func (dm *DatabaseManager) Cleanup() error

Cleanup drops the test database and closes connections

func (*DatabaseManager) CleanupTestData

func (dm *DatabaseManager) CleanupTestData() error

CleanupTestData removes all test data but keeps schema

func (*DatabaseManager) GetConfig

func (dm *DatabaseManager) GetConfig() *config.DatabaseConfig

GetConfig returns the test database configuration

func (*DatabaseManager) GetDB

func (dm *DatabaseManager) GetDB() *sql.DB

GetDB returns the test database connection

func (*DatabaseManager) GetWorkspaceDB

func (dm *DatabaseManager) GetWorkspaceDB(workspaceID string) (*sql.DB, error)

GetWorkspaceDB returns a connection to the workspace database

func (*DatabaseManager) SeedTestData

func (dm *DatabaseManager) SeedTestData() error

SeedTestData seeds the database with test data Note: Installation settings are already seeded during database initialization

func (*DatabaseManager) Setup

func (dm *DatabaseManager) Setup() error

Setup creates the test database and initializes it

func (*DatabaseManager) SkipInstallationSeeding

func (dm *DatabaseManager) SkipInstallationSeeding()

SkipInstallationSeeding configures the database manager to skip seeding installation settings This is used for setup wizard tests that need an uninstalled system

func (*DatabaseManager) WaitForDatabase

func (dm *DatabaseManager) WaitForDatabase(maxRetries int) error

WaitForDatabase waits for the database to be ready

type IntegrationOption

type IntegrationOption func(*domain.Integration)

func WithIntegrationEmailProvider

func WithIntegrationEmailProvider(emailProvider domain.EmailProvider) IntegrationOption

func WithIntegrationName

func WithIntegrationName(name string) IntegrationOption

Integration options

func WithIntegrationType

func WithIntegrationType(integrationType domain.IntegrationType) IntegrationOption

func WithSMTPOAuth2

func WithSMTPOAuth2(config SMTPOAuth2Config) IntegrationOption

WithSMTPOAuth2 creates an integration option for OAuth2 SMTP configuration

type IntegrationTestSuite

type IntegrationTestSuite struct {
	DBManager     *DatabaseManager
	ServerManager *ServerManager
	APIClient     *APIClient
	DataFactory   *TestDataFactory
	Config        *config.Config
	T             *testing.T
}

IntegrationTestSuite provides a complete testing environment

func NewIntegrationTestSuite

func NewIntegrationTestSuite(t *testing.T, appFactory func(*config.Config) AppInterface) *IntegrationTestSuite

NewIntegrationTestSuite creates a new integration test suite

func (*IntegrationTestSuite) Cleanup

func (s *IntegrationTestSuite) Cleanup()

Cleanup cleans up all test resources

func (*IntegrationTestSuite) ResetData

func (s *IntegrationTestSuite) ResetData()

ResetData cleans and reseeds test data

type ListOption

type ListOption func(*domain.List)

func WithListDoubleOptin

func WithListDoubleOptin(enabled bool) ListOption

func WithListName

func WithListName(name string) ListOption

List options

func WithListPublic

func WithListPublic(enabled bool) ListOption

type MailpitMessage

type MailpitMessage struct {
	ID        string `json:"ID"`
	MessageID string `json:"MessageID"`
	From      struct {
		Name    string `json:"Name"`
		Address string `json:"Address"`
	} `json:"From"`
	To []struct {
		Name    string `json:"Name"`
		Address string `json:"Address"`
	} `json:"To"`
	Cc []struct {
		Name    string `json:"Name"`
		Address string `json:"Address"`
	} `json:"Cc"`
	Subject string              `json:"Subject"`
	Date    time.Time           `json:"Date"`
	Text    string              `json:"Text"`
	HTML    string              `json:"HTML"`
	Size    int                 `json:"Size"`
	Headers map[string][]string `json:"Headers,omitempty"`
}

MailpitMessage represents a full message from Mailpit API (with headers and content)

func GetMailpitMessage

func GetMailpitMessage(t *testing.T, messageID string) (*MailpitMessage, error)

GetMailpitMessage fetches a single message with full headers from Mailpit

type MailpitMessageSummary

type MailpitMessageSummary struct {
	ID        string `json:"ID"`
	MessageID string `json:"MessageID"`
	From      struct {
		Name    string `json:"Name"`
		Address string `json:"Address"`
	} `json:"From"`
	To []struct {
		Name    string `json:"Name"`
		Address string `json:"Address"`
	} `json:"To"`
	Cc []struct {
		Name    string `json:"Name"`
		Address string `json:"Address"`
	} `json:"Cc"`
	Bcc []struct {
		Name    string `json:"Name"`
		Address string `json:"Address"`
	} `json:"Bcc"`
	Subject     string    `json:"Subject"`
	Created     time.Time `json:"Created"`
	Size        int       `json:"Size"`
	Attachments int       `json:"Attachments"`
}

MailpitMessageSummary represents a message summary from Mailpit API list endpoint

type MailpitMessagesResponse

type MailpitMessagesResponse struct {
	Total         int                     `json:"total"`
	Count         int                     `json:"count"`
	MessagesCount int                     `json:"messages_count"`
	Start         int                     `json:"start"`
	Messages      []MailpitMessageSummary `json:"messages"`
}

MailpitMessagesResponse represents the response from Mailpit's messages API

func WaitForMailpitMessagesFast

func WaitForMailpitMessagesFast(t *testing.T, subject string, timeout time.Duration) (*MailpitMessagesResponse, error)

WaitForMailpitMessagesFast waits for messages with fast polling (200ms interval). Returns the MailpitMessagesResponse when at least one message matching subject is found. If subject is empty, returns when any message is found.

type MessageHistoryOption

type MessageHistoryOption func(*domain.MessageHistory)

func WithMessageBounced

func WithMessageBounced(bounced bool) MessageHistoryOption

func WithMessageBroadcast

func WithMessageBroadcast(broadcastID string) MessageHistoryOption

func WithMessageChannel

func WithMessageChannel(channel string) MessageHistoryOption

func WithMessageClicked

func WithMessageClicked(clicked bool) MessageHistoryOption

func WithMessageContact

func WithMessageContact(email string) MessageHistoryOption

Convenience aliases for cleaner test code

func WithMessageDelivered

func WithMessageDelivered(delivered bool) MessageHistoryOption

func WithMessageFailed

func WithMessageFailed(failed bool) MessageHistoryOption

func WithMessageHistoryChannel

func WithMessageHistoryChannel(channel string) MessageHistoryOption

func WithMessageHistoryContactEmail

func WithMessageHistoryContactEmail(email string) MessageHistoryOption

Message history options

func WithMessageHistoryTemplateID

func WithMessageHistoryTemplateID(templateID string) MessageHistoryOption

func WithMessageHistoryTemplateVersion

func WithMessageHistoryTemplateVersion(version int64) MessageHistoryOption

func WithMessageID

func WithMessageID(id string) MessageHistoryOption

func WithMessageListID

func WithMessageListID(listID string) MessageHistoryOption

func WithMessageOpened

func WithMessageOpened(opened bool) MessageHistoryOption

func WithMessageSentAt

func WithMessageSentAt(sentAt time.Time) MessageHistoryOption

func WithMessageTemplate

func WithMessageTemplate(templateID string) MessageHistoryOption

type MockOAuth2SMTPServer

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

MockOAuth2SMTPServer is an SMTP server that validates XOAUTH2 authentication Follows RFC 5321 (SMTP) and RFC 7628 (SASL XOAUTH2)

func NewMockOAuth2SMTPServer

func NewMockOAuth2SMTPServer(validTokens map[string]string) *MockOAuth2SMTPServer

NewMockOAuth2SMTPServer creates a new mock SMTP server that validates XOAUTH2

func (*MockOAuth2SMTPServer) Addr

func (s *MockOAuth2SMTPServer) Addr() string

Addr returns the full address (host:port)

func (*MockOAuth2SMTPServer) ClearAuthAttempts

func (s *MockOAuth2SMTPServer) ClearAuthAttempts()

ClearAuthAttempts clears all authentication attempts

func (*MockOAuth2SMTPServer) ClearMessages

func (s *MockOAuth2SMTPServer) ClearMessages()

ClearMessages clears all received messages

func (*MockOAuth2SMTPServer) Close

func (s *MockOAuth2SMTPServer) Close()

Close shuts down the mock server

func (*MockOAuth2SMTPServer) GetAuthAttempts

func (s *MockOAuth2SMTPServer) GetAuthAttempts() []SMTPAuthAttempt

GetAuthAttempts returns a copy of all authentication attempts

func (*MockOAuth2SMTPServer) GetMessages

func (s *MockOAuth2SMTPServer) GetMessages() []CapturedSMTPMessage

GetMessages returns a copy of all received messages

func (*MockOAuth2SMTPServer) Host

func (s *MockOAuth2SMTPServer) Host() string

Host returns the host address

func (*MockOAuth2SMTPServer) Port

func (s *MockOAuth2SMTPServer) Port() int

Port returns the port the server is listening on

func (*MockOAuth2SMTPServer) ResetRetryCounter

func (s *MockOAuth2SMTPServer) ResetRetryCounter()

ResetRetryCounter resets the authentication attempt counter

func (*MockOAuth2SMTPServer) SetErrorResponse

func (s *MockOAuth2SMTPServer) SetErrorResponse(jsonError string)

SetErrorResponse sets a custom error response for failed authentication The response should be a base64-encoded JSON string

func (*MockOAuth2SMTPServer) SetFailFirstAuth

func (s *MockOAuth2SMTPServer) SetFailFirstAuth(fail bool)

SetFailFirstAuth configures the server to fail the first authentication attempt This is useful for testing retry logic

type MockOAuth2Server

type MockOAuth2Server struct {
	Server          *httptest.Server
	MicrosoftTokens map[string]MockTokenResponse // key: clientID
	GoogleTokens    map[string]MockTokenResponse // key: refreshToken
	RequestLog      []TokenRequest
	// contains filtered or unexported fields
}

MockOAuth2Server provides mock OAuth2 token endpoints for Microsoft and Google Validates grant_type, client_id, client_secret, scope (Microsoft) / refresh_token (Google)

func NewMockOAuth2Server

func NewMockOAuth2Server() *MockOAuth2Server

NewMockOAuth2Server creates a new mock OAuth2 token server

func (*MockOAuth2Server) ClearRequests

func (s *MockOAuth2Server) ClearRequests()

ClearRequests clears the request log

func (*MockOAuth2Server) Close

func (s *MockOAuth2Server) Close()

Close shuts down the mock server

func (*MockOAuth2Server) GetRequestCount

func (s *MockOAuth2Server) GetRequestCount() int

GetRequestCount returns the total number of token requests received

func (*MockOAuth2Server) GetRequests

func (s *MockOAuth2Server) GetRequests() []TokenRequest

GetRequests returns a copy of all token requests received

func (*MockOAuth2Server) GoogleURL

func (s *MockOAuth2Server) GoogleURL() string

GoogleURL returns the Google token endpoint URL

func (*MockOAuth2Server) MicrosoftURL

func (s *MockOAuth2Server) MicrosoftURL(tenantID string) string

MicrosoftURL returns the Microsoft token endpoint URL for a given tenant

func (*MockOAuth2Server) SetGoogleToken

func (s *MockOAuth2Server) SetGoogleToken(refreshToken string, response MockTokenResponse)

SetGoogleToken configures a token response for a Google refresh token

func (*MockOAuth2Server) SetMicrosoftToken

func (s *MockOAuth2Server) SetMicrosoftToken(clientID string, response MockTokenResponse)

SetMicrosoftToken configures a token response for a Microsoft client ID

type MockTokenResponse

type MockTokenResponse struct {
	AccessToken string
	ExpiresIn   int    // seconds (default 3600)
	Error       string // if set, return OAuth2 error response
	ErrorDesc   string // error_description field
}

MockTokenResponse defines the response for a token request

type SMTPAuthAttempt

type SMTPAuthAttempt struct {
	Username   string
	Token      string
	Success    bool
	RawXOAuth2 string // Base64-decoded XOAUTH2 string for validation
	Timestamp  time.Time
}

SMTPAuthAttempt records details of an XOAUTH2 authentication attempt

type SMTPOAuth2Config

type SMTPOAuth2Config struct {
	Host         string // SMTP server host
	Port         int    // SMTP server port
	Provider     string // "microsoft" or "google"
	TenantID     string // Microsoft only - Azure tenant ID
	ClientID     string // OAuth2 client ID
	ClientSecret string // OAuth2 client secret
	RefreshToken string // Google only - refresh token
	Username     string // Email address for XOAUTH2
	SenderEmail  string // Sender email address (defaults to Username if empty)
	SenderName   string // Sender display name
}

SMTPOAuth2Config holds configuration for OAuth2 SMTP integration

type ServerManager

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

ServerManager manages test server lifecycle

func NewServerManager

func NewServerManager(appFactory func(*config.Config) AppInterface, dbManager *DatabaseManager) *ServerManager

NewServerManager creates a new server manager for testing

func (*ServerManager) GetApp

func (sm *ServerManager) GetApp() AppInterface

GetApp returns the app instance

func (*ServerManager) GetURL

func (sm *ServerManager) GetURL() string

GetURL returns the server URL

func (*ServerManager) IsStarted

func (sm *ServerManager) IsStarted() bool

IsStarted returns whether the server is started

func (*ServerManager) Restart

func (sm *ServerManager) Restart() error

Restart stops and starts the server

func (*ServerManager) Start

func (sm *ServerManager) Start() error

Start starts the test server

func (*ServerManager) StartBackgroundWorkers

func (sm *ServerManager) StartBackgroundWorkers(ctx context.Context) error

StartBackgroundWorkers starts the email queue worker and other background services Call this after Start() when you need workers to process queued items

func (*ServerManager) Stop

func (sm *ServerManager) Stop() error

Stop stops the test server

func (*ServerManager) WaitForReady

func (sm *ServerManager) WaitForReady(timeout time.Duration) error

WaitForReady waits for the server to be ready with custom timeout

type TaskOption

type TaskOption func(*domain.Task)

TaskOption defines options for creating tasks

func WithTaskBroadcastID

func WithTaskBroadcastID(broadcastID string) TaskOption

WithTaskBroadcastID sets the broadcast ID for the task

func WithTaskErrorMessage

func WithTaskErrorMessage(errorMsg string) TaskOption

WithTaskErrorMessage sets the error message for the task

func WithTaskMaxRetries

func WithTaskMaxRetries(maxRetries int) TaskOption

WithTaskMaxRetries sets the max retries for the task

func WithTaskMaxRuntime

func WithTaskMaxRuntime(maxRuntime int) TaskOption

WithTaskMaxRuntime sets the max runtime for the task

func WithTaskNextRunAfter

func WithTaskNextRunAfter(nextRunAfter time.Time) TaskOption

WithTaskNextRunAfter sets when the task should run next

func WithTaskProgress

func WithTaskProgress(progress float64) TaskOption

WithTaskProgress sets the task progress

func WithTaskRetryInterval

func WithTaskRetryInterval(retryInterval int) TaskOption

WithTaskRetryInterval sets the retry interval for the task

func WithTaskState

func WithTaskState(state *domain.TaskState) TaskOption

WithTaskState sets the task state

func WithTaskStatus

func WithTaskStatus(status domain.TaskStatus) TaskOption

WithTaskStatus sets the task status

func WithTaskType

func WithTaskType(taskType string) TaskOption

WithTaskType sets the task type

type TemplateOption

type TemplateOption func(*domain.Template)

func WithTemplateCategory

func WithTemplateCategory(category string) TemplateOption

func WithTemplateEmailContent

func WithTemplateEmailContent(content string) TemplateOption

WithTemplateEmailContent sets the text content in the email template's mj-text block This is useful for testing Liquid template variable substitution

func WithTemplateName

func WithTemplateName(name string) TemplateOption

Template options

func WithTemplateSubject

func WithTemplateSubject(subject string) TemplateOption

type TestConnectionPool

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

TestConnectionPool manages a pool of database connections for integration tests

func GetGlobalTestPool

func GetGlobalTestPool() *TestConnectionPool

GetGlobalTestPool returns a singleton connection pool for all tests

func NewTestConnectionPool

func NewTestConnectionPool(cfg *config.DatabaseConfig) *TestConnectionPool

NewTestConnectionPool creates a new connection pool for tests with fast timing

func NewTestConnectionPoolWithTiming

func NewTestConnectionPoolWithTiming(cfg *config.DatabaseConfig, timing TestConnectionPoolTimingConfig) *TestConnectionPool

NewTestConnectionPoolWithTiming creates a new connection pool with custom timing configuration

func (*TestConnectionPool) Cleanup

func (pool *TestConnectionPool) Cleanup() error

Cleanup closes all connections in the pool with proper verification

func (*TestConnectionPool) CleanupWorkspace

func (pool *TestConnectionPool) CleanupWorkspace(workspaceID string) error

CleanupWorkspace removes a workspace connection from the pool

func (*TestConnectionPool) EnsureWorkspaceDatabase

func (pool *TestConnectionPool) EnsureWorkspaceDatabase(workspaceID string) error

EnsureWorkspaceDatabase creates the workspace database if it doesn't exist

func (*TestConnectionPool) GetConnectionCount

func (pool *TestConnectionPool) GetConnectionCount() int

GetConnectionCount returns the current number of active connections

func (*TestConnectionPool) GetSystemConnection

func (pool *TestConnectionPool) GetSystemConnection() (*sql.DB, error)

GetSystemConnection returns a connection to the system database

func (*TestConnectionPool) GetWorkspaceConnection

func (pool *TestConnectionPool) GetWorkspaceConnection(workspaceID string) (*sql.DB, error)

GetWorkspaceConnection returns a pooled connection to a workspace database

type TestConnectionPoolManager

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

TestConnectionPoolManager manages multiple isolated connection pools for tests Each test can get its own isolated pool to prevent connection leaks between tests

func NewTestConnectionPoolManager

func NewTestConnectionPoolManager() *TestConnectionPoolManager

NewTestConnectionPoolManager creates a new connection pool manager for tests

func (*TestConnectionPoolManager) CleanupAll

func (m *TestConnectionPoolManager) CleanupAll() error

CleanupAll closes all test connection pools

func (*TestConnectionPoolManager) CleanupPool

func (m *TestConnectionPoolManager) CleanupPool(testID string) error

CleanupPool cleans up a specific test's connection pool

func (*TestConnectionPoolManager) GetOrCreatePool

func (m *TestConnectionPoolManager) GetOrCreatePool(testID string, config *config.DatabaseConfig) *TestConnectionPool

GetOrCreatePool gets or creates an isolated connection pool for a specific test

func (*TestConnectionPoolManager) GetPoolCount

func (m *TestConnectionPoolManager) GetPoolCount() int

GetPoolCount returns the number of active test pools

type TestConnectionPoolTimingConfig

type TestConnectionPoolTimingConfig struct {
	CleanupWorkspaceSleep    time.Duration // Sleep after terminating workspace connections
	CleanupBatchSleep        time.Duration // Sleep after closing all workspace connections
	CleanupPerWorkspaceSleep time.Duration // Sleep per workspace during drain
	DropDatabaseSleep        time.Duration // Sleep before dropping database
	SystemPoolPreCloseSleep  time.Duration // Sleep before closing system pool
	SystemPoolPostCloseSleep time.Duration // Sleep after closing system pool
}

TestConnectionPoolTimingConfig holds tunable timing parameters for cleanup operations

func DefaultTimingConfig

func DefaultTimingConfig() TestConnectionPoolTimingConfig

DefaultTimingConfig returns conservative defaults for reliability

func FastTimingConfig

func FastTimingConfig() TestConnectionPoolTimingConfig

FastTimingConfig returns aggressive timings for performance tests

type TestDataFactory

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

TestDataFactory creates test data entities using domain repositories

func NewTestDataFactory

func NewTestDataFactory(
	db *sql.DB,
	userRepo domain.UserRepository,
	workspaceRepo domain.WorkspaceRepository,
	contactRepo domain.ContactRepository,
	listRepo domain.ListRepository,
	templateRepo domain.TemplateRepository,
	broadcastRepo domain.BroadcastRepository,
	messageHistoryRepo domain.MessageHistoryRepository,
	contactListRepo domain.ContactListRepository,
	transactionalNotificationRepo domain.TransactionalNotificationRepository,
) *TestDataFactory

NewTestDataFactory creates a new test data factory with repository dependencies

func (*TestDataFactory) ActivateAutomation

func (tdf *TestDataFactory) ActivateAutomation(workspaceID, automationID string) error

ActivateAutomation activates an automation (creates DB trigger)

func (*TestDataFactory) AddUserToWorkspace

func (tdf *TestDataFactory) AddUserToWorkspace(userID, workspaceID, role string) error

AddUserToWorkspace adds a user to a workspace with the specified role

func (*TestDataFactory) AddUserToWorkspaceWithPermissions

func (tdf *TestDataFactory) AddUserToWorkspaceWithPermissions(userID, workspaceID, role string, permissions domain.UserPermissions) error

AddUserToWorkspaceWithPermissions adds a user to a workspace with the specified role and permissions

func (*TestDataFactory) CleanupWorkspace

func (tdf *TestDataFactory) CleanupWorkspace(workspaceID string) error

CleanupWorkspace removes a workspace and its database from the connection pool

func (*TestDataFactory) CountContactAutomations

func (tdf *TestDataFactory) CountContactAutomations(workspaceID, automationID string) (int, error)

CountContactAutomations counts contact automation records for an automation

func (*TestDataFactory) CreateAPIKey

func (tdf *TestDataFactory) CreateAPIKey(workspaceID string, opts ...UserOption) (*domain.User, error)

CreateAPIKey creates an API key user for a workspace

func (*TestDataFactory) CreateAutomation

func (tdf *TestDataFactory) CreateAutomation(workspaceID string, opts ...AutomationOption) (*domain.Automation, error)

CreateAutomation creates a test automation

func (*TestDataFactory) CreateAutomationNode

func (tdf *TestDataFactory) CreateAutomationNode(workspaceID string, opts ...AutomationNodeOption) (*domain.AutomationNode, error)

CreateAutomationNode creates a test automation node by appending to the automation's embedded nodes array

func (*TestDataFactory) CreateBlogCategory

func (tdf *TestDataFactory) CreateBlogCategory(workspaceID string, opts ...BlogCategoryOption) (*domain.BlogCategory, error)

CreateBlogCategory creates a test blog category using the blog repository

func (*TestDataFactory) CreateBlogPost

func (tdf *TestDataFactory) CreateBlogPost(workspaceID, categoryID string, opts ...BlogPostOption) (*domain.BlogPost, error)

CreateBlogPost creates a test blog post using the blog repository

func (*TestDataFactory) CreateBlogTheme

func (tdf *TestDataFactory) CreateBlogTheme(workspaceID string, opts ...BlogThemeOption) (*domain.BlogTheme, error)

CreateBlogTheme creates a test blog theme using the blog repository

func (*TestDataFactory) CreateBroadcast

func (tdf *TestDataFactory) CreateBroadcast(workspaceID string, opts ...BroadcastOption) (*domain.Broadcast, error)

CreateBroadcast creates a test broadcast using the broadcast repository

func (*TestDataFactory) CreateContact

func (tdf *TestDataFactory) CreateContact(workspaceID string, opts ...ContactOption) (*domain.Contact, error)

CreateContact creates a test contact using the contact repository

func (*TestDataFactory) CreateContactList

func (tdf *TestDataFactory) CreateContactList(workspaceID string, opts ...ContactListOption) (*domain.ContactList, error)

CreateContactList creates a test contact list relationship using the repository

func (*TestDataFactory) CreateContactTimelineEvent

func (tdf *TestDataFactory) CreateContactTimelineEvent(workspaceID, email, kind string, metadata map[string]interface{}) error

CreateContactTimelineEvent creates a timeline event for a contact

func (*TestDataFactory) CreateCustomEvent

func (tdf *TestDataFactory) CreateCustomEvent(workspaceID, email, eventName string, properties map[string]interface{}) error

CreateCustomEvent creates a custom event which triggers the timeline event with proper format This is used for testing automations with custom_event triggers

func (*TestDataFactory) CreateFailingSMTPIntegration

func (tdf *TestDataFactory) CreateFailingSMTPIntegration(workspaceID string, opts ...IntegrationOption) (*domain.Integration, error)

CreateFailingSMTPIntegration creates an SMTP integration that will fail to send emails Used for testing circuit breaker behavior

func (*TestDataFactory) CreateGoogleOAuth2SMTPIntegration

func (tdf *TestDataFactory) CreateGoogleOAuth2SMTPIntegration(
	workspaceID string,
	host string,
	port int,
	clientID, clientSecret, refreshToken, username string,
	opts ...IntegrationOption,
) (*domain.Integration, error)

CreateGoogleOAuth2SMTPIntegration creates an SMTP integration configured for Google OAuth2

func (*TestDataFactory) CreateIntegration

func (tdf *TestDataFactory) CreateIntegration(workspaceID string, opts ...IntegrationOption) (*domain.Integration, error)

CreateIntegration creates a test integration using the workspace repository

func (*TestDataFactory) CreateList

func (tdf *TestDataFactory) CreateList(workspaceID string, opts ...ListOption) (*domain.List, error)

CreateList creates a test list using the list repository

func (*TestDataFactory) CreateMailpitSMTPIntegration

func (tdf *TestDataFactory) CreateMailpitSMTPIntegration(workspaceID string, opts ...IntegrationOption) (*domain.Integration, error)

CreateMailpitSMTPIntegration creates an SMTP integration configured for Mailpit

func (*TestDataFactory) CreateMessageHistory

func (tdf *TestDataFactory) CreateMessageHistory(workspaceID string, opts ...MessageHistoryOption) (*domain.MessageHistory, error)

CreateMessageHistory creates a test message history using the message history repository

func (*TestDataFactory) CreateMicrosoftOAuth2SMTPIntegration

func (tdf *TestDataFactory) CreateMicrosoftOAuth2SMTPIntegration(
	workspaceID string,
	host string,
	port int,
	tenantID, clientID, clientSecret, username string,
	opts ...IntegrationOption,
) (*domain.Integration, error)

CreateMicrosoftOAuth2SMTPIntegration creates an SMTP integration configured for Microsoft OAuth2

func (*TestDataFactory) CreateSESIntegration

func (tdf *TestDataFactory) CreateSESIntegration(workspaceID string, opts ...IntegrationOption) (*domain.Integration, error)

CreateSESIntegration creates a test SES integration for webhook testing

func (*TestDataFactory) CreateSMTPIntegration

func (tdf *TestDataFactory) CreateSMTPIntegration(workspaceID string, opts ...IntegrationOption) (*domain.Integration, error)

CreateSMTPIntegration creates a test SMTP integration using the workspace repository

func (*TestDataFactory) CreateSegment

func (tdf *TestDataFactory) CreateSegment(workspaceID string) (*domain.Segment, error)

CreateSegment creates a test segment using direct DB insert

func (*TestDataFactory) CreateSendBroadcastTask

func (tdf *TestDataFactory) CreateSendBroadcastTask(workspaceID, broadcastID string, opts ...TaskOption) (*domain.Task, error)

CreateSendBroadcastTask creates a task specifically for sending broadcasts

func (*TestDataFactory) CreateTask

func (tdf *TestDataFactory) CreateTask(workspaceID string, opts ...TaskOption) (*domain.Task, error)

CreateTask creates a test task with optional configuration

func (*TestDataFactory) CreateTaskWithABTesting

func (tdf *TestDataFactory) CreateTaskWithABTesting(workspaceID, broadcastID string, opts ...TaskOption) (*domain.Task, error)

CreateTaskWithABTesting creates a task for A/B testing broadcasts

func (*TestDataFactory) CreateTemplate

func (tdf *TestDataFactory) CreateTemplate(workspaceID string, opts ...TemplateOption) (*domain.Template, error)

CreateTemplate creates a test template using the template repository

func (*TestDataFactory) CreateTransactionalNotification

func (tdf *TestDataFactory) CreateTransactionalNotification(workspaceID string, opts ...TransactionalNotificationOption) (*domain.TransactionalNotification, error)

CreateTransactionalNotification creates a test transactional notification using the repository

func (*TestDataFactory) CreateUser

func (tdf *TestDataFactory) CreateUser(opts ...UserOption) (*domain.User, error)

CreateUser creates a test user using the user repository

func (*TestDataFactory) CreateWorkspace

func (tdf *TestDataFactory) CreateWorkspace(opts ...WorkspaceOption) (*domain.Workspace, error)

CreateWorkspace creates a test workspace using the workspace repository

func (*TestDataFactory) DeactivateAutomation

func (tdf *TestDataFactory) DeactivateAutomation(workspaceID, automationID string) error

DeactivateAutomation deactivates an automation (drops DB trigger)

func (*TestDataFactory) EnsureSegmentRecomputeTask

func (tdf *TestDataFactory) EnsureSegmentRecomputeTask(workspaceID string) error

EnsureSegmentRecomputeTask ensures the check_segment_recompute task exists for a workspace (for testing)

func (*TestDataFactory) GetAllContactAutomations

func (tdf *TestDataFactory) GetAllContactAutomations(workspaceID, automationID string) ([]*domain.ContactAutomation, error)

GetAllContactAutomations retrieves all contact automation records for an automation

func (*TestDataFactory) GetAutomationStats

func (tdf *TestDataFactory) GetAutomationStats(workspaceID, automationID string) (*domain.AutomationStats, error)

GetAutomationStats retrieves an automation's stats

func (*TestDataFactory) GetConnectionCount

func (tdf *TestDataFactory) GetConnectionCount() int

GetConnectionCount returns the current number of active connections in the pool

func (*TestDataFactory) GetContactAutomation

func (tdf *TestDataFactory) GetContactAutomation(workspaceID, automationID, email string) (*domain.ContactAutomation, error)

GetContactAutomation retrieves a contact automation record

func (*TestDataFactory) GetContactTimelineEvents

func (tdf *TestDataFactory) GetContactTimelineEvents(workspaceID, email, kind string) ([]TimelineEventResult, error)

GetContactTimelineEvents retrieves timeline events for a contact filtered by kind

func (*TestDataFactory) GetNodeExecutions

func (tdf *TestDataFactory) GetNodeExecutions(workspaceID, contactAutomationID string) ([]*domain.NodeExecution, error)

GetNodeExecutions retrieves node executions for a contact automation

func (*TestDataFactory) GetTriggerLogEntry

func (tdf *TestDataFactory) GetTriggerLogEntry(workspaceID, automationID, email string) (bool, error)

GetTriggerLogEntry checks if a trigger log entry exists for deduplication

func (*TestDataFactory) GetWorkspaceDB

func (tdf *TestDataFactory) GetWorkspaceDB(workspaceID string) (*sql.DB, error)

GetWorkspaceDB returns a database connection for the specified workspace This is useful for tests that need direct database access to simulate edge cases

func (*TestDataFactory) MarkTaskAsCompleted

func (tdf *TestDataFactory) MarkTaskAsCompleted(workspaceID, taskID string, state *domain.TaskState) error

MarkTaskAsCompleted marks a task as completed with the final state

func (*TestDataFactory) MarkTaskAsFailed

func (tdf *TestDataFactory) MarkTaskAsFailed(workspaceID, taskID string, errorMsg string) error

MarkTaskAsFailed marks a task as failed with an error message

func (*TestDataFactory) MarkTaskAsPaused

func (tdf *TestDataFactory) MarkTaskAsPaused(workspaceID, taskID string, nextRunAfter time.Time, progress float64, state *domain.TaskState) error

MarkTaskAsPaused marks a task as paused with next run time

func (*TestDataFactory) MarkTaskAsRunning

func (tdf *TestDataFactory) MarkTaskAsRunning(workspaceID, taskID string) error

MarkTaskAsRunning marks a task as running with a timeout

func (*TestDataFactory) SetSegmentRecomputeAfter

func (tdf *TestDataFactory) SetSegmentRecomputeAfter(workspaceID, segmentID string, recomputeAfter time.Time) error

SetSegmentRecomputeAfter sets the recompute_after timestamp for a segment (for testing)

func (*TestDataFactory) SetupWorkspaceWithSMTPProvider

func (tdf *TestDataFactory) SetupWorkspaceWithSMTPProvider(workspaceID string, opts ...IntegrationOption) (*domain.Integration, error)

SetupWorkspaceWithSMTPProvider creates a workspace with an SMTP email provider and sets it as the marketing and transactional provider

func (*TestDataFactory) UpdateAutomationNodeNextNodeID

func (tdf *TestDataFactory) UpdateAutomationNodeNextNodeID(workspaceID, automationID, nodeID, nextNodeID string) error

UpdateAutomationNodeNextNodeID updates a node's next_node_id in the automation's embedded nodes array

func (*TestDataFactory) UpdateAutomationRootNode

func (tdf *TestDataFactory) UpdateAutomationRootNode(workspaceID, automationID, rootNodeID string) error

UpdateAutomationRootNode updates an automation's root_node_id

func (*TestDataFactory) UpdateContactAutomationScheduledAt

func (tdf *TestDataFactory) UpdateContactAutomationScheduledAt(workspaceID, contactAutomationID string, scheduledAt time.Time) error

UpdateContactAutomationScheduledAt updates scheduled_at for a contact automation (for testing delays)

func (*TestDataFactory) UpdateTaskMaxRuntime

func (tdf *TestDataFactory) UpdateTaskMaxRuntime(workspaceID, taskID string, maxRuntime int) error

UpdateTaskMaxRuntime updates a task's max_runtime value for testing timeout behavior

func (*TestDataFactory) UpdateTaskState

func (tdf *TestDataFactory) UpdateTaskState(workspaceID, taskID string, progress float64, state *domain.TaskState) error

UpdateTaskState updates a task's state and progress

type TimelineEventResult

type TimelineEventResult struct {
	ID         string
	Email      string
	Operation  string
	EntityType string
	Kind       string
	EntityID   *string
	Changes    map[string]interface{}
	CreatedAt  time.Time
}

TimelineEventResult represents a timeline event returned from query

type TokenCache

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

TokenCache provides a thread-safe cache for authentication tokens within a test suite. This significantly reduces test execution time by avoiding repeated sign-in flows for the same user across multiple subtests.

func NewTokenCache

func NewTokenCache(client *APIClient) *TokenCache

NewTokenCache creates a token cache bound to an API client

func (*TokenCache) Clear

func (tc *TokenCache) Clear()

Clear removes all cached tokens (useful for test isolation if needed)

func (*TokenCache) GetOrCreate

func (tc *TokenCache) GetOrCreate(t *testing.T, email string) string

GetOrCreate returns a cached token or performs the authentication flow. This method is thread-safe and handles concurrent access properly.

type TokenRequest

type TokenRequest struct {
	Provider     string // "microsoft" or "google"
	GrantType    string // "client_credentials" or "refresh_token"
	ClientID     string
	ClientSecret string
	Scope        string // Microsoft: "https://outlook.office365.com/.default"
	RefreshToken string // Google only
	TenantID     string // Microsoft only (extracted from URL path)
	Timestamp    time.Time
}

TokenRequest logs details of a token request

type TransactionalNotificationOption

type TransactionalNotificationOption func(*domain.TransactionalNotification)

func WithNotificationID

func WithNotificationID(id string) TransactionalNotificationOption

WithNotificationID is an alias for WithTransactionalNotificationID for consistency

func WithNotificationTemplateID

func WithNotificationTemplateID(templateID string) TransactionalNotificationOption

WithNotificationTemplateID sets the template ID for email channel

func WithTransactionalNotificationChannels

func WithTransactionalNotificationChannels(channels domain.ChannelTemplates) TransactionalNotificationOption

func WithTransactionalNotificationDescription

func WithTransactionalNotificationDescription(description string) TransactionalNotificationOption

func WithTransactionalNotificationID

func WithTransactionalNotificationID(id string) TransactionalNotificationOption

func WithTransactionalNotificationMetadata

func WithTransactionalNotificationMetadata(metadata map[string]interface{}) TransactionalNotificationOption

func WithTransactionalNotificationName

func WithTransactionalNotificationName(name string) TransactionalNotificationOption

TransactionalNotification option functions

type UserOption

type UserOption func(*domain.User)

Option types for customizing test data

func WithUserEmail

func WithUserEmail(email string) UserOption

User options

func WithUserName

func WithUserName(name string) UserOption

func WithUserType

func WithUserType(userType domain.UserType) UserOption

type WorkspaceOption

type WorkspaceOption func(*domain.Workspace)

func WithBlogEnabled

func WithBlogEnabled(enabled bool) WorkspaceOption

func WithCustomDomain

func WithCustomDomain(customDomain string) WorkspaceOption

func WithWorkspaceName

func WithWorkspaceName(name string) WorkspaceOption

Workspace options

func WithWorkspaceSettings

func WithWorkspaceSettings(settings domain.WorkspaceSettings) WorkspaceOption

Jump to

Keyboard shortcuts

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