From 8f671120f1d99b47f28d67183855d634d006389a Mon Sep 17 00:00:00 2001 From: akr Date: Sat, 20 Apr 2013 23:03:52 +0000 Subject: * test/csv/test_features.rb, test/logger/test_logger.rb test/mkmf/test_have_macro.rb, test/net/http/test_http.rb, test/openssl/test_config.rb, test/psych/test_encoding.rb, test/psych/test_exception.rb, test/psych/test_psych.rb, test/psych/test_tainted.rb, test/readline/test_readline.rb, test/rexml/test_contrib.rb, test/ruby/test_autoload.rb, test/ruby/test_beginendblock.rb, test/ruby/test_exception.rb, test/ruby/test_file.rb, test/ruby/test_io.rb, test/ruby/test_marshal.rb, test/ruby/test_process.rb, test/ruby/test_require.rb, test/ruby/test_rubyoptions.rb, test/syslog/test_syslog_logger.rb, test/webrick/test_httpauth.rb, test/zlib/test_zlib.rb: Use Tempfile.create. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@40400 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- test/csv/test_features.rb | 44 +-- test/logger/test_logger.rb | 13 +- test/mkmf/test_have_macro.rb | 6 +- test/net/http/test_http.rb | 88 +++-- test/openssl/test_config.rb | 26 +- test/psych/test_encoding.rb | 74 ++-- test/psych/test_exception.rb | 39 +- test/psych/test_psych.rb | 27 +- test/psych/test_tainted.rb | 14 +- test/readline/test_readline.rb | 65 ++-- test/rexml/test_contrib.rb | 16 +- test/ruby/test_autoload.rb | 162 ++++----- test/ruby/test_beginendblock.rb | 92 +++-- test/ruby/test_exception.rb | 39 +- test/ruby/test_file.rb | 192 +++++----- test/ruby/test_io.rb | 44 +-- test/ruby/test_marshal.rb | 7 +- test/ruby/test_process.rb | 3 +- test/ruby/test_require.rb | 310 ++++++++-------- test/ruby/test_rubyoptions.rb | 193 +++++----- test/syslog/test_syslog_logger.rb | 13 +- test/webrick/test_httpauth.rb | 162 ++++----- test/zlib/test_zlib.rb | 739 +++++++++++++++++++------------------- 23 files changed, 1159 insertions(+), 1209 deletions(-) (limited to 'test') diff --git a/test/csv/test_features.rb b/test/csv/test_features.rb index 698d92144d..8c2b3eb2b7 100755 --- a/test/csv/test_features.rb +++ b/test/csv/test_features.rb @@ -212,21 +212,21 @@ class TestCSV::Features < TestCSV end if defined?(Zlib::GzipReader) def test_gzip_writer_bug_fix - tempfile = Tempfile.new(%w"temp .gz") - tempfile.close - file = tempfile.path - zipped = nil - assert_nothing_raised(NoMethodError) do - zipped = CSV.new(Zlib::GzipWriter.open(file)) - end - zipped << %w[one two three] - zipped << [1, 2, 3] - zipped.close - - assert( Zlib::GzipReader.open(file) { |f| f.read }. - include?($INPUT_RECORD_SEPARATOR), - "@row_sep did not default" ) - tempfile.close(true) + Tempfile.create(%w"temp .gz") {|tempfile| + tempfile.close + file = tempfile.path + zipped = nil + assert_nothing_raised(NoMethodError) do + zipped = CSV.new(Zlib::GzipWriter.open(file)) + end + zipped << %w[one two three] + zipped << [1, 2, 3] + zipped.close + + assert( Zlib::GzipReader.open(file) { |f| f.read }. + include?($INPUT_RECORD_SEPARATOR), + "@row_sep did not default" ) + } end if defined?(Zlib::GzipWriter) def test_inspect_is_smart_about_io_types @@ -236,13 +236,13 @@ class TestCSV::Features < TestCSV str = CSV.new($stderr).inspect assert(str.include?("io_type:$stderr"), "IO type not detected.") - tempfile = Tempfile.new(%w"temp .csv") - tempfile.close - path = tempfile.path - File.open(path, "w") { |csv| csv << "one,two,three\n1,2,3\n" } - str = CSV.open(path) { |csv| csv.inspect } - assert(str.include?("io_type:File"), "IO type not detected.") - tempfile.close(true) + Tempfile.create(%w"temp .csv") {|tempfile| + tempfile.close + path = tempfile.path + File.open(path, "w") { |csv| csv << "one,two,three\n1,2,3\n" } + str = CSV.open(path) { |csv| csv.inspect } + assert(str.include?("io_type:File"), "IO type not detected.") + } end def test_inspect_shows_key_attributes diff --git a/test/logger/test_logger.rb b/test/logger/test_logger.rb index b153658659..eac2c7a5a6 100644 --- a/test/logger/test_logger.rb +++ b/test/logger/test_logger.rb @@ -41,13 +41,12 @@ class TestLogger < Test::Unit::TestCase end def log_raw(logger, msg_id, *arg, &block) - logdev = Tempfile.new(File.basename(__FILE__) + '.log') - logger.instance_eval { @logdev = Logger::LogDevice.new(logdev) } - logger.__send__(msg_id, *arg, &block) - logdev.open - msg = logdev.read - logdev.close(true) - msg + Tempfile.create(File.basename(__FILE__) + '.log') {|logdev| + logger.instance_eval { @logdev = Logger::LogDevice.new(logdev) } + logger.__send__(msg_id, *arg, &block) + logdev.rewind + logdev.read + } end def test_level diff --git a/test/mkmf/test_have_macro.rb b/test/mkmf/test_have_macro.rb index 5ee953c68f..43c4029f70 100644 --- a/test/mkmf/test_have_macro.rb +++ b/test/mkmf/test_have_macro.rb @@ -10,13 +10,12 @@ class TestMkmf end def test_have_macro_header - Tempfile.open(%w"test_mkmf .h", ".") do |tmp| + Tempfile.create(%w"test_mkmf .h", ".") do |tmp| tmp.puts("#undef #{MACRO_NAME}") tmp.puts("#define #{MACRO_NAME} 1") tmp.close base = File.basename(tmp.path) assert_equal(true, have_macro(MACRO_NAME, base, "-I."), MKMFLOG) - tmp.close(true) end end @@ -25,12 +24,11 @@ class TestMkmf end def test_not_have_macro_header - Tempfile.open(%w"test_mkmf .h", ".") do |tmp| + Tempfile.create(%w"test_mkmf .h", ".") do |tmp| tmp.puts("#undef #{MACRO_NAME}") tmp.close base = File.basename(tmp.path) assert_equal(false, have_macro(MACRO_NAME, base, "-I."), MKMFLOG) - tmp.close(true) end end end diff --git a/test/net/http/test_http.rb b/test/net/http/test_http.rb index 0b3eeeb6bf..b83844377f 100644 --- a/test/net/http/test_http.rb +++ b/test/net/http/test_http.rb @@ -599,15 +599,15 @@ module TestNetHTTP_version_1_2_methods def test_set_form require 'tempfile' - file = Tempfile.new('ruby-test') - file << "\u{30c7}\u{30fc}\u{30bf}" - data = [ - ['name', 'Gonbei Nanashi'], - ['name', "\u{540d}\u{7121}\u{3057}\u{306e}\u{6a29}\u{5175}\u{885b}"], - ['s"i\o', StringIO.new("\u{3042 3044 4e9c 925b}")], - ["file", file, filename: "ruby-test"] - ] - expected = <<"__EOM__".gsub(/\n/, "\r\n") + Tempfile.create('ruby-test') {|file| + file << "\u{30c7}\u{30fc}\u{30bf}" + data = [ + ['name', 'Gonbei Nanashi'], + ['name', "\u{540d}\u{7121}\u{3057}\u{306e}\u{6a29}\u{5175}\u{885b}"], + ['s"i\o', StringIO.new("\u{3042 3044 4e9c 925b}")], + ["file", file, filename: "ruby-test"] + ] + expected = <<"__EOM__".gsub(/\n/, "\r\n") -- Content-Disposition: form-data; name="name" @@ -627,13 +627,12 @@ Content-Type: application/octet-stream \xE3\x83\x87\xE3\x83\xBC\xE3\x82\xBF ---- __EOM__ - start {|http| - _test_set_form_urlencoded(http, data.reject{|k,v|!v.is_a?(String)}) - _test_set_form_multipart(http, false, data, expected) - _test_set_form_multipart(http, true, data, expected) + start {|http| + _test_set_form_urlencoded(http, data.reject{|k,v|!v.is_a?(String)}) + _test_set_form_multipart(http, false, data, expected) + _test_set_form_multipart(http, true, data, expected) + } } - ensure - file.close! if file end def _test_set_form_urlencoded(http, data) @@ -658,12 +657,12 @@ __EOM__ def test_set_form_with_file require 'tempfile' - file = Tempfile.new('ruby-test') - file.binmode - file << $test_net_http_data - filename = File.basename(file.to_path) - data = [['file', file]] - expected = <<"__EOM__".gsub(/\n/, "\r\n") + Tempfile.create('ruby-test') {|file| + file.binmode + file << $test_net_http_data + filename = File.basename(file.to_path) + data = [['file', file]] + expected = <<"__EOM__".gsub(/\n/, "\r\n") -- Content-Disposition: form-data; name="file"; filename="" Content-Type: application/octet-stream @@ -671,31 +670,30 @@ Content-Type: application/octet-stream ---- __EOM__ - expected.sub!(//, filename) - expected.sub!(//, $test_net_http_data) - start {|http| - data.each{|k,v|v.rewind rescue nil} - req = Net::HTTP::Post.new('/') - req.set_form(data, 'multipart/form-data') - res = http.request req - body = res.body - header, _ = body.split(/\r\n\r\n/, 2) - assert_match(/\A--(?\S+)/, body) - /\A--(?\S+)/ =~ body - expected = expected.gsub(//, boundary) - assert_match(/^--(?\S+)\r\n/, header) - assert_match( - /^Content-Disposition: form-data; name="file"; filename="#{filename}"\r\n/, - header) - assert_equal(expected, body) - - data.each{|k,v|v.rewind rescue nil} - req['Transfer-Encoding'] = 'chunked' - res = http.request req - #assert_equal(expected, res.body) + expected.sub!(//, filename) + expected.sub!(//, $test_net_http_data) + start {|http| + data.each{|k,v|v.rewind rescue nil} + req = Net::HTTP::Post.new('/') + req.set_form(data, 'multipart/form-data') + res = http.request req + body = res.body + header, _ = body.split(/\r\n\r\n/, 2) + assert_match(/\A--(?\S+)/, body) + /\A--(?\S+)/ =~ body + expected = expected.gsub(//, boundary) + assert_match(/^--(?\S+)\r\n/, header) + assert_match( + /^Content-Disposition: form-data; name="file"; filename="#{filename}"\r\n/, + header) + assert_equal(expected, body) + + data.each{|k,v|v.rewind rescue nil} + req['Transfer-Encoding'] = 'chunked' + res = http.request req + #assert_equal(expected, res.body) + } } - ensure - file.close! if file end end diff --git a/test/openssl/test_config.rb b/test/openssl/test_config.rb index 88bb5af7be..1cd3cb6391 100644 --- a/test/openssl/test_config.rb +++ b/test/openssl/test_config.rb @@ -121,13 +121,12 @@ __EOC__ assert_equal("", c.to_s) assert_equal([], c.sections) # - file = Tempfile.open("openssl.cnf") - file.close - c = OpenSSL::Config.load(file.path) - assert_equal("[ default ]\n\n", c.to_s) - assert_equal(['default'], c.sections) - ensure - file.unlink if file + Tempfile.create("openssl.cnf") {|file| + file.close + c = OpenSSL::Config.load(file.path) + assert_equal("[ default ]\n\n", c.to_s) + assert_equal(['default'], c.sections) + } end def test_initialize @@ -137,13 +136,12 @@ __EOC__ end def test_initialize_with_empty_file - file = Tempfile.open("openssl.cnf") - file.close - c = OpenSSL::Config.new(file.path) - assert_equal("[ default ]\n\n", c.to_s) - assert_equal(['default'], c.sections) - ensure - file.unlink if file + Tempfile.create("openssl.cnf") {|file| + file.close + c = OpenSSL::Config.new(file.path) + assert_equal("[ default ]\n\n", c.to_s) + assert_equal(['default'], c.sections) + } end def test_initialize_with_example_file diff --git a/test/psych/test_encoding.rb b/test/psych/test_encoding.rb index 2cddd5983f..4f26fa3c9c 100644 --- a/test/psych/test_encoding.rb +++ b/test/psych/test_encoding.rb @@ -50,58 +50,54 @@ module Psych end def test_io_shiftjis - t = Tempfile.new(['shiftjis', 'yml'], :encoding => 'SHIFT_JIS') - t.write '--- こんにちは!' - t.close - - # If the external encoding isn't utf8, utf16le, or utf16be, we cannot - # process the file. - File.open(t.path, 'r', :encoding => 'SHIFT_JIS') do |f| - assert_raises Psych::SyntaxError do - Psych.load(f) + Tempfile.create(['shiftjis', 'yml'], :encoding => 'SHIFT_JIS') {|t| + t.write '--- こんにちは!' + t.close + + # If the external encoding isn't utf8, utf16le, or utf16be, we cannot + # process the file. + File.open(t.path, 'r', :encoding => 'SHIFT_JIS') do |f| + assert_raises Psych::SyntaxError do + Psych.load(f) + end end - end - - t.close(true) + } end def test_io_utf16le - t = Tempfile.new(['utf16le', 'yml']) - t.binmode - t.write '--- こんにちは!'.encode('UTF-16LE') - t.close + Tempfile.create(['utf16le', 'yml']) {|t| + t.binmode + t.write '--- こんにちは!'.encode('UTF-16LE') + t.close - File.open(t.path, 'rb', :encoding => 'UTF-16LE') do |f| - assert_equal "こんにちは!", Psych.load(f) - end - - t.close(true) + File.open(t.path, 'rb', :encoding => 'UTF-16LE') do |f| + assert_equal "こんにちは!", Psych.load(f) + end + } end def test_io_utf16be - t = Tempfile.new(['utf16be', 'yml']) - t.binmode - t.write '--- こんにちは!'.encode('UTF-16BE') - t.close + Tempfile.create(['utf16be', 'yml']) {|t| + t.binmode + t.write '--- こんにちは!'.encode('UTF-16BE') + t.close - File.open(t.path, 'rb', :encoding => 'UTF-16BE') do |f| - assert_equal "こんにちは!", Psych.load(f) - end - - t.close(true) + File.open(t.path, 'rb', :encoding => 'UTF-16BE') do |f| + assert_equal "こんにちは!", Psych.load(f) + end + } end def test_io_utf8 - t = Tempfile.new(['utf8', 'yml']) - t.binmode - t.write '--- こんにちは!'.encode('UTF-8') - t.close + Tempfile.create(['utf8', 'yml']) {|t| + t.binmode + t.write '--- こんにちは!'.encode('UTF-8') + t.close - File.open(t.path, 'rb', :encoding => 'UTF-8') do |f| - assert_equal "こんにちは!", Psych.load(f) - end - - t.close(true) + File.open(t.path, 'rb', :encoding => 'UTF-8') do |f| + assert_equal "こんにちは!", Psych.load(f) + end + } end def test_emit_alias diff --git a/test/psych/test_exception.rb b/test/psych/test_exception.rb index d54c7d4fbb..a9fe5c43d1 100644 --- a/test/psych/test_exception.rb +++ b/test/psych/test_exception.rb @@ -56,27 +56,27 @@ module Psych end def test_parse_file_exception - t = Tempfile.new(['parsefile', 'yml']) - t.binmode - t.write '--- `' - t.close - ex = assert_raises(Psych::SyntaxError) do - Psych.parse_file t.path - end - assert_equal t.path, ex.file - t.close(true) + Tempfile.create(['parsefile', 'yml']) {|t| + t.binmode + t.write '--- `' + t.close + ex = assert_raises(Psych::SyntaxError) do + Psych.parse_file t.path + end + assert_equal t.path, ex.file + } end def test_load_file_exception - t = Tempfile.new(['loadfile', 'yml']) - t.binmode - t.write '--- `' - t.close - ex = assert_raises(Psych::SyntaxError) do - Psych.load_file t.path - end - assert_equal t.path, ex.file - t.close(true) + Tempfile.create(['loadfile', 'yml']) {|t| + t.binmode + t.write '--- `' + t.close + ex = assert_raises(Psych::SyntaxError) do + Psych.load_file t.path + end + assert_equal t.path, ex.file + } end def test_psych_parse_takes_file @@ -128,7 +128,7 @@ module Psych end def test_psych_syntax_error - Tempfile.open(['parsefile', 'yml']) do |t| + Tempfile.create(['parsefile', 'yml']) do |t| t.binmode t.write '--- `' t.close @@ -138,7 +138,6 @@ module Psych rescue StandardError assert true # count assertion ensure - t.close(true) return unless $! ancestors = $!.class.ancestors.inspect diff --git a/test/psych/test_psych.rb b/test/psych/test_psych.rb index 96dde9d5b7..8054bd6234 100644 --- a/test/psych/test_psych.rb +++ b/test/psych/test_psych.rb @@ -64,11 +64,10 @@ class TestPsych < Psych::TestCase def test_dump_file hash = {'hello' => 'TGIF!'} - Tempfile.open('fun.yml') do |io| + Tempfile.create('fun.yml') do |io| assert_equal io, Psych.dump(hash, io) io.rewind assert_equal Psych.dump(hash), io.read - io.close(true) end end @@ -126,21 +125,21 @@ class TestPsych < Psych::TestCase end def test_load_file - t = Tempfile.new(['yikes', 'yml']) - t.binmode - t.write('--- hello world') - t.close - assert_equal 'hello world', Psych.load_file(t.path) - t.close(true) + Tempfile.create(['yikes', 'yml']) {|t| + t.binmode + t.write('--- hello world') + t.close + assert_equal 'hello world', Psych.load_file(t.path) + } end def test_parse_file - t = Tempfile.new(['yikes', 'yml']) - t.binmode - t.write('--- hello world') - t.close - assert_equal 'hello world', Psych.parse_file(t.path).transform - t.close(true) + Tempfile.create(['yikes', 'yml']) {|t| + t.binmode + t.write('--- hello world') + t.close + assert_equal 'hello world', Psych.parse_file(t.path).transform + } end def test_degenerate_strings diff --git a/test/psych/test_tainted.rb b/test/psych/test_tainted.rb index 62872b00e0..37fc5b2b80 100644 --- a/test/psych/test_tainted.rb +++ b/test/psych/test_tainted.rb @@ -117,14 +117,14 @@ module Psych class TestIOTainted < TestStringTainted def assert_taintedness string - t = Tempfile.new(['something', 'yml']) - t.binmode - t.write string - t.close - File.open(t.path, 'r:bom|utf-8') { |f| - @parser.parse f + Tempfile.create(['something', 'yml']) {|t| + t.binmode + t.write string + t.close + File.open(t.path, 'r:bom|utf-8') { |f| + @parser.parse f + } } - t.close(true) end end end diff --git a/test/readline/test_readline.rb b/test/readline/test_readline.rb index 88ad10195b..a4c8e581a3 100644 --- a/test/readline/test_readline.rb +++ b/test/readline/test_readline.rb @@ -72,13 +72,13 @@ class TestReadline < Test::Unit::TestCase with_temp_stdio do |stdin, stdout| stdin.write("hello\n") stdin.close - stdout.close + stdout.flush line = replace_stdio(stdin.path, stdout.path) { Readline.readline("> ", true) } assert_equal("hello", line) assert_equal(true, line.tainted?) - stdout.open + stdout.rewind assert_equal("> ", stdout.read(2)) assert_equal(1, Readline::HISTORY.length) assert_equal("hello", Readline::HISTORY[0]) @@ -118,8 +118,8 @@ class TestReadline < Test::Unit::TestCase actual_point = Readline.point actual_line_buffer = Readline.line_buffer stdin.write(" finish\n") - stdin.close - stdout.close + stdin.flush + stdout.flush return ["complete"] } @@ -137,8 +137,8 @@ class TestReadline < Test::Unit::TestCase assert_equal(true, Readline.line_buffer.tainted?) assert_equal(22, Readline.point) - stdin.open - stdout.open + stdin.rewind + stdout.rewind stdin.write("first second\t") stdin.flush @@ -377,31 +377,29 @@ class TestReadline < Test::Unit::TestCase end if !/EditLine/n.match(Readline::VERSION) def test_modify_text_in_pre_input_hook - begin - stdin = Tempfile.new("readline_redisplay_stdin") - stdout = Tempfile.new("readline_redisplay_stdout") - stdin.write("world\n") - stdin.close - Readline.pre_input_hook = proc do - assert_equal("", Readline.line_buffer) - Readline.insert_text("hello ") - Readline.redisplay - end - replace_stdio(stdin.path, stdout.path) do - line = Readline.readline("> ") - assert_equal("hello world", line) - end - assert_equal("> hello world\n", stdout.read) - stdout.close - rescue NotImplementedError - ensure + with_temp_stdio {|stdin, stdout| begin - Readline.pre_input_hook = nil + stdin.write("world\n") + stdin.close + Readline.pre_input_hook = proc do + assert_equal("", Readline.line_buffer) + Readline.insert_text("hello ") + Readline.redisplay + end + replace_stdio(stdin.path, stdout.path) do + line = Readline.readline("> ") + assert_equal("hello world", line) + end + assert_equal("> hello world\n", stdout.read) + stdout.close rescue NotImplementedError + ensure + begin + Readline.pre_input_hook = nil + rescue NotImplementedError + end end - stdin.close(true) - stdout.close(true) - end + } end if !/EditLine|\A4\.3\z/n.match(Readline::VERSION) def test_input_metachar @@ -472,12 +470,11 @@ class TestReadline < Test::Unit::TestCase end def with_temp_stdio - stdin = Tempfile.new("test_readline_stdin") - stdout = Tempfile.new("test_readline_stdout") - yield stdin, stdout - ensure - stdin.close(true) if stdin - stdout.close(true) if stdout + Tempfile.create("test_readline_stdin") {|stdin| + Tempfile.create("test_readline_stdout") {|stdout| + yield stdin, stdout + } + } end def with_pipe diff --git a/test/rexml/test_contrib.rb b/test/rexml/test_contrib.rb index 356dfc1425..d97b5a7753 100644 --- a/test/rexml/test_contrib.rb +++ b/test/rexml/test_contrib.rb @@ -511,8 +511,8 @@ EOL def test_pos require 'tempfile' - testfile = Tempfile.new("tidal") - testdata = %Q{ + Tempfile.create("tidal") {|testfile| + testdata = %Q{
760 50 @@ -520,12 +520,12 @@ EOL } - testfile.puts testdata - testfile.rewind - assert_nothing_raised do - REXML::Document.new(testfile) - end - testfile.close(true) + testfile.puts testdata + testfile.rewind + assert_nothing_raised do + REXML::Document.new(testfile) + end + } end def test_deep_clone diff --git a/test/ruby/test_autoload.rb b/test/ruby/test_autoload.rb index 8ca2187970..1931df45c5 100644 --- a/test/ruby/test_autoload.rb +++ b/test/ruby/test_autoload.rb @@ -57,109 +57,103 @@ p Foo::Bar end def test_require_explicit - file = Tempfile.open(['autoload', '.rb']) - file.puts 'class Object; AutoloadTest = 1; end' - file.close - add_autoload(file.path) - begin - assert_nothing_raised do - assert(require file.path) - assert_equal(1, ::AutoloadTest) + Tempfile.create(['autoload', '.rb']) {|file| + file.puts 'class Object; AutoloadTest = 1; end' + file.close + add_autoload(file.path) + begin + assert_nothing_raised do + assert(require file.path) + assert_equal(1, ::AutoloadTest) + end + ensure + remove_autoload_constant end - ensure - remove_autoload_constant - end - ensure - file.unlink + } end def test_threaded_accessing_constant - file = Tempfile.open(['autoload', '.rb']) - file.puts 'sleep 0.5; class AutoloadTest; X = 1; end' - file.close - add_autoload(file.path) - begin - assert_nothing_raised do - t1 = Thread.new { ::AutoloadTest::X } - t2 = Thread.new { ::AutoloadTest::X } - [t1, t2].each(&:join) + Tempfile.create(['autoload', '.rb']) {|file| + file.puts 'sleep 0.5; class AutoloadTest; X = 1; end' + file.close + add_autoload(file.path) + begin + assert_nothing_raised do + t1 = Thread.new { ::AutoloadTest::X } + t2 = Thread.new { ::AutoloadTest::X } + [t1, t2].each(&:join) + end + ensure + remove_autoload_constant end - ensure - remove_autoload_constant - end - ensure - file.unlink + } end def test_threaded_accessing_inner_constant - file = Tempfile.open(['autoload', '.rb']) - file.puts 'class AutoloadTest; sleep 0.5; X = 1; end' - file.close - add_autoload(file.path) - begin - assert_nothing_raised do - t1 = Thread.new { ::AutoloadTest::X } - t2 = Thread.new { ::AutoloadTest::X } - [t1, t2].each(&:join) + Tempfile.create(['autoload', '.rb']) {|file| + file.puts 'class AutoloadTest; sleep 0.5; X = 1; end' + file.close + add_autoload(file.path) + begin + assert_nothing_raised do + t1 = Thread.new { ::AutoloadTest::X } + t2 = Thread.new { ::AutoloadTest::X } + [t1, t2].each(&:join) + end + ensure + remove_autoload_constant end - ensure - remove_autoload_constant - end - ensure - file.unlink + } end def test_nameerror_when_autoload_did_not_define_the_constant - file = Tempfile.open(['autoload', '.rb']) - file.puts '' - file.close - add_autoload(file.path) - begin - assert_raise(NameError) do - AutoloadTest + Tempfile.create(['autoload', '.rb']) {|file| + file.puts '' + file.close + add_autoload(file.path) + begin + assert_raise(NameError) do + AutoloadTest + end + ensure + remove_autoload_constant end - ensure - remove_autoload_constant - end - ensure - file.unlink + } end def test_override_autoload - file = Tempfile.open(['autoload', '.rb']) - file.puts '' - file.close - add_autoload(file.path) - begin - eval %q(class AutoloadTest; end) - assert_equal(Class, AutoloadTest.class) - ensure - remove_autoload_constant - end - ensure - file.unlink + Tempfile.create(['autoload', '.rb']) {|file| + file.puts '' + file.close + add_autoload(file.path) + begin + eval %q(class AutoloadTest; end) + assert_equal(Class, AutoloadTest.class) + ensure + remove_autoload_constant + end + } end def test_override_while_autoloading - file = Tempfile.open(['autoload', '.rb']) - file.puts 'class AutoloadTest; sleep 0.5; end' - file.close - add_autoload(file.path) - begin - # while autoloading... - t = Thread.new { AutoloadTest } - sleep 0.1 - # override it - EnvUtil.suppress_warning { - eval %q(AutoloadTest = 1) - } - t.join - assert_equal(1, AutoloadTest) - ensure - remove_autoload_constant - end - ensure - file.unlink + Tempfile.create(['autoload', '.rb']) {|file| + file.puts 'class AutoloadTest; sleep 0.5; end' + file.close + add_autoload(file.path) + begin + # while autoloading... + t = Thread.new { AutoloadTest } + sleep 0.1 + # override it + EnvUtil.suppress_warning { + eval %q(AutoloadTest = 1) + } + t.join + assert_equal(1, AutoloadTest) + ensure + remove_autoload_constant + end + } end def add_autoload(path) diff --git a/test/ruby/test_beginendblock.rb b/test/ruby/test_beginendblock.rb index beb934b1ac..85b2afb139 100644 --- a/test/ruby/test_beginendblock.rb +++ b/test/ruby/test_beginendblock.rb @@ -16,22 +16,19 @@ class TestBeginEndBlock < Test::Unit::TestCase 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) - input = Tempfile.new(self.class.name) - inputpath = input.path - input.close - 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.open - 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) - ensure - input.unlink + 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 @@ -56,10 +53,10 @@ class TestBeginEndBlock < Test::Unit::TestCase def test_endblockwarn ruby = EnvUtil.rubybin # Use Tempfile to create temporary file path. - launcher = Tempfile.new(self.class.name) - errout = Tempfile.new(self.class.name) + Tempfile.create(self.class.name) {|launcher| + Tempfile.create(self.class.name) {|errout| - launcher << <true}, {:binmode=>true}].each do |mode| - f = Tempfile.new("test-extended-file", mode) - assert_nil(f.getc) - f.print "a" - f.rewind - assert_equal("a", f.read, "mode = <#{mode}>") - f.close(true) + Tempfile.create("test-extended-file", mode) {|f| + assert_nil(f.getc) + f.print "a" + f.rewind + assert_equal("a", f.read, "mode = <#{mode}>") + } end end def test_gets_extended_file [nil, {:textmode=>true}, {:binmode=>true}].each do |mode| - f = Tempfile.new("test-extended-file", mode) - assert_nil(f.getc) - f.print "a" - f.rewind - assert_equal("a", f.gets("a"), "mode = <#{mode}>") - f.close(true) + Tempfile.create("test-extended-file", mode) {|f| + assert_nil(f.getc) + f.print "a" + f.rewind + assert_equal("a", f.gets("a"), "mode = <#{mode}>") + } end end def test_gets_para_extended_file [nil, {:textmode=>true}, {:binmode=>true}].each do |mode| - f = Tempfile.new("test-extended-file", mode) - assert_nil(f.getc) - f.print "\na" - f.rewind - assert_equal("a", f.gets(""), "mode = <#{mode}>") - f.close(true) + Tempfile.create("test-extended-file", mode) {|f| + assert_nil(f.getc) + f.print "\na" + f.rewind + assert_equal("a", f.gets(""), "mode = <#{mode}>") + } end end def test_each_char_extended_file [nil, {:textmode=>true}, {:binmode=>true}].each do |mode| - f = Tempfile.new("test-extended-file", mode) - assert_nil(f.getc) - f.print "a" - f.rewind - result = [] - f.each_char {|b| result << b } - assert_equal([?a], result, "mode = <#{mode}>") - f.close(true) + Tempfile.create("test-extended-file", mode) {|f| + assert_nil(f.getc) + f.print "a" + f.rewind + result = [] + f.each_char {|b| result << b } + assert_equal([?a], result, "mode = <#{mode}>") + } end end def test_each_byte_extended_file [nil, {:textmode=>true}, {:binmode=>true}].each do |mode| - f = Tempfile.new("test-extended-file", mode) - assert_nil(f.getc) - f.print "a" - f.rewind - result = [] - f.each_byte {|b| result << b.chr } - assert_equal([?a], result, "mode = <#{mode}>") - f.close(true) + Tempfile.create("test-extended-file", mode) {|f| + assert_nil(f.getc) + f.print "a" + f.rewind + result = [] + f.each_byte {|b| result << b.chr } + assert_equal([?a], result, "mode = <#{mode}>") + } end end def test_getc_extended_file [nil, {:textmode=>true}, {:binmode=>true}].each do |mode| - f = Tempfile.new("test-extended-file", mode) - assert_nil(f.getc) - f.print "a" - f.rewind - assert_equal(?a, f.getc, "mode = <#{mode}>") - f.close(true) + Tempfile.create("test-extended-file", mode) {|f| + assert_nil(f.getc) + f.print "a" + f.rewind + assert_equal(?a, f.getc, "mode = <#{mode}>") + } end end def test_getbyte_extended_file [nil, {:textmode=>true}, {:binmode=>true}].each do |mode| - f = Tempfile.new("test-extended-file", mode) - assert_nil(f.getc) - f.print "a" - f.rewind - assert_equal(?a, f.getbyte.chr, "mode = <#{mode}>") - f.close(true) + Tempfile.create("test-extended-file", mode) {|f| + assert_nil(f.getc) + f.print "a" + f.rewind + assert_equal(?a, f.getbyte.chr, "mode = <#{mode}>") + } end end @@ -258,11 +255,10 @@ class TestFile < Test::Unit::TestCase require "tempfile" t = Time.at(-1) begin - f = Tempfile.new('test_utime_with_minus_time_segv') - File.utime(t, t, f) + Tempfile.create('test_utime_with_minus_time_segv') {|f| + File.utime(t, t, f) + } rescue - ensure - f.close(true) end puts '#{bug5596}' EOS diff --git a/test/ruby/test_io.rb b/test/ruby/test_io.rb index b968bb6fcd..58cae7e291 100644 --- a/test/ruby/test_io.rb +++ b/test/ruby/test_io.rb @@ -2204,7 +2204,7 @@ End return if /x86_64-linux/ !~ RUBY_PLATFORM # A binary form of struct flock depend on platform pad=0 - Tempfile.open(self.class.name) do |f| + Tempfile.create(self.class.name) do |f| r, w = IO.pipe pid = fork do r.close @@ -2230,7 +2230,6 @@ End Process.kill :TERM, pid Process.waitpid2(pid) - f.close(true) end end @@ -2240,7 +2239,7 @@ End start = 12 len = 34 sysid = 0 - Tempfile.open(self.class.name) do |f| + Tempfile.create(self.class.name) do |f| r, w = IO.pipe pid = fork do r.close @@ -2270,14 +2269,13 @@ End end def test_fcntl_dupfd - Tempfile.open(self.class.name) do |f| + Tempfile.create(self.class.name) do |f| fd = f.fcntl(Fcntl::F_DUPFD, 63) begin assert_operator(fd, :>=, 63) ensure IO.for_fd(fd).close end - f.unlink end end @@ -2396,23 +2394,25 @@ End end def test_race_between_read - file = Tempfile.new("test") - path = file.path - file.close - write_file = File.open(path, "wt") - read_file = File.open(path, "rt") - - threads = [] - 10.times do |i| - threads << Thread.new {write_file.print(i)} - threads << Thread.new {read_file.read} - end - threads.each {|t| t.join} - assert(true, "[ruby-core:37197]") - ensure - read_file.close - write_file.close - file.close! + Tempfile.create("test") {|file| + begin + path = file.path + file.close + write_file = File.open(path, "wt") + read_file = File.open(path, "rt") + + threads = [] + 10.times do |i| + threads << Thread.new {write_file.print(i)} + threads << Thread.new {read_file.read} + end + threads.each {|t| t.join} + assert(true, "[ruby-core:37197]") + ensure + read_file.close + write_file.close + end + } end def test_warn diff --git a/test/ruby/test_marshal.rb b/test/ruby/test_marshal.rb index 6d610b3a28..a642385a8e 100644 --- a/test/ruby/test_marshal.rb +++ b/test/ruby/test_marshal.rb @@ -333,11 +333,10 @@ class TestMarshal < Test::Unit::TestCase assert_equal(c, Marshal.load(Marshal.dump(c)), bug2109) assert_nothing_raised(ArgumentError, '[ruby-dev:40386]') do - re = Tempfile.open("marshal_regexp") do |f| + re = Tempfile.create("marshal_regexp") do |f| f.binmode.write("\x04\bI/\x00\x00\x06:\rencoding\"\rUS-ASCII") - f.close - re2 = Marshal.load(f.open.binmode) - f.close(true) + f.rewind + re2 = Marshal.load(f) re2 end assert_equal(//, re) diff --git a/test/ruby/test_process.rb b/test/ruby/test_process.rb index a70dca692e..99723f625f 100644 --- a/test/ruby/test_process.rb +++ b/test/ruby/test_process.rb @@ -808,14 +808,13 @@ class TestProcess < Test::Unit::TestCase def test_execopts_redirect_tempfile bug6269 = '[ruby-core:44181]' - Tempfile.open("execopts") do |tmp| + Tempfile.create("execopts") do |tmp| pid = assert_nothing_raised(ArgumentError, bug6269) do break spawn(RUBY, "-e", "print $$", out: tmp) end Process.wait(pid) tmp.rewind assert_equal(pid.to_s, tmp.read) - tmp.close(true) end end diff --git a/test/ruby/test_require.rb b/test/ruby/test_require.rb index c03876d223..663c125708 100644 --- a/test/ruby/test_require.rb +++ b/test/ruby/test_require.rb @@ -14,19 +14,19 @@ class TestRequire < Test::Unit::TestCase end def test_require_invalid_shared_object - t = Tempfile.new(["test_ruby_test_require", ".so"]) - t.puts "dummy" - t.close + Tempfile.create(["test_ruby_test_require", ".so"]) {|t| + t.puts "dummy" + t.close - assert_in_out_err([], <<-INPUT, %w(:ok), []) - $:.replace([IO::NULL]) - begin - require \"#{ t.path }\" - rescue LoadError - p :ok - end - INPUT - t.close(true) + assert_in_out_err([], <<-INPUT, %w(:ok), []) + $:.replace([IO::NULL]) + begin + require \"#{ t.path }\" + rescue LoadError + p :ok + end + INPUT + } end def test_require_too_long_filename @@ -111,21 +111,20 @@ class TestRequire < Test::Unit::TestCase def test_require_path_home_3 env_rubypath, env_home = ENV["RUBYPATH"], ENV["HOME"] - t = Tempfile.new(["test_ruby_test_require", ".rb"]) - t.puts "p :ok" - t.close - - ENV["RUBYPATH"] = "~" - ENV["HOME"] = t.path - assert_in_out_err(%w(-S test_ruby_test_require), "", [], /\(LoadError\)/) + Tempfile.create(["test_ruby_test_require", ".rb"]) {|t| + t.puts "p :ok" + t.close - ENV["HOME"], name = File.split(t.path) - assert_in_out_err(["-S", name], "", %w(:ok), []) + ENV["RUBYPATH"] = "~" + ENV["HOME"] = t.path + assert_in_out_err(%w(-S test_ruby_test_require), "", [], /\(LoadError\)/) + ENV["HOME"], name = File.split(t.path) + assert_in_out_err(["-S", name], "", %w(:ok), []) + } ensure env_rubypath ? ENV["RUBYPATH"] = env_rubypath : ENV.delete("RUBYPATH") env_home ? ENV["HOME"] = env_home : ENV.delete("HOME") - t.close(true) end def test_require_with_unc @@ -269,86 +268,85 @@ class TestRequire < Test::Unit::TestCase end def test_load - t = Tempfile.new(["test_ruby_test_require", ".rb"]) - t.puts "module Foo; end" - t.puts "at_exit { p :wrap_end }" - t.puts "at_exit { raise 'error in at_exit test' }" - t.puts "p :ok" - t.close - - assert_in_out_err([], <<-INPUT, %w(:ok :end :wrap_end), /error in at_exit test/) - load(#{ t.path.dump }, true) - GC.start - p :end - INPUT + Tempfile.create(["test_ruby_test_require", ".rb"]) {|t| + t.puts "module Foo; end" + t.puts "at_exit { p :wrap_end }" + t.puts "at_exit { raise 'error in at_exit test' }" + t.puts "p :ok" + t.close + + assert_in_out_err([], <<-INPUT, %w(:ok :end :wrap_end), /error in at_exit test/) + load(#{ t.path.dump }, true) + GC.start + p :end + INPUT - assert_raise(ArgumentError) { at_exit } - t.close(true) + assert_raise(ArgumentError) { at_exit } + } end def test_load2 # [ruby-core:25039] - t = Tempfile.new(["test_ruby_test_require", ".rb"]) - t.puts "Hello = 'hello'" - t.puts "class Foo" - t.puts " p Hello" - t.puts "end" - t.close - - assert_in_out_err([], <<-INPUT, %w("hello"), []) - load(#{ t.path.dump }, true) - INPUT - t.close(true) + Tempfile.create(["test_ruby_test_require", ".rb"]) {|t| + t.puts "Hello = 'hello'" + t.puts "class Foo" + t.puts " p Hello" + t.puts "end" + t.close + + assert_in_out_err([], <<-INPUT, %w("hello"), []) + load(#{ t.path.dump }, true) + INPUT + } end def test_tainted_loadpath - t = Tempfile.new(["test_ruby_test_require", ".rb"]) - abs_dir, file = File.split(t.path) - abs_dir = File.expand_path(abs_dir).untaint - - assert_in_out_err([], <<-INPUT, %w(:ok), []) - abs_dir = "#{ abs_dir }" - $: << abs_dir - require "#{ file }" - p :ok - INPUT - - assert_in_out_err([], <<-INPUT, %w(:ok), []) - abs_dir = "#{ abs_dir }" - $: << abs_dir.taint - require "#{ file }" - p :ok - INPUT + Tempfile.create(["test_ruby_test_require", ".rb"]) {|t| + abs_dir, file = File.split(t.path) + abs_dir = File.expand_path(abs_dir).untaint - assert_in_out_err([], <<-INPUT, %w(:ok), []) - abs_dir = "#{ abs_dir }" - $: << abs_dir.taint - $SAFE = 1 - begin + assert_in_out_err([], <<-INPUT, %w(:ok), []) + abs_dir = "#{ abs_dir }" + $: << abs_dir require "#{ file }" - rescue SecurityError p :ok - end - INPUT + INPUT - assert_in_out_err([], <<-INPUT, %w(:ok), []) - abs_dir = "#{ abs_dir }" - $: << abs_dir.taint - $SAFE = 1 - begin + assert_in_out_err([], <<-INPUT, %w(:ok), []) + abs_dir = "#{ abs_dir }" + $: << abs_dir.taint require "#{ file }" - rescue SecurityError p :ok - end - INPUT + INPUT - assert_in_out_err([], <<-INPUT, %w(:ok), []) - abs_dir = "#{ abs_dir }" - $: << abs_dir << 'elsewhere'.taint - require "#{ file }" - p :ok - INPUT + assert_in_out_err([], <<-INPUT, %w(:ok), []) + abs_dir = "#{ abs_dir }" + $: << abs_dir.taint + $SAFE = 1 + begin + require "#{ file }" + rescue SecurityError + p :ok + end + INPUT - t.close(true) + assert_in_out_err([], <<-INPUT, %w(:ok), []) + abs_dir = "#{ abs_dir }" + $: << abs_dir.taint + $SAFE = 1 + begin + require "#{ file }" + rescue SecurityError + p :ok + end + INPUT + + assert_in_out_err([], <<-INPUT, %w(:ok), []) + abs_dir = "#{ abs_dir }" + $: << abs_dir << 'elsewhere'.taint + require "#{ file }" + p :ok + INPUT + } end def test_relative @@ -402,65 +400,66 @@ class TestRequire < Test::Unit::TestCase def test_race_exception bug5754 = '[ruby-core:41618]' - tmp = Tempfile.new(%w"bug5754 .rb") - path = tmp.path - tmp.print %{\ - th = Thread.current - t = th[:t] - scratch = th[:scratch] - - if scratch.empty? - scratch << :pre - Thread.pass until t.stop? - raise RuntimeError - else - scratch << :post - end - } - tmp.close - - # "circular require" warnings to $stderr, but backtraces to stderr - # in C-level. And redirecting stderr to a pipe seems to change - # some blocking timings and causes a deadlock, so run in a - # separated process for the time being. - assert_separately(["-w", "-", path, bug5754], <<-'end;', ignore_stderr: true) - path, bug5754 = *ARGV - start = false - - scratch = [] - t1_res = nil - t2_res = nil - - t1 = Thread.new do - Thread.pass until start - begin - require(path) - rescue RuntimeError - end + path = nil + Tempfile.create(%w"bug5754 .rb") {|tmp| + path = tmp.path + tmp.print %{\ + th = Thread.current + t = th[:t] + scratch = th[:scratch] + + if scratch.empty? + scratch << :pre + Thread.pass until t.stop? + raise RuntimeError + else + scratch << :post + end + } + tmp.close + + # "circular require" warnings to $stderr, but backtraces to stderr + # in C-level. And redirecting stderr to a pipe seems to change + # some blocking timings and causes a deadlock, so run in a + # separated process for the time being. + assert_separately(["-w", "-", path, bug5754], <<-'end;', ignore_stderr: true) + path, bug5754 = *ARGV + start = false + + scratch = [] + t1_res = nil + t2_res = nil + + t1 = Thread.new do + Thread.pass until start + begin + require(path) + rescue RuntimeError + end - t1_res = require(path) - end + t1_res = require(path) + end - t2 = Thread.new do - Thread.pass until scratch[0] - t2_res = require(path) - end + t2 = Thread.new do + Thread.pass until scratch[0] + t2_res = require(path) + end - t1[:scratch] = t2[:scratch] = scratch - t1[:t] = t2 - t2[:t] = t1 + t1[:scratch] = t2[:scratch] = scratch + t1[:t] = t2 + t2[:t] = t1 - start = true + start = true - assert_nothing_raised(ThreadError, bug5754) {t1.join} - assert_nothing_raised(ThreadError, bug5754) {t2.join} + assert_nothing_raised(ThreadError, bug5754) {t1.join} + assert_nothing_raised(ThreadError, bug5754) {t2.join} - assert_equal(true, (t1_res ^ t2_res), bug5754 + " t1:#{t1_res} t2:#{t2_res}") - assert_equal([:pre, :post], scratch, bug5754) - end; + assert_equal(true, (t1_res ^ t2_res), bug5754 + " t1:#{t1_res} t2:#{t2_res}") + assert_equal([:pre, :post], scratch, bug5754) + end; + } ensure $".delete(path) - tmp.close(true) if tmp end def test_loaded_features_encoding @@ -642,24 +641,23 @@ class TestRequire < Test::Unit::TestCase def test_require_with_loaded_features_pop bug7530 = '[ruby-core:50645]' - script = Tempfile.new(%w'bug-7530- .rb') - script.close - assert_in_out_err([{"RUBYOPT" => nil}, "-", script.path], <<-INPUT, %w(:ok), [], bug7530) - PATH = ARGV.shift - THREADS = 2 - ITERATIONS_PER_THREAD = 1000 - - THREADS.times.map { - Thread.new do - ITERATIONS_PER_THREAD.times do - require PATH - $".pop + Tempfile.create(%w'bug-7530- .rb') {|script| + script.close + assert_in_out_err([{"RUBYOPT" => nil}, "-", script.path], <<-INPUT, %w(:ok), [], bug7530) + PATH = ARGV.shift + THREADS = 2 + ITERATIONS_PER_THREAD = 1000 + + THREADS.times.map { + Thread.new do + ITERATIONS_PER_THREAD.times do + require PATH + $".pop + end end - end - }.each(&:join) - p :ok - INPUT - ensure - script.close(true) if script + }.each(&:join) + p :ok + INPUT + } end end diff --git a/test/ruby/test_rubyoptions.rb b/test/ruby/test_rubyoptions.rb index cd100de3bd..fbc18f3ef0 100644 --- a/test/ruby/test_rubyoptions.rb +++ b/test/ruby/test_rubyoptions.rb @@ -271,20 +271,21 @@ class TestRubyOptions < Test::Unit::TestCase rubypath_orig = ENV['RUBYPATH'] path_orig = ENV['PATH'] - t = Tempfile.new(["test_ruby_test_rubyoption", ".rb"]) - t.puts "p 1" - t.close + Tempfile.create(["test_ruby_test_rubyoption", ".rb"]) {|t| + t.puts "p 1" + t.close - @verbose = $VERBOSE - $VERBOSE = nil + @verbose = $VERBOSE + $VERBOSE = nil - ENV['PATH'] = File.dirname(t.path) + ENV['PATH'] = File.dirname(t.path) - assert_in_out_err(%w(-S) + [File.basename(t.path)], "", %w(1), []) + assert_in_out_err(%w(-S) + [File.basename(t.path)], "", %w(1), []) - ENV['RUBYPATH'] = File.dirname(t.path) + ENV['RUBYPATH'] = File.dirname(t.path) - assert_in_out_err(%w(-S) + [File.basename(t.path)], "", %w(1), []) + assert_in_out_err(%w(-S) + [File.basename(t.path)], "", %w(1), []) + } ensure if rubypath_orig @@ -297,7 +298,6 @@ class TestRubyOptions < Test::Unit::TestCase else ENV.delete('PATH') end - t.close(true) if t $VERBOSE = @verbose end @@ -333,81 +333,79 @@ class TestRubyOptions < Test::Unit::TestCase end def test_assignment_in_conditional - t = Tempfile.new(["test_ruby_test_rubyoption", ".rb"]) - t.puts "if a = 1" - t.puts "end" - t.puts "0.times do" - t.puts " if b = 2" - t.puts " a += b" - t.puts " end" - t.puts "end" - t.close - warning = ' warning: found = in conditional, should be ==' - err = ["#{t.path}:1:#{warning}", - "#{t.path}:4:#{warning}", - ] - bug2136 = '[ruby-dev:39363]' - assert_in_out_err(["-w", t.path], "", [], err, bug2136) - assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err, bug2136) - - t.open - t.truncate(0) - t.puts "if a = ''; end" - t.puts "if a = []; end" - t.puts "if a = [1]; end" - t.puts "if a = [a]; end" - t.puts "if a = {}; end" - t.puts "if a = {1=>2}; end" - t.puts "if a = {3=>a}; end" - t.close - err = ["#{t.path}:1:#{warning}", - "#{t.path}:2:#{warning}", - "#{t.path}:3:#{warning}", - "#{t.path}:5:#{warning}", - "#{t.path}:6:#{warning}", - ] - feature4299 = '[ruby-dev:43083]' - assert_in_out_err(["-w", t.path], "", [], err, feature4299) - assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err, feature4299) - ensure - t.close(true) if t + Tempfile.create(["test_ruby_test_rubyoption", ".rb"]) {|t| + t.puts "if a = 1" + t.puts "end" + t.puts "0.times do" + t.puts " if b = 2" + t.puts " a += b" + t.puts " end" + t.puts "end" + t.flush + warning = ' warning: found = in conditional, should be ==' + err = ["#{t.path}:1:#{warning}", + "#{t.path}:4:#{warning}", + ] + bug2136 = '[ruby-dev:39363]' + assert_in_out_err(["-w", t.path], "", [], err, bug2136) + assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err, bug2136) + + t.rewind + t.truncate(0) + t.puts "if a = ''; end" + t.puts "if a = []; end" + t.puts "if a = [1]; end" + t.puts "if a = [a]; end" + t.puts "if a = {}; end" + t.puts "if a = {1=>2}; end" + t.puts "if a = {3=>a}; end" + t.flush + err = ["#{t.path}:1:#{warning}", + "#{t.path}:2:#{warning}", + "#{t.path}:3:#{warning}", + "#{t.path}:5:#{warning}", + "#{t.path}:6:#{warning}", + ] + feature4299 = '[ruby-dev:43083]' + assert_in_out_err(["-w", t.path], "", [], err, feature4299) + assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err, feature4299) + } end def test_indentation_check - t = Tempfile.new(["test_ruby_test_rubyoption", ".rb"]) - t.puts "begin" - t.puts " end" - t.close - err = ["#{t.path}:2: warning: mismatched indentations at 'end' with 'begin' at 1"] - assert_in_out_err(["-w", t.path], "", [], err) - assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err) - - t.open - t.puts "# -*- warn-indent: false -*-" - t.puts "begin" - t.puts " end" - t.close - assert_in_out_err(["-w", t.path], "", [], [], '[ruby-core:25442]') - - err = ["#{t.path}:4: warning: mismatched indentations at 'end' with 'begin' at 3"] - t.open - t.puts "# -*- warn-indent: false -*-" - t.puts "# -*- warn-indent: true -*-" - t.puts "begin" - t.puts " end" - t.close - assert_in_out_err(["-w", t.path], "", [], err, '[ruby-core:25442]') - - err = ["#{t.path}:4: warning: mismatched indentations at 'end' with 'begin' at 2"] - t.open - t.puts "# -*- warn-indent: true -*-" - t.puts "begin" - t.puts "# -*- warn-indent: false -*-" - t.puts " end" - t.close - assert_in_out_err(["-w", t.path], "", [], [], '[ruby-core:25442]') - ensure - t.close(true) if t + Tempfile.create(["test_ruby_test_rubyoption", ".rb"]) {|t| + t.puts "begin" + t.puts " end" + t.flush + err = ["#{t.path}:2: warning: mismatched indentations at 'end' with 'begin' at 1"] + assert_in_out_err(["-w", t.path], "", [], err) + assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err) + + t.rewind + t.puts "# -*- warn-indent: false -*-" + t.puts "begin" + t.puts " end" + t.flush + assert_in_out_err(["-w", t.path], "", [], [], '[ruby-core:25442]') + + err = ["#{t.path}:4: warning: mismatched indentations at 'end' with 'begin' at 3"] + t.rewind + t.puts "# -*- warn-indent: false -*-" + t.puts "# -*- warn-indent: true -*-" + t.puts "begin" + t.puts " end" + t.flush + assert_in_out_err(["-w", t.path], "", [], err, '[ruby-core:25442]') + + err = ["#{t.path}:4: warning: mismatched indentations at 'end' with 'begin' at 2"] + t.rewind + t.puts "# -*- warn-indent: true -*-" + t.puts "begin" + t.puts "# -*- warn-indent: false -*-" + t.puts " end" + t.flush + assert_in_out_err(["-w", t.path], "", [], [], '[ruby-core:25442]') + } end def test_notfound @@ -523,25 +521,24 @@ class TestRubyOptions < Test::Unit::TestCase assert_not_predicate(status, :success?, "segv but success #{bug7402}") bug7597 = '[ruby-dev:46786]' - t = Tempfile.new(["test_ruby_test_bug7597", ".rb"]) - t.write "f" * 100 - t.flush - assert_in_out_err(["-e", "$0=ARGV[0]; Process.kill :SEGV, $$", t.path], - "", [], expected_stderr, bug7597, opts) - t.close(true) + Tempfile.create(["test_ruby_test_bug7597", ".rb"]) {|t| + t.write "f" * 100 + t.flush + assert_in_out_err(["-e", "$0=ARGV[0]; Process.kill :SEGV, $$", t.path], + "", [], expected_stderr, bug7597, opts) + } end def test_DATA - t = Tempfile.new(["test_ruby_test_rubyoption", ".rb"]) - t.puts "puts DATA.read.inspect" - t.puts "__END__" - t.puts "foo" - t.puts "bar" - t.puts "baz" - t.close - assert_in_out_err([t.path], "", %w("foo\\nbar\\nbaz\\n"), []) - ensure - t.close(true) if t + Tempfile.create(["test_ruby_test_rubyoption", ".rb"]) {|t| + t.puts "puts DATA.read.inspect" + t.puts "__END__" + t.puts "foo" + t.puts "bar" + t.puts "baz" + t.flush + assert_in_out_err([t.path], "", %w("foo\\nbar\\nbaz\\n"), []) + } end def test_unused_variable diff --git a/test/syslog/test_syslog_logger.rb b/test/syslog/test_syslog_logger.rb index 0b6328443f..65b4a9437f 100644 --- a/test/syslog/test_syslog_logger.rb +++ b/test/syslog/test_syslog_logger.rb @@ -80,13 +80,12 @@ class TestSyslogRootLogger < Test::Unit::TestCase end def log_raw(msg_id, *arg, &block) - logdev = Tempfile.new(File.basename(__FILE__) + '.log') - @logger.instance_eval { @logdev = Logger::LogDevice.new(logdev) } - assert_equal true, @logger.__send__(msg_id, *arg, &block) - logdev.open - msg = logdev.read - logdev.close(true) - msg + Tempfile.create(File.basename(__FILE__) + '.log') {|logdev| + @logger.instance_eval { @logdev = Logger::LogDevice.new(logdev) } + assert_equal true, @logger.__send__(msg_id, *arg, &block) + logdev.rewind + logdev.read + } end def test_initialize diff --git a/test/webrick/test_httpauth.rb b/test/webrick/test_httpauth.rb index 8d530fa84a..6668e1bacf 100644 --- a/test/webrick/test_httpauth.rb +++ b/test/webrick/test_httpauth.rb @@ -31,54 +31,54 @@ class TestWEBrickHTTPAuth < Test::Unit::TestCase realm = "WEBrick's realm" path = "/basic_auth2" - tmpfile = Tempfile.new("test_webrick_auth") - tmpfile.close - tmp_pass = WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path) - tmp_pass.set_passwd(realm, "webrick", "supersecretpassword") - tmp_pass.set_passwd(realm, "foo", "supersecretpassword") - tmp_pass.flush - - htpasswd = WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path) - users = [] - htpasswd.each{|user, pass| users << user } - assert_equal(2, users.size, log.call) - assert(users.member?("webrick"), log.call) - assert(users.member?("foo"), log.call) - - server.mount_proc(path){|req, res| - auth = WEBrick::HTTPAuth::BasicAuth.new( - :Realm => realm, :UserDB => htpasswd, - :Logger => server.logger - ) - auth.authenticate(req, res) - res.body = "hoge" + Tempfile.create("test_webrick_auth") {|tmpfile| + tmpfile.close + tmp_pass = WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path) + tmp_pass.set_passwd(realm, "webrick", "supersecretpassword") + tmp_pass.set_passwd(realm, "foo", "supersecretpassword") + tmp_pass.flush + + htpasswd = WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path) + users = [] + htpasswd.each{|user, pass| users << user } + assert_equal(2, users.size, log.call) + assert(users.member?("webrick"), log.call) + assert(users.member?("foo"), log.call) + + server.mount_proc(path){|req, res| + auth = WEBrick::HTTPAuth::BasicAuth.new( + :Realm => realm, :UserDB => htpasswd, + :Logger => server.logger + ) + auth.authenticate(req, res) + res.body = "hoge" + } + http = Net::HTTP.new(addr, port) + g = Net::HTTP::Get.new(path) + g.basic_auth("webrick", "supersecretpassword") + http.request(g){|res| assert_equal("hoge", res.body, log.call)} + g.basic_auth("webrick", "not super") + http.request(g){|res| assert_not_equal("hoge", res.body, log.call)} } - http = Net::HTTP.new(addr, port) - g = Net::HTTP::Get.new(path) - g.basic_auth("webrick", "supersecretpassword") - http.request(g){|res| assert_equal("hoge", res.body, log.call)} - g.basic_auth("webrick", "not super") - http.request(g){|res| assert_not_equal("hoge", res.body, log.call)} - tmpfile.close(true) } end def test_basic_auth3 - tmpfile = Tempfile.new("test_webrick_auth") - tmpfile.puts("webrick:{SHA}GJYFRpBbdchp595jlh3Bhfmgp8k=") - tmpfile.flush - assert_raise(NotImplementedError){ - WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path) + Tempfile.create("test_webrick_auth") {|tmpfile| + tmpfile.puts("webrick:{SHA}GJYFRpBbdchp595jlh3Bhfmgp8k=") + tmpfile.flush + assert_raise(NotImplementedError){ + WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path) + } } - tmpfile.close(true) - tmpfile = Tempfile.new("test_webrick_auth") - tmpfile.puts("webrick:$apr1$IOVMD/..$rmnOSPXr0.wwrLPZHBQZy0") - tmpfile.flush - assert_raise(NotImplementedError){ - WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path) + Tempfile.create("test_webrick_auth") {|tmpfile| + tmpfile.puts("webrick:$apr1$IOVMD/..$rmnOSPXr0.wwrLPZHBQZy0") + tmpfile.flush + assert_raise(NotImplementedError){ + WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path) + } } - tmpfile.close(true) end DIGESTRES_ = / @@ -96,52 +96,52 @@ class TestWEBrickHTTPAuth < Test::Unit::TestCase realm = "WEBrick's realm" path = "/digest_auth" - tmpfile = Tempfile.new("test_webrick_auth") - tmpfile.close - tmp_pass = WEBrick::HTTPAuth::Htdigest.new(tmpfile.path) - tmp_pass.set_passwd(realm, "webrick", "supersecretpassword") - tmp_pass.set_passwd(realm, "foo", "supersecretpassword") - tmp_pass.flush - - htdigest = WEBrick::HTTPAuth::Htdigest.new(tmpfile.path) - users = [] - htdigest.each{|user, pass| users << user } - assert_equal(2, users.size, log.call) - assert(users.member?("webrick"), log.call) - assert(users.member?("foo"), log.call) - - auth = WEBrick::HTTPAuth::DigestAuth.new( - :Realm => realm, :UserDB => htdigest, - :Algorithm => 'MD5', - :Logger => server.logger - ) - server.mount_proc(path){|req, res| - auth.authenticate(req, res) - res.body = "hoge" - } + Tempfile.create("test_webrick_auth") {|tmpfile| + tmpfile.close + tmp_pass = WEBrick::HTTPAuth::Htdigest.new(tmpfile.path) + tmp_pass.set_passwd(realm, "webrick", "supersecretpassword") + tmp_pass.set_passwd(realm, "foo", "supersecretpassword") + tmp_pass.flush + + htdigest = WEBrick::HTTPAuth::Htdigest.new(tmpfile.path) + users = [] + htdigest.each{|user, pass| users << user } + assert_equal(2, users.size, log.call) + assert(users.member?("webrick"), log.call) + assert(users.member?("foo"), log.call) + + auth = WEBrick::HTTPAuth::DigestAuth.new( + :Realm => realm, :UserDB => htdigest, + :Algorithm => 'MD5', + :Logger => server.logger + ) + server.mount_proc(path){|req, res| + auth.authenticate(req, res) + res.body = "hoge" + } - Net::HTTP.start(addr, port) do |http| - g = Net::HTTP::Get.new(path) - params = {} - http.request(g) do |res| - assert_equal('401', res.code, log.call) - res["www-authenticate"].scan(DIGESTRES_) do |key, quoted, token| - params[key.downcase] = token || quoted.delete('\\') + Net::HTTP.start(addr, port) do |http| + g = Net::HTTP::Get.new(path) + params = {} + http.request(g) do |res| + assert_equal('401', res.code, log.call) + res["www-authenticate"].scan(DIGESTRES_) do |key, quoted, token| + params[key.downcase] = token || quoted.delete('\\') + end + params['uri'] = "http://#{addr}:#{port}#{path}" end - params['uri'] = "http://#{addr}:#{port}#{path}" - end - g['Authorization'] = credentials_for_request('webrick', "supersecretpassword", params) - http.request(g){|res| assert_equal("hoge", res.body, log.call)} + g['Authorization'] = credentials_for_request('webrick', "supersecretpassword", params) + http.request(g){|res| assert_equal("hoge", res.body, log.call)} - params['algorithm'].downcase! #4936 - g['Authorization'] = credentials_for_request('webrick', "supersecretpassword", params) - http.request(g){|res| assert_equal("hoge", res.body, log.call)} + params['algorithm'].downcase! #4936 + g['Authorization'] = credentials_for_request('webrick', "supersecretpassword", params) + http.request(g){|res| assert_equal("hoge", res.body, log.call)} - g['Authorization'] = credentials_for_request('webrick', "not super", params) - http.request(g){|res| assert_not_equal("hoge", res.body, log.call)} - end - tmpfile.close(true) + g['Authorization'] = credentials_for_request('webrick', "not super", params) + http.request(g){|res| assert_not_equal("hoge", res.body, log.call)} + end + } } end diff --git a/test/zlib/test_zlib.rb b/test/zlib/test_zlib.rb index 4849396277..6e21f6d271 100644 --- a/test/zlib/test_zlib.rb +++ b/test/zlib/test_zlib.rb @@ -432,185 +432,184 @@ if defined? Zlib class TestZlibGzipFile < Test::Unit::TestCase def test_to_io - t = Tempfile.new("test_zlib_gzip_file_to_io") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + Tempfile.create("test_zlib_gzip_file_to_io") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - Zlib::GzipReader.open(t.path) do |f| - assert_kind_of(IO, f.to_io) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + assert_kind_of(IO, f.to_io) + end + } end def test_crc - t = Tempfile.new("test_zlib_gzip_file_crc") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + Tempfile.create("test_zlib_gzip_file_crc") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - Zlib::GzipReader.open(t.path) do |f| - f.read - assert_equal(0x8c736521, f.crc) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + f.read + assert_equal(0x8c736521, f.crc) + end + } end def test_mtime tim = Time.now - t = Tempfile.new("test_zlib_gzip_file_mtime") - t.close - Zlib::GzipWriter.open(t.path) do |gz| - gz.mtime = -1 - gz.mtime = tim - gz.print("foo") - gz.flush - assert_raise(Zlib::GzipFile::Error) { gz.mtime = Time.now } - end + Tempfile.create("test_zlib_gzip_file_mtime") {|t| + t.close + Zlib::GzipWriter.open(t.path) do |gz| + gz.mtime = -1 + gz.mtime = tim + gz.print("foo") + gz.flush + assert_raise(Zlib::GzipFile::Error) { gz.mtime = Time.now } + end - Zlib::GzipReader.open(t.path) do |f| - assert_equal(tim.to_i, f.mtime.to_i) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + assert_equal(tim.to_i, f.mtime.to_i) + end + } end def test_level - t = Tempfile.new("test_zlib_gzip_file_level") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + Tempfile.create("test_zlib_gzip_file_level") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - Zlib::GzipReader.open(t.path) do |f| - assert_equal(Zlib::DEFAULT_COMPRESSION, f.level) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + assert_equal(Zlib::DEFAULT_COMPRESSION, f.level) + end + } end def test_os_code - t = Tempfile.new("test_zlib_gzip_file_os_code") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + Tempfile.create("test_zlib_gzip_file_os_code") {|t| + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - Zlib::GzipReader.open(t.path) do |f| - assert_equal(Zlib::OS_CODE, f.os_code) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + assert_equal(Zlib::OS_CODE, f.os_code) + end + } end def test_orig_name - t = Tempfile.new("test_zlib_gzip_file_orig_name") - t.close - Zlib::GzipWriter.open(t.path) do |gz| - gz.orig_name = "foobarbazqux\0quux" - gz.print("foo") - gz.flush - assert_raise(Zlib::GzipFile::Error) { gz.orig_name = "quux" } - end + Tempfile.create("test_zlib_gzip_file_orig_name") {|t| + t.close + Zlib::GzipWriter.open(t.path) do |gz| + gz.orig_name = "foobarbazqux\0quux" + gz.print("foo") + gz.flush + assert_raise(Zlib::GzipFile::Error) { gz.orig_name = "quux" } + end - Zlib::GzipReader.open(t.path) do |f| - assert_equal("foobarbazqux", f.orig_name) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + assert_equal("foobarbazqux", f.orig_name) + end + } end def test_comment - t = Tempfile.new("test_zlib_gzip_file_comment") - t.close - Zlib::GzipWriter.open(t.path) do |gz| - gz.comment = "foobarbazqux\0quux" - gz.print("foo") - gz.flush - assert_raise(Zlib::GzipFile::Error) { gz.comment = "quux" } - end + Tempfile.create("test_zlib_gzip_file_comment") {|t| + t.close + Zlib::GzipWriter.open(t.path) do |gz| + gz.comment = "foobarbazqux\0quux" + gz.print("foo") + gz.flush + assert_raise(Zlib::GzipFile::Error) { gz.comment = "quux" } + end - Zlib::GzipReader.open(t.path) do |f| - assert_equal("foobarbazqux", f.comment) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + assert_equal("foobarbazqux", f.comment) + end + } end def test_lineno - t = Tempfile.new("test_zlib_gzip_file_lineno") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\nqux\n") } - - Zlib::GzipReader.open(t.path) do |f| - assert_equal([0, "foo\n"], [f.lineno, f.gets]) - assert_equal([1, "bar\n"], [f.lineno, f.gets]) - f.lineno = 1000 - assert_equal([1000, "baz\n"], [f.lineno, f.gets]) - assert_equal([1001, "qux\n"], [f.lineno, f.gets]) - end - t.close(true) + Tempfile.create("test_zlib_gzip_file_lineno") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\nqux\n") } + + Zlib::GzipReader.open(t.path) do |f| + assert_equal([0, "foo\n"], [f.lineno, f.gets]) + assert_equal([1, "bar\n"], [f.lineno, f.gets]) + f.lineno = 1000 + assert_equal([1000, "baz\n"], [f.lineno, f.gets]) + assert_equal([1001, "qux\n"], [f.lineno, f.gets]) + end + } end def test_closed_p - t = Tempfile.new("test_zlib_gzip_file_closed_p") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - - Zlib::GzipReader.open(t.path) do |f| - assert_equal(false, f.closed?) - f.read - assert_equal(false, f.closed?) - f.close - assert_equal(true, f.closed?) - end - t.close(true) + Tempfile.create("test_zlib_gzip_file_closed_p") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + + Zlib::GzipReader.open(t.path) do |f| + assert_equal(false, f.closed?) + f.read + assert_equal(false, f.closed?) + f.close + assert_equal(true, f.closed?) + end + } end def test_sync - t = Tempfile.new("test_zlib_gzip_file_sync") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - - Zlib::GzipReader.open(t.path) do |f| - f.sync = true - assert_equal(true, f.sync) - f.read - f.sync = false - assert_equal(false, f.sync) - end - t.close(true) + Tempfile.create("test_zlib_gzip_file_sync") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + + Zlib::GzipReader.open(t.path) do |f| + f.sync = true + assert_equal(true, f.sync) + f.read + f.sync = false + assert_equal(false, f.sync) + end + } end def test_pos - t = Tempfile.new("test_zlib_gzip_file_pos") - t.close - Zlib::GzipWriter.open(t.path) do |gz| - gz.print("foo") - gz.flush - assert_equal(3, gz.tell) - end - t.close(true) + Tempfile.create("test_zlib_gzip_file_pos") {|t| + t.close + Zlib::GzipWriter.open(t.path) do |gz| + gz.print("foo") + gz.flush + assert_equal(3, gz.tell) + end + } end def test_path - t = Tempfile.new("test_zlib_gzip_file_path") - t.close + Tempfile.create("test_zlib_gzip_file_path") {|t| + t.close - gz = Zlib::GzipWriter.open(t.path) - gz.print("foo") - assert_equal(t.path, gz.path) - gz.close - assert_equal(t.path, gz.path) - - Zlib::GzipReader.open(t.path) do |f| - assert_equal(t.path, f.path) - f.close - assert_equal(t.path, f.path) - end + gz = Zlib::GzipWriter.open(t.path) + gz.print("foo") + assert_equal(t.path, gz.path) + gz.close + assert_equal(t.path, gz.path) + + Zlib::GzipReader.open(t.path) do |f| + assert_equal(t.path, f.path) + f.close + assert_equal(t.path, f.path) + end - s = "" - sio = StringIO.new(s) - gz = Zlib::GzipWriter.new(sio) - gz.print("foo") - assert_raise(NoMethodError) { gz.path } - gz.close + s = "" + sio = StringIO.new(s) + gz = Zlib::GzipWriter.new(sio) + gz.print("foo") + assert_raise(NoMethodError) { gz.path } + gz.close - sio = StringIO.new(s) - Zlib::GzipReader.new(sio) do |f| - assert_raise(NoMethodError) { f.path } - end - t.close(true) + sio = StringIO.new(s) + Zlib::GzipReader.new(sio) do |f| + assert_raise(NoMethodError) { f.path } + end + } end end @@ -650,67 +649,67 @@ if defined? Zlib end def test_open - t = Tempfile.new("test_zlib_gzip_reader_open") - t.close - e = assert_raise(Zlib::GzipFile::Error) { - Zlib::GzipReader.open(t.path) - } - assert_equal("not in gzip format", e.message) - assert_nil(e.input) - open(t.path, "wb") {|f| f.write("foo")} - e = assert_raise(Zlib::GzipFile::Error) { - Zlib::GzipReader.open(t.path) - } - assert_equal("not in gzip format", e.message) - assert_equal("foo", e.input) - open(t.path, "wb") {|f| f.write("foobarzothoge")} - e = assert_raise(Zlib::GzipFile::Error) { - Zlib::GzipReader.open(t.path) + Tempfile.create("test_zlib_gzip_reader_open") {|t| + t.close + e = assert_raise(Zlib::GzipFile::Error) { + Zlib::GzipReader.open(t.path) + } + assert_equal("not in gzip format", e.message) + assert_nil(e.input) + open(t.path, "wb") {|f| f.write("foo")} + e = assert_raise(Zlib::GzipFile::Error) { + Zlib::GzipReader.open(t.path) + } + assert_equal("not in gzip format", e.message) + assert_equal("foo", e.input) + open(t.path, "wb") {|f| f.write("foobarzothoge")} + e = assert_raise(Zlib::GzipFile::Error) { + Zlib::GzipReader.open(t.path) + } + assert_equal("not in gzip format", e.message) + assert_equal("foobarzothoge", e.input) + + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + + assert_raise(ArgumentError) { Zlib::GzipReader.open } + + assert_equal("foo", Zlib::GzipReader.open(t.path) {|gz| gz.read }) + + f = Zlib::GzipReader.open(t.path) + begin + assert_equal("foo", f.read) + ensure + f.close + end } - assert_equal("not in gzip format", e.message) - assert_equal("foobarzothoge", e.input) - - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - - assert_raise(ArgumentError) { Zlib::GzipReader.open } - - assert_equal("foo", Zlib::GzipReader.open(t.path) {|gz| gz.read }) - - f = Zlib::GzipReader.open(t.path) - begin - assert_equal("foo", f.read) - ensure - f.close - end - t.close(true) end def test_rewind - t = Tempfile.new("test_zlib_gzip_reader_rewind") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - - Zlib::GzipReader.open(t.path) do |f| - assert_equal("foo", f.read) - f.rewind - assert_equal("foo", f.read) - end - t.close(true) + Tempfile.create("test_zlib_gzip_reader_rewind") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + + Zlib::GzipReader.open(t.path) do |f| + assert_equal("foo", f.read) + f.rewind + assert_equal("foo", f.read) + end + } end def test_unused - t = Tempfile.new("test_zlib_gzip_reader_unused") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } - - Zlib::GzipReader.open(t.path) do |f| - assert_equal(nil, f.unused) - assert_equal("foo", f.read(3)) - assert_equal(nil, f.unused) - assert_equal("bar", f.read) - assert_equal(nil, f.unused) - end - t.close(true) + Tempfile.create("test_zlib_gzip_reader_unused") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } + + Zlib::GzipReader.open(t.path) do |f| + assert_equal(nil, f.unused) + assert_equal("foo", f.read(3)) + assert_equal(nil, f.unused) + assert_equal("bar", f.read) + assert_equal(nil, f.unused) + end + } end def test_unused2 @@ -741,185 +740,185 @@ if defined? Zlib end def test_read - t = Tempfile.new("test_zlib_gzip_reader_read") - t.close - str = "\u3042\u3044\u3046" - Zlib::GzipWriter.open(t.path) {|gz| gz.print(str) } - - Zlib::GzipReader.open(t.path, encoding: "UTF-8") do |f| - assert_raise(ArgumentError) { f.read(-1) } - assert_equal(str, f.read) - end - t.close(true) + Tempfile.create("test_zlib_gzip_reader_read") {|t| + t.close + str = "\u3042\u3044\u3046" + Zlib::GzipWriter.open(t.path) {|gz| gz.print(str) } + + Zlib::GzipReader.open(t.path, encoding: "UTF-8") do |f| + assert_raise(ArgumentError) { f.read(-1) } + assert_equal(str, f.read) + end + } end def test_readpartial - t = Tempfile.new("test_zlib_gzip_reader_readpartial") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } + Tempfile.create("test_zlib_gzip_reader_readpartial") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } - Zlib::GzipReader.open(t.path) do |f| - assert("foo".start_with?(f.readpartial(3))) - end + Zlib::GzipReader.open(t.path) do |f| + assert("foo".start_with?(f.readpartial(3))) + end - Zlib::GzipReader.open(t.path) do |f| - s = "" - f.readpartial(3, s) - assert("foo".start_with?(s)) + Zlib::GzipReader.open(t.path) do |f| + s = "" + f.readpartial(3, s) + assert("foo".start_with?(s)) - assert_raise(ArgumentError) { f.readpartial(-1) } - end - t.close(true) + assert_raise(ArgumentError) { f.readpartial(-1) } + end + } end def test_getc - t = Tempfile.new("test_zlib_gzip_reader_getc") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } + Tempfile.create("test_zlib_gzip_reader_getc") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } - Zlib::GzipReader.open(t.path) do |f| - "foobar".each_char {|c| assert_equal(c, f.getc) } - assert_nil(f.getc) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + "foobar".each_char {|c| assert_equal(c, f.getc) } + assert_nil(f.getc) + end + } end def test_getbyte - t = Tempfile.new("test_zlib_gzip_reader_getbyte") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } + Tempfile.create("test_zlib_gzip_reader_getbyte") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } - Zlib::GzipReader.open(t.path) do |f| - "foobar".each_byte {|c| assert_equal(c, f.getbyte) } - assert_nil(f.getbyte) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + "foobar".each_byte {|c| assert_equal(c, f.getbyte) } + assert_nil(f.getbyte) + end + } end def test_readchar - t = Tempfile.new("test_zlib_gzip_reader_readchar") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } + Tempfile.create("test_zlib_gzip_reader_readchar") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } - Zlib::GzipReader.open(t.path) do |f| - "foobar".each_byte {|c| assert_equal(c, f.readchar.ord) } - assert_raise(EOFError) { f.readchar } - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + "foobar".each_byte {|c| assert_equal(c, f.readchar.ord) } + assert_raise(EOFError) { f.readchar } + end + } end def test_each_byte - t = Tempfile.new("test_zlib_gzip_reader_each_byte") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } - - Zlib::GzipReader.open(t.path) do |f| - a = [] - f.each_byte {|c| a << c } - assert_equal("foobar".each_byte.to_a, a) - end - t.close(true) + Tempfile.create("test_zlib_gzip_reader_each_byte") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foobar") } + + Zlib::GzipReader.open(t.path) do |f| + a = [] + f.each_byte {|c| a << c } + assert_equal("foobar".each_byte.to_a, a) + end + } end def test_gets - t = Tempfile.new("test_zlib_gzip_reader_gets") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\n") } - - Zlib::GzipReader.open(t.path) do |f| - assert_equal("foo\n", f.gets) - assert_equal("bar\n", f.gets) - assert_equal("baz\n", f.gets) - assert_nil(f.gets) - end + Tempfile.create("test_zlib_gzip_reader_gets") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\n") } + + Zlib::GzipReader.open(t.path) do |f| + assert_equal("foo\n", f.gets) + assert_equal("bar\n", f.gets) + assert_equal("baz\n", f.gets) + assert_nil(f.gets) + end - Zlib::GzipReader.open(t.path) do |f| - assert_equal("foo\nbar\nbaz\n", f.gets(nil)) - end + Zlib::GzipReader.open(t.path) do |f| + assert_equal("foo\nbar\nbaz\n", f.gets(nil)) + end - Zlib::GzipReader.open(t.path) do |f| - assert_equal("foo\n", f.gets(10)) - assert_equal("ba", f.gets(2)) - assert_equal("r\nb", f.gets(nil, 3)) - assert_equal("az\n", f.gets(nil, 10)) - assert_nil(f.gets) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + assert_equal("foo\n", f.gets(10)) + assert_equal("ba", f.gets(2)) + assert_equal("r\nb", f.gets(nil, 3)) + assert_equal("az\n", f.gets(nil, 10)) + assert_nil(f.gets) + end + } end def test_gets2 - t = Tempfile.new("test_zlib_gzip_reader_gets2") - t.close - ustrs = %W"\u{3042 3044 3046}\n \u{304b 304d 304f}\n \u{3055 3057 3059}\n" - Zlib::GzipWriter.open(t.path) {|gz| gz.print(*ustrs) } - - Zlib::GzipReader.open(t.path, encoding: "UTF-8") do |f| - assert_equal(ustrs[0], f.gets) - assert_equal(ustrs[1], f.gets) - assert_equal(ustrs[2], f.gets) - assert_nil(f.gets) - end + Tempfile.create("test_zlib_gzip_reader_gets2") {|t| + t.close + ustrs = %W"\u{3042 3044 3046}\n \u{304b 304d 304f}\n \u{3055 3057 3059}\n" + Zlib::GzipWriter.open(t.path) {|gz| gz.print(*ustrs) } + + Zlib::GzipReader.open(t.path, encoding: "UTF-8") do |f| + assert_equal(ustrs[0], f.gets) + assert_equal(ustrs[1], f.gets) + assert_equal(ustrs[2], f.gets) + assert_nil(f.gets) + end - Zlib::GzipReader.open(t.path, encoding: "UTF-8") do |f| - assert_equal(ustrs.join(''), f.gets(nil)) - end + Zlib::GzipReader.open(t.path, encoding: "UTF-8") do |f| + assert_equal(ustrs.join(''), f.gets(nil)) + end - Zlib::GzipReader.open(t.path, encoding: "UTF-8") do |f| - assert_equal(ustrs[0], f.gets(20)) - assert_equal(ustrs[1][0,2], f.gets(5)) - assert_equal(ustrs[1][2..-1]+ustrs[2][0,1], f.gets(nil, 5)) - assert_equal(ustrs[2][1..-1], f.gets(nil, 20)) - assert_nil(f.gets) - end - t.close(true) + Zlib::GzipReader.open(t.path, encoding: "UTF-8") do |f| + assert_equal(ustrs[0], f.gets(20)) + assert_equal(ustrs[1][0,2], f.gets(5)) + assert_equal(ustrs[1][2..-1]+ustrs[2][0,1], f.gets(nil, 5)) + assert_equal(ustrs[2][1..-1], f.gets(nil, 20)) + assert_nil(f.gets) + end + } end def test_readline - t = Tempfile.new("test_zlib_gzip_reader_readline") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\n") } - - Zlib::GzipReader.open(t.path) do |f| - assert_equal("foo\n", f.readline) - assert_equal("bar\n", f.readline) - assert_equal("baz\n", f.readline) - assert_raise(EOFError) { f.readline } - end - t.close(true) + Tempfile.create("test_zlib_gzip_reader_readline") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\n") } + + Zlib::GzipReader.open(t.path) do |f| + assert_equal("foo\n", f.readline) + assert_equal("bar\n", f.readline) + assert_equal("baz\n", f.readline) + assert_raise(EOFError) { f.readline } + end + } end def test_each - t = Tempfile.new("test_zlib_gzip_reader_each") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\n") } + Tempfile.create("test_zlib_gzip_reader_each") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\n") } - Zlib::GzipReader.open(t.path) do |f| - a = ["foo\n", "bar\n", "baz\n"] - f.each {|l| assert_equal(a.shift, l) } - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + a = ["foo\n", "bar\n", "baz\n"] + f.each {|l| assert_equal(a.shift, l) } + end + } end def test_readlines - t = Tempfile.new("test_zlib_gzip_reader_readlines") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\n") } + Tempfile.create("test_zlib_gzip_reader_readlines") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo\nbar\nbaz\n") } - Zlib::GzipReader.open(t.path) do |f| - assert_equal(["foo\n", "bar\n", "baz\n"], f.readlines) - end - t.close(true) + Zlib::GzipReader.open(t.path) do |f| + assert_equal(["foo\n", "bar\n", "baz\n"], f.readlines) + end + } end def test_reader_wrap - t = Tempfile.new("test_zlib_gzip_reader_wrap") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - f = open(t.path) - f.binmode - assert_equal("foo", Zlib::GzipReader.wrap(f) {|gz| gz.read }) - assert_raise(IOError) { f.close } - t.close(true) + Tempfile.create("test_zlib_gzip_reader_wrap") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + f = open(t.path) + f.binmode + assert_equal("foo", Zlib::GzipReader.wrap(f) {|gz| gz.read }) + assert_raise(IOError) { f.close } + } end def test_corrupted_header @@ -937,20 +936,19 @@ if defined? Zlib end def test_encoding - t = Tempfile.new("test_zlib_gzip_reader_encoding") - t.binmode - content = (0..255).to_a.pack('c*') - Zlib::GzipWriter.wrap(t) {|gz| gz.print(content) } - t.close - - read_all = Zlib::GzipReader.open(t.path) {|gz| gz.read } - assert_equal(Encoding.default_external, read_all.encoding) - - # chunks are in BINARY regardless of encoding settings - read_size = Zlib::GzipReader.open(t.path) {|gz| gz.read(1024) } - assert_equal(Encoding::ASCII_8BIT, read_size.encoding) - assert_equal(content, read_size) - t.close(true) + Tempfile.create("test_zlib_gzip_reader_encoding") {|t| + t.binmode + content = (0..255).to_a.pack('c*') + Zlib::GzipWriter.wrap(t) {|gz| gz.print(content) } + + read_all = Zlib::GzipReader.open(t.path) {|gz| gz.read } + assert_equal(Encoding.default_external, read_all.encoding) + + # chunks are in BINARY regardless of encoding settings + read_size = Zlib::GzipReader.open(t.path) {|gz| gz.read(1024) } + assert_equal(Encoding::ASCII_8BIT, read_size.encoding) + assert_equal(content, read_size) + } end end @@ -965,53 +963,52 @@ if defined? Zlib def test_open assert_raise(ArgumentError) { Zlib::GzipWriter.open } - t = Tempfile.new("test_zlib_gzip_writer_open") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - assert_equal("foo", Zlib::GzipReader.open(t.path) {|gz| gz.read }) + Tempfile.create("test_zlib_gzip_writer_open") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + assert_equal("foo", Zlib::GzipReader.open(t.path) {|gz| gz.read }) - f = Zlib::GzipWriter.open(t.path) - begin - f.print("bar") - ensure - f.close - end - assert_equal("bar", Zlib::GzipReader.open(t.path) {|gz| gz.read }) + f = Zlib::GzipWriter.open(t.path) + begin + f.print("bar") + ensure + f.close + end + assert_equal("bar", Zlib::GzipReader.open(t.path) {|gz| gz.read }) - assert_raise(Zlib::StreamError) { Zlib::GzipWriter.open(t.path, 10000) } - t.close(true) + assert_raise(Zlib::StreamError) { Zlib::GzipWriter.open(t.path, 10000) } + } end def test_write - t = Tempfile.new("test_zlib_gzip_writer_write") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } - assert_equal("foo", Zlib::GzipReader.open(t.path) {|gz| gz.read }) - - o = Object.new - def o.to_s; "bar"; end - Zlib::GzipWriter.open(t.path) {|gz| gz.print(o) } - assert_equal("bar", Zlib::GzipReader.open(t.path) {|gz| gz.read }) - t.close(true) + Tempfile.create("test_zlib_gzip_writer_write") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.print("foo") } + assert_equal("foo", Zlib::GzipReader.open(t.path) {|gz| gz.read }) + + o = Object.new + def o.to_s; "bar"; end + Zlib::GzipWriter.open(t.path) {|gz| gz.print(o) } + assert_equal("bar", Zlib::GzipReader.open(t.path) {|gz| gz.read }) + } end def test_putc - t = Tempfile.new("test_zlib_gzip_writer_putc") - t.close - Zlib::GzipWriter.open(t.path) {|gz| gz.putc(?x) } - assert_equal("x", Zlib::GzipReader.open(t.path) {|gz| gz.read }) + Tempfile.create("test_zlib_gzip_writer_putc") {|t| + t.close + Zlib::GzipWriter.open(t.path) {|gz| gz.putc(?x) } + assert_equal("x", Zlib::GzipReader.open(t.path) {|gz| gz.read }) - # todo: multibyte char - t.close(true) + # todo: multibyte char + } end def test_writer_wrap - t = Tempfile.new("test_zlib_gzip_writer_wrap") - t.binmode - Zlib::GzipWriter.wrap(t) {|gz| gz.print("foo") } - t.close - assert_equal("foo", Zlib::GzipReader.open(t.path) {|gz| gz.read }) - t.close(true) + Tempfile.create("test_zlib_gzip_writer_wrap") {|t| + t.binmode + Zlib::GzipWriter.wrap(t) {|gz| gz.print("foo") } + assert_equal("foo", Zlib::GzipReader.open(t.path) {|gz| gz.read }) + } end end -- cgit v1.2.3