state_machines 0.202.0 → 0.301.2
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.
- checksums.yaml +4 -4
- data/README.md +160 -14
- data/lib/state_machines/async_mode/async_event_extensions.rb +6 -10
- data/lib/state_machines/async_mode/async_events.rb +56 -72
- data/lib/state_machines/async_mode/async_machine.rb +3 -5
- data/lib/state_machines/async_mode/async_transition_collection.rb +32 -104
- data/lib/state_machines/async_mode/thread_safe_state.rb +8 -4
- data/lib/state_machines/branch.rb +35 -22
- data/lib/state_machines/callback.rb +4 -4
- data/lib/state_machines/core.rb +1 -0
- data/lib/state_machines/error.rb +37 -0
- data/lib/state_machines/event.rb +125 -2
- data/lib/state_machines/event_collection.rb +6 -1
- data/lib/state_machines/extensions.rb +22 -0
- data/lib/state_machines/helper_module.rb +1 -0
- data/lib/state_machines/machine/class_methods.rb +15 -3
- data/lib/state_machines/machine/configuration.rb +5 -3
- data/lib/state_machines/machine/event_methods.rb +5 -0
- data/lib/state_machines/machine/helper_generators.rb +3 -1
- data/lib/state_machines/machine/utilities.rb +1 -1
- data/lib/state_machines/machine.rb +8 -0
- data/lib/state_machines/machine_collection.rb +7 -6
- data/lib/state_machines/macro_methods.rb +4 -4
- data/lib/state_machines/path.rb +1 -0
- data/lib/state_machines/path_collection.rb +1 -0
- data/lib/state_machines/state_context.rb +1 -0
- data/lib/state_machines/stdio_renderer.rb +8 -6
- data/lib/state_machines/syntax_validator.rb +3 -3
- data/lib/state_machines/test_helper.rb +228 -27
- data/lib/state_machines/transition.rb +19 -5
- data/lib/state_machines/transition_claim.rb +118 -0
- data/lib/state_machines/transition_collection.rb +142 -18
- data/lib/state_machines/version.rb +1 -1
- metadata +8 -7
|
@@ -6,21 +6,22 @@ module StateMachines
|
|
|
6
6
|
# Initializes a new state machine with the given configuration.
|
|
7
7
|
def initialize(owner_class, *args, &)
|
|
8
8
|
options = args.last.is_a?(Hash) ? args.pop : {}
|
|
9
|
-
|
|
9
|
+
|
|
10
10
|
# Find an integration that matches this machine's owner class
|
|
11
11
|
@integration = if options.include?(:integration)
|
|
12
12
|
options[:integration] && StateMachines::Integrations.find_by_name(options[:integration])
|
|
13
13
|
else
|
|
14
14
|
StateMachines::Integrations.match(owner_class)
|
|
15
15
|
end
|
|
16
|
-
|
|
16
|
+
|
|
17
17
|
# Validate options including integration-specific options
|
|
18
|
-
valid_keys = [
|
|
18
|
+
valid_keys = %i[attribute initial initialize action plural namespace integration messages use_transactions async]
|
|
19
19
|
valid_keys += @integration.integration_options if @integration
|
|
20
20
|
StateMachines::OptionsValidator.assert_valid_keys!(options, valid_keys)
|
|
21
21
|
|
|
22
22
|
if @integration
|
|
23
23
|
extend @integration
|
|
24
|
+
|
|
24
25
|
options = (@integration.defaults || {}).merge(options)
|
|
25
26
|
end
|
|
26
27
|
|
|
@@ -40,6 +41,7 @@ module StateMachines
|
|
|
40
41
|
@initialize_state = options[:initialize]
|
|
41
42
|
@action_hook_defined = false
|
|
42
43
|
@async_requested = options[:async]
|
|
44
|
+
@integration_options = @integration ? options.slice(*@integration.integration_options).freeze : {}.freeze
|
|
43
45
|
|
|
44
46
|
self.owner_class = owner_class
|
|
45
47
|
|
|
@@ -39,10 +39,15 @@ module StateMachines
|
|
|
39
39
|
# object or nil if no transitions can be performed. Like <tt>can_park?</tt>
|
|
40
40
|
# this will also *not* run validations or callbacks. It will only
|
|
41
41
|
# determine if the state machine defines a valid transition for the event.
|
|
42
|
+
# * <tt>park_refusal</tt> - Gets the reason the most recent attempt to fire
|
|
43
|
+
# the "park" event was refused (<tt>:no_transition</tt>, <tt>:guard</tt>,
|
|
44
|
+
# <tt>:halted</tt>, <tt>:action_failed</tt> or <tt>:contended</tt>), or nil
|
|
45
|
+
# if it succeeded. See {StateMachines::Event#refusal}.
|
|
42
46
|
#
|
|
43
47
|
# With a namespace of "car", the above names map to the following methods:
|
|
44
48
|
# * <tt>can_park_car?</tt>
|
|
45
49
|
# * <tt>park_car_transition</tt>
|
|
50
|
+
# * <tt>park_car_refusal</tt>
|
|
46
51
|
# * <tt>park_car</tt>
|
|
47
52
|
# * <tt>park_car!</tt>
|
|
48
53
|
#
|
|
@@ -38,7 +38,9 @@ module StateMachines
|
|
|
38
38
|
# Adds predicate method to the owner class for determining the name of the
|
|
39
39
|
# current state
|
|
40
40
|
def define_state_predicate
|
|
41
|
-
|
|
41
|
+
# Interpolated into the helper source, so it must be a literal boolean
|
|
42
|
+
# (the finder answers the ancestor owning the method)
|
|
43
|
+
call_super = owner_class_ancestor_has_method?(:instance, "#{name}?") ? true : false # rubocop:disable Style/IfWithBooleanLiteralBranches
|
|
42
44
|
define_helper :instance, <<-END_EVAL, __FILE__, __LINE__ + 1
|
|
43
45
|
def #{name}?(*args)
|
|
44
46
|
args.empty? && (#{call_super} || defined?(super)) ? super : self.class.state_machine(#{name.inspect}).states.matches?(self, *args)
|
|
@@ -13,7 +13,7 @@ module StateMachines
|
|
|
13
13
|
# base class that may have originally defined the machine.
|
|
14
14
|
def sibling_machines
|
|
15
15
|
owner_class.state_machines.each_with_object([]) do |(name, machine), machines|
|
|
16
|
-
machines <<
|
|
16
|
+
machines << owner_class.state_machine(name) {} if machine.attribute == attribute && machine != self
|
|
17
17
|
end
|
|
18
18
|
end
|
|
19
19
|
|
|
@@ -476,6 +476,14 @@ module StateMachines
|
|
|
476
476
|
# Whether the machine will use transactions when firing events
|
|
477
477
|
attr_reader :use_transactions
|
|
478
478
|
|
|
479
|
+
# The options declared by the machine's integration (see
|
|
480
|
+
# StateMachines::Integrations::Base::ClassMethods#integration_options)
|
|
481
|
+
# that were passed when creating the machine. Available from
|
|
482
|
+
# +owner_class=+ onward.
|
|
483
|
+
#
|
|
484
|
+
# @return [Hash{Symbol => Object}] frozen option name => value
|
|
485
|
+
attr_reader :integration_options
|
|
486
|
+
|
|
479
487
|
# Defines a new helper method in an instance or class scope with the given
|
|
480
488
|
# name. If the method is already defined in the scope, then this will not
|
|
481
489
|
# override it.
|
|
@@ -61,15 +61,16 @@ module StateMachines
|
|
|
61
61
|
raise(InvalidEvent.new(object, event_name)) unless event
|
|
62
62
|
|
|
63
63
|
# Get the transition that will be performed for the event
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
64
|
+
transition = event.transition_for(object)
|
|
65
|
+
event.record_refusal(object, transition ? nil : event.refusal_without_transition(object))
|
|
66
|
+
event.on_failure(object) unless transition
|
|
67
67
|
transition
|
|
68
|
-
end
|
|
68
|
+
end
|
|
69
69
|
|
|
70
70
|
# Run the events in parallel only if valid transitions were found for
|
|
71
|
-
# all of them
|
|
72
|
-
|
|
71
|
+
# all of them. Otherwise only the events without a transition carry a
|
|
72
|
+
# refusal reason.
|
|
73
|
+
if transitions.all?
|
|
73
74
|
TransitionCollection.new(transitions, { use_transactions: resolve_use_transactions, actions: run_action }).perform
|
|
74
75
|
else
|
|
75
76
|
false
|
|
@@ -185,13 +185,13 @@ module StateMachines
|
|
|
185
185
|
#
|
|
186
186
|
# # Getting current event / transition availability
|
|
187
187
|
# vehicle.state_events # => [:park]
|
|
188
|
-
# vehicle.park # =>
|
|
188
|
+
# vehicle.park # => #<StateMachines::Transition attribute=:state event=:park ...>
|
|
189
189
|
# vehicle.state_events # => [:ignite]
|
|
190
190
|
# vehicle.state_events(:from => :idling) # => [:park]
|
|
191
191
|
# vehicle.state_events(:to => :parked) # => []
|
|
192
192
|
#
|
|
193
193
|
# vehicle.state_transitions # => [#<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>]
|
|
194
|
-
# vehicle.ignite # =>
|
|
194
|
+
# vehicle.ignite # => #<StateMachines::Transition attribute=:state event=:ignite ...>
|
|
195
195
|
# vehicle.state_transitions # => [#<StateMachines::Transition attribute=:state event=:park from="idling" from_name=:idling to="parked" to_name=:parked>]
|
|
196
196
|
#
|
|
197
197
|
# vehicle.state_transitions(:on => :ignite) # => []
|
|
@@ -207,7 +207,7 @@ module StateMachines
|
|
|
207
207
|
# # ]
|
|
208
208
|
#
|
|
209
209
|
# # Fire arbitrary events
|
|
210
|
-
# vehicle.fire_state_event(:park) # =>
|
|
210
|
+
# vehicle.fire_state_event(:park) # => #<StateMachines::Transition attribute=:state event=:park ...>
|
|
211
211
|
#
|
|
212
212
|
# == Attribute initialization
|
|
213
213
|
#
|
|
@@ -414,7 +414,7 @@ module StateMachines
|
|
|
414
414
|
#
|
|
415
415
|
# # Fire +ignite+ event directly
|
|
416
416
|
# vehicle = Vehicle.create # => #<Vehicle id=1 state="parked" alarm_state="active">
|
|
417
|
-
# vehicle.ignite # =>
|
|
417
|
+
# vehicle.ignite # => #<StateMachines::Transition attribute=:state event=:ignite ...>
|
|
418
418
|
# vehicle.state # => "idling"
|
|
419
419
|
# vehicle.alarm_state # => "active"
|
|
420
420
|
#
|
data/lib/state_machines/path.rb
CHANGED
|
@@ -22,6 +22,7 @@ module StateMachines
|
|
|
22
22
|
# * <tt>:guard</tt> - Whether to guard transitions with the if/unless
|
|
23
23
|
# conditionals defined for each one
|
|
24
24
|
def initialize(object, machine, options = {})
|
|
25
|
+
super()
|
|
25
26
|
StateMachines::OptionsValidator.assert_valid_keys!(options, :target, :guard)
|
|
26
27
|
|
|
27
28
|
@object = object
|
|
@@ -27,6 +27,7 @@ module StateMachines
|
|
|
27
27
|
# * <tt>:guard</tt> - Whether to guard transitions with the if/unless
|
|
28
28
|
# conditionals defined for each one
|
|
29
29
|
def initialize(object, machine, options = {})
|
|
30
|
+
super()
|
|
30
31
|
options = { deep: false, from: machine.states.match!(object).name }.merge(options)
|
|
31
32
|
StateMachines::OptionsValidator.assert_valid_keys!(options, :from, :to, :deep, :guard)
|
|
32
33
|
|
|
@@ -23,18 +23,17 @@ module StateMachines
|
|
|
23
23
|
end
|
|
24
24
|
end
|
|
25
25
|
|
|
26
|
-
module_function def draw_event(event, _graph, options
|
|
27
|
-
io =
|
|
26
|
+
module_function def draw_event(event, _graph, options = {}, io = $stdout)
|
|
27
|
+
io = options[:io] || io
|
|
28
28
|
io.puts " Event: #{event.name}"
|
|
29
29
|
end
|
|
30
30
|
|
|
31
|
-
module_function def draw_branch(branch, _graph, _event,
|
|
32
|
-
io = io || options[:io] || $stdout
|
|
31
|
+
module_function def draw_branch(branch, _graph, _event, _valid_states = [], io = $stdout)
|
|
33
32
|
io.puts " Branch: #{branch.inspect}"
|
|
34
33
|
end
|
|
35
34
|
|
|
36
|
-
module_function def draw_state(state, _graph, options
|
|
37
|
-
io =
|
|
35
|
+
module_function def draw_state(state, _graph, options = {}, io = $stdout)
|
|
36
|
+
io = options[:io] || io
|
|
38
37
|
io.puts " State: #{state.name}"
|
|
39
38
|
end
|
|
40
39
|
|
|
@@ -51,6 +50,9 @@ module StateMachines
|
|
|
51
50
|
out << "#{draw_requirement(requirement[:from])} => #{draw_requirement(requirement[:to])}"
|
|
52
51
|
out << " IF #{branch.if_condition}" if branch.if_condition
|
|
53
52
|
out << " UNLESS #{branch.unless_condition}" if branch.unless_condition
|
|
53
|
+
branch.state_guards.each do |kind, conditions|
|
|
54
|
+
out << " #{kind.upcase} #{conditions.map { |name, state| "#{name}: #{state}" }.join(', ')}"
|
|
55
|
+
end
|
|
54
56
|
io.puts out
|
|
55
57
|
end
|
|
56
58
|
end
|
|
@@ -42,9 +42,9 @@ module StateMachines
|
|
|
42
42
|
module UniversalBackend
|
|
43
43
|
def validate!(code, filename)
|
|
44
44
|
code = code.b
|
|
45
|
-
code.sub!(/\A(?:\xef\xbb\xbf)?(\s*\#.*$)*(\n)?/n)
|
|
46
|
-
"
|
|
47
|
-
|
|
45
|
+
code.sub!(/\A(?:\xef\xbb\xbf)?(\s*\#.*$)*(\n)?/n) do
|
|
46
|
+
"#{::Regexp.last_match(0)}#{"\n" if ::Regexp.last_match(1) && !::Regexp.last_match(2)}BEGIN{throw tag, :ok}\n"
|
|
47
|
+
end
|
|
48
48
|
code = code.force_encoding(Encoding::UTF_8)
|
|
49
49
|
catch { |tag| eval(code, binding, filename, __LINE__ - 1) } == :ok
|
|
50
50
|
end
|
|
@@ -403,9 +403,7 @@ module StateMachines
|
|
|
403
403
|
async_machines = []
|
|
404
404
|
|
|
405
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
|
|
406
|
+
async_machines << name if machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
|
|
409
407
|
end
|
|
410
408
|
|
|
411
409
|
default_message = "Expected all state machines to be sync-only, but these have async enabled: #{async_machines.inspect}"
|
|
@@ -443,41 +441,36 @@ module StateMachines
|
|
|
443
441
|
|
|
444
442
|
default_message = "Expected sync execution of '#{event}' to change #{machine_name} from '#{initial_state}' to '#{expected_state}', but got '#{final_state}'"
|
|
445
443
|
|
|
446
|
-
_sm_assert(result, "Event #{event} should return
|
|
444
|
+
_sm_assert(result, "Event #{event} should return the performed transition on success, but returned #{result.inspect}")
|
|
447
445
|
_sm_assert(state_changed, "State should change from #{initial_state}")
|
|
448
446
|
_sm_assert(correct_final_state, message || default_message)
|
|
449
447
|
end
|
|
450
448
|
|
|
451
|
-
# Assert that event execution is immediate
|
|
449
|
+
# Assert that event execution is immediate: the state has changed when the
|
|
450
|
+
# bang event returns, and it returned no async task to wait on. Decided by
|
|
451
|
+
# what the call did, not by how long it took, so a slow runner (a cold
|
|
452
|
+
# JIT) cannot fail it.
|
|
452
453
|
#
|
|
453
454
|
# @param object [Object] The object with state machines
|
|
454
455
|
# @param event [Symbol] The event to trigger
|
|
455
456
|
# @param machine_name [Symbol] The name of the state machine (defaults to :state)
|
|
456
457
|
# @param message [String, nil] Custom failure message
|
|
457
458
|
# @return [void]
|
|
458
|
-
# @raise [AssertionError] If
|
|
459
|
+
# @raise [AssertionError] If the event did not complete synchronously
|
|
459
460
|
#
|
|
460
461
|
# @example
|
|
461
462
|
# car = Car.new
|
|
462
463
|
# assert_sm_immediate_execution(car, :start)
|
|
463
464
|
def assert_sm_immediate_execution(object, event, machine_name = :state, message = nil)
|
|
464
465
|
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
|
-
|
|
466
|
+
result = object.send("#{event}!")
|
|
471
467
|
final_state = object.send(machine_name)
|
|
472
|
-
state_changed = initial_state != final_state
|
|
473
468
|
|
|
474
|
-
|
|
475
|
-
|
|
469
|
+
deferred = defined?(::Async::Task) && result.is_a?(::Async::Task)
|
|
470
|
+
default_message = "Expected immediate sync execution of '#{event}', but it returned #{result.class} (async)"
|
|
476
471
|
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
_sm_assert(state_changed, 'Event should trigger state change')
|
|
480
|
-
_sm_assert(is_immediate, message || default_message)
|
|
472
|
+
_sm_assert(initial_state != final_state, message || "Event #{event} should change #{machine_name} before returning")
|
|
473
|
+
_sm_assert(!deferred, message || default_message)
|
|
481
474
|
end
|
|
482
475
|
|
|
483
476
|
# === Async Mode Assertions ===
|
|
@@ -518,7 +511,7 @@ module StateMachines
|
|
|
518
511
|
async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
|
|
519
512
|
available_async_methods = async_methods.select { |method| object.respond_to?(method) }
|
|
520
513
|
|
|
521
|
-
default_message =
|
|
514
|
+
default_message = 'Expected async methods to be available, but found none'
|
|
522
515
|
|
|
523
516
|
_sm_refute_empty(available_async_methods, message || default_message)
|
|
524
517
|
end
|
|
@@ -547,11 +540,11 @@ module StateMachines
|
|
|
547
540
|
_sm_assert_empty(non_async_machines, message || default_message)
|
|
548
541
|
else
|
|
549
542
|
# Check that at least one machine has async
|
|
550
|
-
async_machines = object.class.state_machines.select do |
|
|
543
|
+
async_machines = object.class.state_machines.select do |_name, machine|
|
|
551
544
|
machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
|
|
552
545
|
end
|
|
553
546
|
|
|
554
|
-
default_message =
|
|
547
|
+
default_message = 'Expected at least one state machine to have async enabled, but none found'
|
|
555
548
|
|
|
556
549
|
_sm_refute_empty(async_machines, message || default_message)
|
|
557
550
|
end
|
|
@@ -569,15 +562,14 @@ module StateMachines
|
|
|
569
562
|
# drone = AutonomousDrone.new
|
|
570
563
|
# assert_sm_async_event_methods(drone, :launch) # Checks launch_async and launch_async!
|
|
571
564
|
def assert_sm_async_event_methods(object, event, message = nil)
|
|
572
|
-
async_method = "#{event}_async"
|
|
573
|
-
async_bang_method = "#{event}_async!"
|
|
565
|
+
async_method = :"#{event}_async"
|
|
566
|
+
async_bang_method = :"#{event}_async!"
|
|
574
567
|
|
|
575
568
|
has_async = object.respond_to?(async_method)
|
|
576
569
|
has_async_bang = object.respond_to?(async_bang_method)
|
|
577
570
|
|
|
578
|
-
|
|
579
|
-
_sm_assert(
|
|
580
|
-
_sm_assert(has_async_bang, "Missing #{async_bang_method} method")
|
|
571
|
+
_sm_assert(has_async, message || "Missing #{async_method} method")
|
|
572
|
+
_sm_assert(has_async_bang, message || "Missing #{async_bang_method} method")
|
|
581
573
|
end
|
|
582
574
|
|
|
583
575
|
# Assert that an object has thread-safe state methods when async is enabled
|
|
@@ -599,12 +591,211 @@ module StateMachines
|
|
|
599
591
|
_sm_assert_empty(missing_methods, message || default_message)
|
|
600
592
|
end
|
|
601
593
|
|
|
594
|
+
# === Refusal Reason Assertions ===
|
|
595
|
+
|
|
596
|
+
# The reasons an event can be refused for
|
|
597
|
+
#
|
|
598
|
+
# @see StateMachines::Event#refusal
|
|
599
|
+
REFUSAL_REASONS = %i[no_transition guard halted action_failed contended].freeze
|
|
600
|
+
|
|
601
|
+
# Assert that firing an event is refused, leaving the machine's state unchanged
|
|
602
|
+
#
|
|
603
|
+
# Fires the non-bang event method, which must return false. When a reason is
|
|
604
|
+
# given, the refusal recorded for the event must equal it.
|
|
605
|
+
#
|
|
606
|
+
# @param object [Object] The object with state machines
|
|
607
|
+
# @param event [Symbol] The event name (plain or namespace-qualified)
|
|
608
|
+
# @param reason [Symbol, nil] The expected refusal reason, or nil to accept any
|
|
609
|
+
# @param machine_name [Symbol] The name of the state machine (defaults to :state)
|
|
610
|
+
# @param message [String, nil] Custom failure message
|
|
611
|
+
# @return [Symbol, nil] The recorded refusal reason
|
|
612
|
+
# @raise [ArgumentError] If the reason is not a known refusal reason
|
|
613
|
+
# @raise [AssertionError] If the event succeeds, changes the state, or is refused for another reason
|
|
614
|
+
#
|
|
615
|
+
# @example
|
|
616
|
+
# vehicle = Vehicle.new # parked
|
|
617
|
+
# assert_sm_refused(vehicle, :park) # Any reason
|
|
618
|
+
# assert_sm_refused(vehicle, :park, :no_transition) # Specific reason
|
|
619
|
+
# assert_sm_refused(vehicle, :enable, :guard, machine_name: :alarm_state)
|
|
620
|
+
def assert_sm_refused(object, event, reason = nil, machine_name: :state, message: nil)
|
|
621
|
+
_sm_validate_refusal_reason(reason) if reason
|
|
622
|
+
machine, event_obj = _sm_find_event(object, event, machine_name)
|
|
623
|
+
|
|
624
|
+
state_before = machine.read(object, :state)
|
|
625
|
+
result = object.public_send(event_obj.qualified_name)
|
|
626
|
+
state_after = machine.read(object, :state)
|
|
627
|
+
actual = event_obj.refusal(object)
|
|
628
|
+
|
|
629
|
+
unless result == false
|
|
630
|
+
outcome = result.is_a?(StateMachines::Transition) ? "it transitioned #{result.from_name.inspect} -> #{result.to_name.inspect}" : "it returned #{result.inspect}"
|
|
631
|
+
_sm_flunk(message || "Expected :#{event_obj.qualified_name} on #{machine.name} to be refused, but #{outcome}")
|
|
632
|
+
end
|
|
633
|
+
_sm_assert(state_before == state_after,
|
|
634
|
+
message || "Expected a refused :#{event_obj.qualified_name} to leave #{machine.name} at #{state_before.inspect}, but it became #{state_after.inspect}")
|
|
635
|
+
if reason
|
|
636
|
+
_sm_assert_equal(reason, actual,
|
|
637
|
+
message || "Expected :#{event_obj.qualified_name} on #{machine.name} to be refused for #{reason.inspect}, but was refused for #{actual.inspect}")
|
|
638
|
+
end
|
|
639
|
+
|
|
640
|
+
actual
|
|
641
|
+
end
|
|
642
|
+
|
|
643
|
+
# Assert that the most recent attempt to fire an event was refused for the expected reason
|
|
644
|
+
#
|
|
645
|
+
# Reads the recorded refusal without firing the event.
|
|
646
|
+
#
|
|
647
|
+
# @param object [Object] The object with state machines
|
|
648
|
+
# @param event [Symbol] The event name (plain or namespace-qualified)
|
|
649
|
+
# @param expected_reason [Symbol] The expected refusal reason
|
|
650
|
+
# @param machine_name [Symbol] The name of the state machine (defaults to :state)
|
|
651
|
+
# @param message [String, nil] Custom failure message
|
|
652
|
+
# @return [Symbol] The recorded refusal reason
|
|
653
|
+
# @raise [ArgumentError] If the reason is not a known refusal reason
|
|
654
|
+
# @raise [AssertionError] If the recorded reason differs
|
|
655
|
+
#
|
|
656
|
+
# @example
|
|
657
|
+
# vehicle.park
|
|
658
|
+
# assert_sm_refusal(vehicle, :park, :no_transition)
|
|
659
|
+
def assert_sm_refusal(object, event, expected_reason, machine_name: :state, message: nil)
|
|
660
|
+
_sm_validate_refusal_reason(expected_reason)
|
|
661
|
+
machine, event_obj = _sm_find_event(object, event, machine_name)
|
|
662
|
+
actual = event_obj.refusal(object)
|
|
663
|
+
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'}"
|
|
664
|
+
|
|
665
|
+
_sm_assert_equal(expected_reason, actual, message || default_message)
|
|
666
|
+
actual
|
|
667
|
+
end
|
|
668
|
+
|
|
669
|
+
# Assert that the most recent attempt to fire an event recorded no refusal
|
|
670
|
+
#
|
|
671
|
+
# Reads the recorded refusal without firing the event. Passes after a
|
|
672
|
+
# success, or when the event was never fired.
|
|
673
|
+
#
|
|
674
|
+
# @param object [Object] The object with state machines
|
|
675
|
+
# @param event [Symbol] The event name (plain or namespace-qualified)
|
|
676
|
+
# @param machine_name [Symbol] The name of the state machine (defaults to :state)
|
|
677
|
+
# @param message [String, nil] Custom failure message
|
|
678
|
+
# @return [void]
|
|
679
|
+
# @raise [AssertionError] If a refusal is recorded
|
|
680
|
+
#
|
|
681
|
+
# @example
|
|
682
|
+
# vehicle.ignite
|
|
683
|
+
# refute_sm_refusal(vehicle, :ignite)
|
|
684
|
+
def refute_sm_refusal(object, event, machine_name: :state, message: nil)
|
|
685
|
+
machine, event_obj = _sm_find_event(object, event, machine_name)
|
|
686
|
+
actual = event_obj.refusal(object)
|
|
687
|
+
default_message = "Expected no refusal for the last :#{event_obj.qualified_name} on #{machine.name}, but it was refused for #{actual.inspect}"
|
|
688
|
+
|
|
689
|
+
_sm_assert_nil(actual, message || default_message)
|
|
690
|
+
end
|
|
691
|
+
alias assert_sm_no_refusal refute_sm_refusal
|
|
692
|
+
|
|
693
|
+
# Assert that the bang event method raises StateMachines::InvalidTransition with the expected reason
|
|
694
|
+
#
|
|
695
|
+
# @param object [Object] The object with state machines
|
|
696
|
+
# @param event [Symbol] The event name (plain or namespace-qualified)
|
|
697
|
+
# @param expected_reason [Symbol] The expected StateMachines::InvalidTransition#reason
|
|
698
|
+
# @param machine_name [Symbol] The name of the state machine (defaults to :state)
|
|
699
|
+
# @param message [String, nil] Custom failure message
|
|
700
|
+
# @return [StateMachines::InvalidTransition] The raised error
|
|
701
|
+
# @raise [ArgumentError] If the reason is not a known refusal reason
|
|
702
|
+
# @raise [AssertionError] If nothing is raised or the reason differs
|
|
703
|
+
#
|
|
704
|
+
# @example
|
|
705
|
+
# assert_sm_raises_refusal(vehicle, :park, :no_transition)
|
|
706
|
+
def assert_sm_raises_refusal(object, event, expected_reason, machine_name: :state, message: nil)
|
|
707
|
+
_sm_validate_refusal_reason(expected_reason)
|
|
708
|
+
machine, event_obj = _sm_find_event(object, event, machine_name)
|
|
709
|
+
bang = "#{event_obj.qualified_name}!"
|
|
710
|
+
|
|
711
|
+
error = _sm_capture_error(StateMachines::InvalidTransition) { object.public_send(bang) }
|
|
712
|
+
_sm_flunk(message || "Expected #{bang} on #{machine.name} to raise StateMachines::InvalidTransition, but nothing was raised") unless error
|
|
713
|
+
|
|
714
|
+
_sm_assert_equal(expected_reason, error.reason,
|
|
715
|
+
message || "Expected #{bang} on #{machine.name} to be refused for #{expected_reason.inspect}, but was refused for #{error.reason.inspect}")
|
|
716
|
+
error
|
|
717
|
+
end
|
|
718
|
+
|
|
719
|
+
# Assert that firing events in parallel is refused with the expected reasons
|
|
720
|
+
#
|
|
721
|
+
# +fire_events+ must return false, and +fire_events!+ must raise
|
|
722
|
+
# StateMachines::InvalidParallelTransition whose #reasons equals the
|
|
723
|
+
# expected Hash. Only the events that caused the refusal carry a reason.
|
|
724
|
+
#
|
|
725
|
+
# @param object [Object] The object with state machines
|
|
726
|
+
# @param events [Array<Symbol>] The (qualified) event names to fire together
|
|
727
|
+
# @param expected_reasons [Hash{Symbol => Symbol}] The expected reason per event
|
|
728
|
+
# @param message [String, nil] Custom failure message
|
|
729
|
+
# @return [StateMachines::InvalidParallelTransition] The raised error
|
|
730
|
+
# @raise [ArgumentError] If a reason is not a known refusal reason
|
|
731
|
+
# @raise [AssertionError] If the events are not refused or the reasons differ
|
|
732
|
+
#
|
|
733
|
+
# @example
|
|
734
|
+
# assert_sm_parallel_refused(vehicle, %i[ignite enable_alarm], { enable_alarm: :no_transition })
|
|
735
|
+
def assert_sm_parallel_refused(object, events, expected_reasons, message: nil)
|
|
736
|
+
raise ArgumentError, "Expected reasons must be a Hash of event => reason, got #{expected_reasons.inspect}" unless expected_reasons.is_a?(Hash)
|
|
737
|
+
|
|
738
|
+
expected_reasons.each_value { |reason| _sm_validate_refusal_reason(reason) }
|
|
739
|
+
events = Array(events)
|
|
740
|
+
|
|
741
|
+
result = object.fire_events(*events)
|
|
742
|
+
_sm_flunk(message || "Expected fire_events(#{events.map(&:inspect).join(', ')}) to be refused, but it returned #{result.inspect}") unless result == false
|
|
743
|
+
|
|
744
|
+
error = _sm_capture_error(StateMachines::InvalidParallelTransition) { object.fire_events!(*events) }
|
|
745
|
+
_sm_flunk(message || "Expected fire_events!(#{events.map(&:inspect).join(', ')}) to raise StateMachines::InvalidParallelTransition, but nothing was raised") unless error
|
|
746
|
+
|
|
747
|
+
_sm_assert_equal(expected_reasons, error.reasons,
|
|
748
|
+
message || "Expected fire_events!(#{events.map(&:inspect).join(', ')}) to be refused for #{expected_reasons.inspect}, but was refused for #{error.reasons.inspect}")
|
|
749
|
+
error
|
|
750
|
+
end
|
|
751
|
+
|
|
602
752
|
# RSpec-style aliases for event triggering (for consistency with RSpec expectations)
|
|
603
753
|
alias expect_to_trigger_event assert_sm_triggers_event
|
|
604
754
|
alias have_triggered_event assert_sm_triggers_event
|
|
605
755
|
|
|
756
|
+
# RSpec-style aliases for refusal reasons
|
|
757
|
+
alias expect_to_be_refused assert_sm_refused
|
|
758
|
+
alias expect_refusal assert_sm_refusal
|
|
759
|
+
alias expect_no_refusal refute_sm_refusal
|
|
760
|
+
alias expect_to_raise_refusal assert_sm_raises_refusal
|
|
761
|
+
alias expect_parallel_refused assert_sm_parallel_refused
|
|
762
|
+
|
|
606
763
|
private
|
|
607
764
|
|
|
765
|
+
# Finds the machine and its event, accepting the plain or the
|
|
766
|
+
# namespace-qualified event name, and raising when either is missing
|
|
767
|
+
def _sm_find_event(object, event, machine_name)
|
|
768
|
+
machine = object.class.state_machines[machine_name] if object.class.respond_to?(:state_machines)
|
|
769
|
+
unless machine
|
|
770
|
+
available = object.class.respond_to?(:state_machines) ? object.class.state_machines.keys : []
|
|
771
|
+
raise ArgumentError, "No state machine '#{machine_name}' found. Available machines: #{available.inspect}"
|
|
772
|
+
end
|
|
773
|
+
|
|
774
|
+
event_obj = machine.events[event.to_sym] || machine.events[event.to_sym, :qualified_name]
|
|
775
|
+
return [machine, event_obj] if event_obj
|
|
776
|
+
|
|
777
|
+
raise ArgumentError, "No event :#{event} found on machine :#{machine_name}. Available events: #{machine.events.map(&:qualified_name).inspect}"
|
|
778
|
+
end
|
|
779
|
+
|
|
780
|
+
# Raises a descriptive ArgumentError for an unknown refusal reason, so a
|
|
781
|
+
# typo in the expectation is not reported as a failed refusal
|
|
782
|
+
def _sm_validate_refusal_reason(reason)
|
|
783
|
+
return if REFUSAL_REASONS.include?(reason)
|
|
784
|
+
|
|
785
|
+
suggestion = DidYouMean::SpellChecker.new(dictionary: REFUSAL_REASONS).correct(reason.to_s).first if defined?(DidYouMean::SpellChecker)
|
|
786
|
+
hint = suggestion ? " Did you mean #{suggestion.inspect}?" : ''
|
|
787
|
+
raise ArgumentError, "Unknown refusal reason #{reason.inspect}.#{hint} Valid reasons: #{REFUSAL_REASONS.inspect}"
|
|
788
|
+
end
|
|
789
|
+
|
|
790
|
+
# Runs the block and returns the error of the given class it raised, or
|
|
791
|
+
# nil when it raised nothing; other errors propagate
|
|
792
|
+
def _sm_capture_error(error_class)
|
|
793
|
+
yield
|
|
794
|
+
nil
|
|
795
|
+
rescue error_class => e
|
|
796
|
+
e
|
|
797
|
+
end
|
|
798
|
+
|
|
608
799
|
# Finds the can_<event>? method for the event, trying both the default and
|
|
609
800
|
# namespaced naming patterns, and raising when neither exists
|
|
610
801
|
def _sm_find_can_method(object, event, machine_name)
|
|
@@ -653,6 +844,16 @@ module StateMachines
|
|
|
653
844
|
end
|
|
654
845
|
end
|
|
655
846
|
|
|
847
|
+
def _sm_assert_nil(value, message)
|
|
848
|
+
if defined?(::Minitest)
|
|
849
|
+
assert_nil value, message
|
|
850
|
+
elsif defined?(::RSpec)
|
|
851
|
+
expect(value).to be_nil, message
|
|
852
|
+
else
|
|
853
|
+
raise message unless value.nil?
|
|
854
|
+
end
|
|
855
|
+
end
|
|
856
|
+
|
|
656
857
|
def _sm_assert_empty(collection, message)
|
|
657
858
|
if defined?(::Minitest)
|
|
658
859
|
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
|
-
|
|
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
|
|
@@ -504,7 +518,7 @@ module StateMachines
|
|
|
504
518
|
#
|
|
505
519
|
# Once the callbacks are run, they cannot be run again until this transition
|
|
506
520
|
# is reset.
|
|
507
|
-
def before(complete = true, index = 0, &
|
|
521
|
+
def before(complete = true, index = 0, &)
|
|
508
522
|
return if @before_run
|
|
509
523
|
|
|
510
524
|
callback = machine.callbacks[:before][index]
|
|
@@ -519,7 +533,7 @@ module StateMachines
|
|
|
519
533
|
# * The block succeeds, but after callbacks are disabled (in which
|
|
520
534
|
# case a continuation is stored for later execution)
|
|
521
535
|
callback.call(object, context, self) do
|
|
522
|
-
before(complete, index + 1, &
|
|
536
|
+
before(complete, index + 1, &)
|
|
523
537
|
|
|
524
538
|
pause if @success && !complete
|
|
525
539
|
|
|
@@ -531,11 +545,11 @@ module StateMachines
|
|
|
531
545
|
# Normal before callback
|
|
532
546
|
callback.call(object, context, self)
|
|
533
547
|
# Continue with next callback
|
|
534
|
-
before(complete, index + 1, &
|
|
548
|
+
before(complete, index + 1, &)
|
|
535
549
|
end
|
|
536
550
|
else
|
|
537
551
|
# Skip to next callback if it doesn't match
|
|
538
|
-
before(complete, index + 1, &
|
|
552
|
+
before(complete, index + 1, &)
|
|
539
553
|
end
|
|
540
554
|
else
|
|
541
555
|
# No more callbacks, execute the action block if at the end
|