mocks

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Mock Infrastructure

This package provides MockClient, a mock of the client.AhaSendClient interface for testing API operations without calling the API. It uses the testify/mock framework.

MockClient

A test sets the calls it expects a command to make, installs the mock as the command's client with testutil.RunWithClient (or testutil.InjectClient), runs the command and checks its output. A test that calls the mock directly only checks the mock, so tests always go through a command.

import (
    "testing"

    "github.com/AhaSend/ahasend-cli/cmd/groups/domains"
    "github.com/AhaSend/ahasend-cli/internal/mocks"
    "github.com/AhaSend/ahasend-cli/internal/testutil"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

func TestDomainsGet(t *testing.T) {
    mockClient := &mocks.MockClient{}

    // Set up the call the command makes
    mockClient.On("GetDomain", "example.com").Return(mocks.NewDomain(), nil)

    // Run the command with the mock as its client
    output, err := testutil.RunWithClient(t, mockClient, domains.NewGetCommand(), "plain", "example.com")

    require.NoError(t, err)
    assert.Contains(t, output, "example.com")

    // Verify the command made every expected call
    mockClient.AssertExpectations(t)
}
Methods

MockClient has every method of the client.AhaSendClient interface, with the same signature; a test sets an expectation with the method's name and arguments. A method that takes request options, such as an idempotency key, passes each option to the mock as one more argument, so a test matches it with mock.MatchedBy or testutil.IdempotencyKeyArg.

Raw API Responses

JSON output prints the API's response body unchanged, so a test of JSON output needs a result that carries its body. mocks.APIResponse[T](t, body) decodes body into a new T, records body as the API response behind it, and returns the *T for use in Return. Table, plain and CSV output then see the decoded struct, and JSON output prints body:

func TestListCommand_JSONPrintsBody(t *testing.T) {
    body := `{"object":"list","data":[{"domain":"example.com","future_field":1.50}],"pagination":{"has_more":false}}`
    mockClient := &mocks.MockClient{}
    mockClient.On("ListDomains", requests.GetDomainsParams{}).
        Return(mocks.APIResponse[responses.PaginatedDomainsResponse](t, body), nil)

    out, err := testutil.RunWithClient(t, mockClient, NewListCommand(), "json")

    require.NoError(t, err)
    assert.Equal(t, testutil.IndentedJSON(t, body), out)
    mockClient.AssertExpectations(t)
}

A body that does not decode into T fails the test. A result built as a Go value, such as one of the fixtures below, has no recorded body, and JSON output encodes the struct instead.

Fixtures

fixtures.go holds the fixtures that the tests share, in one place. Their values are fixed, so a test can compare output exactly:

  • NewSubAccount() *responses.SubAccount: a sub-account with every field set; its ID is FixtureSubAccountID and its parent account FixtureParentAccountID
  • NewSubAccountUsage(removedReception int64) *responses.SubAccountUsageResponse: the June 2026 usage of the parent account and one sub-account, with removedReception messages of removed sub-accounts
  • NewAPIKey() *responses.APIKey: an API key of the sub-account of NewSubAccount, with the ID FixtureAPIKeyID, without scopes, IP allow list or secret key
  • NewMessageResponse(messageID string) *responses.CreateMessageResponse: the response of a send to one recipient
  • NewDomain() *responses.Domain: the domain example.com of the account FixtureSubAccountID, with the ID FixtureDomainID and a DMARC and a tracking DNS record
apiKey := mocks.NewAPIKey()
apiKey.Scopes = []responses.APIKeyScope{{Scope: "messages:send:all"}}
mockClient.On("GetAPIKey", uuid.MustParse(mocks.FixtureAPIKeyID)).Return(apiKey, nil)

Design Principles

Interface Compliance

MockClient implements the client interface with compile-time verification:

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

Every MockClient method that returns (*T, error) reads its results with the result[T] helper, which returns a nil *T when the first result is nil, typed or untyped, so Return(nil, err) never panics:

func (m *MockClient) CreateDomain(req requests.CreateDomainRequest, opts ...api.RequestOption) (*responses.Domain, error) {
    return result[responses.Domain](m.Called(withOptions([]interface{}{req}, opts)...))
}

Testing Patterns

Error Testing
func TestDomainsGetNotFound(t *testing.T) {
    mockClient := &mocks.MockClient{}
    mockClient.On("GetDomain", "example.com").
        Return(nil, &api.APIError{StatusCode: 404, Message: "domain not found"})

    _, err := testutil.RunWithClient(t, mockClient, domains.NewGetCommand(), "plain", "example.com")

    require.Error(t, err)
    assert.Equal(t, 5, clierrors.GetExitCode(err))
    mockClient.AssertExpectations(t)
}
Validation Before Authentication

testutil.RefuseAuth makes a command that asks for its client fail the test by name and stop with an error, with no client to call, and returns a flag that reports whether the command asked, so a test can check that bad input fails before any request. A regression then fails that one test: a MockClient without expectations would panic on the call instead, and in messages send's worker goroutines that ends the whole test binary.

func TestDomainsCreateRejectsABadDomain(t *testing.T) {
    called := testutil.RefuseAuth(t)

    _, err := testutil.RunPlain(t, domains.NewCreateCommand(), "not a domain")

    require.Error(t, err)
    assert.False(t, *called)
}

Best Practices

  1. Test a command, not the mock: run the command with the mock as its client, and check its output, error and exit code
  2. Always call AssertExpectations(t) at the end of tests to verify all expected calls were made
  3. Use the shared fixtures when possible to create consistent test data
  4. Use mocks.APIResponse for any test that checks JSON output
  5. Set up specific expectations for each test rather than generic catch-all expectations
  6. Test error cases explicitly with appropriate error expectations
  7. Keep mock setup close to usage to improve test readability
  8. Use meaningful test data that reflects realistic scenarios

Documentation

Overview

Package mocks holds MockClient, a testify mock of client.AhaSendClient, with which tests run commands without calling the API, and fixtures of the resources commands print. APIResponse records a body behind a mocked result, as the real client does, so a test can check JSON output.

Index

Constants

View Source
const (
	// FixtureSubAccountID is the ID of NewSubAccount and the account of
	// NewAPIKey.
	FixtureSubAccountID = "11111111-1111-1111-1111-111111111111"
	// FixtureParentAccountID is the parent account of NewSubAccount.
	FixtureParentAccountID = "22222222-2222-2222-2222-222222222222"
	// FixtureAPIKeyID is the ID of NewAPIKey.
	FixtureAPIKeyID = "44444444-4444-4444-4444-444444444444"
	// FixtureDomainID is the ID of NewDomain, which belongs to the account
	// FixtureSubAccountID.
	FixtureDomainID = "55555555-5555-4555-8555-555555555555"
)

Variables

This section is empty.

Functions

func APIResponse added in v0.3.0

func APIResponse[T any](t testing.TB, body string) *T

APIResponse decodes body into a new T, records body as the API response behind it, and returns it for use in a mock's Return. Table and plain output then see the decoded struct, and JSON output sees body.

func NewAPIKey added in v0.3.0

func NewAPIKey() *responses.APIKey

NewAPIKey returns an API key of the sub-account of NewSubAccount, without scopes, IP allow list or secret key.

func NewDomain added in v0.3.0

func NewDomain() *responses.Domain

NewDomain returns the domain example.com with a DMARC and a tracking DNS record.

func NewMessageResponse added in v0.3.0

func NewMessageResponse(messageID string) *responses.CreateMessageResponse

NewMessageResponse returns the response of a send to one recipient, whose message has the ID messageID.

func NewSubAccount added in v0.3.0

func NewSubAccount() *responses.SubAccount

NewSubAccount returns a sub-account with every field set.

func NewSubAccountUsage added in v0.3.0

func NewSubAccountUsage(removedReception int64) *responses.SubAccountUsageResponse

NewSubAccountUsage returns the June 2026 usage of the parent account and one sub-account, with removedReception messages of removed sub-accounts.

Types

type MockClient

type MockClient struct {
	mock.Mock
}

MockClient is a mock implementation of the AhaSendClient interface

func (*MockClient) BatchAddListContacts added in v0.3.0

func (*MockClient) BatchUpsertContacts added in v0.3.0

func (*MockClient) CancelMessage

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

func (*MockClient) CheckDomainDNS

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

func (*MockClient) ConnectWebSocket

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

func (*MockClient) CreateAPIKey

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

func (*MockClient) CreateCampaign added in v0.3.0

func (m *MockClient) CreateCampaign(req requests.CreateCampaignRequest, opts ...api.RequestOption) (*responses.Campaign, error)

func (*MockClient) CreateCampaignTemplate added in v0.3.0

func (*MockClient) CreateContact added in v0.3.0

func (m *MockClient) CreateContact(req requests.CreateContactRequest, opts ...api.RequestOption) (*responses.Contact, error)

func (*MockClient) CreateDomain

func (m *MockClient) CreateDomain(req requests.CreateDomainRequest, opts ...api.RequestOption) (*responses.Domain, error)

func (*MockClient) CreateList added in v0.3.0

func (*MockClient) CreateRoute

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

func (*MockClient) CreateSMTPCredential

func (*MockClient) CreateSubAccount

func (m *MockClient) CreateSubAccount(req requests.CreateSubAccountRequest, opts ...api.RequestOption) (*responses.SubAccount, error)

func (*MockClient) CreateSubAccountAPIKey

func (m *MockClient) CreateSubAccountAPIKey(subAccountID uuid.UUID, req requests.CreateAPIKeyRequest, opts ...api.RequestOption) (*responses.APIKey, error)

func (*MockClient) CreateTemplate added in v0.3.0

func (m *MockClient) CreateTemplate(req requests.CreateTemplateRequest, opts ...api.RequestOption) (*responses.Template, error)

func (*MockClient) CreateWebhook

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

func (*MockClient) DeleteAPIKey

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

func (*MockClient) DeleteCampaign added in v0.3.0

func (m *MockClient) DeleteCampaign(campaignID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) DeleteCampaignTemplate added in v0.3.0

func (m *MockClient) DeleteCampaignTemplate(templateID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) DeleteContact added in v0.3.0

func (m *MockClient) DeleteContact(idOrEmail string) (*common.SuccessResponse, error)

func (*MockClient) DeleteDomain

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

func (*MockClient) DeleteList added in v0.3.0

func (m *MockClient) DeleteList(listID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) DeleteListContact added in v0.3.0

func (m *MockClient) DeleteListContact(listID uuid.UUID, idOrEmail string) (*common.SuccessResponse, error)

func (*MockClient) DeleteRoute

func (m *MockClient) DeleteRoute(routeID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) DeleteSMTPCredential

func (m *MockClient) DeleteSMTPCredential(credentialID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) DeleteSubAccount

func (m *MockClient) DeleteSubAccount(subAccountID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) DeleteSubAccountAPIKey

func (m *MockClient) DeleteSubAccountAPIKey(subAccountID, keyID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) DeleteSuppression

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

func (*MockClient) DeleteTemplate added in v0.3.0

func (m *MockClient) DeleteTemplate(templateID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) DeleteWebhook

func (m *MockClient) DeleteWebhook(webhookID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) DiscardTemplateDraft added in v0.3.0

func (m *MockClient) DiscardTemplateDraft(templateID uuid.UUID) (*responses.Template, error)

func (*MockClient) DuplicateCampaign added in v0.3.0

func (m *MockClient) DuplicateCampaign(campaignID uuid.UUID, req requests.DuplicateCampaignRequest, opts ...api.RequestOption) (*responses.Campaign, error)

func (*MockClient) GetAPIKey

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

func (*MockClient) GetAccount

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

func (*MockClient) GetAccountID

func (m *MockClient) GetAccountID() string

func (*MockClient) GetBounceStatistics

func (*MockClient) GetCampaign added in v0.3.0

func (m *MockClient) GetCampaign(campaignID uuid.UUID) (*responses.Campaign, error)

func (*MockClient) GetCampaignStats added in v0.3.0

func (m *MockClient) GetCampaignStats(campaignID uuid.UUID) (*responses.CampaignStats, error)

func (*MockClient) GetCampaignTemplate added in v0.3.0

func (m *MockClient) GetCampaignTemplate(templateID uuid.UUID) (*responses.CampaignTemplate, error)

func (*MockClient) GetContact added in v0.3.0

func (m *MockClient) GetContact(idOrEmail string) (*responses.Contact, error)

func (*MockClient) GetContactLists added in v0.3.0

func (*MockClient) GetContacts added in v0.3.0

func (*MockClient) GetDeliverabilityStatistics

Statistics operations methods

func (*MockClient) GetDomain

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

func (*MockClient) GetList added in v0.3.0

func (m *MockClient) GetList(listID uuid.UUID) (*responses.ContactList, error)

func (*MockClient) GetListContacts added in v0.3.0

func (*MockClient) GetLists added in v0.3.0

func (*MockClient) GetMessage

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

func (*MockClient) GetMessages

func (*MockClient) GetRoute

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

func (*MockClient) GetSMTPCredential

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

func (*MockClient) GetSubAccount

func (m *MockClient) GetSubAccount(subAccountID uuid.UUID) (*responses.SubAccount, error)

func (*MockClient) GetSubAccountAPIKey

func (m *MockClient) GetSubAccountAPIKey(subAccountID, keyID uuid.UUID) (*responses.APIKey, error)

func (*MockClient) GetSubAccountsUsage

func (m *MockClient) GetSubAccountsUsage() (*responses.SubAccountUsageResponse, error)

func (*MockClient) GetTemplate added in v0.3.0

func (m *MockClient) GetTemplate(templateID uuid.UUID) (*responses.Template, error)

func (*MockClient) GetTemplateDraft added in v0.3.0

func (m *MockClient) GetTemplateDraft(templateID uuid.UUID) (*responses.TemplateDraft, error)

func (*MockClient) GetTemplateVersion added in v0.3.0

func (m *MockClient) GetTemplateVersion(templateID, versionID uuid.UUID) (*responses.TemplateVersionDetail, error)

func (*MockClient) GetTemplateVersions added in v0.3.0

func (m *MockClient) GetTemplateVersions(templateID uuid.UUID) (*responses.TemplateVersionsResponse, error)

func (*MockClient) GetTemplates added in v0.3.0

func (*MockClient) GetWebhook

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

func (*MockClient) InitiateRouteStream

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

func (*MockClient) InitiateWebhookStream

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

func (*MockClient) ListAPIKeys

API Key operations methods

func (*MockClient) ListCampaignRecipients added in v0.3.0

func (*MockClient) ListCampaignTemplates added in v0.3.0

func (*MockClient) ListCampaigns added in v0.3.0

func (*MockClient) ListDomains

func (*MockClient) ListRoutes

func (*MockClient) ListSMTPCredentials

func (m *MockClient) ListSMTPCredentials(pagination common.PaginationParams) (*responses.PaginatedSMTPCredentialsResponse, error)

func (*MockClient) ListSubAccountAPIKeys

func (m *MockClient) ListSubAccountAPIKeys(subAccountID uuid.UUID, pagination common.PaginationParams) (*responses.PaginatedAPIKeysResponse, error)

Sub-account API key operations methods

func (*MockClient) ListSubAccounts

Sub-account operations methods

func (*MockClient) ListSuppressions

func (*MockClient) ListWebhooks

func (m *MockClient) ListWebhooks(pagination common.PaginationParams, enabled *bool) (*responses.PaginatedWebhooksResponse, error)

func (*MockClient) Ping

func (m *MockClient) Ping() (*common.SuccessResponse, error)

func (*MockClient) PublishTemplate added in v0.3.0

func (m *MockClient) PublishTemplate(templateID uuid.UUID, opts ...api.RequestOption) (*responses.Template, error)

func (*MockClient) RestoreTemplateVersion added in v0.3.0

func (m *MockClient) RestoreTemplateVersion(templateID, versionID uuid.UUID, req requests.RestoreTemplateVersionRequest, opts ...api.RequestOption) (*responses.Template, error)

func (*MockClient) SendCampaign added in v0.3.0

func (m *MockClient) SendCampaign(campaignID uuid.UUID, req requests.SendCampaignRequest, opts ...api.RequestOption) (*responses.CampaignSend, error)

func (*MockClient) SendMessageWithIdempotencyKey

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

func (*MockClient) SendTemplateMessageWithIdempotencyKey added in v0.3.0

func (m *MockClient) SendTemplateMessageWithIdempotencyKey(req requests.CreateTemplateMessageRequest, idempotencyKey string) (*responses.CreateMessageResponse, error)

func (*MockClient) SuspendSubAccount

func (m *MockClient) SuspendSubAccount(subAccountID uuid.UUID, req requests.SuspendSubAccountRequest) (*responses.SubAccount, error)

func (*MockClient) TestCampaign added in v0.3.0

func (m *MockClient) TestCampaign(campaignID uuid.UUID, req requests.TestCampaignRequest, opts ...api.RequestOption) (*responses.CampaignTest, error)

func (*MockClient) TriggerRoute

func (m *MockClient) TriggerRoute(routeID uuid.UUID) (*common.SuccessResponse, error)

func (*MockClient) TriggerWebhook

func (m *MockClient) TriggerWebhook(webhookID uuid.UUID, events []string) (*common.SuccessResponse, error)

func (*MockClient) UnpauseSubAccountDomain added in v0.3.0

func (m *MockClient) UnpauseSubAccountDomain(subAccountID uuid.UUID, domain string) (*responses.Domain, error)

func (*MockClient) UnscheduleCampaign added in v0.3.0

func (m *MockClient) UnscheduleCampaign(campaignID uuid.UUID, opts ...api.RequestOption) (*responses.Campaign, error)

func (*MockClient) UnsuspendSubAccount

func (m *MockClient) UnsuspendSubAccount(subAccountID uuid.UUID) (*responses.SubAccount, error)

func (*MockClient) UpdateAPIKey

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

func (*MockClient) UpdateCampaign added in v0.3.0

func (m *MockClient) UpdateCampaign(campaignID uuid.UUID, req requests.UpdateCampaignRequest, opts ...api.RequestOption) (*responses.Campaign, error)

func (*MockClient) UpdateCampaignTemplate added in v0.3.0

func (m *MockClient) UpdateCampaignTemplate(templateID uuid.UUID, req requests.UpdateCampaignTemplateRequest, opts ...api.RequestOption) (*responses.CampaignTemplate, error)

func (*MockClient) UpdateContact added in v0.3.0

func (m *MockClient) UpdateContact(idOrEmail string, req requests.UpdateContactRequest) (*responses.Contact, error)

func (*MockClient) UpdateDomain

func (m *MockClient) UpdateDomain(domain string, req requests.UpdateDomainRequest) (*responses.Domain, error)

func (*MockClient) UpdateList added in v0.3.0

func (m *MockClient) UpdateList(listID uuid.UUID, req requests.UpdateListRequest) (*responses.ContactList, error)

func (*MockClient) UpdateRoute

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

func (*MockClient) UpdateSubAccount

func (m *MockClient) UpdateSubAccount(subAccountID uuid.UUID, req requests.UpdateSubAccountRequest) (*responses.SubAccount, error)

func (*MockClient) UpdateSubAccountAPIKey

func (m *MockClient) UpdateSubAccountAPIKey(subAccountID, keyID uuid.UUID, req requests.UpdateAPIKeyRequest) (*responses.APIKey, error)

func (*MockClient) UpdateTemplate added in v0.3.0

func (m *MockClient) UpdateTemplate(templateID uuid.UUID, req requests.UpdateTemplateRequest, opts ...api.RequestOption) (*responses.Template, error)

func (*MockClient) UpdateWebhook

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

func (*MockClient) UpsertListContact added in v0.3.0

func (m *MockClient) UpsertListContact(listID uuid.UUID, idOrEmail string, req requests.UpsertListContactRequest) (*responses.ListContact, error)

func (*MockClient) WipeSuppressions

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

Jump to

Keyboard shortcuts

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