Skip to content

Instantly share code, notes, and snippets.

@tkareine
Created October 28, 2013 17:53
Show Gist options
  • Save tkareine/7201399 to your computer and use it in GitHub Desktop.
Save tkareine/7201399 to your computer and use it in GitHub Desktop.
$ ruby test_pty.rb ./ex19
[child] You enter the The great hall.
[child]
[child] >
--(interaction)--
[child] You can go:
[child] NORTH
[child]
[child] >
--(interaction)--
[child] The throne room.
[child]
[child] >
(RuntimeError)n `assert': Expected "The throne room.
> " to match (?-mix:^You go north, into:)
from test_pty.rb:13:in `assert_match'
from test_pty.rb:42:in `block (2 levels) in <main>'
from test_pty.rb:37:in `each'
from test_pty.rb:37:in `block in <main>'
from test_pty.rb:35:in `spawn'
from test_pty.rb:35:in `<main>'
$ ruby test_pty.rb ./ex19
[child] You enter the The great hall.
[child]
[child] >
--(interaction)--
[child] You can go:
[child] NORTH
[child]
[child] >
--(interaction)--
[child] You go north, into:
[child] The throne room.
[child]
[child] >
# Buggy: misses output sometimes
require 'pty'
MAX_OUTPUT_SIZE = 4096
def assert(exp)
raise yield unless exp
true
end
def assert_match(actual, regex)
assert(actual =~ regex) { "Expected \"#{actual}\" to match #{regex}" }
end
def read_output(io)
buffer = ''
until buffer =~ /\n> /
io.readpartial MAX_OUTPUT_SIZE, buffer
end
buffer
end
def echo_output(str)
str.split("\n").each do |line|
puts "[child] #{line}"
end
end
commands = [
['l', /^NORTH/],
['n', /^You go north, into:/]
]
PTY.spawn(ARGV.join(' ')) do |read_io, write_io, pid|
echo_output read_output(read_io)
commands.each do |input, expectation|
puts "--(interaction)--"
write_io.puts input
actual_output = read_output read_io
echo_output actual_output
assert_match actual_output, expectation
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment