require 'test/unit' require 'tempfile' require 'timeout' require_relative 'envutil' class TestBeginEndBlock < Test::Unit::TestCase DIR = File.dirname(File.expand_path(__FILE__)) def q(content) "\"#{content}\"" end def test_beginendblock ruby = EnvUtil.rubybin target = File.join(DIR, 'beginmainend.rb') result = IO.popen([ruby, target]){|io|io.read} assert_equal(%w(b1 b2-1 b2 main b3-1 b3 b4 e1 e1-1 e4 e4-2 e4-1 e4-1-1 e3 e2), result.split) Tempfile.create(self.class.name) {|input| inputpath = input.path result = IO.popen([ruby, "-n", "-eBEGIN{p :begin}", "-eEND{p :end}", inputpath]){|io|io.read} assert_equal(%w(:begin), result.split) result = IO.popen([ruby, "-p", "-eBEGIN{p :begin}", "-eEND{p :end}", inputpath]){|io|io.read} assert_equal(%w(:begin), result.split) input.puts "foo\nbar" input.close result = IO.popen([ruby, "-n", "-eBEGIN{p :begin}", "-eEND{p :end}", inputpath]){|io|io.read} assert_equal(%w(:begin :end), result.split) result = IO.popen([ruby, "-p", "-eBEGIN{p :begin}", "-eEND{p :end}", inputpath]){|io|io.read} assert_equal(%w(:begin foo bar :end), result.split) } end def test_begininmethod assert_raise_with_message(SyntaxError, /BEGIN is permitted only at toplevel/) do eval("def foo; BEGIN {}; end") end assert_raise_with_message(SyntaxError, /BEGIN is permitted only at toplevel/) do eval('eval("def foo; BEGIN {}; end")') end end def test_begininclass assert_raise_with_message(SyntaxError, /BEGIN is permitted only at toplevel/) do eval("class TestBeginEndBlock; BEGIN {}; end") end end def test_endblockwarn ruby = EnvUtil.rubybin # Use Tempfile to create temporary file path. Tempfile.create(self.class.name) {|launcher| Tempfile.create(self.class.name) {|errout| launcher << <