Skip to content

Commit

Permalink
Add tests for Kernel.sleep calling the Fiber scheduler hook
Browse files Browse the repository at this point in the history
  • Loading branch information
herwinw committed Oct 30, 2023
1 parent 09d73f4 commit 3ab4773
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
30 changes: 30 additions & 0 deletions core/fiber/fixtures/scheduler.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
module FiberSpecs

class LoggingScheduler
attr_reader :events
def initialize
@events = []
end

def block(*args)
@events << { event: :block, fiber: Fiber.current, args: args }
Fiber.yield
end

def io_wait(*args)
@events << { event: :io_wait, fiber: Fiber.current, args: args }
Fiber.yield
end

def kernel_sleep(*args)
@events << { event: :kernel_sleep, fiber: Fiber.current, args: args }
Fiber.yield
end

def unblock(*args)
@events << { event: :unblock, fiber: Fiber.current, args: args }
Fiber.yield
end
end

end
36 changes: 36 additions & 0 deletions core/kernel/sleep_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
require_relative '../../spec_helper'
require_relative '../fiber/fixtures/scheduler'
require 'fiber'

describe "Kernel#sleep" do
it "is a private method" do
Expand Down Expand Up @@ -73,6 +75,40 @@ def o.divmod(*); [0, 0.001]; end
t.value.should == 5
end
end

context "Kernel.sleep with Fiber scheduler" do
before :each do
Fiber.set_scheduler(FiberSpecs::LoggingScheduler.new)
end

after :each do
Fiber.set_scheduler(nil)
end

it "calls the scheduler without arguments when no duration is given" do
sleeper = Fiber.new(blocking: false) do
sleep
end
sleeper.resume
Fiber.scheduler.events.should == [{ event: :kernel_sleep, fiber: sleeper, args: [] }]
end

it "calls the scheduler with the given duration" do
sleeper = Fiber.new(blocking: false) do
sleep(0.01)
end
sleeper.resume
Fiber.scheduler.events.should == [{ event: :kernel_sleep, fiber: sleeper, args: [0.01] }]
end

it "does not call the scheduler if the fiber is blocking" do
sleeper = Fiber.new(blocking: true) do
sleep(0.01)
end
sleeper.resume
Fiber.scheduler.events.should == []
end
end
end

describe "Kernel.sleep" do
Expand Down

0 comments on commit 3ab4773

Please sign in to comment.