Class: Phronomy::Testing::FakeClock
- Inherits:
-
Object
- Object
- Phronomy::Testing::FakeClock
- Defined in:
- lib/phronomy/testing/fake_clock.rb
Overview
Deterministic manually-advanced clock for tests.
Instance Attribute Summary collapse
-
#now ⇒ Object
readonly
Returns the value of attribute now.
Instance Method Summary collapse
- #advance(seconds) ⇒ Object
- #advance_to_next_timer ⇒ Object
- #at(at, &block) ⇒ Object
-
#initialize ⇒ FakeClock
constructor
A new instance of FakeClock.
- #next_timer_at ⇒ Object
- #pending_callbacks ⇒ Object
- #pending_timer_entries ⇒ Object
- #schedule(seconds:, &block) ⇒ Object
Constructor Details
#initialize ⇒ FakeClock
Returns a new instance of FakeClock.
9 10 11 12 13 |
# File 'lib/phronomy/testing/fake_clock.rb', line 9 def initialize @now = 0.0 @callbacks = [] @mutex = Mutex.new end |
Instance Attribute Details
#now ⇒ Object (readonly)
Returns the value of attribute now.
7 8 9 |
# File 'lib/phronomy/testing/fake_clock.rb', line 7 def now @now end |
Instance Method Details
#advance(seconds) ⇒ Object
15 16 17 18 19 20 21 |
# File 'lib/phronomy/testing/fake_clock.rb', line 15 def advance(seconds) @mutex.synchronize do @now += seconds.to_f fire_expired_callbacks! end self end |
#advance_to_next_timer ⇒ Object
40 41 42 43 44 |
# File 'lib/phronomy/testing/fake_clock.rb', line 40 def advance_to_next_timer target = next_timer_at raise "No pending timers to advance to" unless target advance(target - @now) end |
#at(at, &block) ⇒ Object
23 24 25 26 |
# File 'lib/phronomy/testing/fake_clock.rb', line 23 def at(at, &block) @mutex.synchronize { @callbacks << [at.to_f, block] } self end |
#next_timer_at ⇒ Object
36 37 38 |
# File 'lib/phronomy/testing/fake_clock.rb', line 36 def next_timer_at @mutex.synchronize { @callbacks.min_by { |(t, _)| t }&.first } end |
#pending_callbacks ⇒ Object
32 33 34 |
# File 'lib/phronomy/testing/fake_clock.rb', line 32 def pending_callbacks @mutex.synchronize { @callbacks.size } end |
#pending_timer_entries ⇒ Object
46 47 48 49 50 51 52 |
# File 'lib/phronomy/testing/fake_clock.rb', line 46 def pending_timer_entries @mutex.synchronize do @callbacks.sort_by { |(t, _)| t }.map do |(time, _)| {fire_at: time, description: nil} end end end |
#schedule(seconds:, &block) ⇒ Object
28 29 30 |
# File 'lib/phronomy/testing/fake_clock.rb', line 28 def schedule(seconds:, &block) at(@now + seconds.to_f, &block) end |