|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'test' |
| 4 | +require 'securerandom' |
| 5 | +require 'saga/activities' |
| 6 | +require 'saga/saga_workflow' |
| 7 | +require 'temporalio/testing' |
| 8 | +require 'temporalio/worker' |
| 9 | +require 'polling/infrequent/compose_greeting_activity' |
| 10 | +require 'polling/infrequent/test_service' |
| 11 | + |
| 12 | +module Saga |
| 13 | + class SagaWorkflowTest < Test |
| 14 | + def test_workflow_runs_compensations |
| 15 | + # Run worker in test environment |
| 16 | + Temporalio::Testing::WorkflowEnvironment.start_local do |env| |
| 17 | + worker = Temporalio::Worker.new( |
| 18 | + client: env.client, |
| 19 | + task_queue: "tq-#{SecureRandom.uuid}", |
| 20 | + activities: [Activities::Withdraw, Activities::WithdrawCompensation, |
| 21 | + Activities::Deposit, Activities::DepositCompensation, |
| 22 | + Activities::SomethingThatFails], |
| 23 | + workflows: [SagaWorkflow] |
| 24 | + ) |
| 25 | + worker.run do |
| 26 | + # Start workflow |
| 27 | + handle = env.client.start_workflow( |
| 28 | + SagaWorkflow, |
| 29 | + Saga::Activities::TransferDetails.new( |
| 30 | + amount: 100, |
| 31 | + from_account: 'acc1000', |
| 32 | + to_account: 'acc2000', |
| 33 | + reference_id: '1324' |
| 34 | + ), |
| 35 | + id: "wf-#{SecureRandom.uuid}", |
| 36 | + task_queue: worker.task_queue |
| 37 | + ) |
| 38 | + |
| 39 | + # Confirm it failed as expected |
| 40 | + err = assert_raises(Temporalio::Error::WorkflowFailedError) { handle.result } |
| 41 | + assert_instance_of(Temporalio::Error::ActivityError, err.cause) |
| 42 | + assert_instance_of(Temporalio::Error::ApplicationError, err.cause.cause) |
| 43 | + assert_equal('Simulated failure', err.cause.cause.message) |
| 44 | + |
| 45 | + # Confirm last two events are the compensations |
| 46 | + activity_events = handle.fetch_history_events.map(&:activity_task_scheduled_event_attributes).compact |
| 47 | + assert_equal('DepositCompensation', activity_events[-2].activity_type.name) |
| 48 | + assert_equal('WithdrawCompensation', activity_events[-1].activity_type.name) |
| 49 | + end |
| 50 | + end |
| 51 | + end |
| 52 | + end |
| 53 | +end |
0 commit comments