Testing Temporal Activities: Side Effects, Heartbeats, and Cancellation
Activities are the workhorses of Temporal workflows—they execute the side effects that workflows orchestrate. Unlike workflows, which must be deterministic and are replayed from history, activities can do anything: call APIs, write to databases, send emails, process files. This freedom makes them powerful but also makes them critical to test thoroughly.
This guide covers how to unit test Temporal activities in isolation, including the tricky parts: heartbeating long-running operations, detecting cancellation, and testing retry behavior.
Activities vs Workflows: Why They're Tested Differently
In Temporal, workflows and activities have fundamentally different constraints:
- Workflows must be deterministic—the same input always produces the same sequence of decisions. They're replay-safe, meaning Temporal can re-execute them from history.
- Activities have no such constraints. They can use random numbers, call external APIs, read environment variables, and produce different outputs each time.
This means activity testing is closer to traditional function testing: you call the function with inputs and assert on outputs and side effects. The Temporal-specific concerns are the activity context, heartbeating, and cancellation.
Basic Activity Testing
At its simplest, an activity is just a Go function that accepts a context.Context and returns an error. You can test it directly:
package activities_test
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.temporal.io/sdk/activity"
"go.temporal.io/sdk/testsuite"
)
// The activity function
func ProcessFileActivity(ctx context.Context, filePath string) (int, error) {
file, err := os.Open(filePath)
if err != nil {
return 0, fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
lineCount := 0
for scanner.Scan() {
lineCount++
}
return lineCount, scanner.Err()
}
func TestProcessFileActivity(t *testing.T) {
// Create a temp file with known content
tmpFile, err := os.CreateTemp("", "test-*.txt")
require.NoError(t, err)
defer os.Remove(tmpFile.Name())
_, err = tmpFile.WriteString("line 1\nline 2\nline 3\n")
require.NoError(t, err)
tmpFile.Close()
count, err := ProcessFileActivity(context.Background(), tmpFile.Name())
assert.NoError(t, err)
assert.Equal(t, 3, count)
}This is fine for simple activities, but Temporal activities often use the activity context for heartbeating and detecting cancellation. For those, you need a proper activity context.
Creating a Proper Activity Context for Tests
Temporal's activity context carries metadata the activity runtime uses. The testsuite package provides a way to create a valid activity context:
package activities_test
import (
"testing"
"github.com/stretchr/testify/assert"
"go.temporal.io/sdk/activity"
"go.temporal.io/sdk/testsuite"
)
type ActivityTestSuite struct {
suite.Suite
testsuite.WorkflowTestSuite
env *testsuite.TestActivityEnvironment
}
func (s *ActivityTestSuite) SetupTest() {
s.env = s.NewTestActivityEnvironment()
}
func TestActivityTestSuite(t *testing.T) {
suite.Run(t, new(ActivityTestSuite))
}
func (s *ActivityTestSuite) TestProcessFileActivity() {
// Register the activity
s.env.RegisterActivity(ProcessFileActivity)
// Create a temp file
tmpFile, err := os.CreateTemp("", "test-*.txt")
s.Require().NoError(err)
defer os.Remove(tmpFile.Name())
_, _ = tmpFile.WriteString("line 1\nline 2\nline 3\n")
tmpFile.Close()
// Execute the activity through the test environment
val, err := s.env.ExecuteActivity(ProcessFileActivity, tmpFile.Name())
s.NoError(err)
var count int
s.NoError(val.Get(&count))
s.Equal(3, count)
}The TestActivityEnvironment provides a proper activity context with all the Temporal machinery in place, including heartbeat support and cancellation hooks.
Testing Heartbeats in Long-Running Activities
Heartbeats are critical for long-running activities. They tell the Temporal server the activity is still alive, and they enable graceful cancellation. An activity that processes 10,000 records should heartbeat every few seconds:
func BatchProcessActivity(ctx context.Context, batchID string, recordCount int) (int, error) {
processed := 0
for i := 0; i < recordCount; i++ {
// Check for cancellation
select {
case <-ctx.Done():
return processed, ctx.Err()
default:
}
// Simulate processing one record
if err := processRecord(i); err != nil {
return processed, err
}
processed++
// Heartbeat every 100 records
if processed%100 == 0 {
activity.RecordHeartbeat(ctx, processed)
}
}
return processed, nil
}Testing that an activity heartbeats correctly requires intercepting the heartbeat calls:
func (s *ActivityTestSuite) TestBatchProcessHeartbeats() {
s.env.RegisterActivity(BatchProcessActivity)
var heartbeatValues []int
// Set up heartbeat listener
s.env.SetOnActivityHeartbeatListener(func(activityInfo *activity.Info, value interface{}) {
if count, ok := value.(int); ok {
heartbeatValues = append(heartbeatValues, count)
}
})
val, err := s.env.ExecuteActivity(BatchProcessActivity, "batch-001", 250)
s.NoError(err)
var processed int
s.NoError(val.Get(&processed))
s.Equal(250, processed)
// Should have heartbeated at 100 and 200
s.Len(heartbeatValues, 2)
s.Equal(100, heartbeatValues[0])
s.Equal(200, heartbeatValues[1])
}You can also test that a restarted activity picks up from its last heartbeat detail:
func ResumableBatchActivity(ctx context.Context, batchID string, totalCount int) (int, error) {
// Check for previous heartbeat to resume from
startFrom := 0
if heartbeatDetails := activity.GetHeartbeatDetails(ctx); heartbeatDetails != nil {
if err := heartbeatDetails.Get(&startFrom); err == nil {
// Resume from where we left off
}
}
processed := startFrom
for i := startFrom; i < totalCount; i++ {
select {
case <-ctx.Done():
return processed, ctx.Err()
default:
}
if err := processRecord(i); err != nil {
return processed, err
}
processed++
if processed%50 == 0 {
activity.RecordHeartbeat(ctx, processed)
}
}
return processed, nil
}
func (s *ActivityTestSuite) TestResumableBatchActivityFromHeartbeat() {
s.env.RegisterActivity(ResumableBatchActivity)
// Simulate activity resuming from heartbeat at record 150
s.env.SetTestTimeout(5 * time.Second)
// First, set the heartbeat detail that would have been saved before crash
// In practice, you'd do this by calling the activity twice
// Here we test the resume logic directly
val, err := s.env.ExecuteActivity(ResumableBatchActivity, "batch-002", 200)
s.NoError(err)
var processed int
s.NoError(val.Get(&processed))
s.Equal(200, processed)
}Testing Cancellation Detection
Activities must respect workflow cancellation. When a workflow is cancelled, the activity's context is cancelled, and the activity should detect this and return promptly:
func CancellableDownloadActivity(ctx context.Context, url string, destPath string) error {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
if ctx.Err() != nil {
return temporal.NewCanceledError("download cancelled")
}
return err
}
defer resp.Body.Close()
file, err := os.Create(destPath)
if err != nil {
return err
}
defer file.Close()
buf := make([]byte, 32*1024)
for {
select {
case <-ctx.Done():
return temporal.NewCanceledError("download cancelled during transfer")
default:
}
n, err := resp.Body.Read(buf)
if n > 0 {
if _, writeErr := file.Write(buf[:n]); writeErr != nil {
return writeErr
}
activity.RecordHeartbeat(ctx, file.Name())
}
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return nil
}Testing cancellation with the TestActivityEnvironment:
func (s *ActivityTestSuite) TestActivityCancellation() {
s.env.RegisterActivity(LongPollingActivity)
// Cancel the activity after 100ms
s.env.SetTestTimeout(500 * time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
// Use a channel to coordinate cancellation
cancelCh := make(chan struct{})
s.env.SetOnActivityHeartbeatListener(func(info *activity.Info, value interface{}) {
// Cancel on first heartbeat
select {
case <-cancelCh:
default:
close(cancelCh)
s.env.CancelWorkflow()
}
})
_ = ctx
_, err := s.env.ExecuteActivity(LongPollingActivity, "test-resource")
// Activity should be cancelled
s.Error(err)
var cancelErr *temporal.CanceledError
s.True(errors.As(err, &cancelErr))
}For a cleaner cancellation test that doesn't depend on heartbeating:
func CancellationCheckActivity(ctx context.Context, delay time.Duration) (string, error) {
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
elapsed := time.Duration(0)
for {
select {
case <-ctx.Done():
return "", temporal.NewCanceledError(fmt.Sprintf("cancelled after %v", elapsed))
case <-ticker.C:
elapsed += 10 * time.Millisecond
activity.RecordHeartbeat(ctx, elapsed)
if elapsed >= delay {
return "completed", nil
}
}
}
}
func TestActivityCancellationDirect(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
// Cancel after a brief delay
go func() {
time.Sleep(50 * time.Millisecond)
cancel()
}()
result, err := CancellationCheckActivity(ctx, 10*time.Second)
assert.Empty(t, result)
assert.Error(t, err)
assert.Contains(t, err.Error(), "cancelled")
}Testing Activity Retry Logic
Activities in Temporal can be retried automatically. But your activity code needs to be written correctly to take advantage of this—specifically, it needs to return retryable errors for transient failures and non-retryable errors for permanent failures:
func CallExternalAPIActivity(ctx context.Context, endpoint string, payload map[string]interface{}) (map[string]interface{}, error) {
client := &http.Client{Timeout: 30 * time.Second}
body, _ := json.Marshal(payload)
resp, err := client.Post(endpoint, "application/json", bytes.NewReader(body))
if err != nil {
// Network errors are retryable
return nil, err
}
defer resp.Body.Close()
switch resp.StatusCode {
case 200, 201:
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
case 400, 422:
// Client errors are NOT retryable
return nil, temporal.NewNonRetryableApplicationError(
fmt.Sprintf("bad request: %d", resp.StatusCode),
"BAD_REQUEST",
nil,
)
case 401, 403:
return nil, temporal.NewNonRetryableApplicationError(
"unauthorized",
"AUTH_ERROR",
nil,
)
case 429, 503:
// Rate limiting and service unavailable ARE retryable
return nil, temporal.NewApplicationError(
fmt.Sprintf("server error: %d", resp.StatusCode),
"TRANSIENT_ERROR",
)
default:
return nil, temporal.NewApplicationError(
fmt.Sprintf("unexpected status: %d", resp.StatusCode),
"UNKNOWN_ERROR",
)
}
}Testing the error classification:
func TestAPIActivityErrorClassification(t *testing.T) {
tests := []struct {
name string
statusCode int
expectRetry bool
expectErrType string
}{
{"success", 200, false, ""},
{"bad request", 400, false, "BAD_REQUEST"},
{"unauthorized", 401, false, "AUTH_ERROR"},
{"rate limited", 429, true, "TRANSIENT_ERROR"},
{"service unavailable", 503, true, "TRANSIENT_ERROR"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a test HTTP server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.statusCode)
if tt.statusCode == 200 {
json.NewEncoder(w).Encode(map[string]interface{}{"status": "ok"})
}
}))
defer server.Close()
result, err := CallExternalAPIActivity(
context.Background(),
server.URL,
map[string]interface{}{"test": "data"},
)
if tt.expectErrType == "" {
assert.NoError(t, err)
assert.NotNil(t, result)
} else {
assert.Error(t, err)
assert.Nil(t, result)
var appErr *temporal.ApplicationError
require.True(t, errors.As(err, &appErr))
assert.Equal(t, tt.expectErrType, appErr.Type())
if !tt.expectRetry {
var nonRetryErr *temporal.ApplicationError
assert.True(t, errors.As(err, &nonRetryErr))
assert.True(t, nonRetryErr.NonRetryable())
}
}
})
}
}Local Activities vs Regular Activities
Temporal supports local activities—activities that run in the same process as the workflow worker, without going through the Temporal server. They're faster and cheaper for short operations, but they can't be heartbeated and don't benefit from Temporal's retry infrastructure.
// Regular activity - goes through Temporal server
func SendEmailActivity(ctx context.Context, to, subject, body string) error {
// ... send email via SMTP
return nil
}
// Local activity - runs in the same process, faster but no heartbeat
func FormatEmailBodyActivity(ctx workflow.Context, template string, data map[string]interface{}) (string, error) {
// Template rendering is fast and CPU-bound - good candidate for local activity
return renderTemplate(template, data)
}
// Workflow using both
func NotificationWorkflow(ctx workflow.Context, userID string, eventData map[string]interface{}) error {
// Local activity for formatting (fast, no I/O)
lao := workflow.LocalActivityOptions{
ScheduleToCloseTimeout: 5 * time.Second,
}
localCtx := workflow.WithLocalActivityOptions(ctx, lao)
var formattedBody string
err := workflow.ExecuteLocalActivity(localCtx, FormatEmailBodyActivity, "welcome-template", eventData).Get(ctx, &formattedBody)
if err != nil {
return err
}
// Regular activity for sending (I/O, can heartbeat if slow)
ao := workflow.ActivityOptions{
StartToCloseTimeout: 30 * time.Second,
RetryPolicy: &temporal.RetryPolicy{MaximumAttempts: 3},
}
ctx = workflow.WithActivityOptions(ctx, ao)
userEmail, err := getUserEmail(userID) // not shown, another activity
if err != nil {
return err
}
return workflow.ExecuteActivity(ctx, SendEmailActivity, userEmail, "Welcome!", formattedBody).Get(ctx, nil)
}Testing local activities requires registering them differently:
func (s *WorkflowTestSuite) TestNotificationWorkflowWithLocalActivity() {
s.env.RegisterWorkflow(NotificationWorkflow)
s.env.RegisterActivity(SendEmailActivity)
// Local activities are registered the same way in tests
s.env.RegisterActivity(FormatEmailBodyActivity)
var capturedEmail, capturedBody string
s.env.OnActivity(SendEmailActivity, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(func(ctx context.Context, to, subject, body string) error {
capturedEmail = to
capturedBody = body
return nil
})
s.env.OnActivity(FormatEmailBodyActivity, mock.Anything, "welcome-template", mock.Anything).
Return("Hello, welcome to our service!", nil)
s.env.OnActivity(GetUserEmailActivity, mock.Anything, "user-123").
Return("user@example.com", nil)
s.env.ExecuteWorkflow(NotificationWorkflow, "user-123", map[string]interface{}{
"name": "Alice",
})
s.True(s.env.IsWorkflowCompleted())
s.NoError(s.env.GetWorkflowError())
s.Equal("user@example.com", capturedEmail)
s.Equal("Hello, welcome to our service!", capturedBody)
}Testing Activities with Database Dependencies
Activities that interact with databases are common. The key is to use interfaces so you can swap in test doubles:
// Define the interface
type UserRepository interface {
FindByID(ctx context.Context, id string) (*User, error)
Update(ctx context.Context, user *User) error
Delete(ctx context.Context, id string) error
}
// Activity struct that holds dependencies
type UserActivities struct {
repo UserRepository
}
func NewUserActivities(repo UserRepository) *UserActivities {
return &UserActivities{repo: repo}
}
func (a *UserActivities) DeactivateUserActivity(ctx context.Context, userID string) error {
user, err := a.repo.FindByID(ctx, userID)
if err != nil {
return temporal.NewApplicationError("user not found", "NOT_FOUND", err)
}
if !user.Active {
return nil // Already inactive, idempotent
}
user.Active = false
user.DeactivatedAt = time.Now()
return a.repo.Update(ctx, user)
}Now testing with a mock repository:
type MockUserRepository struct {
mock.Mock
}
func (m *MockUserRepository) FindByID(ctx context.Context, id string) (*User, error) {
args := m.Called(ctx, id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*User), args.Error(1)
}
func (m *MockUserRepository) Update(ctx context.Context, user *User) error {
args := m.Called(ctx, user)
return args.Error(0)
}
func (m *MockUserRepository) Delete(ctx context.Context, id string) error {
args := m.Called(ctx, id)
return args.Error(0)
}
func TestDeactivateUserActivity(t *testing.T) {
t.Run("active user gets deactivated", func(t *testing.T) {
repo := new(MockUserRepository)
activities := NewUserActivities(repo)
activeUser := &User{ID: "user-1", Active: true, Name: "Alice"}
repo.On("FindByID", mock.Anything, "user-1").Return(activeUser, nil)
repo.On("Update", mock.Anything, mock.MatchedBy(func(u *User) bool {
return u.ID == "user-1" && !u.Active && !u.DeactivatedAt.IsZero()
})).Return(nil)
err := activities.DeactivateUserActivity(context.Background(), "user-1")
assert.NoError(t, err)
repo.AssertExpectations(t)
})
t.Run("already inactive user is idempotent", func(t *testing.T) {
repo := new(MockUserRepository)
activities := NewUserActivities(repo)
inactiveUser := &User{ID: "user-2", Active: false}
repo.On("FindByID", mock.Anything, "user-2").Return(inactiveUser, nil)
// Update should NOT be called
err := activities.DeactivateUserActivity(context.Background(), "user-2")
assert.NoError(t, err)
repo.AssertNotCalled(t, "Update")
})
t.Run("user not found returns non-retryable error", func(t *testing.T) {
repo := new(MockUserRepository)
activities := NewUserActivities(repo)
repo.On("FindByID", mock.Anything, "user-404").
Return(nil, sql.ErrNoRows)
err := activities.DeactivateUserActivity(context.Background(), "user-404")
assert.Error(t, err)
var appErr *temporal.ApplicationError
require.True(t, errors.As(err, &appErr))
assert.Equal(t, "NOT_FOUND", appErr.Type())
})
}Integration Testing Activities Against Real Services
While unit tests with mocks cover the logic, you also need integration tests that verify the activity works against real (or realistic) external services. Use build tags to separate these:
//go:build integration
// +build integration
package activities_test
import (
"context"
"os"
"testing"
"github.com/stretchr/testify/require"
)
func TestSendEmailActivityIntegration(t *testing.T) {
smtpHost := os.Getenv("TEST_SMTP_HOST")
if smtpHost == "" {
t.Skip("TEST_SMTP_HOST not set, skipping integration test")
}
activity := NewEmailActivity(smtpHost, 587)
err := activity.SendEmailActivity(
context.Background(),
"test@example.com",
"Integration Test Email",
"This is a test",
)
require.NoError(t, err)
}Run integration tests with:
go test -tags integration ./activities/...Activity Testing Checklist
Before shipping an activity, verify your tests cover:
- Happy path: Normal inputs produce expected outputs
- Input validation: Invalid inputs return appropriate non-retryable errors
- Transient failures: Network errors, timeouts return retryable errors
- Permanent failures: Bad data, auth errors return non-retryable errors
- Idempotency: Running the activity twice with same inputs is safe
- Heartbeating: Long-running activities heartbeat at appropriate intervals
- Cancellation: Activity checks
ctx.Done()and exits cleanly - Resource cleanup: Deferred cleanup runs even on error paths
- Resume from heartbeat: Activity correctly reads and uses heartbeat details
Activities are where your business logic lives. Test them thoroughly in isolation, and you'll spend far less time debugging production incidents.