state_machines 0.201.0 → 0.300.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.
@@ -443,7 +443,7 @@ module StateMachines
443
443
 
444
444
  default_message = "Expected sync execution of '#{event}' to change #{machine_name} from '#{initial_state}' to '#{expected_state}', but got '#{final_state}'"
445
445
 
446
- _sm_assert(result, "Event #{event} should return true on success")
446
+ _sm_assert(result, "Event #{event} should return the performed transition on success, but returned #{result.inspect}")
447
447
  _sm_assert(state_changed, "State should change from #{initial_state}")
448
448
  _sm_assert(correct_final_state, message || default_message)
449
449
  end
@@ -599,12 +599,211 @@ module StateMachines
599
599
  _sm_assert_empty(missing_methods, message || default_message)
600
600
  end
601
601
 
602
+ # === Refusal Reason Assertions ===
603
+
604
+ # The reasons an event can be refused for
605
+ #
606
+ # @see StateMachines::Event#refusal
607
+ REFUSAL_REASONS = %i[no_transition guard halted action_failed contended].freeze
608
+
609
+ # Assert that firing an event is refused, leaving the machine's state unchanged
610
+ #
611
+ # Fires the non-bang event method, which must return false. When a reason is
612
+ # given, the refusal recorded for the event must equal it.
613
+ #
614
+ # @param object [Object] The object with state machines
615
+ # @param event [Symbol] The event name (plain or namespace-qualified)
616
+ # @param reason [Symbol, nil] The expected refusal reason, or nil to accept any
617
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
618
+ # @param message [String, nil] Custom failure message
619
+ # @return [Symbol, nil] The recorded refusal reason
620
+ # @raise [ArgumentError] If the reason is not a known refusal reason
621
+ # @raise [AssertionError] If the event succeeds, changes the state, or is refused for another reason
622
+ #
623
+ # @example
624
+ # vehicle = Vehicle.new # parked
625
+ # assert_sm_refused(vehicle, :park) # Any reason
626
+ # assert_sm_refused(vehicle, :park, :no_transition) # Specific reason
627
+ # assert_sm_refused(vehicle, :enable, :guard, machine_name: :alarm_state)
628
+ def assert_sm_refused(object, event, reason = nil, machine_name: :state, message: nil)
629
+ _sm_validate_refusal_reason(reason) if reason
630
+ machine, event_obj = _sm_find_event(object, event, machine_name)
631
+
632
+ state_before = machine.read(object, :state)
633
+ result = object.public_send(event_obj.qualified_name)
634
+ state_after = machine.read(object, :state)
635
+ actual = event_obj.refusal(object)
636
+
637
+ unless result == false
638
+ outcome = result.is_a?(StateMachines::Transition) ? "it transitioned #{result.from_name.inspect} -> #{result.to_name.inspect}" : "it returned #{result.inspect}"
639
+ _sm_flunk(message || "Expected :#{event_obj.qualified_name} on #{machine.name} to be refused, but #{outcome}")
640
+ end
641
+ _sm_assert(state_before == state_after,
642
+ message || "Expected a refused :#{event_obj.qualified_name} to leave #{machine.name} at #{state_before.inspect}, but it became #{state_after.inspect}")
643
+ if reason
644
+ _sm_assert_equal(reason, actual,
645
+ message || "Expected :#{event_obj.qualified_name} on #{machine.name} to be refused for #{reason.inspect}, but was refused for #{actual.inspect}")
646
+ end
647
+
648
+ actual
649
+ end
650
+
651
+ # Assert that the most recent attempt to fire an event was refused for the expected reason
652
+ #
653
+ # Reads the recorded refusal without firing the event.
654
+ #
655
+ # @param object [Object] The object with state machines
656
+ # @param event [Symbol] The event name (plain or namespace-qualified)
657
+ # @param expected_reason [Symbol] The expected refusal reason
658
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
659
+ # @param message [String, nil] Custom failure message
660
+ # @return [Symbol] The recorded refusal reason
661
+ # @raise [ArgumentError] If the reason is not a known refusal reason
662
+ # @raise [AssertionError] If the recorded reason differs
663
+ #
664
+ # @example
665
+ # vehicle.park
666
+ # assert_sm_refusal(vehicle, :park, :no_transition)
667
+ def assert_sm_refusal(object, event, expected_reason, machine_name: :state, message: nil)
668
+ _sm_validate_refusal_reason(expected_reason)
669
+ machine, event_obj = _sm_find_event(object, event, machine_name)
670
+ actual = event_obj.refusal(object)
671
+ 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'}"
672
+
673
+ _sm_assert_equal(expected_reason, actual, message || default_message)
674
+ actual
675
+ end
676
+
677
+ # Assert that the most recent attempt to fire an event recorded no refusal
678
+ #
679
+ # Reads the recorded refusal without firing the event. Passes after a
680
+ # success, or when the event was never fired.
681
+ #
682
+ # @param object [Object] The object with state machines
683
+ # @param event [Symbol] The event name (plain or namespace-qualified)
684
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
685
+ # @param message [String, nil] Custom failure message
686
+ # @return [void]
687
+ # @raise [AssertionError] If a refusal is recorded
688
+ #
689
+ # @example
690
+ # vehicle.ignite
691
+ # refute_sm_refusal(vehicle, :ignite)
692
+ def refute_sm_refusal(object, event, machine_name: :state, message: nil)
693
+ machine, event_obj = _sm_find_event(object, event, machine_name)
694
+ actual = event_obj.refusal(object)
695
+ default_message = "Expected no refusal for the last :#{event_obj.qualified_name} on #{machine.name}, but it was refused for #{actual.inspect}"
696
+
697
+ _sm_assert_nil(actual, message || default_message)
698
+ end
699
+ alias assert_sm_no_refusal refute_sm_refusal
700
+
701
+ # Assert that the bang event method raises StateMachines::InvalidTransition with the expected reason
702
+ #
703
+ # @param object [Object] The object with state machines
704
+ # @param event [Symbol] The event name (plain or namespace-qualified)
705
+ # @param expected_reason [Symbol] The expected StateMachines::InvalidTransition#reason
706
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
707
+ # @param message [String, nil] Custom failure message
708
+ # @return [StateMachines::InvalidTransition] The raised error
709
+ # @raise [ArgumentError] If the reason is not a known refusal reason
710
+ # @raise [AssertionError] If nothing is raised or the reason differs
711
+ #
712
+ # @example
713
+ # assert_sm_raises_refusal(vehicle, :park, :no_transition)
714
+ def assert_sm_raises_refusal(object, event, expected_reason, machine_name: :state, message: nil)
715
+ _sm_validate_refusal_reason(expected_reason)
716
+ machine, event_obj = _sm_find_event(object, event, machine_name)
717
+ bang = "#{event_obj.qualified_name}!"
718
+
719
+ error = _sm_capture_error(StateMachines::InvalidTransition) { object.public_send(bang) }
720
+ _sm_flunk(message || "Expected #{bang} on #{machine.name} to raise StateMachines::InvalidTransition, but nothing was raised") unless error
721
+
722
+ _sm_assert_equal(expected_reason, error.reason,
723
+ message || "Expected #{bang} on #{machine.name} to be refused for #{expected_reason.inspect}, but was refused for #{error.reason.inspect}")
724
+ error
725
+ end
726
+
727
+ # Assert that firing events in parallel is refused with the expected reasons
728
+ #
729
+ # +fire_events+ must return false, and +fire_events!+ must raise
730
+ # StateMachines::InvalidParallelTransition whose #reasons equals the
731
+ # expected Hash. Only the events that caused the refusal carry a reason.
732
+ #
733
+ # @param object [Object] The object with state machines
734
+ # @param events [Array<Symbol>] The (qualified) event names to fire together
735
+ # @param expected_reasons [Hash{Symbol => Symbol}] The expected reason per event
736
+ # @param message [String, nil] Custom failure message
737
+ # @return [StateMachines::InvalidParallelTransition] The raised error
738
+ # @raise [ArgumentError] If a reason is not a known refusal reason
739
+ # @raise [AssertionError] If the events are not refused or the reasons differ
740
+ #
741
+ # @example
742
+ # assert_sm_parallel_refused(vehicle, %i[ignite enable_alarm], { enable_alarm: :no_transition })
743
+ def assert_sm_parallel_refused(object, events, expected_reasons, message: nil)
744
+ raise ArgumentError, "Expected reasons must be a Hash of event => reason, got #{expected_reasons.inspect}" unless expected_reasons.is_a?(Hash)
745
+
746
+ expected_reasons.each_value { |reason| _sm_validate_refusal_reason(reason) }
747
+ events = Array(events)
748
+
749
+ result = object.fire_events(*events)
750
+ _sm_flunk(message || "Expected fire_events(#{events.map(&:inspect).join(', ')}) to be refused, but it returned #{result.inspect}") unless result == false
751
+
752
+ error = _sm_capture_error(StateMachines::InvalidParallelTransition) { object.fire_events!(*events) }
753
+ _sm_flunk(message || "Expected fire_events!(#{events.map(&:inspect).join(', ')}) to raise StateMachines::InvalidParallelTransition, but nothing was raised") unless error
754
+
755
+ _sm_assert_equal(expected_reasons, error.reasons,
756
+ message || "Expected fire_events!(#{events.map(&:inspect).join(', ')}) to be refused for #{expected_reasons.inspect}, but was refused for #{error.reasons.inspect}")
757
+ error
758
+ end
759
+
602
760
  # RSpec-style aliases for event triggering (for consistency with RSpec expectations)
603
761
  alias expect_to_trigger_event assert_sm_triggers_event
604
762
  alias have_triggered_event assert_sm_triggers_event
605
763
 
764
+ # RSpec-style aliases for refusal reasons
765
+ alias expect_to_be_refused assert_sm_refused
766
+ alias expect_refusal assert_sm_refusal
767
+ alias expect_no_refusal refute_sm_refusal
768
+ alias expect_to_raise_refusal assert_sm_raises_refusal
769
+ alias expect_parallel_refused assert_sm_parallel_refused
770
+
606
771
  private
607
772
 
773
+ # Finds the machine and its event, accepting the plain or the
774
+ # namespace-qualified event name, and raising when either is missing
775
+ def _sm_find_event(object, event, machine_name)
776
+ machine = object.class.state_machines[machine_name] if object.class.respond_to?(:state_machines)
777
+ unless machine
778
+ available = object.class.respond_to?(:state_machines) ? object.class.state_machines.keys : []
779
+ raise ArgumentError, "No state machine '#{machine_name}' found. Available machines: #{available.inspect}"
780
+ end
781
+
782
+ event_obj = machine.events[event.to_sym] || machine.events[event.to_sym, :qualified_name]
783
+ return [machine, event_obj] if event_obj
784
+
785
+ raise ArgumentError, "No event :#{event} found on machine :#{machine_name}. Available events: #{machine.events.map(&:qualified_name).inspect}"
786
+ end
787
+
788
+ # Raises a descriptive ArgumentError for an unknown refusal reason, so a
789
+ # typo in the expectation is not reported as a failed refusal
790
+ def _sm_validate_refusal_reason(reason)
791
+ return if REFUSAL_REASONS.include?(reason)
792
+
793
+ suggestion = DidYouMean::SpellChecker.new(dictionary: REFUSAL_REASONS).correct(reason.to_s).first if defined?(DidYouMean::SpellChecker)
794
+ hint = suggestion ? " Did you mean #{suggestion.inspect}?" : ''
795
+ raise ArgumentError, "Unknown refusal reason #{reason.inspect}.#{hint} Valid reasons: #{REFUSAL_REASONS.inspect}"
796
+ end
797
+
798
+ # Runs the block and returns the error of the given class it raised, or
799
+ # nil when it raised nothing; other errors propagate
800
+ def _sm_capture_error(error_class)
801
+ yield
802
+ nil
803
+ rescue error_class => e
804
+ e
805
+ end
806
+
608
807
  # Finds the can_<event>? method for the event, trying both the default and
609
808
  # namespaced naming patterns, and raising when neither exists
610
809
  def _sm_find_can_method(object, event, machine_name)
@@ -653,6 +852,16 @@ module StateMachines
653
852
  end
654
853
  end
655
854
 
855
+ def _sm_assert_nil(value, message)
856
+ if defined?(::Minitest)
857
+ assert_nil value, message
858
+ elsif defined?(::RSpec)
859
+ expect(value).to be_nil, message
860
+ else
861
+ raise message unless value.nil?
862
+ end
863
+ end
864
+
656
865
  def _sm_assert_empty(collection, message)
657
866
  if defined?(::Minitest)
658
867
  assert_empty collection, message
@@ -35,6 +35,14 @@ module StateMachines
35
35
  # Whether the transition is only existing temporarily for the object
36
36
  attr_writer :transient
37
37
 
38
+ # Why the most recent perform of this transition was refused.
39
+ #
40
+ # @return [:halted, :action_failed, :contended, nil] the refusal reason, or
41
+ # nil if the transition succeeded or was refused only because another
42
+ # transition in the same collection was
43
+ # @see StateMachines::Event#refusal for the meaning of each reason
44
+ attr_accessor :refusal
45
+
38
46
  # Creates a new, specific transition
39
47
  def initialize(object, machine, event, from_name, to_name, read_state = true) # :nodoc:
40
48
  @object = object
@@ -161,6 +169,9 @@ module StateMachines
161
169
  # transition.perform(Time.now) # => Passes in additional arguments and runs the +save+ action
162
170
  # transition.perform(Time.now, false) # => Passes in additional arguments and only sets the state attribute
163
171
  # transition.perform(Time.now, run_action: false) # => Passes in additional arguments and only sets the state attribute
172
+ #
173
+ # @return [StateMachines::Transition, false] this transition when it
174
+ # succeeds, false when it is refused (see {#refusal})
164
175
  def perform(*args)
165
176
  run_action = case args.last
166
177
  in true | false
@@ -174,7 +185,7 @@ module StateMachines
174
185
  self.args = args
175
186
 
176
187
  # Run the transition
177
- !!TransitionCollection.new([self], { use_transactions: machine.use_transactions, actions: run_action }).perform
188
+ TransitionCollection.new([self], { use_transactions: machine.use_transactions, actions: run_action }).perform ? self : false
178
189
  end
179
190
 
180
191
  # Runs a block within a transaction for the object being transitioned.
@@ -287,6 +298,9 @@ module StateMachines
287
298
  # the state has already been persisted
288
299
  def reset
289
300
  @before_run = @persisted = @after_run = false
301
+ # Kill so ensure blocks in paused callbacks still run (CRuby only:
302
+ # TruffleRuby lacks Fiber#kill, JRuby's doesn't wait for ensure)
303
+ @paused_fiber.kill if RUBY_ENGINE == 'ruby' && @paused_fiber&.alive? && !@paused_fiber.equal?(Fiber.current)
290
304
  @paused_fiber = nil
291
305
  @resuming = false
292
306
  @continuation_block = nil
@@ -407,9 +421,7 @@ module StateMachines
407
421
  else
408
422
  # Capture current fiber's Thread.current storage to preserve object identity
409
423
  # This is needed for compatibility but has limitations with dynamic assignments
410
- parent_fiber_locals = Thread.current.keys.each_with_object({}) do |key, storage|
411
- storage[key] = Thread.current[key]
412
- end
424
+ parent_fiber_locals = capture_thread_locals
413
425
 
414
426
  # Create a new fiber to run the block
415
427
  fiber = Fiber.new do
@@ -428,11 +440,7 @@ module StateMachines
428
440
  end
429
441
 
430
442
  # Export the final thread storage state along with the result
431
- thread_storage = Thread.current.keys.each_with_object({}) do |key, storage|
432
- storage[key] = Thread.current[key]
433
- end
434
-
435
- [halted ? :halted : :completed, thread_storage]
443
+ [halted ? :halted : :completed, capture_thread_locals]
436
444
  rescue StandardError => e
437
445
  # Store the exception for re-raising
438
446
  [:error, e]
@@ -459,6 +467,14 @@ module StateMachines
459
467
  end
460
468
  end
461
469
 
470
+ # Snapshots the current fiber's Thread.current storage, preserving object
471
+ # identity of the stored values
472
+ def capture_thread_locals
473
+ Thread.current.keys.each_with_object({}) do |key, storage|
474
+ storage[key] = Thread.current[key]
475
+ end
476
+ end
477
+
462
478
  # Unwraps a result returned from a pausable fiber, re-raising any exception
463
479
  # captured inside the fiber and importing its exported thread storage
464
480
  def unwrap_fiber_result(result)
@@ -502,7 +518,7 @@ module StateMachines
502
518
  #
503
519
  # Once the callbacks are run, they cannot be run again until this transition
504
520
  # is reset.
505
- def before(complete = true, index = 0, &block)
521
+ def before(complete = true, index = 0, &)
506
522
  return if @before_run
507
523
 
508
524
  callback = machine.callbacks[:before][index]
@@ -517,7 +533,7 @@ module StateMachines
517
533
  # * The block succeeds, but after callbacks are disabled (in which
518
534
  # case a continuation is stored for later execution)
519
535
  callback.call(object, context, self) do
520
- before(complete, index + 1, &block)
536
+ before(complete, index + 1, &)
521
537
 
522
538
  pause if @success && !complete
523
539
 
@@ -529,11 +545,11 @@ module StateMachines
529
545
  # Normal before callback
530
546
  callback.call(object, context, self)
531
547
  # Continue with next callback
532
- before(complete, index + 1, &block)
548
+ before(complete, index + 1, &)
533
549
  end
534
550
  else
535
551
  # Skip to next callback if it doesn't match
536
- before(complete, index + 1, &block)
552
+ before(complete, index + 1, &)
537
553
  end
538
554
  else
539
555
  # No more callbacks, execute the action block if at the end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StateMachines
4
+ # A hold on one of an object's machine attributes, granted for the duration
5
+ # of a single TransitionCollection#perform
6
+ class TransitionClaim
7
+ # The authority a perform holds over the attributes it claimed. The fibers
8
+ # a perform spawns inherit its authority, which is retired once that
9
+ # perform ends.
10
+ class Owner
11
+ def initialize
12
+ @active = true
13
+ end
14
+
15
+ def active?
16
+ @active
17
+ end
18
+
19
+ def retire
20
+ @active = false
21
+ end
22
+ end
23
+
24
+ CLAIMS_VARIABLE = :@_state_machine_transition_claims
25
+ OWNER_KEY = :state_machines_transition_owner
26
+ LOCK = Thread::Mutex.new
27
+
28
+ class << self
29
+ # Claims an attribute for every given transition whose machine runs in
30
+ # async mode, ordered by attribute so that collections over the same
31
+ # attributes claim them in the same order.
32
+ #
33
+ # Returns the granted claims, or nil when an attribute is held by another
34
+ # active owner or has left the transition's source state. Every exit
35
+ # that does not grant the whole set - a refusal, an exception, a throw -
36
+ # releases the claims it took.
37
+ #
38
+ # @param transitions [Array<StateMachines::Transition>] the transitions
39
+ # to claim attributes for
40
+ # @yieldparam transition [StateMachines::Transition] the transition whose
41
+ # attribute could not be claimed, when the claim is refused
42
+ # @return [Array<StateMachines::TransitionClaim>, nil]
43
+ def claim(transitions)
44
+ claimable = transitions.select { |transition| transition.machine.async_mode_enabled? }
45
+ granted = []
46
+ admitted = false
47
+
48
+ begin
49
+ admitted = claimable.sort_by { |transition| transition.attribute.to_s }.all? do |transition|
50
+ next true if hold(transition, granted) && at_source?(transition)
51
+
52
+ yield(transition) if block_given?
53
+ false
54
+ end
55
+
56
+ granted if admitted
57
+ ensure
58
+ release(granted) unless admitted
59
+ end
60
+ end
61
+
62
+ # Releases the claims granted by .claim
63
+ def release(claims)
64
+ claims.reverse_each(&:release)
65
+ end
66
+
67
+ private
68
+
69
+ # Takes the transition's attribute, appending the claim to +granted+ as it
70
+ # is taken. Returns nil when another active owner holds the attribute.
71
+ def hold(transition, granted)
72
+ previous_owner = Fiber[OWNER_KEY]
73
+ owner = previous_owner&.active? ? previous_owner : Owner.new
74
+ object = transition.object
75
+ attribute = transition.attribute
76
+
77
+ LOCK.synchronize do
78
+ claims = claims_for(object)
79
+ holder = claims[attribute]
80
+ next unless holder.nil? || !holder.active? || holder.equal?(owner)
81
+
82
+ claim = new(claims, attribute, owner, previous_owner, !holder.equal?(owner))
83
+ granted << claim
84
+ claims[attribute] = owner
85
+ Fiber[OWNER_KEY] = owner
86
+ claim
87
+ end
88
+ end
89
+
90
+ def at_source?(transition)
91
+ transition.machine.states.match!(transition.object).name == transition.from_name
92
+ end
93
+
94
+ def claims_for(object)
95
+ object.instance_variable_get(CLAIMS_VARIABLE) || object.instance_variable_set(CLAIMS_VARIABLE, {})
96
+ end
97
+ end
98
+
99
+ def initialize(claims, attribute, owner, previous_owner, held) # :nodoc:
100
+ @claims = claims
101
+ @attribute = attribute
102
+ @owner = owner
103
+ @previous_owner = previous_owner
104
+ @held = held
105
+ end
106
+
107
+ # Gives up this claim, retiring its owner's authority when the claim
108
+ # created it
109
+ def release
110
+ Fiber[OWNER_KEY] = @previous_owner
111
+
112
+ LOCK.synchronize do
113
+ @owner.retire unless @owner.equal?(@previous_owner)
114
+ @claims.delete(@attribute) if @held
115
+ end
116
+ end
117
+ end
118
+ end