Skip to content

Commit

Permalink
Optional clock gettime 2 (#427)
Browse files Browse the repository at this point in the history
* Disable Process#clock_gettime mocking by default

* prepare release 0.9.9

* update readme

---------

Co-authored-by: Alex Watt <alex@alexcwatt.com>
  • Loading branch information
joshuacronemeyer and alexcwatt committed Jun 14, 2024
1 parent 69405ac commit b5783d8
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
9 changes: 9 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,15 @@ Timecop.freeze
# => Timecop::SafeModeException: Safe mode is enabled, only calls passing a block are allowed.
```

### Configuring Mocking Process.clock_gettime

By default Timecop does not mock Process.clock_gettime. You must enable it like this:

``` ruby
# turn on
Timecop.mock_process_clock = true
```

### Rails v Ruby Date/Time libraries

Sometimes [Rails Date/Time methods don't play nicely with Ruby Date/Time methods.](https://rails.lighthouseapp.com/projects/8994/tickets/6410-dateyesterday-datetoday)
Expand Down
2 changes: 1 addition & 1 deletion lib/timecop/time_extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def clock_gettime_mock_time(clock_id, unit = :float_second)
mock_time_realtime
end

return clock_gettime_without_mock(clock_id, unit) unless mock_time
return clock_gettime_without_mock(clock_id, unit) unless Timecop.mock_process_clock? && mock_time

divisor = case unit
when :float_second
Expand Down
8 changes: 8 additions & 0 deletions lib/timecop/timecop.rb
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,14 @@ def scaled?
!instance.stack.empty? && instance.stack.last.mock_type == :scale
end

def mock_process_clock=(mock)
@mock_process_clock = mock
end

def mock_process_clock?
@mock_process_clock ||= false
end

private
def send_travel(mock_type, *args, &block)
val = instance.travel(mock_type, *args, &block)
Expand Down
13 changes: 13 additions & 0 deletions test/timecop_with_process_clock_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,24 @@
class TestTimecopWithProcessClock < Minitest::Test
TIME_EPSILON = 0.001 # seconds - represents enough time for Process.clock_gettime to have advanced if not frozen

def setup
Timecop.mock_process_clock = true
end

def teardown
Timecop.return
Timecop.mock_process_clock = false
end

if RUBY_VERSION >= '2.1.0'
def test_process_clock_mock_disabled
Timecop.mock_process_clock = false

Timecop.freeze do
refute_same(*consecutive_monotonic, "CLOCK_MONOTONIC is frozen")
end
end

def test_process_clock_gettime_monotonic
Timecop.freeze do
assert_same(*consecutive_monotonic, "CLOCK_MONOTONIC is not frozen")
Expand Down

0 comments on commit b5783d8

Please sign in to comment.