mocks

package
v0.1.0-beta.4 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

README

Mock Infrastructure

This package provides comprehensive mock implementations for testing AhaSend CLI components. All mocks use the testify/mock framework and implement the same interfaces as production code.

Available Mocks

MockClient

Mock implementation of client.AhaSendClient interface for testing API operations.

import "github.com/AhaSend/ahasend-cli/internal/mocks"

func TestMyCommand(t *testing.T) {
    mockClient := &mocks.MockClient{}
    
    // Setup expectations
    mockClient.On("Ping").Return(nil)
    mockClient.On("GetAccountID").Return("test-account-id")
    
    // Use in your test
    err := mockClient.Ping()
    assert.NoError(t, err)
    
    accountID := mockClient.GetAccountID()
    assert.Equal(t, "test-account-id", accountID)
    
    // Verify all expectations were met
    mockClient.AssertExpectations(t)
}
Supported Methods

Authentication & Account:

  • GetAccountID() string
  • GetAuthContext() context.Context
  • Ping() error
  • ValidateConfiguration() error

Message Operations:

  • SendMessage(req ahasend.CreateMessageRequest) (*ahasend.CreateMessageResponse, error)
  • SendMessageWithIdempotencyKey(req ahasend.CreateMessageRequest, idempotencyKey string) (*ahasend.CreateMessageResponse, error)
  • CancelMessage(accountID, messageID string) error
  • GetMessages(params client.GetMessagesParams) (*ahasend.PaginatedMessagesResponse, error)

Domain Operations:

  • ListDomains(limit *int32, cursor *string) (*ahasend.PaginatedDomainsResponse, error)
  • CreateDomain(domain string) (*ahasend.Domain, error)
  • GetDomain(domain string) (*ahasend.Domain, error)
  • DeleteDomain(domain string) error

Webhook Operations:

  • CreateWebhookVerifier(secret string) (*ahasend.WebhookVerifier, error)
Helper Methods

MockClient provides helper methods for creating common test data:

// Create a mock domain
domain := mockClient.NewMockDomain("example.com", true)

// Create a mock domains response
domains := []*ahasend.Domain{domain}
response := mockClient.NewMockDomainsResponse(domains, false)

// Create a mock message response
messageResponse := mockClient.NewMockMessageResponse("msg-123")
MockConfigManager

Mock implementation of config.ConfigManager interface for testing configuration operations.

func TestConfigOperation(t *testing.T) {
    mockConfig := &mocks.MockConfigManager{}
    
    // Setup expectations
    profile := config.Profile{
        Name:      "test",
        APIKey:    "test-key",
        AccountID: "test-account",
    }
    mockConfig.On("GetCurrentProfile").Return(&profile, nil)
    mockConfig.On("SetPreference", "output_format", "json").Return(nil)
    
    // Use in your test
    currentProfile, err := mockConfig.GetCurrentProfile()
    assert.NoError(t, err)
    assert.Equal(t, "test", currentProfile.Name)
    
    err = mockConfig.SetPreference("output_format", "json")
    assert.NoError(t, err)
    
    mockConfig.AssertExpectations(t)
}
Supported Methods

Configuration File Operations:

  • Load() error
  • Save() error
  • GetConfig() *config.Config

Profile Management:

  • GetCurrentProfile() (*config.Profile, error)
  • SetProfile(name string, profile config.Profile) error
  • RemoveProfile(name string) error
  • ListProfiles() []string
  • SetDefaultProfile(name string) error

Preference Management:

  • SetPreference(key, value string) error
  • GetPreference(key string) (string, error)
Helper Methods

MockConfigManager provides helper methods for creating test data:

// Create a mock profile
profile := mockConfig.NewMockProfile("test", "api-key", "account-123")

// Create a mock config
cfg := mockConfig.NewMockConfig()

Design Principles

Interface Compliance

All mocks implement their corresponding interfaces with compile-time verification:

// Ensures MockClient implements AhaSendClient
var _ client.AhaSendClient = (*MockClient)(nil)

// Ensures MockConfigManager implements ConfigManager
var _ config.ConfigManager = (*MockConfigManager)(nil)
Consistent Error Handling

Mocks handle nil returns properly to avoid panics:

func (m *MockClient) CreateDomain(domain string) (*ahasend.Domain, error) {
    args := m.Called(domain)
    if args.Get(0) == nil {
        return nil, args.Error(1)
    }
    return args.Get(0).(*ahasend.Domain), args.Error(1)
}
Helper Methods

Each mock provides helper methods for creating common test data structures, reducing test boilerplate and ensuring consistent test data.

Testing Patterns

Basic Mock Setup
func TestCommand(t *testing.T) {
    // Create mock
    mockClient := &mocks.MockClient{}
    
    // Set expectations
    mockClient.On("MethodName", arg1, arg2).Return(returnValue, nil)
    
    // Execute test
    result, err := mockClient.MethodName(arg1, arg2)
    
    // Assert results
    assert.NoError(t, err)
    assert.Equal(t, returnValue, result)
    
    // Verify expectations
    mockClient.AssertExpectations(t)
}
Error Testing
func TestCommandError(t *testing.T) {
    mockClient := &mocks.MockClient{}
    
    // Setup error expectation
    mockClient.On("Ping").Return(errors.New("connection failed"))
    
    err := mockClient.Ping()
    assert.Error(t, err)
    assert.Contains(t, err.Error(), "connection failed")
    
    mockClient.AssertExpectations(t)
}
Complex Scenarios
func TestComplexScenario(t *testing.T) {
    mockClient := &mocks.MockClient{}
    
    // Setup multiple expectations
    domain := mockClient.NewMockDomain("example.com", true)
    mockClient.On("GetDomain", "example.com").Return(domain, nil)
    mockClient.On("DeleteDomain", "example.com").Return(nil)
    
    // Test the scenario
    retrievedDomain, err := mockClient.GetDomain("example.com")
    assert.NoError(t, err)
    assert.Equal(t, "example.com", retrievedDomain.Domain)
    
    err = mockClient.DeleteDomain("example.com")
    assert.NoError(t, err)
    
    mockClient.AssertExpectations(t)
}

Migration Guide

From Old Mock Patterns

If you're updating existing tests that used the old mock patterns:

Old Pattern (Inconsistent)
// Various inconsistent mock approaches
type CustomMock struct {
    // Custom implementation
}
New Pattern (Standardized)
// Use standardized interface-based mocks
mockClient := &mocks.MockClient{}
mockClient.On("MethodName", args...).Return(returnValue, nil)
Benefits of New Pattern
  1. Interface Compliance: Compile-time verification that mocks match production interfaces
  2. Consistency: All mocks follow the same patterns and conventions
  3. Maintainability: Easy to update when interfaces change
  4. Feature Completeness: All interface methods are implemented
  5. Helper Methods: Convenient test data creation
  6. Error Handling: Proper nil checking to prevent test panics

Best Practices

  1. Always call AssertExpectations(t) at the end of tests to verify all expected calls were made
  2. Use helper methods when possible to create consistent test data
  3. Set up specific expectations for each test rather than generic catch-all expectations
  4. Test error cases explicitly with appropriate error expectations
  5. Keep mock setup close to usage to improve test readability
  6. Use meaningful test data that reflects realistic scenarios

Documentation

Overview

Package mocks provides comprehensive mock implementations for testing AhaSend CLI components.

This package implements standardized mock objects using the testify/mock framework:

  • MockClient: Complete AhaSendClient interface implementation
  • MockConfigManager: Full ConfigManager interface implementation
  • Interface compliance verification at compile time
  • Helper methods for creating common test data structures
  • Consistent error handling patterns for test scenarios
  • Documentation and examples for proper usage patterns

All mocks follow the same interface-based design patterns as production code, enabling comprehensive testing without external dependencies while maintaining type safety and interface compliance.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MockClient

type MockClient struct {
	mock.Mock
}

MockClient is a mock implementation of the AhaSendClient interface

func (*MockClient) CancelMessage

func (m *MockClient) CancelMessage(accountID, messageID string) (*common.SuccessResponse, error)

func (*MockClient) CheckSuppression

func (m *MockClient) CheckSuppression(email string, domain *string) (bool, *responses.Suppression, error)

func (*MockClient) ConnectWebSocket

func (m *MockClient) ConnectWebSocket(wsURL, webhookID string, forceReconnect, skipVerify bool) (*client.WebSocketClient, error)

func (*MockClient) CreateAPIKey

func (m *MockClient) CreateAPIKey(req requests.CreateAPIKeyRequest) (*responses.APIKey, error)

func (*MockClient) CreateDomain

func (m *MockClient) CreateDomain(domain string) (*responses.Domain, error)

func (*MockClient) CreateRoute

func (m *MockClient) CreateRoute(req requests.CreateRouteRequest) (*responses.Route, error)

func (*MockClient) CreateSMTPCredential

func (*MockClient) CreateWebhook

func (m *MockClient) CreateWebhook(req requests.CreateWebhookRequest) (*responses.Webhook, error)

func (*MockClient) CreateWebhookVerifier

func (m *MockClient) CreateWebhookVerifier(secret string) (*webhooks.WebhookVerifier, error)

func (*MockClient) DeleteAPIKey

func (m *MockClient) DeleteAPIKey(keyID string) (*common.SuccessResponse, error)

func (*MockClient) DeleteDomain

func (m *MockClient) DeleteDomain(domain string) (*common.SuccessResponse, error)

func (*MockClient) DeleteRoute

func (m *MockClient) DeleteRoute(routeID string) error

func (*MockClient) DeleteSMTPCredential

func (m *MockClient) DeleteSMTPCredential(credentialID string) error

func (*MockClient) DeleteSuppression

func (m *MockClient) DeleteSuppression(email string, domain *string) (*common.SuccessResponse, error)

func (*MockClient) DeleteWebhook

func (m *MockClient) DeleteWebhook(webhookID string) error

func (*MockClient) GetAPIKey

func (m *MockClient) GetAPIKey(keyID string) (*responses.APIKey, error)

func (*MockClient) GetAccount

func (m *MockClient) GetAccount() (*responses.Account, error)

func (*MockClient) GetAccountID

func (m *MockClient) GetAccountID() string

func (*MockClient) GetAuthContext

func (m *MockClient) GetAuthContext() context.Context

func (*MockClient) GetBounceStatistics

func (*MockClient) GetDeliverabilityStatistics

Statistics operations methods

func (*MockClient) GetDomain

func (m *MockClient) GetDomain(domain string) (*responses.Domain, error)

func (*MockClient) GetMessage

func (m *MockClient) GetMessage(messageID string) (*responses.Message, error)

func (*MockClient) GetMessages

func (*MockClient) GetRoute

func (m *MockClient) GetRoute(routeID string) (*responses.Route, error)

func (*MockClient) GetSMTPCredential

func (m *MockClient) GetSMTPCredential(credentialID string) (*responses.SMTPCredential, error)

func (*MockClient) GetWebhook

func (m *MockClient) GetWebhook(webhookID string) (*responses.Webhook, error)

func (*MockClient) InitiateRouteStream

func (m *MockClient) InitiateRouteStream(routeID, recipient string) (*client.RouteStreamResponse, error)

func (*MockClient) InitiateWebhookStream

func (m *MockClient) InitiateWebhookStream(webhookID string) (*client.WebhookStreamResponse, error)

func (*MockClient) ListAPIKeys

func (m *MockClient) ListAPIKeys(limit *int32, cursor *string) (*responses.PaginatedAPIKeysResponse, error)

API Key operations methods

func (*MockClient) ListDomains

func (m *MockClient) ListDomains(limit *int32, cursor *string) (*responses.PaginatedDomainsResponse, error)

func (*MockClient) ListRoutes

func (m *MockClient) ListRoutes(limit *int32, cursor *string) (*responses.PaginatedRoutesResponse, error)

func (*MockClient) ListSMTPCredentials

func (m *MockClient) ListSMTPCredentials(limit *int32, cursor *string) (*responses.PaginatedSMTPCredentialsResponse, error)

func (*MockClient) ListSuppressions

func (*MockClient) ListWebhooks

func (m *MockClient) ListWebhooks(limit *int32, cursor *string) (*responses.PaginatedWebhooksResponse, error)

func (*MockClient) NewMockDomain

func (m *MockClient) NewMockDomain(domain string, valid bool) *responses.Domain

NewMockDomain creates a mock domain for testing

func (*MockClient) NewMockDomainsResponse

func (m *MockClient) NewMockDomainsResponse(domains []responses.Domain, hasMore bool) *responses.PaginatedDomainsResponse

NewMockDomainsResponse creates a mock paginated domains response for testing

func (*MockClient) NewMockMessageResponse

func (m *MockClient) NewMockMessageResponse(messageID string) *responses.CreateMessageResponse

NewMockMessageResponse creates a mock create message response for testing

func (*MockClient) NewMockMessagesResponse

func (m *MockClient) NewMockMessagesResponse(messages []responses.Message, hasMore bool) *responses.PaginatedMessagesResponse

NewMockMessagesResponse creates a mock paginated messages response for testing

func (*MockClient) NewMockRoute

func (m *MockClient) NewMockRoute(idStr, name, url, recipientFilter string, enabled bool) *responses.Route

NewMockRoute creates a mock route for testing

func (*MockClient) NewMockRouteWithOptions

func (m *MockClient) NewMockRouteWithOptions(idStr, name, url string, enabled bool, options map[string]bool) *responses.Route

NewMockRouteWithOptions creates a mock route with processing options for testing

func (*MockClient) NewMockRoutesResponse

func (m *MockClient) NewMockRoutesResponse(routes []responses.Route, hasMore bool) *responses.PaginatedRoutesResponse

NewMockRoutesResponse creates a mock paginated routes response for testing

func (*MockClient) NewMockSMTPCredential

func (m *MockClient) NewMockSMTPCredential(id uint64, name, scope string, sandbox bool, domains []string) *responses.SMTPCredential

NewMockSMTPCredential creates a mock SMTP credential for testing

func (*MockClient) NewMockSMTPCredentialsResponse

func (m *MockClient) NewMockSMTPCredentialsResponse(credentials []responses.SMTPCredential, hasMore bool) *responses.PaginatedSMTPCredentialsResponse

NewMockSMTPCredentialsResponse creates a mock paginated SMTP credentials response for testing

func (*MockClient) NewMockSuppression

func (m *MockClient) NewMockSuppression(email, reason, domain string) *responses.Suppression

NewMockSuppression creates a mock suppression for testing

func (*MockClient) NewMockSuppressionWithExpiry

func (m *MockClient) NewMockSuppressionWithExpiry(email, reason, domain string, expiresIn time.Duration) *responses.Suppression

NewMockSuppressionWithExpiry creates a mock suppression with expiry time for testing

func (*MockClient) NewMockSuppressionsResponse

func (m *MockClient) NewMockSuppressionsResponse(suppressions []responses.Suppression, hasMore bool) *responses.PaginatedSuppressionsResponse

NewMockSuppressionsResponse creates a mock paginated suppressions response for testing

func (*MockClient) NewMockWebhook

func (m *MockClient) NewMockWebhook(idStr, name, url string, enabled bool) responses.Webhook

NewMockWebhook creates a mock webhook for testing

func (*MockClient) NewMockWebhooksResponse

func (m *MockClient) NewMockWebhooksResponse(webhooks []responses.Webhook, hasMore bool) *responses.PaginatedWebhooksResponse

NewMockWebhooksResponse creates a mock paginated webhooks response for testing

func (*MockClient) Ping

func (m *MockClient) Ping() error

func (*MockClient) SendMessage

func (*MockClient) SendMessageWithIdempotencyKey

func (m *MockClient) SendMessageWithIdempotencyKey(req requests.CreateMessageRequest, idempotencyKey string) (*responses.CreateMessageResponse, error)

func (*MockClient) TriggerRoute

func (m *MockClient) TriggerRoute(routeID string) error

func (*MockClient) TriggerWebhook

func (m *MockClient) TriggerWebhook(webhookID string, events []string) error

func (*MockClient) UpdateAPIKey

func (m *MockClient) UpdateAPIKey(keyID string, req requests.UpdateAPIKeyRequest) (*responses.APIKey, error)

func (*MockClient) UpdateRoute

func (m *MockClient) UpdateRoute(routeID string, req requests.UpdateRouteRequest) (*responses.Route, error)

func (*MockClient) UpdateWebhook

func (m *MockClient) UpdateWebhook(webhookID string, req requests.UpdateWebhookRequest) (*responses.Webhook, error)

func (*MockClient) ValidateConfiguration

func (m *MockClient) ValidateConfiguration() error

func (*MockClient) WipeSuppressions

func (m *MockClient) WipeSuppressions(domain *string) (*common.SuccessResponse, error)

type MockConfigManager

type MockConfigManager struct {
	mock.Mock
}

MockConfigManager is a mock implementation of the ConfigManager interface

func (*MockConfigManager) GetConfig

func (m *MockConfigManager) GetConfig() *config.Config

func (*MockConfigManager) GetCurrentProfile

func (m *MockConfigManager) GetCurrentProfile() (*config.Profile, error)

func (*MockConfigManager) GetPreference

func (m *MockConfigManager) GetPreference(key string) (string, error)

func (*MockConfigManager) ListProfiles

func (m *MockConfigManager) ListProfiles() []string

func (*MockConfigManager) Load

func (m *MockConfigManager) Load() error

func (*MockConfigManager) NewMockConfig

func (m *MockConfigManager) NewMockConfig() *config.Config

NewMockConfig creates a mock config for testing

func (*MockConfigManager) NewMockProfile

func (m *MockConfigManager) NewMockProfile(name, apiKey, accountID string) config.Profile

NewMockProfile creates a mock profile for testing

func (*MockConfigManager) RemoveProfile

func (m *MockConfigManager) RemoveProfile(name string) error

func (*MockConfigManager) Save

func (m *MockConfigManager) Save() error

func (*MockConfigManager) SetDefaultProfile

func (m *MockConfigManager) SetDefaultProfile(name string) error

func (*MockConfigManager) SetPreference

func (m *MockConfigManager) SetPreference(key, value string) error

func (*MockConfigManager) SetProfile

func (m *MockConfigManager) SetProfile(name string, profile config.Profile) error

Jump to

Keyboard shortcuts

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