1
0
Fork 0
mirror of https://github.com/pry/pry.git synced 2022-11-09 12:35:05 -05:00
pry--pry/spec/spec_helpers/repl_tester.rb

113 lines
2.3 KiB
Ruby
Raw Normal View History

2012-12-23 03:03:29 -05:00
# This is for super-high-level integration testing.
require 'thread'
2012-12-23 22:58:18 -05:00
require 'delegate'
2012-12-23 03:03:29 -05:00
class ReplTester
class Input
def initialize(tester_mailbox)
@tester_mailbox = tester_mailbox
end
2012-12-23 03:03:29 -05:00
def readline(prompt)
2012-12-23 22:58:18 -05:00
@tester_mailbox.push prompt
mailbox.pop
end
def mailbox
Thread.current[:mailbox]
end
2012-12-23 22:58:18 -05:00
end
2012-12-23 22:58:18 -05:00
class Output < SimpleDelegator
def clear
__setobj__(StringIO.new)
2012-12-23 03:03:29 -05:00
end
end
def self.start(options = {}, &block)
Thread.current[:mailbox] = Queue.new
instance = nil
2012-12-23 22:58:18 -05:00
input = Input.new(Thread.current[:mailbox])
output = Output.new(StringIO.new)
2012-12-23 22:58:18 -05:00
redirect_pry_io input, output do
instance = new(options)
instance.instance_eval(&block)
instance.ensure_exit
2012-12-23 03:03:29 -05:00
end
ensure
if instance && instance.thread && instance.thread.alive?
instance.thread.kill
end
2012-12-23 03:03:29 -05:00
end
2012-12-23 22:58:18 -05:00
attr_accessor :thread, :mailbox, :last_prompt
2012-12-23 03:03:29 -05:00
def initialize(options = {})
@pry = Pry.new(options)
@repl = Pry::REPL.new(@pry)
@mailbox = Thread.current[:mailbox]
2012-12-23 03:03:29 -05:00
@thread = Thread.new do
begin
Thread.current[:mailbox] = Queue.new
@repl.start
ensure
Thread.current[:session_ended] = true
mailbox.push nil
end
2012-12-23 03:03:29 -05:00
end
2012-12-23 23:05:37 -05:00
wait # wait until the instance reaches its first readline
2012-12-23 03:03:29 -05:00
end
# Accept a line of input, as if entered by a user.
def input(input)
reset_output
repl_mailbox.push input
2012-12-23 23:05:37 -05:00
wait
2012-12-28 17:12:19 -05:00
Pry.output.string
2012-12-23 03:03:29 -05:00
end
# Assert that the current prompt matches the given string or regex.
2012-12-23 03:03:29 -05:00
def prompt(match)
2012-12-23 22:58:18 -05:00
match.should === last_prompt
2012-12-23 03:03:29 -05:00
end
# Assert that the most recent output (since the last time input was called)
# matches the given string or regex.
def output(match)
2012-12-23 03:03:29 -05:00
match.should === Pry.output.string.chomp
end
# Assert that the Pry session ended naturally after the last input.
def assert_exited
@should_exit_naturally = true
end
# @private
def ensure_exit
if @should_exit_naturally
@thread[:session_ended].should.be.true
else
input "exit-all"
raise "REPL didn't die" unless @thread[:session_ended]
end
end
private
def reset_output
2012-12-23 22:58:18 -05:00
Pry.output.clear
end
def repl_mailbox
@thread[:mailbox]
end
2012-12-23 23:05:37 -05:00
def wait
@last_prompt = mailbox.pop
end
2012-12-23 03:03:29 -05:00
end