state_machines 0.202.0 → 0.305.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +226 -125
  3. data/lib/state_machines/branch.rb +56 -22
  4. data/lib/state_machines/callback.rb +28 -8
  5. data/lib/state_machines/core.rb +1 -0
  6. data/lib/state_machines/error.rb +50 -2
  7. data/lib/state_machines/eval_helpers.rb +31 -18
  8. data/lib/state_machines/event.rb +187 -4
  9. data/lib/state_machines/event_collection.rb +6 -1
  10. data/lib/state_machines/extensions.rb +22 -0
  11. data/lib/state_machines/helper_module.rb +1 -0
  12. data/lib/state_machines/machine/action_hooks.rb +13 -10
  13. data/lib/state_machines/machine/callbacks.rb +15 -0
  14. data/lib/state_machines/machine/class_methods.rb +34 -3
  15. data/lib/state_machines/machine/configuration.rb +12 -8
  16. data/lib/state_machines/machine/event_methods.rb +5 -0
  17. data/lib/state_machines/machine/helper_generators.rb +26 -11
  18. data/lib/state_machines/machine/state_methods.rb +4 -3
  19. data/lib/state_machines/machine/utilities.rb +25 -1
  20. data/lib/state_machines/machine.rb +62 -3
  21. data/lib/state_machines/machine_collection.rb +7 -6
  22. data/lib/state_machines/macro_methods.rb +4 -4
  23. data/lib/state_machines/node_collection.rb +26 -23
  24. data/lib/state_machines/path.rb +1 -0
  25. data/lib/state_machines/path_collection.rb +1 -0
  26. data/lib/state_machines/state.rb +66 -31
  27. data/lib/state_machines/state_collection.rb +10 -2
  28. data/lib/state_machines/state_context.rb +7 -1
  29. data/lib/state_machines/stdio_renderer.rb +8 -6
  30. data/lib/state_machines/syntax_validator.rb +3 -3
  31. data/lib/state_machines/test_helper.rb +309 -259
  32. data/lib/state_machines/transition.rb +136 -230
  33. data/lib/state_machines/transition_claim.rb +119 -0
  34. data/lib/state_machines/transition_collection.rb +147 -31
  35. data/lib/state_machines/version.rb +1 -1
  36. metadata +8 -15
  37. data/lib/state_machines/async_mode/async_event_extensions.rb +0 -49
  38. data/lib/state_machines/async_mode/async_events.rb +0 -286
  39. data/lib/state_machines/async_mode/async_machine.rb +0 -60
  40. data/lib/state_machines/async_mode/async_transition_collection.rb +0 -136
  41. data/lib/state_machines/async_mode/thread_safe_state.rb +0 -47
  42. data/lib/state_machines/async_mode.rb +0 -64
  43. data/lib/state_machines/machine/async_extensions.rb +0 -88
  44. data/lib/state_machines/machine/validation.rb +0 -39
@@ -53,9 +53,9 @@ module StateMachines
53
53
  end
54
54
 
55
55
  actual = object.send(name_method)
56
- default_message = "Expected #{object.class}##{machine_name} to be #{expected_state}, but was #{actual}"
56
+ default_message = "Expected #{object.class}##{machine_name} to be #{expected_state.inspect}, but was #{actual.inspect}"
57
57
 
58
- _sm_assert_equal(expected_state.to_s, actual.to_s, message || default_message)
58
+ _sm_assert(_sm_same_state?(expected_state, actual), message || default_message)
59
59
  end
60
60
 
61
61
  # Assert that an object can transition via a specific event
@@ -119,70 +119,94 @@ module StateMachines
119
119
 
120
120
  # === Extended State Machine Assertions ===
121
121
 
122
+ # Assert the machine's states, in any order. Names resolve through the
123
+ # machine ('parked' is :parked). The nil state is only listed when expected,
124
+ # since a machine without an initial state has one implicitly.
122
125
  def assert_sm_states_list(machine, expected_states, message = nil)
123
- actual_states = machine.states.map(&:name).compact
124
- default_message = "Expected states #{expected_states} but got #{actual_states}"
126
+ expected = expected_states.map { |state| machine.states[state]&.name || state }
127
+ actual = machine.states.map(&:name)
128
+ actual.compact! unless expected_states.include?(nil)
129
+ default_message = "Expected states #{expected.inspect} but got #{actual.inspect}"
125
130
 
126
- _sm_assert_equal(expected_states.sort, actual_states.sort, message || default_message)
131
+ _sm_assert_equal(expected.sort_by(&:inspect), actual.sort_by(&:inspect), message || default_message)
127
132
  end
128
133
 
129
134
  def refute_sm_state_defined(machine, state, message = nil)
130
- state_exists = machine.states.any? { |s| s.name == state }
131
- default_message = "Expected state #{state} to not be defined in machine"
135
+ default_message = "Expected state #{state.inspect} to not be defined in machine"
132
136
 
133
- _sm_refute(state_exists, message || default_message)
137
+ _sm_refute(machine.states[state], message || default_message)
134
138
  end
135
139
  alias assert_sm_state_not_defined refute_sm_state_defined
136
140
 
141
+ # @raise [IndexError] if +expected_state+ is not a known state
137
142
  def assert_sm_initial_state(machine, expected_state, message = nil)
138
- state_obj = machine.state(expected_state)
139
- is_initial = state_obj&.initial?
140
- default_message = "Expected state #{expected_state} to be the initial state"
143
+ state = machine.states.fetch(expected_state)
144
+ default_message = "Expected state #{state.name.inspect} to be the initial state"
141
145
 
142
- _sm_assert(is_initial, message || default_message)
146
+ _sm_assert(state.initial?, message || default_message)
143
147
  end
144
148
 
149
+ # @raise [IndexError] if +state+ is not a known state
145
150
  def assert_sm_final_state(machine, state, message = nil)
146
- state_obj = machine.states[state]
147
- is_final = state_obj&.final?
148
- default_message = "Expected state #{state} to be final"
151
+ state = machine.states.fetch(state)
152
+ default_message = "Expected state #{state.name.inspect} to be final"
149
153
 
150
- _sm_assert(is_final, message || default_message)
154
+ _sm_assert(state.final?, message || default_message)
151
155
  end
152
156
 
157
+ # Assert the set of states the machine's events can lead to from a state,
158
+ # ignoring guards. Each branch contributes the target it would pick for
159
+ # +from+ (a loopback contributes +from+ itself); order does not matter.
160
+ #
161
+ # @param machine [StateMachines::Machine] The state machine
162
+ # @param from [Symbol, String, nil] The source state
163
+ # @param expected_to_states [Array] The expected target states
164
+ # @param message [String, nil] Custom failure message
165
+ # @raise [IndexError] if +from+ or an expected state is not a known state
153
166
  def assert_sm_possible_transitions(machine, from:, expected_to_states:, message: nil)
154
- actual_transitions = machine.events.flat_map do |event|
155
- event.branches.select { |branch| branch.known_states.include?(from) }
156
- .map(&:to)
167
+ from = machine.states.fetch(from).name
168
+ names = machine.states.map(&:name)
169
+ expected = expected_to_states.map { |state| machine.states.fetch(state).name }.uniq
170
+ actual = machine.events.flat_map do |event|
171
+ event.branches.flat_map { |branch| _sm_branch_targets(branch, from, names) }
157
172
  end.uniq
158
- default_message = "Expected transitions from #{from} to #{expected_to_states} but got #{actual_transitions}"
173
+ by_definition = ->(name) { names.index(name) }
174
+ default_message = "Expected transitions from #{from.inspect} to #{expected.inspect} but got #{actual.inspect}"
159
175
 
160
- _sm_assert_equal(expected_to_states.sort, actual_transitions.sort, message || default_message)
176
+ _sm_assert_equal(expected.sort_by(&by_definition), actual.sort_by(&by_definition), message || default_message)
161
177
  end
162
178
 
179
+ # Refute that an event has a branch from +from+ to +to+, ignoring guards.
180
+ #
181
+ # @raise [IndexError] if +on+, +from+ or +to+ is unknown
163
182
  def refute_sm_transition_allowed(machine, from:, to:, on:, message: nil)
164
- event = machine.events[on]
165
- is_allowed = event&.branches&.any? { |branch| branch.known_states.include?(from) && branch.to == to }
166
- default_message = "Expected transition from #{from} to #{to} on #{on} to not be allowed"
183
+ event = machine.events.fetch(on)
184
+ from = machine.states.fetch(from).name
185
+ to = machine.states.fetch(to).name
186
+ names = machine.states.map(&:name)
187
+ is_allowed = event.branches.any? { |branch| _sm_branch_targets(branch, from, names) == [to] }
188
+ default_message = "Expected transition from #{from.inspect} to #{to.inspect} on #{event.name.inspect} to not be allowed"
167
189
 
168
190
  _sm_refute(is_allowed, message || default_message)
169
191
  end
170
192
  alias assert_sm_transition_not_allowed refute_sm_transition_allowed
171
193
 
172
194
  def assert_sm_event_triggers(object, event, machine_name = :state, message = nil)
173
- initial_state = object.send(machine_name)
195
+ machine = object.class.state_machine(machine_name)
196
+ initial_state = machine.read(object, :state)
174
197
  object.send("#{event}!")
175
- state_changed = initial_state != object.send(machine_name)
198
+ state_changed = initial_state != machine.read(object, :state)
176
199
  default_message = "Expected event #{event} to trigger state change on #{machine_name}"
177
200
 
178
201
  _sm_assert(state_changed, message || default_message)
179
202
  end
180
203
 
181
204
  def refute_sm_event_triggers(object, event, machine_name = :state, message = nil)
182
- initial_state = object.send(machine_name)
205
+ machine = object.class.state_machine(machine_name)
206
+ initial_state = machine.read(object, :state)
183
207
  begin
184
208
  object.send("#{event}!")
185
- state_unchanged = initial_state == object.send(machine_name)
209
+ state_unchanged = initial_state == machine.read(object, :state)
186
210
  default_message = "Expected event #{event} to not trigger state change on #{machine_name}"
187
211
 
188
212
  _sm_assert(state_unchanged, message || default_message)
@@ -271,15 +295,14 @@ module StateMachines
271
295
  # # Specific machine
272
296
  # assert_sm_triggers_event(vehicle, :disable, machine_name: :alarm) { vehicle.turn_off_alarm }
273
297
  def assert_sm_triggers_event(object, expected_events, machine_name: :state, message: nil)
274
- expected_events = Array(expected_events)
275
298
  triggered_events = []
276
299
 
277
300
  # Get the state machine
278
301
  machine = object.class.state_machines[machine_name]
279
302
  raise ArgumentError, "No state machine found for #{machine_name}" unless machine
280
303
 
281
- # Save original callbacks to restore later
282
- machine.callbacks[:before].dup
304
+ # Resolve the names ('crash' is :crash); an unknown event raises IndexError
305
+ expected_events = Array(expected_events).map { |event| machine.events.fetch(event).name }
283
306
 
284
307
  # Add a temporary callback to track triggered events
285
308
  temp_callback = machine.before_transition do |_obj, transition|
@@ -346,74 +369,9 @@ module StateMachines
346
369
  _assert_transition_callback(:after, machine_or_class, options, message)
347
370
  end
348
371
 
349
- # === Sync Mode Assertions ===
350
-
351
- # Assert that a state machine is operating in synchronous mode
352
- #
353
- # @param object [Object] The object with state machines
354
- # @param machine_name [Symbol] The name of the state machine (defaults to :state)
355
- # @param message [String, nil] Custom failure message
356
- # @return [void]
357
- # @raise [AssertionError] If the machine has async mode enabled
358
- #
359
- # @example
360
- # user = User.new
361
- # assert_sm_sync_mode(user) # Uses default :state machine
362
- # assert_sm_sync_mode(user, :status) # Uses :status machine
363
- def assert_sm_sync_mode(object, machine_name = :state, message = nil)
364
- machine = object.class.state_machines[machine_name]
365
- raise ArgumentError, "No state machine '#{machine_name}' found" unless machine
366
-
367
- async_enabled = machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
368
- default_message = "Expected state machine '#{machine_name}' to be in sync mode, but async mode is enabled"
369
-
370
- _sm_refute(async_enabled, message || default_message)
371
- end
372
-
373
- # Assert that async methods are not available on a sync-only object
374
- #
375
- # @param object [Object] The object with state machines
376
- # @param message [String, nil] Custom failure message
377
- # @return [void]
378
- # @raise [AssertionError] If async methods are available
379
- #
380
- # @example
381
- # sync_only_car = Car.new # Car has no async: true machines
382
- # assert_sm_no_async_methods(sync_only_car)
383
- def assert_sm_no_async_methods(object, message = nil)
384
- async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
385
- available_async_methods = async_methods.select { |method| object.respond_to?(method) }
386
-
387
- default_message = "Expected no async methods to be available, but found: #{available_async_methods.inspect}"
388
-
389
- _sm_assert_empty(available_async_methods, message || default_message)
390
- end
391
-
392
- # Assert that an object has no async-enabled state machines
393
- #
394
- # @param object [Object] The object with state machines
395
- # @param message [String, nil] Custom failure message
396
- # @return [void]
397
- # @raise [AssertionError] If any machine has async mode enabled
398
- #
399
- # @example
400
- # sync_only_vehicle = Vehicle.new # All machines are sync-only
401
- # assert_sm_all_sync(sync_only_vehicle)
402
- def assert_sm_all_sync(object, message = nil)
403
- async_machines = []
404
-
405
- object.class.state_machines.each do |name, machine|
406
- if machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
407
- async_machines << name
408
- end
409
- end
372
+ # === Execution Assertions ===
410
373
 
411
- default_message = "Expected all state machines to be sync-only, but these have async enabled: #{async_machines.inspect}"
412
-
413
- _sm_assert_empty(async_machines, message || default_message)
414
- end
415
-
416
- # Assert that synchronous event execution works correctly
374
+ # Assert that firing a bang event transitions to the expected state
417
375
  #
418
376
  # @param object [Object] The object with state machines
419
377
  # @param event [Symbol] The event to trigger
@@ -434,177 +392,258 @@ module StateMachines
434
392
  # Execute event synchronously
435
393
  result = object.send("#{event}!")
436
394
 
437
- # Verify immediate state change (no async delay)
395
+ # Verify the state changed by the time the event returned
438
396
  final_state = object.send(machine_name)
439
397
 
440
398
  # Check that transition succeeded
441
399
  state_changed = initial_state != final_state
442
- correct_final_state = final_state.to_s == expected_state.to_s
400
+ correct_final_state = _sm_same_state?(expected_state, final_state)
443
401
 
444
402
  default_message = "Expected sync execution of '#{event}' to change #{machine_name} from '#{initial_state}' to '#{expected_state}', but got '#{final_state}'"
445
403
 
446
- _sm_assert(result, "Event #{event} should return true on success")
404
+ _sm_assert(result, "Event #{event} should return the performed transition on success, but returned #{result.inspect}")
447
405
  _sm_assert(state_changed, "State should change from #{initial_state}")
448
406
  _sm_assert(correct_final_state, message || default_message)
449
407
  end
450
408
 
451
- # Assert that event execution is immediate (no async delay)
409
+ # Assert that event execution is immediate: the state has changed when the
410
+ # bang event returns, and it returned the performed transition rather than
411
+ # something to wait on. Decided by what the call did, not by how long it
412
+ # took, so a slow runner (a cold JIT) cannot fail it.
452
413
  #
453
414
  # @param object [Object] The object with state machines
454
415
  # @param event [Symbol] The event to trigger
455
416
  # @param machine_name [Symbol] The name of the state machine (defaults to :state)
456
417
  # @param message [String, nil] Custom failure message
457
418
  # @return [void]
458
- # @raise [AssertionError] If execution appears to be async
419
+ # @raise [AssertionError] If the event did not complete before returning
459
420
  #
460
421
  # @example
461
422
  # car = Car.new
462
423
  # assert_sm_immediate_execution(car, :start)
463
424
  def assert_sm_immediate_execution(object, event, machine_name = :state, message = nil)
464
425
  initial_state = object.send(machine_name)
465
-
466
- # Record start time and execute
467
- start_time = Time.now
468
- object.send("#{event}!")
469
- execution_time = Time.now - start_time
470
-
426
+ result = object.send("#{event}!")
471
427
  final_state = object.send(machine_name)
472
- state_changed = initial_state != final_state
473
-
474
- # Should complete very quickly (under 10ms for sync operations)
475
- is_immediate = execution_time < 0.01
476
428
 
477
- default_message = "Expected immediate sync execution of '#{event}', but took #{execution_time}s (likely async)"
429
+ default_message = "Expected immediate execution of '#{event}' to return the performed transition, but it returned #{result.class}"
478
430
 
479
- _sm_assert(state_changed, 'Event should trigger state change')
480
- _sm_assert(is_immediate, message || default_message)
431
+ _sm_assert(initial_state != final_state, message || "Event #{event} should change #{machine_name} before returning")
432
+ _sm_assert(result.is_a?(StateMachines::Transition), message || default_message)
481
433
  end
482
434
 
483
- # === Async Mode Assertions ===
435
+ # === Refusal Reason Assertions ===
436
+
437
+ # The reasons an event can be refused for
438
+ #
439
+ # @see StateMachines::Event#refusal
440
+ REFUSAL_REASONS = %i[no_transition guard halted action_failed contended].freeze
484
441
 
485
- # Assert that a state machine is operating in asynchronous mode
442
+ # Assert that firing an event is refused, leaving the machine's state unchanged
443
+ #
444
+ # Fires the non-bang event method, which must return false. When a reason is
445
+ # given, the refusal recorded for the event must equal it.
486
446
  #
487
447
  # @param object [Object] The object with state machines
448
+ # @param event [Symbol] The event name (plain or namespace-qualified)
449
+ # @param reason [Symbol, nil] The expected refusal reason, or nil to accept any
488
450
  # @param machine_name [Symbol] The name of the state machine (defaults to :state)
489
451
  # @param message [String, nil] Custom failure message
490
- # @return [void]
491
- # @raise [AssertionError] If the machine doesn't have async mode enabled
452
+ # @return [Symbol, nil] The recorded refusal reason
453
+ # @raise [ArgumentError] If the reason is not a known refusal reason
454
+ # @raise [AssertionError] If the event succeeds, changes the state, or is refused for another reason
492
455
  #
493
456
  # @example
494
- # drone = AutonomousDrone.new
495
- # assert_sm_async_mode(drone) # Uses default :state machine
496
- # assert_sm_async_mode(drone, :teleporter_status) # Uses :teleporter_status machine
497
- def assert_sm_async_mode(object, machine_name = :state, message = nil)
498
- machine = object.class.state_machines[machine_name]
499
- raise ArgumentError, "No state machine '#{machine_name}' found" unless machine
500
-
501
- async_enabled = machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
502
- default_message = "Expected state machine '#{machine_name}' to have async mode enabled, but it's in sync mode"
457
+ # vehicle = Vehicle.new # parked
458
+ # assert_sm_refused(vehicle, :park) # Any reason
459
+ # assert_sm_refused(vehicle, :park, :no_transition) # Specific reason
460
+ # assert_sm_refused(vehicle, :enable, :guard, machine_name: :alarm_state)
461
+ def assert_sm_refused(object, event, reason = nil, machine_name: :state, message: nil)
462
+ _sm_validate_refusal_reason(reason) if reason
463
+ machine, event_obj = _sm_find_event(object, event, machine_name)
464
+
465
+ state_before = machine.read(object, :state)
466
+ result = object.public_send(event_obj.qualified_name)
467
+ state_after = machine.read(object, :state)
468
+ actual = event_obj.refusal(object)
469
+
470
+ unless result == false
471
+ outcome = result.is_a?(StateMachines::Transition) ? "it transitioned #{result.from_name.inspect} -> #{result.to_name.inspect}" : "it returned #{result.inspect}"
472
+ _sm_flunk(message || "Expected :#{event_obj.qualified_name} on #{machine.name} to be refused, but #{outcome}")
473
+ end
474
+ _sm_assert(state_before == state_after,
475
+ message || "Expected a refused :#{event_obj.qualified_name} to leave #{machine.name} at #{state_before.inspect}, but it became #{state_after.inspect}")
476
+ if reason
477
+ _sm_assert_equal(reason, actual,
478
+ message || "Expected :#{event_obj.qualified_name} on #{machine.name} to be refused for #{reason.inspect}, but was refused for #{actual.inspect}")
479
+ end
503
480
 
504
- _sm_assert(async_enabled, message || default_message)
481
+ actual
505
482
  end
506
483
 
507
- # Assert that async methods are available on an async-enabled object
484
+ # Assert that the most recent attempt to fire an event was refused for the expected reason
485
+ #
486
+ # Reads the recorded refusal without firing the event.
508
487
  #
509
488
  # @param object [Object] The object with state machines
489
+ # @param event [Symbol] The event name (plain or namespace-qualified)
490
+ # @param expected_reason [Symbol] The expected refusal reason
491
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
510
492
  # @param message [String, nil] Custom failure message
511
- # @return [void]
512
- # @raise [AssertionError] If async methods are not available
493
+ # @return [Symbol] The recorded refusal reason
494
+ # @raise [ArgumentError] If the reason is not a known refusal reason
495
+ # @raise [AssertionError] If the recorded reason differs
513
496
  #
514
497
  # @example
515
- # drone = AutonomousDrone.new # Has async: true machines
516
- # assert_sm_async_methods(drone)
517
- def assert_sm_async_methods(object, message = nil)
518
- async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
519
- available_async_methods = async_methods.select { |method| object.respond_to?(method) }
520
-
521
- default_message = "Expected async methods to be available, but found none"
498
+ # vehicle.park
499
+ # assert_sm_refusal(vehicle, :park, :no_transition)
500
+ def assert_sm_refusal(object, event, expected_reason, machine_name: :state, message: nil)
501
+ _sm_validate_refusal_reason(expected_reason)
502
+ machine, event_obj = _sm_find_event(object, event, machine_name)
503
+ actual = event_obj.refusal(object)
504
+ default_message = "Expected the last :#{event_obj.qualified_name} on #{machine.name} to be refused for #{expected_reason.inspect}, but #{actual ? "it was refused for #{actual.inspect}" : 'no refusal was recorded'}"
522
505
 
523
- _sm_refute_empty(available_async_methods, message || default_message)
506
+ _sm_assert_equal(expected_reason, actual, message || default_message)
507
+ actual
524
508
  end
525
509
 
526
- # Assert that an object has async-enabled state machines
510
+ # Assert that the most recent attempt to fire an event recorded no refusal
511
+ #
512
+ # Reads the recorded refusal without firing the event. Passes after a
513
+ # success, or when the event was never fired.
527
514
  #
528
515
  # @param object [Object] The object with state machines
529
- # @param machine_names [Array<Symbol>] Expected async machine names
516
+ # @param event [Symbol] The event name (plain or namespace-qualified)
517
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
530
518
  # @param message [String, nil] Custom failure message
531
519
  # @return [void]
532
- # @raise [AssertionError] If expected machines don't have async mode
520
+ # @raise [AssertionError] If a refusal is recorded
533
521
  #
534
522
  # @example
535
- # drone = AutonomousDrone.new
536
- # assert_sm_has_async(drone, [:status, :teleporter_status, :shields])
537
- def assert_sm_has_async(object, machine_names = nil, message = nil)
538
- if machine_names
539
- # Check specific machines
540
- non_async_machines = machine_names.reject do |name|
541
- machine = object.class.state_machines[name]
542
- machine&.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
543
- end
544
-
545
- default_message = "Expected machines #{machine_names.inspect} to have async enabled, but these don't: #{non_async_machines.inspect}"
546
-
547
- _sm_assert_empty(non_async_machines, message || default_message)
548
- else
549
- # Check that at least one machine has async
550
- async_machines = object.class.state_machines.select do |name, machine|
551
- machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
552
- end
553
-
554
- default_message = "Expected at least one state machine to have async enabled, but none found"
523
+ # vehicle.ignite
524
+ # refute_sm_refusal(vehicle, :ignite)
525
+ def refute_sm_refusal(object, event, machine_name: :state, message: nil)
526
+ machine, event_obj = _sm_find_event(object, event, machine_name)
527
+ actual = event_obj.refusal(object)
528
+ default_message = "Expected no refusal for the last :#{event_obj.qualified_name} on #{machine.name}, but it was refused for #{actual.inspect}"
555
529
 
556
- _sm_refute_empty(async_machines, message || default_message)
557
- end
530
+ _sm_assert_nil(actual, message || default_message)
558
531
  end
532
+ alias assert_sm_no_refusal refute_sm_refusal
559
533
 
560
- # Assert that individual async event methods are available
534
+ # Assert that the bang event method raises StateMachines::InvalidTransition with the expected reason
561
535
  #
562
536
  # @param object [Object] The object with state machines
563
- # @param event [Symbol] The event name
537
+ # @param event [Symbol] The event name (plain or namespace-qualified)
538
+ # @param expected_reason [Symbol] The expected StateMachines::InvalidTransition#reason
539
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
564
540
  # @param message [String, nil] Custom failure message
565
- # @return [void]
566
- # @raise [AssertionError] If async event methods are not available
541
+ # @return [StateMachines::InvalidTransition] The raised error
542
+ # @raise [ArgumentError] If the reason is not a known refusal reason
543
+ # @raise [AssertionError] If nothing is raised or the reason differs
567
544
  #
568
545
  # @example
569
- # drone = AutonomousDrone.new
570
- # assert_sm_async_event_methods(drone, :launch) # Checks launch_async and launch_async!
571
- def assert_sm_async_event_methods(object, event, message = nil)
572
- async_method = "#{event}_async".to_sym
573
- async_bang_method = "#{event}_async!".to_sym
546
+ # assert_sm_raises_refusal(vehicle, :park, :no_transition)
547
+ def assert_sm_raises_refusal(object, event, expected_reason, machine_name: :state, message: nil)
548
+ _sm_validate_refusal_reason(expected_reason)
549
+ machine, event_obj = _sm_find_event(object, event, machine_name)
550
+ bang = "#{event_obj.qualified_name}!"
574
551
 
575
- has_async = object.respond_to?(async_method)
576
- has_async_bang = object.respond_to?(async_bang_method)
552
+ error = _sm_capture_error(StateMachines::InvalidTransition) { object.public_send(bang) }
553
+ _sm_flunk(message || "Expected #{bang} on #{machine.name} to raise StateMachines::InvalidTransition, but nothing was raised") unless error
577
554
 
578
-
579
- _sm_assert(has_async, "Missing #{async_method} method")
580
- _sm_assert(has_async_bang, "Missing #{async_bang_method} method")
555
+ _sm_assert_equal(expected_reason, error.reason,
556
+ message || "Expected #{bang} on #{machine.name} to be refused for #{expected_reason.inspect}, but was refused for #{error.reason.inspect}")
557
+ error
581
558
  end
582
559
 
583
- # Assert that an object has thread-safe state methods when async is enabled
560
+ # Assert that firing events in parallel is refused with the expected reasons
561
+ #
562
+ # +fire_events+ must return false, and +fire_events!+ must raise
563
+ # StateMachines::InvalidParallelTransition whose #reasons equals the
564
+ # expected Hash. Only the events that caused the refusal carry a reason.
584
565
  #
585
566
  # @param object [Object] The object with state machines
567
+ # @param events [Array<Symbol>] The (qualified) event names to fire together
568
+ # @param expected_reasons [Hash{Symbol => Symbol}] The expected reason per event
586
569
  # @param message [String, nil] Custom failure message
587
- # @return [void]
588
- # @raise [AssertionError] If thread-safe methods are not available
570
+ # @return [StateMachines::InvalidParallelTransition] The raised error
571
+ # @raise [ArgumentError] If a reason is not a known refusal reason
572
+ # @raise [AssertionError] If the events are not refused or the reasons differ
589
573
  #
590
574
  # @example
591
- # drone = AutonomousDrone.new
592
- # assert_sm_thread_safe_methods(drone)
593
- def assert_sm_thread_safe_methods(object, message = nil)
594
- thread_safe_methods = %i[state_machine_mutex read_state_safely write_state_safely]
595
- missing_methods = thread_safe_methods.reject { |method| object.respond_to?(method) }
575
+ # assert_sm_parallel_refused(vehicle, %i[ignite enable_alarm], { enable_alarm: :no_transition })
576
+ def assert_sm_parallel_refused(object, events, expected_reasons, message: nil)
577
+ raise ArgumentError, "Expected reasons must be a Hash of event => reason, got #{expected_reasons.inspect}" unless expected_reasons.is_a?(Hash)
596
578
 
597
- default_message = "Expected thread-safe methods to be available, but missing: #{missing_methods.inspect}"
579
+ expected_reasons.each_value { |reason| _sm_validate_refusal_reason(reason) }
580
+ events = Array(events)
598
581
 
599
- _sm_assert_empty(missing_methods, message || default_message)
582
+ result = object.fire_events(*events)
583
+ _sm_flunk(message || "Expected fire_events(#{events.map(&:inspect).join(', ')}) to be refused, but it returned #{result.inspect}") unless result == false
584
+
585
+ error = _sm_capture_error(StateMachines::InvalidParallelTransition) { object.fire_events!(*events) }
586
+ _sm_flunk(message || "Expected fire_events!(#{events.map(&:inspect).join(', ')}) to raise StateMachines::InvalidParallelTransition, but nothing was raised") unless error
587
+
588
+ _sm_assert_equal(expected_reasons, error.reasons,
589
+ message || "Expected fire_events!(#{events.map(&:inspect).join(', ')}) to be refused for #{expected_reasons.inspect}, but was refused for #{error.reasons.inspect}")
590
+ error
600
591
  end
601
592
 
602
593
  # RSpec-style aliases for event triggering (for consistency with RSpec expectations)
603
594
  alias expect_to_trigger_event assert_sm_triggers_event
604
595
  alias have_triggered_event assert_sm_triggers_event
605
596
 
597
+ # RSpec-style aliases for refusal reasons
598
+ alias expect_to_be_refused assert_sm_refused
599
+ alias expect_refusal assert_sm_refusal
600
+ alias expect_no_refusal refute_sm_refusal
601
+ alias expect_to_raise_refusal assert_sm_raises_refusal
602
+ alias expect_parallel_refused assert_sm_parallel_refused
603
+
606
604
  private
607
605
 
606
+ # Compares a state name or value with an expected state, treating a
607
+ # String and its Symbol as equal. nil only equals nil: comparing by to_s
608
+ # alone would make the nil state and a state named :"" indistinguishable.
609
+ def _sm_same_state?(expected, actual)
610
+ expected.nil? || actual.nil? ? expected.nil? && actual.nil? : expected.to_s == actual.to_s
611
+ end
612
+
613
+ # Finds the machine and its event, accepting the plain or the
614
+ # namespace-qualified event name, and raising when either is missing
615
+ def _sm_find_event(object, event, machine_name)
616
+ machine = object.class.state_machines[machine_name] if object.class.respond_to?(:state_machines)
617
+ unless machine
618
+ available = object.class.respond_to?(:state_machines) ? object.class.state_machines.keys : []
619
+ raise ArgumentError, "No state machine '#{machine_name}' found. Available machines: #{available.inspect}"
620
+ end
621
+
622
+ event_obj = machine.events[event.to_sym] || machine.events[event.to_sym, :qualified_name]
623
+ return [machine, event_obj] if event_obj
624
+
625
+ raise ArgumentError, "No event :#{event} found on machine :#{machine_name}. Available events: #{machine.events.map(&:qualified_name).inspect}"
626
+ end
627
+
628
+ # Raises a descriptive ArgumentError for an unknown refusal reason, so a
629
+ # typo in the expectation is not reported as a failed refusal
630
+ def _sm_validate_refusal_reason(reason)
631
+ return if REFUSAL_REASONS.include?(reason)
632
+
633
+ suggestion = DidYouMean::SpellChecker.new(dictionary: REFUSAL_REASONS).correct(reason.to_s).first if defined?(DidYouMean::SpellChecker)
634
+ hint = suggestion ? " Did you mean #{suggestion.inspect}?" : ''
635
+ raise ArgumentError, "Unknown refusal reason #{reason.inspect}.#{hint} Valid reasons: #{REFUSAL_REASONS.inspect}"
636
+ end
637
+
638
+ # Runs the block and returns the error of the given class it raised, or
639
+ # nil when it raised nothing; other errors propagate
640
+ def _sm_capture_error(error_class)
641
+ yield
642
+ nil
643
+ rescue error_class => e
644
+ e
645
+ end
646
+
608
647
  # Finds the can_<event>? method for the event, trying both the default and
609
648
  # namespaced naming patterns, and raising when neither exists
610
649
  def _sm_find_can_method(object, event, machine_name)
@@ -653,6 +692,16 @@ module StateMachines
653
692
  end
654
693
  end
655
694
 
695
+ def _sm_assert_nil(value, message)
696
+ if defined?(::Minitest)
697
+ assert_nil value, message
698
+ elsif defined?(::RSpec)
699
+ expect(value).to be_nil, message
700
+ else
701
+ raise message unless value.nil?
702
+ end
703
+ end
704
+
656
705
  def _sm_assert_empty(collection, message)
657
706
  if defined?(::Minitest)
658
707
  assert_empty collection, message
@@ -679,80 +728,81 @@ module StateMachines
679
728
  assert false, message
680
729
  end
681
730
 
731
+ # The target a branch would pick from +from+ (as Event#transition_for
732
+ # does, ignoring guards), as [] or [target]. first(1), not first: a
733
+ # transition into the nil state must not read as none.
734
+ def _sm_branch_targets(branch, from, names)
735
+ requirement = branch.state_requirements.detect { |candidate| candidate[:from].matches?(from) }
736
+ return [] unless requirement
737
+
738
+ requirement[:to].is_a?(LoopbackMatcher) ? [from] : requirement[:to].filter([from] | names).first(1)
739
+ end
740
+
741
+ # Whether a callback's from/to requirement admits the expected states. A
742
+ # loopback (same) lands where it left, so without an expected source the
743
+ # source is the target itself.
744
+ def _sm_state_requirement_matches?(requirement, states)
745
+ loopback = requirement[:to].is_a?(LoopbackMatcher)
746
+ from = states.key?(:from) ? states[:from] : states[:to]
747
+ return false if (states.key?(:from) || loopback) && !requirement[:from].matches?(from)
748
+
749
+ !states.key?(:to) || requirement[:to].matches?(states[:to], from: from)
750
+ end
751
+
752
+ # Whether every expected callable (one or an Array) is among the defined
753
+ # ones. Method names compare as String/Symbol alike; anything else, such as
754
+ # a lambda, only matches itself.
755
+ def _sm_includes_callables?(defined, expected)
756
+ defined = Array(defined)
757
+ name = ->(value) { value.is_a?(Symbol) || value.is_a?(String) }
758
+ Array(expected).all? do |wanted|
759
+ defined.any? do |candidate|
760
+ name.call(candidate) && name.call(wanted) ? candidate.to_s == wanted.to_s : candidate.equal?(wanted)
761
+ end
762
+ end
763
+ end
764
+
682
765
  # Internal helper for checking transition callbacks
683
766
  def _assert_transition_callback(callback_type, machine_or_class, options, message)
684
767
  # Get the machine
685
768
  machine = machine_or_class.is_a?(StateMachines::Machine) ? machine_or_class : machine_or_class.state_machine
686
769
  raise ArgumentError, 'No state machine found' unless machine
687
770
 
688
- callbacks = machine.callbacks[callback_type] || []
771
+ # Each candidate is [callback, branch it is matched against]: a
772
+ # machine-wide callback has its own branch; a transition's before: /
773
+ # around: / after: callback is matched against that transition branch
774
+ # (its event, states and guards). Before includes around, as the
775
+ # machine keeps both in one chain.
776
+ branch_types = callback_type == :before ? %i[before around] : [callback_type]
777
+ candidates = (machine.callbacks[callback_type] || []).map { |callback| [callback, callback.branch] }
778
+ machine.events.each do |event|
779
+ event.branches.each do |branch|
780
+ branch.callbacks.each { |callback| candidates << [callback, branch] if branch_types.include?(callback.type) }
781
+ end
782
+ end
689
783
 
690
- # Extract expected conditions
691
- expected_event = options[:on]
692
- expected_from = options[:from]
693
- expected_to = options[:to]
784
+ # Extract expected conditions. States and events resolve to their
785
+ # canonical names first, since the branch matchers compare those: a raw
786
+ # 'parked' would never equal :parked, and would pass any all - :parked.
787
+ # An unknown name raises IndexError.
788
+ expected_event = machine.events.fetch(options[:on]).name if options.key?(:on)
789
+ states = options.slice(:from, :to).transform_values { |state| machine.states.fetch(state).name }
790
+ expected_from = states[:from]
791
+ expected_to = states[:to]
694
792
  expected_method = options[:do]
695
793
  expected_if = options[:if]
696
794
  expected_unless = options[:unless]
697
795
 
698
- # Find matching callback
699
- matching_callback = callbacks.find do |callback|
700
- branch = callback.branch
701
-
702
- # Check event requirement
703
- if expected_event
704
- event_requirement = branch.event_requirement
705
- event_matches = if event_requirement && event_requirement.respond_to?(:values)
706
- event_requirement.values.include?(expected_event)
707
- else
708
- false
709
- end
710
- next false unless event_matches
711
- end
712
-
713
- # Check state requirements (from/to)
714
- if expected_from || expected_to
715
- state_matches = false
716
- branch.state_requirements.each do |req|
717
- from_matches = !expected_from || (req[:from] && req[:from].respond_to?(:values) && req[:from].values.include?(expected_from))
718
- to_matches = !expected_to || (req[:to] && req[:to].respond_to?(:values) && req[:to].values.include?(expected_to))
719
-
720
- if from_matches && to_matches
721
- state_matches = true
722
- break
723
- end
724
- end
725
- next false unless state_matches
726
- end
727
-
728
- # Check method requirement
729
- if expected_method
730
- methods = callback.instance_variable_get(:@methods) || []
731
- method_matches = methods.any? do |method|
732
- (method.is_a?(Symbol) && method == expected_method) ||
733
- (method.is_a?(String) && method.to_sym == expected_method) ||
734
- (method.respond_to?(:call) && method.respond_to?(:source_location))
735
- end
736
- next false unless method_matches
737
- end
738
-
739
- # Check if condition
740
- if expected_if
741
- if_condition = branch.if_condition
742
- if_matches = (if_condition.is_a?(Symbol) && if_condition == expected_if) ||
743
- (if_condition.is_a?(String) && if_condition.to_sym == expected_if) ||
744
- if_condition.respond_to?(:call)
745
- next false unless if_matches
746
- end
747
-
748
- # Check unless condition
749
- if expected_unless
750
- unless_condition = branch.unless_condition
751
- unless_matches = (unless_condition.is_a?(Symbol) && unless_condition == expected_unless) ||
752
- (unless_condition.is_a?(String) && unless_condition.to_sym == expected_unless) ||
753
- unless_condition.respond_to?(:call)
754
- next false unless unless_matches
755
- end
796
+ # Find matching callback. Requirements are checked with the matchers'
797
+ # own matches?, so all / all - [...] / same behave as they do at runtime,
798
+ # and an expected nil state is an expectation, not an omission.
799
+ matching_callback = candidates.find do |(callback, branch)|
800
+ next false if options.key?(:on) && !branch.event_requirement.matches?(expected_event)
801
+ next false if states.any? &&
802
+ branch.state_requirements.none? { |requirement| _sm_state_requirement_matches?(requirement, states) }
803
+ next false if options.key?(:do) && !_sm_includes_callables?(callback.callables, expected_method)
804
+ next false if options.key?(:if) && !_sm_includes_callables?(branch.if_condition, expected_if)
805
+ next false if options.key?(:unless) && !_sm_includes_callables?(branch.unless_condition, expected_unless)
756
806
 
757
807
  true
758
808
  end
@@ -760,12 +810,12 @@ module StateMachines
760
810
  return if matching_callback
761
811
 
762
812
  expected_parts = []
763
- expected_parts << "on: #{expected_event.inspect}" if expected_event
764
- expected_parts << "from: #{expected_from.inspect}" if expected_from
765
- expected_parts << "to: #{expected_to.inspect}" if expected_to
766
- expected_parts << "do: #{expected_method.inspect}" if expected_method
767
- expected_parts << "if: #{expected_if.inspect}" if expected_if
768
- expected_parts << "unless: #{expected_unless.inspect}" if expected_unless
813
+ expected_parts << "on: #{expected_event.inspect}" if options.key?(:on)
814
+ expected_parts << "from: #{expected_from.inspect}" if options.key?(:from)
815
+ expected_parts << "to: #{expected_to.inspect}" if options.key?(:to)
816
+ expected_parts << "do: #{expected_method.inspect}" if options.key?(:do)
817
+ expected_parts << "if: #{expected_if.inspect}" if options.key?(:if)
818
+ expected_parts << "unless: #{expected_unless.inspect}" if options.key?(:unless)
769
819
 
770
820
  default_message = "Expected #{callback_type}_transition callback with #{expected_parts.join(', ')} to be defined, but it was not found"
771
821