mocks

package
v1.0.23 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2025 License: Apache-2.0 Imports: 7 Imported by: 1

Documentation

Overview

Package mocks provides mock implementations for DynamORM interfaces and AWS SDK operations

Package mocks provides mock implementations for DynamORM interfaces.

This package solves the common issue of having to implement all 26+ methods of the core.Query interface when writing unit tests. Instead of discovering missing methods through trial and error, you can use these pre-built mocks.

Installation

Import the mocks package in your test files:

import "github.com/pay-theory/dynamorm/pkg/mocks"

Basic Usage

The most common use case is mocking database queries:

func TestUserService(t *testing.T) {
    // Create mocks
    mockDB := new(mocks.MockDB)
    mockQuery := new(mocks.MockQuery)

    // Setup expectations
    mockDB.On("Model", &User{}).Return(mockQuery)
    mockQuery.On("Where", "ID", "=", "123").Return(mockQuery)
    mockQuery.On("First", mock.Anything).Return(nil)

    // Use in your service
    service := NewUserService(mockDB)
    user, err := service.GetUser("123")

    // Assert expectations were met
    mockDB.AssertExpectations(t)
    mockQuery.AssertExpectations(t)
}

Chaining Methods

Query methods typically return themselves to allow chaining:

mockQuery.On("Where", "Status", "=", "active").Return(mockQuery)
mockQuery.On("OrderBy", "CreatedAt", "DESC").Return(mockQuery)
mockQuery.On("Limit", 10).Return(mockQuery)
mockQuery.On("All", mock.Anything).Return(nil)

Working with Results

To return data from queries, use mock.Run to populate the destination:

users := []User{{ID: "1", Name: "Alice"}, {ID: "2", Name: "Bob"}}
mockQuery.On("All", mock.Anything).Run(func(args mock.Arguments) {
    dest := args.Get(0).(*[]User)
    *dest = users
}).Return(nil)

Error Handling

To simulate errors:

mockQuery.On("First", mock.Anything).Return(errors.New("not found"))

Update Operations

For update operations with the builder pattern:

mockUpdateBuilder := new(mocks.MockUpdateBuilder)
mockQuery.On("UpdateBuilder").Return(mockUpdateBuilder)
mockUpdateBuilder.On("Set", "Status", "completed").Return(mockUpdateBuilder)
mockUpdateBuilder.On("Execute").Return(nil)

AWS SDK Level Mocking

For testing infrastructure code that directly uses the AWS SDK:

mockClient := new(mocks.MockDynamoDBClient)
mockWaiter := new(mocks.MockTableExistsWaiter)

// Mock table creation
mockClient.On("CreateTable", mock.Anything, mock.Anything, mock.Anything).
	Return(mocks.NewMockCreateTableOutput("test-table"), nil)

// Mock waiting for table to be ready
mockWaiter.On("Wait", mock.Anything, mock.Anything, mock.Anything, mock.Anything).
	Return(nil)

Tips

1. Use mock.Anything when you don't need to assert on specific arguments 2. Use mock.MatchedBy for custom argument matching 3. Always assert expectations were met with AssertExpectations 4. Return the mock itself for chainable methods 5. Use Run to modify output parameters before returning 6. Use the helper functions (NewMockCreateTableOutput, etc.) for realistic responses 7. AWS SDK mocks complement DynamORM interface mocks for complete test coverage

Package mocks provides mock implementations for DynamORM interfaces. These mocks are designed to be used with github.com/stretchr/testify/mock for unit testing applications that use DynamORM.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewMockCreateTableOutput added in v1.0.15

func NewMockCreateTableOutput(tableName string) *dynamodb.CreateTableOutput

NewMockCreateTableOutput creates a mock CreateTable response

func NewMockDeleteTableOutput added in v1.0.15

func NewMockDeleteTableOutput(tableName string) *dynamodb.DeleteTableOutput

NewMockDeleteTableOutput creates a mock DeleteTable response

func NewMockDescribeTableOutput added in v1.0.15

func NewMockDescribeTableOutput(tableName string, status types.TableStatus) *dynamodb.DescribeTableOutput

NewMockDescribeTableOutput creates a mock DescribeTable response

func NewMockUpdateTimeToLiveOutput added in v1.0.15

func NewMockUpdateTimeToLiveOutput(tableName string) *dynamodb.UpdateTimeToLiveOutput

NewMockUpdateTimeToLiveOutput creates a mock UpdateTimeToLive response

Types

type DB

type DB = MockDB

DB is an alias for MockDB to allow shorter declarations

type DynamoDBClient added in v1.0.15

type DynamoDBClient = MockDynamoDBClient

DynamoDBClient is an alias for MockDynamoDBClient

type ExtendedDB added in v1.0.15

type ExtendedDB = MockExtendedDB

ExtendedDB is an alias for MockExtendedDB to allow shorter declarations

type MockDB

type MockDB struct {
	mock.Mock
}

MockDB is a mock implementation of the core.DB interface. It can be used for unit testing code that depends on DynamORM.

Example usage:

mockDB := new(mocks.MockDB)
mockQuery := new(mocks.MockQuery)
mockDB.On("Model", &User{}).Return(mockQuery)
mockQuery.On("Where", "ID", "=", "123").Return(mockQuery)
mockQuery.On("First", mock.Anything).Return(nil)

func (*MockDB) AutoMigrate

func (m *MockDB) AutoMigrate(models ...any) error

AutoMigrate creates or updates tables based on the given models

func (*MockDB) Close

func (m *MockDB) Close() error

Close closes the database connection

func (*MockDB) Migrate

func (m *MockDB) Migrate() error

Migrate runs all pending migrations

func (*MockDB) Model

func (m *MockDB) Model(model any) core.Query

Model returns a new query builder for the given model

func (*MockDB) Transaction

func (m *MockDB) Transaction(fn func(tx *core.Tx) error) error

Transaction executes a function within a database transaction

func (*MockDB) WithContext

func (m *MockDB) WithContext(ctx context.Context) core.DB

WithContext returns a new DB instance with the given context

type MockDynamoDBClient added in v1.0.15

type MockDynamoDBClient struct {
	mock.Mock
}

MockDynamoDBClient provides a mock implementation of the AWS DynamoDB client for testing infrastructure code that directly uses the AWS SDK.

This complements the existing DynamORM interface mocks by providing low-level AWS SDK operation mocking.

Example usage:

mockClient := new(mocks.MockDynamoDBClient)
mockClient.On("CreateTable", mock.Anything, mock.Anything).Return(&dynamodb.CreateTableOutput{}, nil)

// Use in your infrastructure code
store := &DynamoDBConnectionStore{client: mockClient}

func (*MockDynamoDBClient) BatchGetItem added in v1.0.15

func (m *MockDynamoDBClient) BatchGetItem(ctx context.Context, params *dynamodb.BatchGetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.BatchGetItemOutput, error)

BatchGetItem mocks the DynamoDB BatchGetItem operation

func (*MockDynamoDBClient) BatchWriteItem added in v1.0.15

func (m *MockDynamoDBClient) BatchWriteItem(ctx context.Context, params *dynamodb.BatchWriteItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.BatchWriteItemOutput, error)

BatchWriteItem mocks the DynamoDB BatchWriteItem operation

func (*MockDynamoDBClient) CreateTable added in v1.0.15

func (m *MockDynamoDBClient) CreateTable(ctx context.Context, params *dynamodb.CreateTableInput, optFns ...func(*dynamodb.Options)) (*dynamodb.CreateTableOutput, error)

CreateTable mocks the DynamoDB CreateTable operation

func (*MockDynamoDBClient) DeleteItem added in v1.0.15

func (m *MockDynamoDBClient) DeleteItem(ctx context.Context, params *dynamodb.DeleteItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.DeleteItemOutput, error)

DeleteItem mocks the DynamoDB DeleteItem operation

func (*MockDynamoDBClient) DeleteTable added in v1.0.15

func (m *MockDynamoDBClient) DeleteTable(ctx context.Context, params *dynamodb.DeleteTableInput, optFns ...func(*dynamodb.Options)) (*dynamodb.DeleteTableOutput, error)

DeleteTable mocks the DynamoDB DeleteTable operation

func (*MockDynamoDBClient) DescribeTable added in v1.0.15

func (m *MockDynamoDBClient) DescribeTable(ctx context.Context, params *dynamodb.DescribeTableInput, optFns ...func(*dynamodb.Options)) (*dynamodb.DescribeTableOutput, error)

DescribeTable mocks the DynamoDB DescribeTable operation

func (*MockDynamoDBClient) GetItem added in v1.0.15

func (m *MockDynamoDBClient) GetItem(ctx context.Context, params *dynamodb.GetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error)

GetItem mocks the DynamoDB GetItem operation

func (*MockDynamoDBClient) PutItem added in v1.0.15

func (m *MockDynamoDBClient) PutItem(ctx context.Context, params *dynamodb.PutItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error)

PutItem mocks the DynamoDB PutItem operation

func (*MockDynamoDBClient) Query added in v1.0.15

func (m *MockDynamoDBClient) Query(ctx context.Context, params *dynamodb.QueryInput, optFns ...func(*dynamodb.Options)) (*dynamodb.QueryOutput, error)

Query mocks the DynamoDB Query operation

func (*MockDynamoDBClient) Scan added in v1.0.15

func (m *MockDynamoDBClient) Scan(ctx context.Context, params *dynamodb.ScanInput, optFns ...func(*dynamodb.Options)) (*dynamodb.ScanOutput, error)

Scan mocks the DynamoDB Scan operation

func (*MockDynamoDBClient) UpdateItem added in v1.0.15

func (m *MockDynamoDBClient) UpdateItem(ctx context.Context, params *dynamodb.UpdateItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.UpdateItemOutput, error)

UpdateItem mocks the DynamoDB UpdateItem operation

func (*MockDynamoDBClient) UpdateTimeToLive added in v1.0.15

func (m *MockDynamoDBClient) UpdateTimeToLive(ctx context.Context, params *dynamodb.UpdateTimeToLiveInput, optFns ...func(*dynamodb.Options)) (*dynamodb.UpdateTimeToLiveOutput, error)

UpdateTimeToLive mocks the DynamoDB UpdateTimeToLive operation

type MockExtendedDB added in v1.0.10

type MockExtendedDB struct {
	MockDB // Embed MockDB to inherit base methods
}

MockExtendedDB is a complete mock implementation of core.ExtendedDB. It embeds MockDB to inherit the base DB interface methods and adds the additional methods required by ExtendedDB.

Example usage:

mockDB := mocks.NewMockExtendedDB()
mockQuery := new(mocks.MockQuery)
mockDB.On("Model", &User{}).Return(mockQuery)
mockQuery.On("Create").Return(nil)

func NewMockExtendedDB added in v1.0.10

func NewMockExtendedDB() *MockExtendedDB

NewMockExtendedDB creates a new MockExtendedDB with sensible defaults for methods that are rarely used in unit tests. This reduces boilerplate in tests that only need to mock core functionality.

func NewMockExtendedDBStrict added in v1.0.10

func NewMockExtendedDBStrict() *MockExtendedDB

NewMockExtendedDBStrict creates a MockExtendedDB without any default expectations. Use this when you want to explicitly set all expectations.

func (*MockExtendedDB) AutoMigrateWithOptions added in v1.0.10

func (m *MockExtendedDB) AutoMigrateWithOptions(model any, opts ...any) error

AutoMigrateWithOptions performs enhanced auto-migration with options

func (*MockExtendedDB) CreateTable added in v1.0.10

func (m *MockExtendedDB) CreateTable(model any, opts ...any) error

CreateTable creates a DynamoDB table for the given model

func (*MockExtendedDB) DeleteTable added in v1.0.10

func (m *MockExtendedDB) DeleteTable(model any) error

DeleteTable deletes the DynamoDB table for the given model

func (*MockExtendedDB) DescribeTable added in v1.0.10

func (m *MockExtendedDB) DescribeTable(model any) (any, error)

DescribeTable returns the table description for the given model

func (*MockExtendedDB) EnsureTable added in v1.0.10

func (m *MockExtendedDB) EnsureTable(model any) error

EnsureTable checks if a table exists and creates it if not

func (*MockExtendedDB) TransactionFunc added in v1.0.10

func (m *MockExtendedDB) TransactionFunc(fn func(tx any) error) error

TransactionFunc executes a function within a full transaction context

func (*MockExtendedDB) WithLambdaTimeout added in v1.0.10

func (m *MockExtendedDB) WithLambdaTimeout(ctx context.Context) core.DB

WithLambdaTimeout sets a deadline based on Lambda context

func (*MockExtendedDB) WithLambdaTimeoutBuffer added in v1.0.10

func (m *MockExtendedDB) WithLambdaTimeoutBuffer(buffer time.Duration) core.DB

WithLambdaTimeoutBuffer sets a custom timeout buffer

type MockQuery

type MockQuery struct {
	mock.Mock
}

MockQuery is a mock implementation of the core.Query interface. It can be used for unit testing code that depends on DynamORM queries.

Example usage:

mockQuery := new(mocks.MockQuery)
mockQuery.On("Where", "ID", "=", "123").Return(mockQuery)
mockQuery.On("First", mock.Anything).Return(nil)

func (*MockQuery) All

func (m *MockQuery) All(dest any) error

All retrieves all matching items

func (*MockQuery) AllPaginated

func (m *MockQuery) AllPaginated(dest any) (*core.PaginatedResult, error)

AllPaginated retrieves all matching items with pagination metadata

func (*MockQuery) BatchCreate

func (m *MockQuery) BatchCreate(items any) error

BatchCreate creates multiple items

func (*MockQuery) BatchDelete added in v1.0.3

func (m *MockQuery) BatchDelete(keys []any) error

BatchDelete deletes multiple items by their primary keys

func (*MockQuery) BatchGet

func (m *MockQuery) BatchGet(keys []any, dest any) error

BatchGet retrieves multiple items by their primary keys

func (*MockQuery) BatchUpdateWithOptions added in v1.0.3

func (m *MockQuery) BatchUpdateWithOptions(items []any, fields []string, options ...any) error

BatchUpdateWithOptions performs batch update operations with custom options

func (*MockQuery) BatchWrite added in v1.0.3

func (m *MockQuery) BatchWrite(putItems []any, deleteKeys []any) error

BatchWrite performs mixed batch write operations

func (*MockQuery) ConsistentRead added in v1.0.22

func (m *MockQuery) ConsistentRead() core.Query

ConsistentRead enables strongly consistent reads for Query operations

func (*MockQuery) Count

func (m *MockQuery) Count() (int64, error)

Count returns the number of matching items

func (*MockQuery) Create

func (m *MockQuery) Create() error

Create creates a new item

func (*MockQuery) CreateOrUpdate added in v1.0.5

func (m *MockQuery) CreateOrUpdate() error

CreateOrUpdate creates a new item or updates an existing one (upsert)

func (*MockQuery) Cursor

func (m *MockQuery) Cursor(cursor string) core.Query

Cursor sets the pagination cursor

func (*MockQuery) Delete

func (m *MockQuery) Delete() error

Delete deletes the matching items

func (*MockQuery) Filter

func (m *MockQuery) Filter(field string, op string, value any) core.Query

Filter adds a filter expression to the query

func (*MockQuery) FilterGroup

func (m *MockQuery) FilterGroup(fn func(core.Query)) core.Query

FilterGroup adds a group of filters with AND logic

func (*MockQuery) First

func (m *MockQuery) First(dest any) error

First retrieves the first matching item

func (*MockQuery) Index

func (m *MockQuery) Index(indexName string) core.Query

Index specifies which index to use

func (*MockQuery) Limit

func (m *MockQuery) Limit(limit int) core.Query

Limit sets the maximum number of items to return

func (*MockQuery) Offset

func (m *MockQuery) Offset(offset int) core.Query

Offset sets the starting position for the query

func (*MockQuery) OrFilter

func (m *MockQuery) OrFilter(field string, op string, value any) core.Query

OrFilter adds an OR filter expression to the query

func (*MockQuery) OrFilterGroup

func (m *MockQuery) OrFilterGroup(fn func(core.Query)) core.Query

OrFilterGroup adds a group of filters with OR logic

func (*MockQuery) OrderBy

func (m *MockQuery) OrderBy(field string, order string) core.Query

OrderBy sets the sort order

func (*MockQuery) ParallelScan

func (m *MockQuery) ParallelScan(segment int32, totalSegments int32) core.Query

ParallelScan configures parallel scanning

func (*MockQuery) Scan

func (m *MockQuery) Scan(dest any) error

Scan performs a table scan

func (*MockQuery) ScanAllSegments

func (m *MockQuery) ScanAllSegments(dest any, totalSegments int32) error

ScanAllSegments performs parallel scan across all segments

func (*MockQuery) Select

func (m *MockQuery) Select(fields ...string) core.Query

Select specifies which fields to retrieve

func (*MockQuery) SetCursor

func (m *MockQuery) SetCursor(cursor string) error

SetCursor sets the cursor from a string

func (*MockQuery) Update

func (m *MockQuery) Update(fields ...string) error

Update updates the matching items

func (*MockQuery) UpdateBuilder

func (m *MockQuery) UpdateBuilder() core.UpdateBuilder

UpdateBuilder returns a builder for complex update operations

func (*MockQuery) Where

func (m *MockQuery) Where(field string, op string, value any) core.Query

Where adds a condition to the query

func (*MockQuery) WithContext

func (m *MockQuery) WithContext(ctx context.Context) core.Query

WithContext sets the context for the query

func (*MockQuery) WithRetry added in v1.0.22

func (m *MockQuery) WithRetry(maxRetries int, initialDelay time.Duration) core.Query

WithRetry configures retry behavior for eventually consistent reads

type MockTableExistsWaiter added in v1.0.15

type MockTableExistsWaiter struct {
	mock.Mock
}

MockTableExistsWaiter provides a mock implementation of the DynamoDB table exists waiter

Example usage:

mockWaiter := new(mocks.MockTableExistsWaiter)
mockWaiter.On("Wait", mock.Anything, mock.Anything, mock.Anything).Return(nil)

func (*MockTableExistsWaiter) Wait added in v1.0.15

Wait mocks waiting for a table to exist

type MockTableNotExistsWaiter added in v1.0.15

type MockTableNotExistsWaiter struct {
	mock.Mock
}

MockTableNotExistsWaiter provides a mock implementation of the DynamoDB table not exists waiter

Example usage:

mockWaiter := new(mocks.MockTableNotExistsWaiter)
mockWaiter.On("Wait", mock.Anything, mock.Anything, mock.Anything).Return(nil)

func (*MockTableNotExistsWaiter) Wait added in v1.0.15

Wait mocks waiting for a table to not exist (be deleted)

type MockUpdateBuilder

type MockUpdateBuilder struct {
	mock.Mock
}

MockUpdateBuilder is a mock implementation of the core.UpdateBuilder interface. It can be used for unit testing code that uses DynamORM's update builder pattern.

Example usage:

mockUpdateBuilder := new(mocks.MockUpdateBuilder)
mockUpdateBuilder.On("Set", "status", "active").Return(mockUpdateBuilder)
mockUpdateBuilder.On("Execute").Return(nil)

func (*MockUpdateBuilder) Add

func (m *MockUpdateBuilder) Add(field string, value any) core.UpdateBuilder

Add performs atomic addition (for numbers) or adds to a set

func (*MockUpdateBuilder) AppendToList

func (m *MockUpdateBuilder) AppendToList(field string, values any) core.UpdateBuilder

AppendToList appends values to the end of a list

func (*MockUpdateBuilder) Condition

func (m *MockUpdateBuilder) Condition(field string, operator string, value any) core.UpdateBuilder

Condition adds a condition that must be met for the update to succeed

func (*MockUpdateBuilder) ConditionExists

func (m *MockUpdateBuilder) ConditionExists(field string) core.UpdateBuilder

ConditionExists adds a condition that the field must exist

func (*MockUpdateBuilder) ConditionNotExists

func (m *MockUpdateBuilder) ConditionNotExists(field string) core.UpdateBuilder

ConditionNotExists adds a condition that the field must not exist

func (*MockUpdateBuilder) ConditionVersion

func (m *MockUpdateBuilder) ConditionVersion(currentVersion int64) core.UpdateBuilder

ConditionVersion adds optimistic locking based on version

func (*MockUpdateBuilder) Decrement

func (m *MockUpdateBuilder) Decrement(field string) core.UpdateBuilder

Decrement decrements a numeric field by 1

func (*MockUpdateBuilder) Delete

func (m *MockUpdateBuilder) Delete(field string, value any) core.UpdateBuilder

Delete removes values from a set

func (*MockUpdateBuilder) Execute

func (m *MockUpdateBuilder) Execute() error

Execute performs the update operation

func (*MockUpdateBuilder) ExecuteWithResult

func (m *MockUpdateBuilder) ExecuteWithResult(result any) error

ExecuteWithResult performs the update and returns the result

func (*MockUpdateBuilder) Increment

func (m *MockUpdateBuilder) Increment(field string) core.UpdateBuilder

Increment increments a numeric field by 1

func (*MockUpdateBuilder) OrCondition added in v1.0.6

func (m *MockUpdateBuilder) OrCondition(field string, operator string, value any) core.UpdateBuilder

OrCondition adds a condition with OR logic

func (*MockUpdateBuilder) PrependToList

func (m *MockUpdateBuilder) PrependToList(field string, values any) core.UpdateBuilder

PrependToList prepends values to the beginning of a list

func (*MockUpdateBuilder) Remove

func (m *MockUpdateBuilder) Remove(field string) core.UpdateBuilder

Remove removes an attribute from the item

func (*MockUpdateBuilder) RemoveFromListAt

func (m *MockUpdateBuilder) RemoveFromListAt(field string, index int) core.UpdateBuilder

RemoveFromListAt removes an element at a specific index from a list

func (*MockUpdateBuilder) ReturnValues

func (m *MockUpdateBuilder) ReturnValues(option string) core.UpdateBuilder

ReturnValues specifies what values to return after the update

func (*MockUpdateBuilder) Set

func (m *MockUpdateBuilder) Set(field string, value any) core.UpdateBuilder

Set updates a field to a new value

func (*MockUpdateBuilder) SetIfNotExists

func (m *MockUpdateBuilder) SetIfNotExists(field string, value any, defaultValue any) core.UpdateBuilder

SetIfNotExists sets a field value only if it doesn't already exist

func (*MockUpdateBuilder) SetListElement

func (m *MockUpdateBuilder) SetListElement(field string, index int, value any) core.UpdateBuilder

SetListElement sets a specific element in a list

type Query

type Query = MockQuery

Query is an alias for MockQuery to allow shorter declarations

type TableExistsWaiter added in v1.0.15

type TableExistsWaiter = MockTableExistsWaiter

TableExistsWaiter is an alias for MockTableExistsWaiter

type TableNotExistsWaiter added in v1.0.15

type TableNotExistsWaiter = MockTableNotExistsWaiter

TableNotExistsWaiter is an alias for MockTableNotExistsWaiter

type UpdateBuilder

type UpdateBuilder = MockUpdateBuilder

UpdateBuilder is an alias for MockUpdateBuilder to allow shorter declarations

type User added in v1.0.20

type User struct {
	ID    string `dynamorm:"pk"`
	Email string
	Name  string
	Age   int
}

🏗️ STEP 1: Define your model This is just a regular DynamORM model

type UserService added in v1.0.20

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

🚀 STEP 2: Create a service that uses DynamORM This is the real business logic you want to test

func NewUserService added in v1.0.20

func NewUserService(db core.DB) *UserService

func (*UserService) CreateUser added in v1.0.20

func (s *UserService) CreateUser(user *User) error

CreateUser creates a new user

func (*UserService) GetActiveUsers added in v1.0.20

func (s *UserService) GetActiveUsers() ([]User, error)

GetActiveUsers gets all users over 18

func (*UserService) GetUser added in v1.0.20

func (s *UserService) GetUser(id string) (*User, error)

GetUser fetches a user by ID

func (*UserService) UpdateUserEmail added in v1.0.20

func (s *UserService) UpdateUserEmail(id, newEmail string) error

UpdateUserEmail updates a user's email

Jump to

Keyboard shortcuts

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