diff options
author | Michael Leibowitz <michael.leibowitz@intel.com> | 2013-08-15 15:02:54 -0700 |
---|---|---|
committer | Michael Leibowitz <michael.leibowitz@intel.com> | 2013-08-15 15:02:54 -0700 |
commit | 6b0e2a11aeccf2ebc707c22548a0c15c8c2bae06 (patch) | |
tree | d9d59f4b502927634d32832e963db76629ff5a2e /test | |
parent | 3b35de2a90e26b99e2a6d4f61dc56d6ce7ded748 (diff) | |
download | ruby-upstream.tar.gz ruby-upstream.tar.bz2 ruby-upstream.zip |
Imported Upstream version 1.9.3.p448upstream/1.9.3.p448upstream
Diffstat (limited to 'test')
80 files changed, 1941 insertions, 309 deletions
diff --git a/test/-ext-/test_add_suffix.rb b/test/-ext-/test_add_suffix.rb deleted file mode 100644 index 0520bae..0000000 --- a/test/-ext-/test_add_suffix.rb +++ /dev/null @@ -1,47 +0,0 @@ -require 'test/unit' -require_relative '../ruby/envutil' -require "-test-/add_suffix/bug" - -class Test_AddSuffix < Test::Unit::TestCase - Dir = "/dev/null/".freeze - Style_1 = (Dir+"foo").freeze - - def test_style_0 - assert_equal("a.x.y", Bug.add_suffix("a.x", ".y")) - end - - def test_style_1 - assert_equal(Style_1+".y", Bug.add_suffix(Style_1+".c", ".y")) - suffix = ".bak".freeze - assert_equal(Style_1+suffix, Bug.add_suffix(Style_1.dup, suffix)) - assert_equal(Style_1+suffix, Bug.add_suffix(Style_1+".bar", suffix)) - assert_equal(Style_1+".$$$", Bug.add_suffix(Style_1+suffix, suffix)) - assert_equal(Style_1+suffix, Bug.add_suffix(Style_1+".$$$", suffix)) - assert_equal(Style_1+".~~~", Bug.add_suffix(Style_1+".$$$", ".$$$")) - assert_equal(Dir+"makefile"+suffix, Bug.add_suffix(Dir+"makefile", suffix)) - end - - def test_style_2 - suffix = "~" - assert_equal(Style_1+"~", Bug.add_suffix(Style_1.dup, suffix)) - assert_equal(Style_1+".c~", Bug.add_suffix(Style_1+".c", suffix)) - assert_equal(Style_1+".c~~", Bug.add_suffix(Style_1+".c~", suffix)) - assert_equal(Style_1+"~.c~~", Bug.add_suffix(Style_1+".c~~", suffix)) - assert_equal(Style_1+"~~.c~~", Bug.add_suffix(Style_1+"~.c~~", suffix)) - assert_equal(Style_1+"~~~~~.cc~", Bug.add_suffix(Style_1+"~~~~~.ccc", suffix)) - assert_equal(Style_1+"~~~~~.$$$", Bug.add_suffix(Style_1+"~~~~~.c~~", suffix)) - assert_equal(Dir+"foo~.pas", Bug.add_suffix(Dir+"foo.pas", suffix)) - assert_equal(Dir+"makefile.~", Bug.add_suffix(Dir+"makefile", suffix)) - assert_equal(Dir+"longname.fi~", Bug.add_suffix(Dir+"longname.fil", suffix)) - assert_equal(Dir+"longnam~.fi~", Bug.add_suffix(Dir+"longname.fi~", suffix)) - assert_equal(Dir+"longnam~.$$$", Bug.add_suffix(Dir+"longnam~.fi~", suffix)) - end - - def test_style_3 - base = "a"*1000 - suffix = "-"+"b"*1000 - assert_equal(base+".~~~", Bug.add_suffix(base, suffix)) - assert_equal(base+".~~~", Bug.add_suffix(base+".$$$", suffix)) - assert_equal(base+".$$$", Bug.add_suffix(base+".~~~", suffix)) - end -end diff --git a/test/-ext-/win32/test_fd_setsize.rb b/test/-ext-/win32/test_fd_setsize.rb new file mode 100644 index 0000000..0881971 --- /dev/null +++ b/test/-ext-/win32/test_fd_setsize.rb @@ -0,0 +1,25 @@ +require 'test/unit' +require_relative '../../ruby/envutil' + +module Bug + module Win32 + class TestFdSetSize < Test::Unit::TestCase + def test_select_with_unmatched_fd_setsize + bug6532 = '[ruby-core:44588]' + assert_in_out_err([], <<-INPUT, %w(:ok), [], bug6532) + require '-test-/win32/fd_setsize' + Bug::Win32.test_select + p :ok + INPUT + end + + def test_fdset_with_unmatched_fd_setsize + bug6532 = '[ruby-core:44588]' + assert_in_out_err([], <<-INPUT, %w(:ok), [], bug6532) + require '-test-/win32/fd_setsize' + p :ok if Bug::Win32.test_fdset + INPUT + end + end + end +end if /mswin|mingw/ =~ RUBY_PLATFORM diff --git a/test/bigdecimal/test_bigdecimal.rb b/test/bigdecimal/test_bigdecimal.rb index bd0739c..055b0ff 100644 --- a/test/bigdecimal/test_bigdecimal.rb +++ b/test/bigdecimal/test_bigdecimal.rb @@ -558,6 +558,10 @@ class TestBigDecimal < Test::Unit::TestCase a, b = BigDecimal("0.11111").coerce(1.quo(3)) assert_equal(BigDecimal("0." + "3"*a.precs[0]), a) + + assert_nothing_raised(TypeError, '#7176') do + BigDecimal.new('1') + Rational(1) + end end def test_uplus @@ -593,6 +597,14 @@ class TestBigDecimal < Test::Unit::TestCase assert_equal(BigDecimal.new((2**100-1).to_s), x - 1) end + def test_sub_with_float + assert_kind_of(BigDecimal, BigDecimal.new("3") - 1.0) + end + + def test_sub_with_rational + assert_kind_of(BigDecimal, BigDecimal.new("3") - 1.quo(3)) + end + def test_mult x = BigDecimal.new((2**100).to_s) assert_equal(BigDecimal.new((2**100 * 3).to_s), (x * 3).to_i) @@ -601,6 +613,14 @@ class TestBigDecimal < Test::Unit::TestCase assert_equal(BigDecimal.new((2**200).to_s), (x * x).to_i) end + def test_mult_with_float + assert_kind_of(BigDecimal, BigDecimal.new("3") * 1.5) + end + + def test_mult_with_rational + assert_kind_of(BigDecimal, BigDecimal.new("3") * 1.quo(3)) + end + def test_div x = BigDecimal.new((2**100).to_s) assert_equal(BigDecimal.new((2**100 / 3).to_s), (x / 3).to_i) @@ -610,6 +630,14 @@ class TestBigDecimal < Test::Unit::TestCase assert_equal(-2, BigDecimal.new("2") / -1) end + def test_div_with_float + assert_kind_of(BigDecimal, BigDecimal.new("3") / 1.5) + end + + def test_div_with_rational + assert_kind_of(BigDecimal, BigDecimal.new("3") / 1.quo(3)) + end + def test_mod x = BigDecimal.new((2**100).to_s) assert_equal(1, x % 3) @@ -618,6 +646,14 @@ class TestBigDecimal < Test::Unit::TestCase assert_equal(-1, (-x) % -3) end + def test_mod_with_float + assert_kind_of(BigDecimal, BigDecimal.new("3") % 1.5) + end + + def test_mod_with_rational + assert_kind_of(BigDecimal, BigDecimal.new("3") % 1.quo(3)) + end + def test_remainder x = BigDecimal.new((2**100).to_s) assert_equal(1, x.remainder(3)) @@ -626,6 +662,14 @@ class TestBigDecimal < Test::Unit::TestCase assert_equal(-1, (-x).remainder(-3)) end + def test_remainder_with_float + assert_kind_of(BigDecimal, BigDecimal.new("3").remainder(1.5)) + end + + def test_remainder_with_rational + assert_kind_of(BigDecimal, BigDecimal.new("3").remainder(1.quo(3))) + end + def test_divmod x = BigDecimal.new((2**100).to_s) assert_equal([(x / 3).floor, 1], x.divmod(3)) @@ -1297,4 +1341,10 @@ class TestBigDecimal < Test::Unit::TestCase code = "exit(BigDecimal.new('10.0') == 10.0.to_d)" assert_ruby_status(%w[-rbigdecimal -rbigdecimal/util -rmathn -], code, bug6093) end + + def test_bug6406 + assert_in_out_err(%w[-rbigdecimal --disable-gems], <<-EOS, [], []) + Thread.current.keys.to_s + EOS + end end diff --git a/test/cgi/test_cgi_session.rb b/test/cgi/test_cgi_session.rb index f3b8e60..7fa7ad7 100644 --- a/test/cgi/test_cgi_session.rb +++ b/test/cgi/test_cgi_session.rb @@ -7,8 +7,7 @@ require 'tmpdir' class CGISessionTest < Test::Unit::TestCase def setup - @session_dir = File.join(File.dirname(__FILE__), 'session_dir') - FileUtils.mkdir_p @session_dir + @session_dir = Dir.mktmpdir(%w'session dir') end def teardown diff --git a/test/csv/test_features.rb b/test/csv/test_features.rb index 0da557e..8610949 100755 --- a/test/csv/test_features.rb +++ b/test/csv/test_features.rb @@ -10,6 +10,7 @@ require "zlib" require_relative "base" +require "tempfile" class TestCSV::Features < TestCSV extend DifferentOFS @@ -208,7 +209,9 @@ class TestCSV::Features < TestCSV end def test_gzip_writer_bug_fix - file = File.join(File.dirname(__FILE__), "temp.gz") + 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)) @@ -220,7 +223,7 @@ class TestCSV::Features < TestCSV assert( Zlib::GzipReader.open(file) { |f| f.read }. include?($INPUT_RECORD_SEPARATOR), "@row_sep did not default" ) - File.unlink(file) + tempfile.close(true) end def test_inspect_is_smart_about_io_types @@ -230,11 +233,13 @@ class TestCSV::Features < TestCSV str = CSV.new($stderr).inspect assert(str.include?("io_type:$stderr"), "IO type not detected.") - path = File.join(File.dirname(__FILE__), "temp.csv") + 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.") - File.unlink(path) + tempfile.close(true) end def test_inspect_shows_key_attributes diff --git a/test/csv/test_interface.rb b/test/csv/test_interface.rb index 9cdbcec..73e6ca9 100755 --- a/test/csv/test_interface.rb +++ b/test/csv/test_interface.rb @@ -8,13 +8,16 @@ # under the terms of Ruby's license. require_relative "base" +require "tempfile" class TestCSV::Interface < TestCSV extend DifferentOFS def setup super - @path = File.join(File.dirname(__FILE__), "temp_test_data.csv") + @tempfile = Tempfile.new(%w"temp .csv") + @tempfile.close + @path = @tempfile.path File.open(@path, "wb") do |file| file << "1\t2\t3\r\n" @@ -25,7 +28,7 @@ class TestCSV::Interface < TestCSV end def teardown - File.unlink(@path) + @tempfile.close(true) super end @@ -112,7 +115,7 @@ class TestCSV::Interface < TestCSV assert_equal(nil, csv.shift) end end - + def test_enumerators_are_supported CSV.open(@path, col_sep: "\t", row_sep: "\r\n") do |csv| enum = csv.each diff --git a/test/csv/test_serialization.rb b/test/csv/test_serialization.rb index ba19b7a..dafe12b 100755 --- a/test/csv/test_serialization.rb +++ b/test/csv/test_serialization.rb @@ -8,6 +8,7 @@ # under the terms of Ruby's license. require_relative "base" +require "tempfile" # An example of how to provide custom CSV serialization. class Hash @@ -131,7 +132,9 @@ class TestCSV::Serialization < TestCSV def test_io test_class_dump - data_file = File.join(File.dirname(__FILE__), "serialization_test_data.csv") + tempfile = Tempfile.new(%w"serialization .csv") + tempfile.close + data_file = tempfile.path CSV.dump(@names, File.open(data_file, "wb")) assert(File.exist?(data_file)) @@ -145,7 +148,7 @@ class TestCSV::Serialization < TestCSV assert_equal(@names, CSV.load(File.open(data_file))) - File.unlink(data_file) + tempfile.close(true) end def test_custom_dump_and_load diff --git a/test/dl/test_func.rb b/test/dl/test_func.rb index 761ae43..4e69dea 100644 --- a/test/dl/test_func.rb +++ b/test/dl/test_func.rb @@ -9,6 +9,71 @@ module DL assert_equal 'strcpy', f.name end + def test_name_with_block + begin + cb = Function.new(CFunc.new(0, TYPE_INT, '<callback>qsort'), + [TYPE_VOIDP, TYPE_VOIDP]){|x,y| CPtr.new(x)[0] <=> CPtr.new(y)[0]} + assert_equal('<callback>qsort', cb.name) + ensure + cb.unbind if cb # max number of callbacks is limited to MAX_CALLBACK + end + end + + def test_bound + f = Function.new(CFunc.new(0, TYPE_INT, 'test'), [TYPE_INT, TYPE_INT]) + assert_equal false, f.bound? + begin + f.bind { |x,y| x + y } + assert_equal true, f.bound? + ensure + f.unbind # max number of callbacks is limited to MAX_CALLBACK + end + end + + def test_bound_for_callback_closure + begin + f = Function.new(CFunc.new(0, TYPE_INT, 'test'), + [TYPE_INT, TYPE_INT]) { |x,y| x + y } + assert_equal true, f.bound? + ensure + f.unbind if f # max number of callbacks is limited to MAX_CALLBACK + end + end + + def test_unbind + f = Function.new(CFunc.new(0, TYPE_INT, 'test'), [TYPE_INT, TYPE_INT]) + begin + f.bind { |x, y| x + y } + assert_nothing_raised { f.unbind } + assert_equal false, f.bound? + # unbind() after unbind() should not raise error + assert_nothing_raised { f.unbind } + ensure + f.unbind # max number of callbacks is limited to MAX_CALLBACK + end + end + + def test_unbind_normal_function + f = Function.new(CFunc.new(@libc['strcpy'], TYPE_VOIDP, 'strcpy'), + [TYPE_VOIDP, TYPE_VOIDP]) + assert_nothing_raised { f.unbind } + assert_equal false, f.bound? + # unbind() after unbind() should not raise error + assert_nothing_raised { f.unbind } + end + + def test_bind + f = Function.new(CFunc.new(0, TYPE_INT, 'test'), [TYPE_INT, TYPE_INT]) + begin + assert_nothing_raised { + f.bind { |x, y| x + y } + } + assert_equal 579, f.call(123, 456) + ensure + f.unbind # max number of callbacks is limited to MAX_CALLBACK + end + end + def test_to_i cfunc = CFunc.new(@libc['strcpy'], TYPE_VOIDP, 'strcpy') f = Function.new(cfunc, [TYPE_VOIDP, TYPE_VOIDP]) @@ -88,18 +153,22 @@ module DL end def test_qsort1() - cb = Function.new(CFunc.new(0, TYPE_INT, '<callback>qsort'), - [TYPE_VOIDP, TYPE_VOIDP]){|x,y| CPtr.new(x)[0] <=> CPtr.new(y)[0]} - qsort = Function.new(CFunc.new(@libc['qsort'], TYPE_VOID, 'qsort'), - [TYPE_VOIDP, TYPE_INT, TYPE_INT, TYPE_VOIDP]) - buff = "9341" - qsort.call(buff, buff.size, 1, cb) - assert_equal("1349", buff) + begin + cb = Function.new(CFunc.new(0, TYPE_INT, '<callback>qsort'), + [TYPE_VOIDP, TYPE_VOIDP]){|x,y| CPtr.new(x)[0] <=> CPtr.new(y)[0]} + qsort = Function.new(CFunc.new(@libc['qsort'], TYPE_VOID, 'qsort'), + [TYPE_VOIDP, TYPE_INT, TYPE_INT, TYPE_VOIDP]) + buff = "9341" + qsort.call(buff, buff.size, 1, cb) + assert_equal("1349", buff) - bug4929 = '[ruby-core:37395]' - buff = "9341" - EnvUtil.under_gc_stress {qsort.call(buff, buff.size, 1, cb)} - assert_equal("1349", buff, bug4929) + bug4929 = '[ruby-core:37395]' + buff = "9341" + EnvUtil.under_gc_stress {qsort.call(buff, buff.size, 1, cb)} + assert_equal("1349", buff, bug4929) + ensure + cb.unbind if cb # max number of callbacks is limited to MAX_CALLBACK + end end def test_qsort2() diff --git a/test/drb/drbtest.rb b/test/drb/drbtest.rb index fe39a6e..b9285b5 100644 --- a/test/drb/drbtest.rb +++ b/test/drb/drbtest.rb @@ -11,7 +11,7 @@ class DRbService @@ruby += " -d" if $DEBUG def self.add_service_command(nm) dir = File.dirname(File.expand_path(__FILE__)) - DRb::ExtServManager.command[nm] = "#{@@ruby} \"#{dir}/#{nm}\"" + DRb::ExtServManager.command[nm] = [@@ruby, "#{dir}/#{nm}"] end %w(ut_drb.rb ut_array.rb ut_port.rb ut_large.rb ut_safe1.rb ut_eval.rb ut_eq.rb).each do |nm| @@ -65,12 +65,24 @@ end module DRbCore def setup - @ext = DRbService.ext_service('ut_drb.rb') + @service_name = 'ut_drb.rb' + @ext = DRbService.ext_service(@service_name) @there = @ext.front end def teardown - @ext.stop_service if @ext + @ext.stop_service if defined?(@ext) && @ext + DRbService.manager.unregist(@service_name) + signal = /mswin|mingw/ =~ RUBY_PLATFORM ? :INT : :TERM + Thread.list.each {|th| + if th.respond_to?(:pid) && th[:drb_service] == @service_name + begin + Process.kill signal, th.pid + rescue Errno::ESRCH + end + th.join + end + } end def test_00_DRbObject @@ -271,12 +283,24 @@ end module DRbAry def setup - @ext = DRbService.ext_service('ut_array.rb') + @service_name = 'ut_array.rb' + @ext = DRbService.ext_service(@service_name) @there = @ext.front end def teardown - @ext.stop_service if @ext + @ext.stop_service if defined?(@ext) && @ext + DRbService.manager.unregist(@service_name) + signal = /mswin|mingw/ =~ RUBY_PLATFORM ? :INT : :TERM + Thread.list.each {|th| + if th.respond_to?(:pid) && th[:drb_service] == @service_name + begin + Process.kill signal, th.pid + rescue Errno::ESRCH + end + th.join + end + } end def test_01 diff --git a/test/drb/test_drb.rb b/test/drb/test_drb.rb index 8ab00ec..dc9a47d 100644 --- a/test/drb/test_drb.rb +++ b/test/drb/test_drb.rb @@ -202,7 +202,8 @@ end class TestDRbSafe1 < TestDRbAry def setup - @ext = DRbService.ext_service('ut_safe1.rb') + @service_name = 'ut_safe1.rb' + @ext = DRbService.ext_service(@service_name) @there = @ext.front end end diff --git a/test/drb/test_drbssl.rb b/test/drb/test_drbssl.rb index 8f6c4f2..6322434 100644 --- a/test/drb/test_drbssl.rb +++ b/test/drb/test_drbssl.rb @@ -36,7 +36,8 @@ end class TestDRbSSLCore < Test::Unit::TestCase include DRbCore def setup - @ext = DRbSSLService.ext_service('ut_drb_drbssl.rb') + @service_name = 'ut_drb_drbssl.rb' + @ext = DRbSSLService.ext_service(@service_name) @there = @ext.front end @@ -53,7 +54,8 @@ end class TestDRbSSLAry < Test::Unit::TestCase include DRbAry def setup - @ext = DRbSSLService.ext_service('ut_array_drbssl.rb') + @service_name = 'ut_array_drbssl.rb' + @ext = DRbSSLService.ext_service(@service_name) @there = @ext.front end end diff --git a/test/drb/test_drbunix.rb b/test/drb/test_drbunix.rb index 5b93f52..1fba033 100644 --- a/test/drb/test_drbunix.rb +++ b/test/drb/test_drbunix.rb @@ -20,7 +20,8 @@ end class TestDRbUNIXCore < Test::Unit::TestCase include DRbCore def setup - @ext = DRbUNIXService.ext_service('ut_drb_drbunix.rb') + @service_name = 'ut_drb_drbunix.rb' + @ext = DRbUNIXService.ext_service(@service_name) @there = @ext.front end @@ -37,7 +38,8 @@ end class TestDRbUNIXAry < Test::Unit::TestCase include DRbAry def setup - @ext = DRbUNIXService.ext_service('ut_array_drbunix.rb') + @service_name = 'ut_array_drbunix.rb' + @ext = DRbUNIXService.ext_service(@service_name) @there = @ext.front end end diff --git a/test/etc/test_etc.rb b/test/etc/test_etc.rb index c4db71c..5bc8db4 100644 --- a/test/etc/test_etc.rb +++ b/test/etc/test_etc.rb @@ -28,11 +28,18 @@ class TestEtc < Test::Unit::TestCase end def test_getpwuid - passwd = {} - Etc.passwd {|s| passwd[s.uid] ||= s } - passwd.each_value do |s| - assert_equal(s, Etc.getpwuid(s.uid)) - assert_equal(s, Etc.getpwuid) if Process.euid == s.uid + # password database is not unique on UID, and which entry will be + # returned by getpwuid() is not specified. + passwd = Hash.new {[]} + # on MacOSX, same entries are returned from /etc/passwd and Open + # Directory. + Etc.passwd {|s| passwd[s.uid] |= [s]} + passwd.each_pair do |uid, s| + assert_include(s, Etc.getpwuid(uid)) + end + s = passwd[Process.euid] + unless s.empty? + assert_include(s, Etc.getpwuid) end end diff --git a/test/json/test_json.rb b/test/json/test_json.rb index eafd758..fa96130 100755 --- a/test/json/test_json.rb +++ b/test/json/test_json.rb @@ -4,6 +4,7 @@ require 'test/unit' require File.join(File.dirname(__FILE__), 'setup_variant') require 'stringio' +require 'tempfile' unless Array.method_defined?(:permutation) begin @@ -263,12 +264,12 @@ class TC_JSON < Test::Unit::TestCase def test_generation_of_core_subclasses_with_new_to_json obj = SubHash2["foo" => SubHash2["bar" => true]] obj_json = JSON(obj) - obj_again = JSON(obj_json) + obj_again = JSON.parse(obj_json, :create_additions => true) assert_kind_of SubHash2, obj_again assert_kind_of SubHash2, obj_again['foo'] assert obj_again['foo']['bar'] assert_equal obj, obj_again - assert_equal ["foo"], JSON(JSON(SubArray2["foo"])) + assert_equal ["foo"], JSON(JSON(SubArray2["foo"]), :create_additions => true) end def test_generation_of_core_subclasses_with_default_to_json @@ -414,6 +415,25 @@ EOT JSON.parse('{"foo":"bar", "baz":"quux"}', :symbolize_names => true)) end + def test_load + assert_equal @hash, JSON.load(@json) + tempfile = Tempfile.open('json') + tempfile.write @json + tempfile.rewind + assert_equal @hash, JSON.load(tempfile) + stringio = StringIO.new(@json) + stringio.rewind + assert_equal @hash, JSON.load(stringio) + assert_raise(NoMethodError) { JSON.load(nil) } + assert_raise(JSON::ParserError) {JSON.load('') } + end + + def test_load_with_options + small_hash = JSON("foo" => 'bar') + symbol_hash = { :foo => 'bar' } + assert_equal symbol_hash, JSON.load(small_hash, nil, :symbolize_names => true) + end + def test_load_dump too_deep = '[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]' assert_equal too_deep, JSON.dump(eval(too_deep)) diff --git a/test/json/test_json_addition.rb b/test/json/test_json_addition.rb index cc3820a..37dba6b 100755 --- a/test/json/test_json_addition.rb +++ b/test/json/test_json_addition.rb @@ -69,11 +69,19 @@ class TC_JSONAddition < Test::Unit::TestCase a = A.new(666) assert A.json_creatable? json = generate(a) - a_again = JSON.parse(json) + a_again = JSON.parse(json, :create_additions => true) assert_kind_of a.class, a_again assert_equal a, a_again end + def test_extended_json_default + a = A.new(666) + assert A.json_creatable? + json = generate(a) + a_hash = JSON.parse(json) + assert_kind_of Hash, a_hash + end + def test_extended_json_disabled a = A.new(666) assert A.json_creatable? @@ -100,7 +108,7 @@ class TC_JSONAddition < Test::Unit::TestCase c = C.new assert !C.json_creatable? json = generate(c) - assert_raises(ArgumentError, NameError) { JSON.parse(json) } + assert_raises(ArgumentError, NameError) { JSON.parse(json, :create_additions => true) } end def test_raw_strings @@ -118,7 +126,7 @@ class TC_JSONAddition < Test::Unit::TestCase assert_match(/\A\{.*\}\Z/, json) assert_match(/"json_class":"String"/, json) assert_match(/"raw":\[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json) - raw_again = JSON.parse(json) + raw_again = JSON.parse(json, :create_additions => true) assert_equal raw, raw_again end @@ -126,17 +134,17 @@ class TC_JSONAddition < Test::Unit::TestCase def test_core t = Time.now - assert_equal t.inspect, JSON(JSON(t)).inspect + assert_equal t, JSON(JSON(t), :create_additions => true) d = Date.today - assert_equal d, JSON(JSON(d)) + assert_equal d, JSON(JSON(d), :create_additions => true) d = DateTime.civil(2007, 6, 14, 14, 57, 10, Rational(1, 12), 2299161) - assert_equal d, JSON(JSON(d)) - assert_equal 1..10, JSON(JSON(1..10)) - assert_equal 1...10, JSON(JSON(1...10)) - assert_equal "a".."c", JSON(JSON("a".."c")) - assert_equal "a"..."c", JSON(JSON("a"..."c")) + assert_equal d, JSON(JSON(d), :create_additions => true) + assert_equal 1..10, JSON(JSON(1..10), :create_additions => true) + assert_equal 1...10, JSON(JSON(1...10), :create_additions => true) + assert_equal "a".."c", JSON(JSON("a".."c"), :create_additions => true) + assert_equal "a"..."c", JSON(JSON("a"..."c"), :create_additions => true) s = MyJsonStruct.new 4711, 'foot' - assert_equal s, JSON(JSON(s)) + assert_equal s, JSON(JSON(s), :create_additions => true) struct = Struct.new :foo, :bar s = struct.new 4711, 'foot' assert_raises(JSONError) { JSON(s) } @@ -144,24 +152,24 @@ class TC_JSONAddition < Test::Unit::TestCase raise TypeError, "test me" rescue TypeError => e e_json = JSON.generate e - e_again = JSON e_json + e_again = JSON e_json, :create_additions => true assert_kind_of TypeError, e_again assert_equal e.message, e_again.message assert_equal e.backtrace, e_again.backtrace end - assert_equal(/foo/, JSON(JSON(/foo/))) - assert_equal(/foo/i, JSON(JSON(/foo/i))) + assert_equal(/foo/, JSON(JSON(/foo/), :create_additions => true)) + assert_equal(/foo/i, JSON(JSON(/foo/i), :create_additions => true)) end def test_utc_datetime now = Time.now - d = DateTime.parse(now.to_s) # usual case - assert_equal d, JSON.parse(d.to_json) + d = DateTime.parse(now.to_s, :create_additions => true) # usual case + assert_equal d, JSON.parse(d.to_json, :create_additions => true) d = DateTime.parse(now.utc.to_s) # of = 0 - assert_equal d, JSON.parse(d.to_json) + assert_equal d, JSON.parse(d.to_json, :create_additions => true) d = DateTime.civil(2008, 6, 17, 11, 48, 32, Rational(1,24)) - assert_equal d, JSON.parse(d.to_json) + assert_equal d, JSON.parse(d.to_json, :create_additions => true) d = DateTime.civil(2008, 6, 17, 11, 48, 32, Rational(12,24)) - assert_equal d, JSON.parse(d.to_json) + assert_equal d, JSON.parse(d.to_json, :create_additions => true) end end diff --git a/test/json/test_json_string_matching.rb b/test/json/test_json_string_matching.rb index df26a68..7335c0e 100644 --- a/test/json/test_json_string_matching.rb +++ b/test/json/test_json_string_matching.rb @@ -27,14 +27,13 @@ class TestJsonStringMatching < Test::Unit::TestCase t = TestTime.new t_json = [ t ].to_json assert_equal [ t ], - JSON.parse(t_json, - :match_string => { /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\Z/ => TestTime }) + JSON.parse(t_json, :create_additions => true, + :match_string => { /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\z/ => TestTime }) assert_equal [ t.strftime('%FT%T%z') ], - JSON.parse(t_json, - :match_string => { /\A\d{3}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\Z/ => TestTime }) + JSON.parse(t_json, :create_additions => true, + :match_string => { /\A\d{3}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\z/ => TestTime }) assert_equal [ t.strftime('%FT%T%z') ], JSON.parse(t_json, - :match_string => { /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\Z/ => TestTime }, - :create_additions => false) + :match_string => { /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\z/ => TestTime }) end end diff --git a/test/logger/test_logger.rb b/test/logger/test_logger.rb index 0736314..8fc02f8 100644 --- a/test/logger/test_logger.rb +++ b/test/logger/test_logger.rb @@ -21,13 +21,6 @@ class TestLogger < Test::Unit::TestCase def setup @logger = Logger.new(nil) - @filename = __FILE__ + ".#{$$}" - end - - def teardown - unless $DEBUG - File.unlink(@filename) if File.exist?(@filename) - end end class Log @@ -279,13 +272,14 @@ class TestLogDevice < Test::Unit::TestCase end def setup - @filename = __FILE__ + ".#{$$}" + @tempfile = Tempfile.new("logger") + @tempfile.close + @filename = @tempfile.path + File.unlink(@filename) end def teardown - unless $DEBUG - File.unlink(@filename) if File.exist?(@filename) - end + @tempfile.close(true) end def d(log, opt = {}) @@ -480,13 +474,14 @@ end class TestLoggerApplication < Test::Unit::TestCase def setup @app = Logger::Application.new('appname') - @filename = __FILE__ + ".#{$$}" + @tempfile = Tempfile.new("logger") + @tempfile.close + @filename = @tempfile.path + File.unlink(@filename) end def teardown - unless $DEBUG - File.unlink(@filename) if File.exist?(@filename) - end + @tempfile.close(true) end def test_initialize diff --git a/test/net/http/test_http.rb b/test/net/http/test_http.rb index a1e57dc..c302e10 100644 --- a/test/net/http/test_http.rb +++ b/test/net/http/test_http.rb @@ -1,4 +1,4 @@ -# $Id: test_http.rb 32192 2011-06-21 17:44:44Z nahi $ +# $Id: test_http.rb 37659 2012-11-15 06:15:17Z usa $ require 'test/unit' require 'net/http' @@ -426,7 +426,7 @@ end class TestNetHTTP_v1_2 < Test::Unit::TestCase CONFIG = { 'host' => '127.0.0.1', - 'port' => 10081, + 'port' => 0, 'proxy_host' => nil, 'proxy_port' => nil, } @@ -444,7 +444,7 @@ end class TestNetHTTP_v1_2_chunked < Test::Unit::TestCase CONFIG = { 'host' => '127.0.0.1', - 'port' => 10081, + 'port' => 0, 'proxy_host' => nil, 'proxy_port' => nil, 'chunked' => true, @@ -476,7 +476,7 @@ end class TestNetHTTPContinue < Test::Unit::TestCase CONFIG = { 'host' => '127.0.0.1', - 'port' => 10081, + 'port' => 0, 'proxy_host' => nil, 'proxy_port' => nil, 'chunked' => true, diff --git a/test/net/http/test_https.rb b/test/net/http/test_https.rb index 983ba7f..2f2c699 100644 --- a/test/net/http/test_https.rb +++ b/test/net/http/test_https.rb @@ -24,7 +24,7 @@ class TestNetHTTPS < Test::Unit::TestCase CONFIG = { 'host' => '127.0.0.1', - 'port' => 10082, # different from test_http.rb + 'port' => 0, 'proxy_host' => nil, 'proxy_port' => nil, 'ssl_enable' => true, diff --git a/test/net/http/utils.rb b/test/net/http/utils.rb index 50f616f..db01b18 100644 --- a/test/net/http/utils.rb +++ b/test/net/http/utils.rb @@ -19,7 +19,8 @@ module TestNetHTTPUtils end def config(key) - self.class::CONFIG[key] + @config ||= self.class::CONFIG + @config[key] end def logfile @@ -42,6 +43,7 @@ module TestNetHTTPUtils end def spawn_server + @config = self.class::CONFIG server_config = { :BindAddress => config('host'), :Port => config('port'), @@ -61,6 +63,7 @@ module TestNetHTTPUtils @server = WEBrick::HTTPServer.new(server_config) @server.mount('/', Servlet, config('chunked')) @server.start + @config['port'] = @server[:Port] if @config['port'] == 0 n_try_max = 5 begin TCPSocket.open(config('host'), config('port')).close diff --git a/test/net/imap/test_imap_response_parser.rb b/test/net/imap/test_imap_response_parser.rb index 6a5a117..1547a05 100644 --- a/test/net/imap/test_imap_response_parser.rb +++ b/test/net/imap/test_imap_response_parser.rb @@ -116,4 +116,29 @@ EOF * 1 FETCH (UID 92285 ) EOF end + + # [Bug #8281] + def test_acl + parser = Net::IMAP::ResponseParser.new + response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint) +* ACL "INBOX/share" "imshare2copy1366146467@xxxxxxxxxxxxxxxxxx.com" lrswickxteda +EOF + assert_equal("ACL", response.name) + assert_equal(1, response.data.length) + assert_equal("INBOX/share", response.data[0].mailbox) + assert_equal("imshare2copy1366146467@xxxxxxxxxxxxxxxxxx.com", + response.data[0].user) + assert_equal("lrswickxteda", response.data[0].rights) + end + + # [Bug #8415] + def test_capability + parser = Net::IMAP::ResponseParser.new + response = parser.parse("* CAPABILITY st11p00mm-iscream009 1Q49 XAPPLEPUSHSERVICE IMAP4 IMAP4rev1 SASL-IR AUTH=ATOKEN AUTH=PLAIN\r\n") + assert_equal("CAPABILITY", response.name) + assert_equal("AUTH=PLAIN", response.data.last) + response = parser.parse("* CAPABILITY st11p00mm-iscream009 1Q49 XAPPLEPUSHSERVICE IMAP4 IMAP4rev1 SASL-IR AUTH=ATOKEN AUTH=PLAIN \r\n") + assert_equal("CAPABILITY", response.name) + assert_equal("AUTH=PLAIN", response.data.last) + end end diff --git a/test/net/protocol/test_protocol.rb b/test/net/protocol/test_protocol.rb new file mode 100644 index 0000000..d8f816e --- /dev/null +++ b/test/net/protocol/test_protocol.rb @@ -0,0 +1,20 @@ +# coding: utf-8 +require "test/unit" +require "net/protocol" +require "stringio" + +class TestProtocol < Test::Unit::TestCase + def test_each_crlf_line + assert_output('', '') do + sio = StringIO.new("") + imio = Net::InternetMessageIO.new(sio) + assert_equal(23, imio.write_message("\u3042\r\u3044\n\u3046\r\n\u3048")) + assert_equal("\u3042\r\n\u3044\r\n\u3046\r\n\u3048\r\n.\r\n", sio.string) + + sio = StringIO.new("") + imio = Net::InternetMessageIO.new(sio) + assert_equal(8, imio.write_message("\u3042\r")) + assert_equal("\u3042\r\n.\r\n", sio.string) + end + end +end diff --git a/test/openssl/test_asn1.rb b/test/openssl/test_asn1.rb index 0932476..811fe38 100644 --- a/test/openssl/test_asn1.rb +++ b/test/openssl/test_asn1.rb @@ -198,6 +198,18 @@ class OpenSSL::TestASN1 < Test::Unit::TestCase encode_decode_test(OpenSSL::ASN1::Integer, [72, -127, -128, 128, -1, 0, 1, -(2**12345), 2**12345]) end + def test_encode_nil + m = OpenSSL::ASN1 + [ + m::Boolean, m::Integer, m::BitString, m::OctetString, + m::ObjectId, m::Enumerated, m::UTF8String, m::UTCTime, + m::GeneralizedTime, m::Sequence, m::Set + ].each do |klass| + #Primitives raise TypeError, Constructives NoMethodError + assert_raise(TypeError, NoMethodError) { klass.send(:new, nil).to_der } + end + end + def encode_decode_test(type, values) values.each do |v| assert_equal(v, OpenSSL::ASN1.decode(type.new(v).to_der).value) diff --git a/test/openssl/test_config.rb b/test/openssl/test_config.rb index 77f89b2..1ed455c 100644 --- a/test/openssl/test_config.rb +++ b/test/openssl/test_config.rb @@ -16,9 +16,10 @@ __EOD__ end def test_constants - assert(defined?(OpenSSL::Config::DEFAULT_CONFIG_FILE)) + config_file = OpenSSL::Config::DEFAULT_CONFIG_FILE + skip "DEFAULT_CONFIG_FILE may return a wrong path on your platforms. [Bug #6830]" unless File.readable?(config_file) assert_nothing_raised do - OpenSSL::Config.load(OpenSSL::Config::DEFAULT_CONFIG_FILE) + OpenSSL::Config.load(config_file) end end diff --git a/test/openssl/test_ssl.rb b/test/openssl/test_ssl.rb index 5d40a55..58493bf 100644 --- a/test/openssl/test_ssl.rb +++ b/test/openssl/test_ssl.rb @@ -351,6 +351,28 @@ class OpenSSL::TestSSL < OpenSSL::SSLTestCase } end + def test_verify_certificate_identity + # creating NULL byte SAN certificate + ef = OpenSSL::X509::ExtensionFactory.new + cert = OpenSSL::X509::Certificate.new + cert.subject = OpenSSL::X509::Name.parse "/DC=some/DC=site/CN=Some Site" + ext = ef.create_ext('subjectAltName', 'DNS:placeholder,IP:192.168.7.1,IP:13::17') + ext_asn1 = OpenSSL::ASN1.decode(ext.to_der) + san_list_der = ext_asn1.value.reduce(nil) { |memo,val| val.tag == 4 ? val.value : memo } + san_list_asn1 = OpenSSL::ASN1.decode(san_list_der) + san_list_asn1.value[0].value = 'www.example.com\0.evil.com' + ext_asn1.value[1].value = san_list_asn1.to_der + real_ext = OpenSSL::X509::Extension.new ext_asn1 + cert.add_extension(real_ext) + + assert_equal(false, OpenSSL::SSL.verify_certificate_identity(cert, 'www.example.com')) + assert_equal(true, OpenSSL::SSL.verify_certificate_identity(cert, 'www.example.com\0.evil.com')) + assert_equal(false, OpenSSL::SSL.verify_certificate_identity(cert, '192.168.7.255')) + assert_equal(true, OpenSSL::SSL.verify_certificate_identity(cert, '192.168.7.1')) + assert_equal(false, OpenSSL::SSL.verify_certificate_identity(cert, '13::17')) + assert_equal(true, OpenSSL::SSL.verify_certificate_identity(cert, '13:0:0:0:0:0:0:17')) + end + def test_tlsext_hostname return unless OpenSSL::SSL::SSLSocket.instance_methods.include?(:hostname) @@ -438,6 +460,33 @@ class OpenSSL::TestSSL < OpenSSL::SSLTestCase } end + def test_invalid_shutdown_by_gc + assert_nothing_raised { + start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port| + 10.times { + sock = TCPSocket.new("127.0.0.1", port) + ssl = OpenSSL::SSL::SSLSocket.new(sock) + GC.start + ssl.connect + sock.close + } + } + } + end + + def test_close_after_socket_close + start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port| + sock = TCPSocket.new("127.0.0.1", port) + ssl = OpenSSL::SSL::SSLSocket.new(sock) + ssl.sync_close = true + ssl.connect + sock.close + assert_nothing_raised do + ssl.close + end + } + end + end end diff --git a/test/optparse/test_summary.rb b/test/optparse/test_summary.rb index 0c67d7f..d777173 100644 --- a/test/optparse/test_summary.rb +++ b/test/optparse/test_summary.rb @@ -18,4 +18,21 @@ class TestOptionParser::SummaryTest < TestOptionParser assert_match(/description 2/, s[1]) assert_match(/last-option/, s[-1]) end + + def test_banner + o = OptionParser.new("foo bar") + assert_equal("foo bar", o.banner) + end + + def test_banner_from_progname + o = OptionParser.new + o.program_name = "foobar" + assert_equal("Usage: foobar [options]\n", o.help) + end + + def test_summary + o = OptionParser.new("foo\nbar") + assert_equal("foo\nbar\n", o.to_s) + assert_equal(["foo\n", "bar"], o.to_a) + end end diff --git a/test/pathname/test_pathname.rb b/test/pathname/test_pathname.rb index 8a8c0d9..61d288d 100644 --- a/test/pathname/test_pathname.rb +++ b/test/pathname/test_pathname.rb @@ -1,5 +1,3 @@ -#!/usr/bin/env ruby - require 'test/unit' require 'pathname' @@ -185,10 +183,8 @@ class TestPathname < Test::Unit::TestCase if DOSISH defassert(:del_trailing_separator, "a", "a\\") - require 'Win32API' - if Win32API.new('kernel32', 'GetACP', nil, 'L').call == 932 - defassert(:del_trailing_separator, "\225\\", "\225\\\\") # SJIS - end + defassert(:del_trailing_separator, "\225\\".force_encoding("cp932"), "\225\\\\".force_encoding("cp932")) + defassert(:del_trailing_separator, "\225".force_encoding("cp437"), "\225\\\\".force_encoding("cp437")) end def test_plus diff --git a/test/psych/test_alias_and_anchor.rb b/test/psych/test_alias_and_anchor.rb index 48771d6..aa4773b 100644 --- a/test/psych/test_alias_and_anchor.rb +++ b/test/psych/test_alias_and_anchor.rb @@ -1,5 +1,13 @@ require 'psych/helper' +class ObjectWithInstanceVariables + attr_accessor :var1, :var2 +end + +class SubStringWithInstanceVariables < String + attr_accessor :var1 +end + module Psych class TestAliasAndAnchor < TestCase def test_mri_compatibility @@ -14,6 +22,40 @@ EOYAML result.each {|el| assert_same(result[0], el) } end + def test_mri_compatibility_object_with_ivars + yaml = <<EOYAML +--- +- &id001 !ruby/object:ObjectWithInstanceVariables + var1: test1 + var2: test2 +- *id001 +- *id001 +EOYAML + + result = Psych.load yaml + result.each do |el| + assert_same(result[0], el) + assert_equal('test1', el.var1) + assert_equal('test2', el.var2) + end + end + + def test_mri_compatibility_substring_with_ivars + yaml = <<EOYAML +--- +- &id001 !str:SubStringWithInstanceVariables + str: test + "@var1": test +- *id001 +- *id001 +EOYAML + result = Psych.load yaml + result.each do |el| + assert_same(result[0], el) + assert_equal('test', el.var1) + end + end + def test_anchor_alias_round_trip o = Object.new original = [o,o,o] @@ -22,5 +64,33 @@ EOYAML result = Psych.load yaml result.each {|el| assert_same(result[0], el) } end + + def test_anchor_alias_round_trip_object_with_ivars + o = ObjectWithInstanceVariables.new + o.var1 = 'test1' + o.var2 = 'test2' + original = [o,o,o] + + yaml = Psych.dump original + result = Psych.load yaml + result.each do |el| + assert_same(result[0], el) + assert_equal('test1', el.var1) + assert_equal('test2', el.var2) + end + end + + def test_anchor_alias_round_trip_substring_with_ivars + o = SubStringWithInstanceVariables.new + o.var1 = 'test' + original = [o,o,o] + + yaml = Psych.dump original + result = Psych.load yaml + result.each do |el| + assert_same(result[0], el) + assert_equal('test', el.var1) + end + end end end diff --git a/test/psych/test_array.rb b/test/psych/test_array.rb index 9eedbb4..747fe95 100644 --- a/test/psych/test_array.rb +++ b/test/psych/test_array.rb @@ -14,6 +14,16 @@ module Psych @list = [{ :a => 'b' }, 'foo'] end + def test_another_subclass_with_attributes + y = Y.new.tap {|y| y.val = 1} + y << "foo" << "bar" + y = Psych.load Psych.dump y + + assert_equal %w{foo bar}, y + assert_equal Y, y.class + assert_equal 1, y.val + end + def test_subclass yaml = Psych.dump X.new assert_match X.name, yaml diff --git a/test/psych/test_omap.rb b/test/psych/test_omap.rb index 53f55f5..34df724 100644 --- a/test/psych/test_omap.rb +++ b/test/psych/test_omap.rb @@ -2,6 +2,13 @@ require 'psych/helper' module Psych class TestOmap < TestCase + def test_parse_as_map + o = Psych.load "--- !!omap\na: 1\nb: 2" + assert_kind_of Psych::Omap, o + assert_equal 1, o['a'] + assert_equal 2, o['b'] + end + def test_self_referential map = Psych::Omap.new map['foo'] = 'bar' diff --git a/test/psych/test_string.rb b/test/psych/test_string.rb index c7d5c60..77aefc6 100644 --- a/test/psych/test_string.rb +++ b/test/psych/test_string.rb @@ -9,6 +9,13 @@ module Psych attr_accessor :val end + def test_another_subclass_with_attributes + y = Psych.load Psych.dump Y.new("foo").tap {|y| y.val = 1} + assert_equal "foo", y + assert_equal Y, y.class + assert_equal 1, y.val + end + def test_backwards_with_syck x = Psych.load "--- !str:#{X.name} foo\n\n" assert_equal X, x.class diff --git a/test/rexml/test_comment.rb b/test/rexml/test_comment.rb new file mode 100644 index 0000000..ebe3eea --- /dev/null +++ b/test/rexml/test_comment.rb @@ -0,0 +1,25 @@ +require "test/unit/testcase" + +require 'rexml/document' + +module REXMLTest + class CommentTester < Test::Unit::TestCase + # Bug #5278 + def test_hyphen_end_line_in_doctype + xml = <<-XML +<?xml version="1.0"?> +<!DOCTYPE root [ +<!-- comment end with hyphen - + here --> +]> +<root/> + XML + document = REXML::Document.new(xml) + comments = document.doctype.children.find_all do |child| + child.is_a?(REXML::Comment) + end + assert_equal([" comment end with hyphen -\n here "], + comments.collect(&:to_s)) + end + end +end diff --git a/test/rexml/test_encoding.rb b/test/rexml/test_encoding.rb index e359914..8b93460 100644 --- a/test/rexml/test_encoding.rb +++ b/test/rexml/test_encoding.rb @@ -3,6 +3,7 @@ require "rexml_test_utils" require 'rexml/source' +require 'rexml/document' class EncodingTester < Test::Unit::TestCase include REXMLTestUtils diff --git a/test/rexml/test_entity.rb b/test/rexml/test_entity.rb index e6d6f29..5900fac 100644 --- a/test/rexml/test_entity.rb +++ b/test/rexml/test_entity.rb @@ -104,6 +104,24 @@ class EntityTester < Test::Unit::TestCase assert_equal source, out end + def test_entity_string_limit + template = '<!DOCTYPE bomb [ <!ENTITY a "^" > ]> <bomb>$</bomb>' + len = 5120 # 5k per entity + template.sub!(/\^/, "B" * len) + + # 10k is OK + entities = '&a;' * 2 # 5k entity * 2 = 10k + xmldoc = REXML::Document.new(template.sub(/\$/, entities)) + assert_equal(len * 2, xmldoc.root.text.bytesize) + + # above 10k explodes + entities = '&a;' * 3 # 5k entity * 2 = 15k + xmldoc = REXML::Document.new(template.sub(/\$/, entities)) + assert_raises(RuntimeError) do + xmldoc.root.text + end + end + def test_raw source = '<!DOCTYPE foo [ <!ENTITY ent "replace"> diff --git a/test/rinda/test_rinda.rb b/test/rinda/test_rinda.rb index 8154b46..e49a685 100644 --- a/test/rinda/test_rinda.rb +++ b/test/rinda/test_rinda.rb @@ -94,7 +94,7 @@ end class TupleSpace def sleep(n) - Time.sleep(n) + Kernel.sleep(n * 0.01) end end @@ -308,70 +308,35 @@ module TupleSpaceTestModule def test_core_03_notify notify1 = @ts.notify(nil, [:req, Integer]) - notify2 = @ts.notify(nil, {"message"=>String, "name"=>String}, 8) + notify2 = @ts.notify(nil, {"message"=>String, "name"=>String}) - @ts.write({"message"=>"first", "name"=>"3"}, 3) - @ts.write({"message"=>"second", "name"=>"1"}, 1) - @ts.write({"message"=>"third", "name"=>"0"}) - @ts.take({"message"=>"third", "name"=>"0"}) - - listener = Thread.new do - lv = 0 - n = 0 - notify1.each do |ev, tuple| - n += 1 - if ev == 'write' - lv = lv + 1 - elsif ev == 'take' - lv = lv - 1 - else - break - end - assert(lv >= 0) - assert_equal([:req, 2], tuple) - end - [lv, n] + 5.times do |n| + @ts.write([:req, 2]) end - taker = Thread.new(5) do |count| - s = 0 - count.times do - tuple = @ts.take([:req, Integer]) - assert_equal(2, tuple[1]) - s += tuple[1] - end - @ts.write([:ans, s]) - s + 5.times do + tuple = @ts.take([:req, Integer]) + assert_equal(2, tuple[1]) end - 5.times do |n| - @ts.write([:req, 2]) + 5.times do + assert_equal(['write', [:req, 2]], notify1.pop) + end + 5.times do + assert_equal(['take', [:req, 2]], notify1.pop) end + @ts.write({"message"=>"first", "name"=>"3"}) + @ts.write({"message"=>"second", "name"=>"1"}) + @ts.write({"message"=>"third", "name"=>"0"}) + @ts.take({"message"=>"third", "name"=>"0"}) @ts.take({"message"=>"first", "name"=>"3"}) - assert_equal(10, thread_join(taker)) - assert_equal([:ans, 10], @ts.take([:ans, 10])) - assert_equal([], @ts.read_all([nil, nil])) - - notify1.cancel - sleep(8) - - assert_equal([0, 11], thread_join(listener)) - - ary = [] - ary.push(["write", {"message"=>"first", "name"=>"3"}]) - ary.push(["write", {"message"=>"second", "name"=>"1"}]) - ary.push(["write", {"message"=>"third", "name"=>"0"}]) - ary.push(["take", {"message"=>"third", "name"=>"0"}]) - ary.push(["take", {"message"=>"first", "name"=>"3"}]) - ary.push(["delete", {"message"=>"second", "name"=>"1"}]) - ary.push(["close"]) - - notify2.each do |ev| - assert_equal(ary.shift, ev) - end - assert_equal([], ary) + assert_equal(["write", {"message"=>"first", "name"=>"3"}], notify2.pop) + assert_equal(["write", {"message"=>"second", "name"=>"1"}], notify2.pop) + assert_equal(["write", {"message"=>"third", "name"=>"0"}], notify2.pop) + assert_equal(["take", {"message"=>"third", "name"=>"0"}], notify2.pop) + assert_equal(["take", {"message"=>"first", "name"=>"3"}], notify2.pop) end def test_cancel_01 diff --git a/test/ripper/test_parser_events.rb b/test/ripper/test_parser_events.rb index e6968e1..af41d3e 100644 --- a/test/ripper/test_parser_events.rb +++ b/test/ripper/test_parser_events.rb @@ -592,8 +592,8 @@ class TestRipper::ParserEvents < Test::Unit::TestCase def test_magic_comment thru_magic_comment = false - parse('# -*- foo:bar -*-', :on_magic_comment) {thru_magic_comment = true} - assert_equal true, thru_magic_comment + parse('# -*- bug-5753: ruby-dev:44984 -*-', :on_magic_comment) {|*x|thru_magic_comment = x} + assert_equal [:on_magic_comment, "bug_5753", "ruby-dev:44984"], thru_magic_comment end def test_method_add_block diff --git a/test/ripper/test_scanner_events.rb b/test/ripper/test_scanner_events.rb index e792ca8..c92ec49 100644 --- a/test/ripper/test_scanner_events.rb +++ b/test/ripper/test_scanner_events.rb @@ -657,6 +657,13 @@ class TestRipper::ScannerEvents < Test::Unit::TestCase scan('tstring_content', "<<EOS\nhere\ndoc \nEOS \n") assert_equal ["heredoc\n\tEOS \n"], scan('tstring_content', "<<-EOS\nheredoc\n\tEOS \n") + bug7255 = '[ruby-core:48703]' + assert_equal ["there\n""heredoc", "\n"], + scan('tstring_content', "<<""EOS\n""there\n""heredoc\#{foo}\nEOS"), + bug7255 + assert_equal ["there\n""heredoc", "\n"], + scan('tstring_content', "<<""EOS\n""there\n""heredoc\#@foo\nEOS"), + bug7255 end def test_heredoc_end diff --git a/test/ruby/test_argf.rb b/test/ruby/test_argf.rb index bf6996f..1f82415 100644 --- a/test/ruby/test_argf.rb +++ b/test/ruby/test_argf.rb @@ -201,21 +201,14 @@ class TestArgf < Test::Unit::TestCase t = make_tempfile assert_in_out_err(["-", t.path], <<-INPUT) do |r, e| - ARGF.inplace_mode = '/\\\\' + ARGF.inplace_mode = '/\\\\:' while line = ARGF.gets puts line.chomp + '.new' end INPUT - if no_safe_rename - assert_equal([], e) - assert_equal([], r) - assert_equal("foo.new\nbar.new\nbaz.new\n", File.read(t.path)) - File.unlink(t.path + ".~~~") rescue nil - else - assert_match(/Can't rename .* to .*: .*. skipping file/, e.first) #' - assert_equal([], r) - assert_equal("foo\nbar\nbaz\n", File.read(t.path)) - end + assert_match(/Can't rename .* to .*: .*. skipping file/, e.first) #' + assert_equal([], r) + assert_equal("foo\nbar\nbaz\n", File.read(t.path)) end end @@ -763,4 +756,28 @@ class TestArgf < Test::Unit::TestCase bug5952 = '[ruby-dev:45160]' assert_ruby_status(["-e", "2.times {STDIN.tty?; readlines}"], "", bug5952) end + + def test_bytes + ruby('-e', <<-SRC, @t1.path, @t2.path, @t3.path) do |f| + print Marshal.dump(ARGF.bytes.to_a) + SRC + assert_equal([49, 10, 50, 10, 51, 10, 52, 10, 53, 10, 54, 10], Marshal.load(f.read)) + end + end + + def test_chars + ruby('-e', <<-SRC, @t1.path, @t2.path, @t3.path) do |f| + print [Marshal.dump(ARGF.chars.to_a)].pack('m') + SRC + assert_equal(["1", "\n", "2", "\n", "3", "\n", "4", "\n", "5", "\n", "6", "\n"], Marshal.load(f.read.unpack('m').first)) + end + end + + def test_codepoints + ruby('-e', <<-SRC, @t1.path, @t2.path, @t3.path) do |f| + print Marshal.dump(ARGF.codepoints.to_a) + SRC + assert_equal([49, 10, 50, 10, 51, 10, 52, 10, 53, 10, 54, 10], Marshal.load(f.read)) + end + end end diff --git a/test/ruby/test_basicinstructions.rb b/test/ruby/test_basicinstructions.rb index ff14e4a..7e57530 100644 --- a/test/ruby/test_basicinstructions.rb +++ b/test/ruby/test_basicinstructions.rb @@ -632,7 +632,7 @@ class TestBasicInstructions < Test::Unit::TestCase assert_equal 'i', $~[9] assert_equal 'x', $` assert_equal 'abcdefghi', $& - assert_equal 'y', $' + assert_equal "y", $' assert_equal 'i', $+ assert_equal 'a', $1 assert_equal 'b', $2 @@ -662,15 +662,20 @@ class TestBasicInstructions < Test::Unit::TestCase end def test_array_splat + feature1125 = '[ruby-core:21901]' + a = [] assert_equal [], [*a] assert_equal [1], [1, *a] + assert_not_same(a, [*a], feature1125) a = [2] assert_equal [2], [*a] assert_equal [1, 2], [1, *a] + assert_not_same(a, [*a], feature1125) a = [2, 3] assert_equal [2, 3], [*a] assert_equal [1, 2, 3], [1, *a] + assert_not_same(a, [*a], feature1125) a = nil assert_equal [], [*a] diff --git a/test/ruby/test_beginendblock.rb b/test/ruby/test_beginendblock.rb index 7e460b9..b590835 100644 --- a/test/ruby/test_beginendblock.rb +++ b/test/ruby/test_beginendblock.rb @@ -145,4 +145,17 @@ EOW assert_in_out_err(t.path, "", expected, [], "[ruby-core:35237]") t.close end + + def test_rescue_at_exit + bug5218 = '[ruby-core:43173][Bug #5218]' + cmd = [ + "raise 'X' rescue nil", + "nil", + "exit(42)", + ] + %w[at_exit END].each do |ex| + out, err, status = EnvUtil.invoke_ruby(cmd.map {|s|["-e", "#{ex} {#{s}}"]}.flatten, "", true, true) + assert_equal(["", "", 42], [out, err, status.exitstatus], "#{bug5218}: #{ex}") + end + end end diff --git a/test/ruby/test_bignum.rb b/test/ruby/test_bignum.rb index 264c68b..582a7b2 100644 --- a/test/ruby/test_bignum.rb +++ b/test/ruby/test_bignum.rb @@ -246,6 +246,116 @@ class TestBignum < Test::Unit::TestCase assert_equal(3**7000, (3**5000) * (3**2000)) end + def test_mul_large_numbers + a = %w[ + 32580286268570032115047167942578356789222410206194227403993117616454027392 + 62501901985861926098797067562795526004375784403965882943322008991129440928 + 33855888840298794008677656280486901895499985197580043127115026675632969396 + 55040226415022070581995493731570435346323030715226718346725312551631168110 + 83966158581772380474470605428802018934282425947323171408377505151988776271 + 85865548747366001752375899635539662017095652855537225416899242508164949615 + 96848508410008685252121247181772953744297349638273854170932226446528911938 + 03430429031094465344063914822790537339912760237589085026016396616506014081 + 53557719631183538265614091691713138728177917059624255801026099255450058876 + 97412698978242128457751836011774504753020608663272925708049430557191193188 + 23212591809241860763625985763438355314593186083254640117460724730431447842 + 15432124830037389073162094304199742919767272162759192882136828372588787906 + 96027938532441670018954643423581446981760344524184231299785949158765352788 + 38452309862972527623669323263424418781899966895996672291193305401609553502 + 63893514163147729201340204483973131948541009975283778189609285614445485714 + 63843850089417416331356938086609682943037801440660232801570877143192251897 + 63026816485314923378023904237699794122181407920355722922555234540701118607 + 37971417665315821995516986204709574657462370947443531049033704997194647442 + 13711787319587466437795542850136751816475182349380345341647976135081955799 + 56787050815348701001765730577514591032367920292271016649813170789854524395 + 72571698998841196411826453893352760318867994518757872432266374568779920489 + 55597104558927387008506485038236352630863481679853742412042588244086070827 + 43705456833283086410967648483312972903432798923897357373793064381177468258 + 69131640408147806442422254638590386673344704147156793990832671592488742473 + 31524606724894164324227362735271650556732855509929890983919463699819116427 + ].join.to_i + b = %w[ + 31519454770031243652776765515030872050264386564379909299874378289835540661 + 99756262835346828114038365624177182230027040172583473561802565238817167503 + 85144159132462819032164726177606533272071955542237648482852154879445654746 + 25061253606344846225905712926863168413666058602449408307586532461776530803 + 56810626880722653177544008166119272373179841889454920521993413902672848145 + 77974951972342194855267960390195830413354782136431833731467699250684103370 + 98571305167189174270854698169136844578685346745340041520068176478277580590 + 43810457765638903028049263788987034217272442328962400931269515791911786205 + 15357047519615932249418012945178659435259428163356223753159488306813844040 + 93609959555018799309373542926110109744437994067754004273450659607204900586 + 28878103661124568217617766580438460505513654179249613168352070584906185237 + 34829991855182473813233425492094534396541544295119674419522772382981982574 + 64708442087451070125274285088681225122475041996116377707892328889948526913 + 82239084041628877737628853240361038273348062246951097300286513836140601495 + 63604611754185656404194406869925540477185577643853560887894081047256701731 + 66884554460428760857958761948461476977864005799494946578017758268987123749 + 85937011490156431231903167442071541493304390639100774497107347884381581049 + 85451663323551635322518839895028929788021096587229364219084708576998525298 + 39594168681411529110089531428721005176467479027585291807482375043729783455 + 35827667428080449919778142400266842990117940984804919512360370451936835708 + 76338722049621773169385978521438867493162717866679193103745711403152099047 + 27294943901673885707639094215339506973982546487889199083181789561917985023 + 82368442718514694400160954955539704757794969665555505203532944598698824542 + 00599461848630034847211204029842422678421808487300084850702007663003230882 + 16645745324467830796203354080471008809087072562876681588151822072260738003 + ].join.to_i + c = %w[ + 10269128594368631269792194698469828812223242061960065022209211719149714886 + 03494742299892841188636314745174778237781513956755034582435818316155459882 + 71422025990633195596790290038198841087091600598192959108790192789550336119 + 13849937951116346796903163312950010689963716629093190601532313463306463573 + 64436438673379454947908896258675634478867189655764364639888427350090856831 + 84369949421175534994092429682748078316130135651006102162888937624830856951 + 64818150356583421988135211585954838926347035741143424980258821170351244310 + 33072045488402539147707418016613224788469923473310249137422855065567940804 + 75231970365923936034328561426062696074717204901606475826224235014948198414 + 19979210494282212322919438926816203585575357874850252052656098969732107129 + 30639419804565653489687198910271702181183420960744232756057631336661646896 + 48734093497394719644969417287962767186599484579769717220518657324467736902 + 16947995288312851432262922140679347615046098863974141226499783975470926697 + 95970415188661518504275964397022973192968233221707696639386238428211541334 + 69925631385166494600401675904803418143232703594169525858261988389529181035 + 06048776134746377586210180203524132714354779486439559392942733781343640971 + 02430607931736785273011780813863748280091795277451796799961887248262211653 + 38966967509803488282644299584920109534552889962877144862747797551711984992 + 00726518175235286668236031649728858774545087668286506201943248842967749907 + 05345423019480534625965140632428736051632750698608916592720742728646191514 + 86268964807395494825321744802493138032936406889713953832376411900451422777 + 06372983421062172556566901346288286168790235741528630664513209619789835729 + 36999522461733403414326366959273556098219489572448083984779946889707480205 + 42459898495081687425132939473146331452400120169525968892769310016015870148 + 66821361032541586130017904207971120217385522074967066199941112154460026348 + 07223950375610474071278649031647998546085807777970592429037128484222394216 + 33776560239741740193444702279919018283324070210090106960567819910943036248 + 16660475627526085805165023447934326510232828674828006752369603151390527384 + 16810180735871644266726954590262010744712519045524839388305761859432443670 + 05188791334908140831469790180096209292338569623252372975043915954675335333 + 66614002146554533771788633057869340167604765688639181655208751680821446276 + 75871494160208888666798836473728725968253820774671626436794492530356258709 + 62318715778035246655925307167306434486713879511272648637608703497794724929 + 54912261106702913491290913962825303534484477936036071463820553314826894581 + 36951927032835690160443252405644718368516656317176848748544135126122940034 + 68454782581240953957381976073459570718038035358630417744490242611126043987 + 89191812971310096496208294948623403471433467614886863238916702384858514703 + 24327715474804343531844042107910755966152655912676456945146277848606406879 + 49724219295823540160221752189725460676360350860849986313532861445465771187 + 86822806696323658053947125253562001971534265078959827450518368635828010637 + 91977444206363529864361796188661941906329947840521598310396004328950804758 + 79728679236044038853668859284513594307352133390781441610395116807369310560 + 35193762565748328526426224069629084264376146174383444988110993194030351064 + 29660536743256949099972314033972121470913480844652490838985461134989129492 + 75577567064571716731774820127381261057956083604361635892088585967074514802 + 51958582645785905276289980534832170529946494815794770854644518463332458915 + 77572397432680871220602513555535017751714443325264019171753694163676670792 + 04353584782364068773777058727187323211012094819929720407636607815292764459 + 21851731257845562153822058534043916834839514338448582518847879059020959697 + 90538105704766415685100946308842788321400392381169436435078204622400475281 + ].join.to_i + assert_equal(c, a*b, '[ruby-core:48552]') + end + def test_divrem assert_equal(0, T32 / T64) end @@ -299,6 +409,9 @@ class TestBignum < Test::Unit::TestCase ### rational changes the behavior of Bignum#** #assert_raise(TypeError) { T32**"foo" } assert_raise(TypeError, ArgumentError) { T32**"foo" } + + feature3429 = '[ruby-core:30735]' + assert_instance_of(Bignum, (2 ** 7830457), feature3429) end def test_and @@ -378,7 +491,7 @@ class TestBignum < Test::Unit::TestCase assert_equal(true, (2**32).even?) end - def interrupt + def assert_interrupt time = Time.now start_flag = false end_flag = false @@ -387,14 +500,16 @@ class TestBignum < Test::Unit::TestCase yield end_flag = true end - sleep 1 + Thread.pass until start_flag thread.raise thread.join rescue nil - start_flag && !end_flag && Time.now - time < 10 + time = Time.now - time + assert_equal([true, false], [start_flag, end_flag]) + assert_operator(time, :<, 10) end def test_interrupt - assert(interrupt { (65536 ** 65536).to_s }) + assert_interrupt {(65536 ** 65536).to_s} end def test_too_big_to_s diff --git a/test/ruby/test_class.rb b/test/ruby/test_class.rb index 55940a8..3d894da 100644 --- a/test/ruby/test_class.rb +++ b/test/ruby/test_class.rb @@ -258,4 +258,19 @@ class TestClass < Test::Unit::TestCase END assert_equal(42, PrivateClass.new.foo) end + + def test_cannot_reinitialize_class_with_initialize_copy # [ruby-core:50869] + assert_in_out_err([], <<-RUBY, ["Object"], []) + class Class + def initialize_copy(*); super; end + end + + class A; end + class B; end + + A.send(:initialize_copy, Class.new(B)) rescue nil + + p A.superclass + RUBY + end end diff --git a/test/ruby/test_dir.rb b/test/ruby/test_dir.rb index 236fd99..b688cc4 100644 --- a/test/ruby/test_dir.rb +++ b/test/ruby/test_dir.rb @@ -171,6 +171,20 @@ class TestDir < Test::Unit::TestCase assert_raise(Encoding::CompatibilityError) {Dir.glob(m.new)} end + def test_glob_recursive + bug6977 = '[ruby-core:47418]' + Dir.chdir(@root) do + FileUtils.mkdir_p("a/b/c/d/e/f") + assert_equal(["a/b/c/d/e/f"], Dir.glob("a/**/e/f"), bug6977) + assert_equal(["a/b/c/d/e/f"], Dir.glob("a/**/d/e/f"), bug6977) + assert_equal(["a/b/c/d/e/f"], Dir.glob("a/**/c/d/e/f"), bug6977) + assert_equal(["a/b/c/d/e/f"], Dir.glob("a/**/b/c/d/e/f"), bug6977) + assert_equal(["a/b/c/d/e/f"], Dir.glob("a/**/c/?/e/f"), bug6977) + assert_equal(["a/b/c/d/e/f"], Dir.glob("a/**/c/**/d/e/f"), bug6977) + assert_equal(["a/b/c/d/e/f"], Dir.glob("a/**/c/**/d/e/f"), bug6977) + end + end + def test_foreach assert_equal(Dir.foreach(@root).to_a.sort, %w(. ..) + (?a..?z).to_a) end diff --git a/test/ruby/test_dir_m17n.rb b/test/ruby/test_dir_m17n.rb index b376393..2cf1c15 100644 --- a/test/ruby/test_dir_m17n.rb +++ b/test/ruby/test_dir_m17n.rb @@ -11,6 +11,33 @@ class TestDir_M17N < Test::Unit::TestCase } end + def create_and_check_raw_file_name(code, encoding) + with_tmpdir { |dir| + create_file_program = %Q[ + filename = #{code}.chr('UTF-8').force_encoding("#{encoding}") + File.open(filename, "w") {} + opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM + ents = Dir.entries(".", opts) + exit ents.include?(filename) + ] + assert_ruby_status(["-E#{encoding}"], create_file_program, nil, :chdir=>dir) + + test_file_program = %Q[ + filename = #{code}.chr('UTF-8').force_encoding("ASCII-8BIT") + opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM + ents = Dir.entries(".", opts) + expected_filename = #{code}.chr('UTF-8').encode(Encoding.find("filesystem")) rescue expected_filename = "?" + expected_filename = expected_filename.force_encoding("ASCII-8BIT") + result = ents.include?(filename) || (/mswin|mingw/ =~ RUBY_PLATFORM && ents.include?(expected_filename)) + if !result && /mswin|mingw/ =~ RUBY_PLATFORM + exit Dir.entries(".", {:encoding => Encoding.find("filesystem")}).include?(expected_filename) + end + exit result + ] + assert_ruby_status(%w[-EASCII-8BIT], test_file_program, nil, :chdir=>dir) + } + end + ## UTF-8 default_external, no default_internal def test_filename_extutf8 @@ -32,14 +59,14 @@ class TestDir_M17N < Test::Unit::TestCase File.open(filename, "w") {} opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM ents = Dir.entries(".", opts) - exit ents.include?(filename) || ((RUBY_PLATFORM =~ /darwin/) != nil && ents.include?("%FF")) + exit ents.include?(filename) || (/darwin/ =~ RUBY_PLATFORM && ents.include?("%FF")) EOS assert_ruby_status(%w[-EUTF-8], <<-'EOS', nil, :chdir=>d) filename = "\xff".force_encoding("UTF-8") # invalid byte sequence as UTF-8 File.open(filename, "w") {} opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM ents = Dir.entries(".", opts) - exit ents.include?(filename) || ((RUBY_PLATFORM =~ /darwin/) != nil && ents.include?("%FF")) + exit ents.include?(filename) || (/darwin/ =~ RUBY_PLATFORM && ents.include?("%FF")) EOS } end unless /mswin|mingw/ =~ RUBY_PLATFORM @@ -153,7 +180,7 @@ class TestDir_M17N < Test::Unit::TestCase ents = Dir.entries(".", opts) ents.each {|e| e.force_encoding("ASCII-8BIT") } exit ents.include?(filename.force_encoding("ASCII-8BIT")) || - ((RUBY_PLATFORM =~ /darwin/) != nil && ents.include?("%A4%A2".force_encoding("ASCII-8BIT"))) + (/darwin/ =~ RUBY_PLATFORM && ents.include?("%A4%A2".force_encoding("ASCII-8BIT"))) EOS } end @@ -165,35 +192,34 @@ class TestDir_M17N < Test::Unit::TestCase File.open(filename, "w") {} opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM ents = Dir.entries(".", opts) - exit ents.include?(filename) || ((RUBY_PLATFORM =~ /darwin/) != nil && ents.include?("%A4%A2".force_encoding("euc-jp"))) + exit ents.include?(filename) || (/darwin/ =~ RUBY_PLATFORM && ents.include?("%A4%A2".force_encoding("euc-jp"))) EOS assert_ruby_status(%w[-EASCII-8BIT], <<-'EOS', nil, :chdir=>d) - filename = "\xA4\xA2" + filename = "\xA4\xA2".force_encoding('ASCII-8BIT') + win_expected_filename = filename.encode(Encoding.find("filesystem"), "euc-jp") rescue "?" opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM ents = Dir.entries(".", opts) - exit ents.include?(filename) || - ((RUBY_PLATFORM =~ /darwin/) != nil && ents.include?("%A4%A2".force_encoding("ASCII-8BIT"))) || - ((RUBY_PLATFORM =~ /mswin|mingw/) != nil && ents.include?("\x82\xA0".force_encoding("ASCII-8BIT"))) + result = ents.include?(filename) || + (/darwin/ =~ RUBY_PLATFORM && ents.include?("%A4%A2".force_encoding("ASCII-8BIT"))) || + (/mswin|mingw/ =~ RUBY_PLATFORM && ents.include?(win_expected_filename.force_encoding("ASCII-8BIT"))) + if !result && /mswin|mingw/ =~ RUBY_PLATFORM + exit Dir.entries(".", {:encoding => Encoding.find("filesystem")}).include?(win_expected_filename) + end + exit result EOS } end - def test_filename_utf8_raw_name - with_tmpdir {|d| - assert_ruby_status(%w[-EUTF-8], <<-'EOS', nil, :chdir=>d) - filename = "\u3042".force_encoding("utf-8") - File.open(filename, "w") {} - opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM - ents = Dir.entries(".", opts) - exit ents.include?(filename) - EOS - assert_ruby_status(%w[-EASCII-8BIT], <<-'EOS', nil, :chdir=>d) - filename = "\u3042".force_encoding("ASCII-8BIT") - opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM - ents = Dir.entries(".", opts) - exit ents.include?(filename) || ((RUBY_PLATFORM =~ /mswin|mingw/) != nil && ents.include?("\x82\xA0".force_encoding("ASCII-8BIT"))) - EOS - } + def test_filename_utf8_raw_jp_name + create_and_check_raw_file_name(0x3042, "UTF-8") + end + + def test_filename_utf8_raw_windows_1251_name + create_and_check_raw_file_name(0x0424, "UTF-8") + end + + def test_filename_utf8_raw_windows_1252_name + create_and_check_raw_file_name(0x00c6, "UTF-8") end def test_filename_ext_euc_jp_and_int_utf_8 @@ -203,13 +229,13 @@ class TestDir_M17N < Test::Unit::TestCase File.open(filename, "w") {} opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM ents = Dir.entries(".", opts) - exit ents.include?(filename) || ((RUBY_PLATFORM =~ /darwin/) != nil && ents.include?("%A4%A2".force_encoding("euc-jp"))) + exit ents.include?(filename) || (/darwin/ =~ RUBY_PLATFORM && ents.include?("%A4%A2".force_encoding("euc-jp"))) EOS assert_ruby_status(%w[-EEUC-JP:UTF-8], <<-'EOS', nil, :chdir=>d) filename = "\u3042" opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM ents = Dir.entries(".", opts) - exit ents.include?(filename) || ((RUBY_PLATFORM =~ /darwin/) != nil && ents.include?("%A4%A2")) + exit ents.include?(filename) || (/darwin/ =~ RUBY_PLATFORM && ents.include?("%A4%A2")) EOS } end diff --git a/test/ruby/test_econv.rb b/test/ruby/test_econv.rb index 080d027..f667d73 100644 --- a/test/ruby/test_econv.rb +++ b/test/ruby/test_econv.rb @@ -1,4 +1,5 @@ require 'test/unit' +require 'envutil' class TestEncodingConverter < Test::Unit::TestCase def check_ec(edst, esrc, eres, dst, src, ec, off, len, opts=nil) @@ -908,4 +909,23 @@ class TestEncodingConverter < Test::Unit::TestCase ec2 = Encoding::Converter.new("", "", newline: :universal) assert_equal(ec1, ec2) end + + def test_default_external + cmd = <<EOS + Encoding.default_external = ext = ARGV[0] + Encoding.default_internal = int ='utf-8' + begin + Encoding::Converter.new(ext, int) + ensure + Marshal.dump($!, STDOUT) + STDOUT.flush + end +EOS + Encoding.list.grep(->(enc) {/^ISO-8859-\d(?:[0-5])?\z/i =~ enc.name}) do |enc| + error = IO.popen([EnvUtil.rubybin, "-e", cmd, enc.name]) do |child| + Marshal.load(child) + end + assert_nil(error) + end + end end diff --git a/test/ruby/test_exception.rb b/test/ruby/test_exception.rb index b410b70..281dc70 100644 --- a/test/ruby/test_exception.rb +++ b/test/ruby/test_exception.rb @@ -92,7 +92,16 @@ class TestException < Test::Unit::TestCase end false }) + end + def test_catch_throw_in_require + bug7185 = '[ruby-dev:46234]' + t = Tempfile.open(["dep", ".rb"]) + t.puts("throw :extdep, 42") + t.close + assert_equal(42, catch(:extdep) {require t.path}, bug7185) + ensure + t.close! if t end def test_else @@ -333,4 +342,54 @@ end.join load(t.path) end end + + def test_to_s_taintness_propagation + for exc in [Exception, NameError] + m = "abcdefg" + e = exc.new(m) + e.taint + s = e.to_s + assert_equal(false, m.tainted?, + "#{exc}#to_s should not propagate taintness") + assert_equal(false, s.tainted?, + "#{exc}#to_s should not propagate taintness") + end + + o = Object.new + def o.to_str + "foo" + end + o.taint + e = NameError.new(o) + s = e.to_s + assert_equal(false, s.tainted?) + end + + def test_exception_to_s_should_not_propagate_untrustedness + favorite_lang = "Ruby" + + for exc in [Exception, NameError] + assert_raise(SecurityError) do + lambda { + $SAFE = 4 + exc.new(favorite_lang).to_s + favorite_lang.replace("Python") + }.call + end + end + + assert_raise(SecurityError) do + lambda { + $SAFE = 4 + o = Object.new + o.singleton_class.send(:define_method, :to_str) { + favorite_lang + } + NameError.new(o).to_s + favorite_lang.replace("Python") + }.call + end + + assert_equal("Ruby", favorite_lang) + end end diff --git a/test/ruby/test_file.rb b/test/ruby/test_file.rb index 765458c..b888233 100644 --- a/test/ruby/test_file.rb +++ b/test/ruby/test_file.rb @@ -37,6 +37,57 @@ class TestFile < Test::Unit::TestCase include TestEOF::Seek + def test_empty_file_bom + bug6487 = '[ruby-core:45203]' + f = Tempfile.new(__method__.to_s) + f.close + assert File.exist? f.path + assert_nothing_raised(bug6487) {File.read(f.path, mode: 'r:utf-8')} + assert_nothing_raised(bug6487) {File.read(f.path, mode: 'r:bom|utf-8')} + f.close(true) + end + + def assert_bom(bytes, name) + bug6487 = '[ruby-core:45203]' + + f = Tempfile.new(name.to_s) + f.sync = true + expected = "" + result = nil + bytes[0...-1].each do |x| + f.write x + f.write ' ' + f.pos -= 1 + expected << x + assert_nothing_raised(bug6487) {result = File.read(f.path, mode: 'rb:bom|utf-8')} + assert_equal("#{expected} ".force_encoding("utf-8"), result) + end + f.write bytes[-1] + assert_nothing_raised(bug6487) {result = File.read(f.path, mode: 'rb:bom|utf-8')} + assert_equal '', result, "valid bom" + f.close(true) + end + + def test_bom_8 + assert_bom(["\xEF", "\xBB", "\xBF"], __method__) + end + + def test_bom_16be + assert_bom(["\xFE", "\xFF"], __method__) + end + + def test_bom_16le + assert_bom(["\xFF", "\xFE"], __method__) + end + + def test_bom_32be + assert_bom(["\0", "\0", "\xFE", "\xFF"], __method__) + end + + def test_bom_32le + assert_bom(["\xFF\xFE\0", "\0"], __method__) + end + def test_truncate_wbuf f = Tempfile.new("test-truncate") f.print "abc" @@ -181,6 +232,26 @@ class TestFile < Test::Unit::TestCase } end + def test_utime + bug6385 = '[ruby-core:44776]' + + mod_time_contents = Time.at 1306527039 + + file = Tempfile.new("utime") + file.close + path = file.path + + File.utime(File.atime(path), mod_time_contents, path) + stats = File.stat(path) + + file.open + file_mtime = file.mtime + file.close(true) + + assert_equal(mod_time_contents, file_mtime, bug6385) + assert_equal(mod_time_contents, stats.mtime, bug6385) + end + def test_chmod_m17n bug5671 = '[ruby-dev:44898]' Dir.mktmpdir('test-file-chmod-m17n-') do |tmpdir| @@ -189,4 +260,14 @@ class TestFile < Test::Unit::TestCase assert_equal(File.chmod(0666, file), 1, bug5671) end end + + def test_open_nul + Dir.mktmpdir(__method__.to_s) do |tmpdir| + path = File.join(tmpdir, "foo") + assert_raise(ArgumentError) do + open(path + "\0bar", "w") {} + end + refute File.exist?(path) + end + end end diff --git a/test/ruby/test_file_exhaustive.rb b/test/ruby/test_file_exhaustive.rb index c10b05a..df7140f 100644 --- a/test/ruby/test_file_exhaustive.rb +++ b/test/ruby/test_file_exhaustive.rb @@ -1,8 +1,11 @@ +# -*- coding: us-ascii -*- require "test/unit" require "fileutils" require "tmpdir" class TestFileExhaustive < Test::Unit::TestCase + DRIVE = Dir.pwd[%r'\A(?:[a-z]:|//[^/]+/[^/]+)'i] + def assert_incompatible_encoding d = "\u{3042}\u{3044}".encode("utf-16le") assert_raise(Encoding::CompatibilityError) {yield d} @@ -12,6 +15,7 @@ class TestFileExhaustive < Test::Unit::TestCase def setup @dir = Dir.mktmpdir("rubytest-file") + @rootdir = "#{DRIVE}/" File.chown(-1, Process.gid, @dir) @file = make_tmp_filename("file") @zerofile = make_tmp_filename("zerofile") @@ -400,20 +404,31 @@ class TestFileExhaustive < Test::Unit::TestCase assert_match(/\Ac:\//i, File.expand_path('c:foo', 'd:/bar')) assert_match(%r'\Ac:/bar/foo\z'i, File.expand_path('c:foo', 'c:/bar')) end - if drive = Dir.pwd[%r'\A(?:[a-z]:|//[^/]+/[^/]+)'i] + if DRIVE assert_match(%r"\Az:/foo\z"i, File.expand_path('/foo', "z:/bar")) assert_match(%r"\A//host/share/foo\z"i, File.expand_path('/foo', "//host/share/bar")) - assert_match(%r"\A#{drive}/foo\z"i, File.expand_path('/foo')) + assert_match(%r"\A#{DRIVE}/foo\z"i, File.expand_path('/foo')) else assert_equal("/foo", File.expand_path('/foo')) end + end + + UnknownUserHome = "~foo_bar_baz_unknown_user_wahaha".freeze + + def test_expand_path_home assert_kind_of(String, File.expand_path("~")) if ENV["HOME"] - assert_raise(ArgumentError) { File.expand_path("~foo_bar_baz_unknown_user_wahaha") } - assert_raise(ArgumentError) { File.expand_path("~foo_bar_baz_unknown_user_wahaha", "/") } + assert_raise(ArgumentError) { File.expand_path(UnknownUserHome) } + assert_raise(ArgumentError) { File.expand_path(UnknownUserHome, "/") } begin bug3630 = '[ruby-core:31537]' home = ENV["HOME"] + home_drive = ENV["HOMEDRIVE"] + home_path = ENV["HOMEPATH"] + user_profile = ENV["USERPROFILE"] ENV["HOME"] = nil + ENV["HOMEDRIVE"] = nil + ENV["HOMEPATH"] = nil + ENV["USERPROFILE"] = nil assert_raise(ArgumentError) { File.expand_path("~") } ENV["HOME"] = "~" assert_raise(ArgumentError, bug3630) { File.expand_path("~") } @@ -421,8 +436,213 @@ class TestFileExhaustive < Test::Unit::TestCase assert_raise(ArgumentError, bug3630) { File.expand_path("~") } ensure ENV["HOME"] = home + ENV["HOMEDRIVE"] = home_drive + ENV["HOMEPATH"] = home_path + ENV["USERPROFILE"] = user_profile + end + end + + def test_expand_path_home_dir_string + home = ENV["HOME"] + new_home = "#{DRIVE}/UserHome" + ENV["HOME"] = new_home + bug8034 = "[ruby-core:53168]" + + assert_equal File.join(new_home, "foo"), File.expand_path("foo", "~"), bug8034 + assert_equal File.join(new_home, "bar", "foo"), File.expand_path("foo", "~/bar"), bug8034 + + assert_raise(ArgumentError) { File.expand_path(".", UnknownUserHome) } + assert_nothing_raised(ArgumentError) { File.expand_path("#{DRIVE}/", UnknownUserHome) } + ensure + ENV["HOME"] = home + end + + def test_expand_path_remove_trailing_alternative_data + assert_equal File.join(@rootdir, "aaa"), File.expand_path("#{@rootdir}/aaa::$DATA") + assert_equal File.join(@rootdir, "aa:a"), File.expand_path("#{@rootdir}/aa:a:$DATA") + assert_equal File.join(@rootdir, "aaa:$DATA"), File.expand_path("#{@rootdir}/aaa:$DATA") + end if DRIVE + + def test_expand_path_resolve_empty_string_current_directory + assert_equal(Dir.pwd, File.expand_path("")) + end + + def test_expand_path_resolve_dot_current_directory + assert_equal(Dir.pwd, File.expand_path(".")) + end + + def test_expand_path_resolve_file_name_relative_current_directory + assert_equal(File.join(Dir.pwd, "foo"), File.expand_path("foo")) + end + + def test_ignore_nil_dir_string + assert_equal(File.join(Dir.pwd, "foo"), File.expand_path("foo", nil)) + end + + def test_expand_path_resolve_file_name_and_dir_string_relative + assert_equal(File.join(Dir.pwd, "bar", "foo"), + File.expand_path("foo", "bar")) + end + + def test_expand_path_cleanup_dots_file_name + bug = "[ruby-talk:18512]" + + assert_equal(File.join(Dir.pwd, ".a"), File.expand_path(".a"), bug) + assert_equal(File.join(Dir.pwd, "..a"), File.expand_path("..a"), bug) + + if DRIVE + # cleanup dots only on Windows + assert_equal(File.join(Dir.pwd, "a"), File.expand_path("a."), bug) + skip "FIXME" + assert_equal(File.join(Dir.pwd, "a"), File.expand_path("a.."), bug) + else + assert_equal(File.join(Dir.pwd, "a."), File.expand_path("a."), bug) + assert_equal(File.join(Dir.pwd, "a.."), File.expand_path("a.."), bug) + end + end + + def test_expand_path_converts_a_pathname_to_an_absolute_pathname_using_a_complete_path + assert_equal(@dir, File.expand_path("", "#{@dir}")) + assert_equal(File.join(@dir, "a"), File.expand_path("a", "#{@dir}")) + assert_equal(File.join(@dir, "a"), File.expand_path("../a", "#{@dir}/xxx")) + assert_equal(@rootdir, File.expand_path(".", "#{@rootdir}")) + end + + def test_expand_path_ignores_supplied_dir_if_path_contains_a_drive_letter + assert_equal(@rootdir, File.expand_path(@rootdir, "D:/")) + end if DRIVE + + def test_expand_path_removes_trailing_slashes_from_absolute_path + assert_equal(File.join(@rootdir, "foo"), File.expand_path("#{@rootdir}foo/")) + assert_equal(File.join(@rootdir, "foo.rb"), File.expand_path("#{@rootdir}foo.rb/")) + end + + def test_expand_path_removes_trailing_spaces_from_absolute_path + assert_equal(File.join(@rootdir, "a"), File.expand_path("#{@rootdir}a ")) + end if DRIVE + + def test_expand_path_converts_a_pathname_which_starts_with_a_slash_using_dir_s_drive + assert_match(%r"\Az:/foo\z"i, File.expand_path('/foo', "z:/bar")) + end if DRIVE + + def test_expand_path_converts_a_pathname_which_starts_with_a_slash_and_unc_pathname + assert_equal("//foo", File.expand_path('//foo', "//bar")) + assert_equal("//bar/foo", File.expand_path('/foo', "//bar")) + assert_equal("//foo", File.expand_path('//foo', "/bar")) + end if DRIVE + + def test_expand_path_converts_a_dot_with_unc_dir + assert_equal("//", File.expand_path('.', "//")) + end + + def test_expand_path_preserves_unc_path_root + assert_equal("//", File.expand_path("//")) + assert_equal("//", File.expand_path("//.")) + assert_equal("//", File.expand_path("//..")) + end + + def test_expand_path_converts_a_pathname_which_starts_with_a_slash_using_host_share + assert_match(%r"\A//host/share/foo\z"i, File.expand_path('/foo', "//host/share/bar")) + end if DRIVE + + def test_expand_path_converts_a_pathname_which_starts_with_a_slash_using_a_current_drive + assert_match(%r"\A#{DRIVE}/foo\z"i, File.expand_path('/foo')) + end + + def test_expand_path_returns_tainted_strings_or_not + assert_equal(true, File.expand_path('foo').tainted?) + assert_equal(true, File.expand_path('foo'.taint).tainted?) + assert_equal(true, File.expand_path('/foo'.taint).tainted?) + assert_equal(true, File.expand_path('foo', 'bar').tainted?) + assert_equal(true, File.expand_path('foo', '/bar'.taint).tainted?) + assert_equal(true, File.expand_path('foo'.taint, '/bar').tainted?) + assert_equal(true, File.expand_path('~').tainted?) if ENV["HOME"] + + if DRIVE + assert_equal(true, File.expand_path('/foo').tainted?) + assert_equal(false, File.expand_path('//foo').tainted?) + assert_equal(true, File.expand_path('C:/foo'.taint).tainted?) + assert_equal(false, File.expand_path('C:/foo').tainted?) + assert_equal(true, File.expand_path('foo', '/bar').tainted?) + assert_equal(true, File.expand_path('foo', 'C:/bar'.taint).tainted?) + assert_equal(true, File.expand_path('foo'.taint, 'C:/bar').tainted?) + assert_equal(false, File.expand_path('foo', 'C:/bar').tainted?) + assert_equal(false, File.expand_path('C:/foo/../bar').tainted?) + assert_equal(false, File.expand_path('foo', '//bar').tainted?) + else + assert_equal(false, File.expand_path('/foo').tainted?) + assert_equal(false, File.expand_path('foo', '/bar').tainted?) end - assert_incompatible_encoding {|d| File.expand_path(d)} + end + + def test_expand_path_converts_a_pathname_to_an_absolute_pathname_using_home_as_base + old_home = ENV["HOME"] + home = ENV["HOME"] = "#{DRIVE}/UserHome" + assert_equal(home, File.expand_path("~")) + assert_equal(home, File.expand_path("~", "C:/FooBar")) + assert_equal(File.join(home, "a"), File.expand_path("~/a", "C:/FooBar")) + ensure + ENV["HOME"] = old_home + end + + def test_expand_path_converts_a_pathname_to_an_absolute_pathname_using_unc_home + old_home = ENV["HOME"] + unc_home = ENV["HOME"] = "//UserHome" + assert_equal(unc_home, File.expand_path("~")) + ensure + ENV["HOME"] = old_home + end if DRIVE + + def test_expand_path_does_not_modify_a_home_string_argument + old_home = ENV["HOME"] + home = ENV["HOME"] = "#{DRIVE}/UserHome" + str = "~/a" + assert_equal("#{home}/a", File.expand_path(str)) + assert_equal("~/a", str) + ensure + ENV["HOME"] = old_home + end + + def test_expand_path_raises_argument_error_for_any_supplied_username + bug = '[ruby-core:39597]' + assert_raise(ArgumentError, bug) { File.expand_path("~anything") } + end if DRIVE + + def test_expand_path_raises_a_type_error_if_not_passed_a_string_type + assert_raise(TypeError) { File.expand_path(1) } + assert_raise(TypeError) { File.expand_path(nil) } + assert_raise(TypeError) { File.expand_path(true) } + end + + def test_expand_path_expands_dot_dir + assert_equal("#{DRIVE}/dir", File.expand_path("#{DRIVE}/./dir")) + end + + def test_expand_path_does_not_expand_wildcards + assert_equal("#{DRIVE}/*", File.expand_path("./*", "#{DRIVE}/")) + assert_equal("#{Dir.pwd}/*", File.expand_path("./*", Dir.pwd)) + assert_equal("#{DRIVE}/?", File.expand_path("./?", "#{DRIVE}/")) + assert_equal("#{Dir.pwd}/?", File.expand_path("./?", Dir.pwd)) + end if DRIVE + + def test_expand_path_does_not_modify_the_string_argument + str = "./a/b/../c" + assert_equal("#{Dir.pwd}/a/c", File.expand_path(str, Dir.pwd)) + assert_equal("./a/b/../c", str) + end + + def test_expand_path_returns_a_string_when_passed_a_string_subclass + sub = Class.new(String) + str = sub.new "./a/b/../c" + path = File.expand_path(str, Dir.pwd) + assert_equal("#{Dir.pwd}/a/c", path) + assert_instance_of(String, path) + end + + def test_expand_path_accepts_objects_that_have_a_to_path_method + klass = Class.new { def to_path; "a/b/c"; end } + obj = klass.new + assert_equal("#{Dir.pwd}/a/b/c", File.expand_path(obj)) end def test_basename @@ -447,16 +667,31 @@ class TestFileExhaustive < Test::Unit::TestCase assert_equal(basename, File.basename(@file + ".", ".*")) assert_equal(basename, File.basename(@file + "::$DATA", ".*")) end + if File::ALT_SEPARATOR == '\\' + a = "foo/\225\\\\" + [%W"cp437 \225", %W"cp932 \225\\"].each do |cp, expected| + assert_equal(expected.force_encoding(cp), File.basename(a.dup.force_encoding(cp)), cp) + end + end assert_incompatible_encoding {|d| File.basename(d)} assert_incompatible_encoding {|d| File.basename(d, ".*")} assert_raise(Encoding::CompatibilityError) {File.basename("foo.ext", ".*".encode("utf-16le"))} + + s = "foo\x93_a".force_encoding("cp932") + assert_equal(s, File.basename(s, "_a")) end def test_dirname assert(@file.start_with?(File.dirname(@file))) assert_equal(".", File.dirname("")) assert_incompatible_encoding {|d| File.dirname(d)} + if File::ALT_SEPARATOR == '\\' + a = "\225\\\\foo" + [%W"cp437 \225", %W"cp932 \225\\"].each do |cp, expected| + assert_equal(expected.force_encoding(cp), File.dirname(a.dup.force_encoding(cp)), cp) + end + end end def test_extname @@ -500,6 +735,13 @@ class TestFileExhaustive < Test::Unit::TestCase def o.to_path; "foo"; end assert_equal(s, File.join(o, "bar", "baz")) assert_equal(s, File.join("foo" + File::SEPARATOR, "bar", File::SEPARATOR + "baz")) + if File::ALT_SEPARATOR == '\\' + a = "\225\\" + b = "foo" + [%W"cp437 \225\\foo", %W"cp932 \225\\/foo"].each do |cp, expected| + assert_equal(expected.force_encoding(cp), File.join(a.dup.force_encoding(cp), b.dup.force_encoding(cp)), cp) + end + end end def test_truncate @@ -770,6 +1012,13 @@ class TestFileExhaustive < Test::Unit::TestCase assert_equal(0, File::Stat.new(@zerofile).size) end + def test_stat_special_file + # test for special files such as pagefile.sys on Windows + assert_nothing_raised do + Dir::glob("C:/*.sys") {|f| File::Stat.new(f) } + end + end if DRIVE + def test_path_check assert_nothing_raised { ENV["PATH"] } end diff --git a/test/ruby/test_flip.rb b/test/ruby/test_flip.rb new file mode 100644 index 0000000..bd14228 --- /dev/null +++ b/test/ruby/test_flip.rb @@ -0,0 +1,21 @@ +require 'test/unit' +require_relative 'envutil' + +class TestFlip < Test::Unit::TestCase + def test_hidden_key + bug6899 = '[ruby-core:47253]' + foo = "foor" + bar = "bar" + assert_nothing_raised(NotImplementedError, bug6899) do + 2000.times {eval %[(foo..bar) ? 1 : 2]} + end + end + + def test_shared_eval + bug7671 = '[ruby-core:51296]' + vs = (1..9).to_a + vs.select {|n| if n==2..n==16 then 1 end} + v = eval("vs.select {|n| if n==3..n==6 then 1 end}") + assert_equal([*3..6], v, bug7671) + end +end diff --git a/test/ruby/test_float.rb b/test/ruby/test_float.rb index 440fd39..d2cee75 100644 --- a/test/ruby/test_float.rb +++ b/test/ruby/test_float.rb @@ -196,7 +196,7 @@ class TestFloat < Test::Unit::TestCase end def test_modulo3 - bug6048 = '[ruby-core:42726]' + bug6044 = '[ruby-core:42726]' assert_equal(4.2, 4.2.send(:%, Float::INFINITY)) assert_equal(4.2, 4.2 % Float::INFINITY) assert_is_minus_zero(-0.0 % 4.2) diff --git a/test/ruby/test_gc.rb b/test/ruby/test_gc.rb index bcc4906..f04e7e0 100644 --- a/test/ruby/test_gc.rb +++ b/test/ruby/test_gc.rb @@ -97,4 +97,19 @@ class TestGc < Test::Unit::TestCase assert_in_out_err([env, "-W1", "-e", "exit"], "", [], [], "[ruby-core:39795]") assert_in_out_err([env, "-w", "-e", "exit"], "", [], /heap_min_slots=100000/, "[ruby-core:39795]") end + + def test_profiler_enabled + GC::Profiler.enable + assert_equal(true, GC::Profiler.enabled?) + GC::Profiler.disable + assert_equal(false, GC::Profiler.enabled?) + ensure + GC::Profiler.disable + end + + def test_finalizing_main_thread + assert_in_out_err(%w[--disable-gems], <<-EOS, ["\"finalize\""], [], "[ruby-dev:46647]") + ObjectSpace.define_finalizer(Thread.main) { p 'finalize' } + EOS + end end diff --git a/test/ruby/test_io.rb b/test/ruby/test_io.rb index edf449d..da6c904 100644 --- a/test/ruby/test_io.rb +++ b/test/ruby/test_io.rb @@ -1799,7 +1799,7 @@ End } end ensure - fds.each {|fd| IO.for_fd(fd).close rescue next} + GC.start end def test_flush_in_finalizer2 @@ -1951,15 +1951,18 @@ End def test_open_mode feature4742 = "[ruby-core:36338]" + bug6055 = '[ruby-dev:45268]' mkcdtmpdir do - refute_nil(f = File.open('symbolic', 'w')) + assert_not_nil(f = File.open('symbolic', 'w')) f.close - refute_nil(f = File.open('numeric', File::WRONLY|File::TRUNC|File::CREAT)) + assert_not_nil(f = File.open('numeric', File::WRONLY|File::TRUNC|File::CREAT)) f.close - refute_nil(f = File.open('hash-symbolic', :mode => 'w')) + assert_not_nil(f = File.open('hash-symbolic', :mode => 'w')) f.close - refute_nil(f = File.open('hash-numeric', :mode => File::WRONLY|File::TRUNC|File::CREAT), feature4742) + assert_not_nil(f = File.open('hash-numeric', :mode => File::WRONLY|File::TRUNC|File::CREAT), feature4742) + f.close + assert_nothing_raised(bug6055) {f = File.open('hash-symbolic', binmode: true)} f.close end end @@ -2039,4 +2042,140 @@ End write_file.close file.close! end + + def test_ioctl_linux + return if /linux/ !~ RUBY_PLATFORM + + assert_nothing_raised do + File.open('/dev/urandom'){|f1| + entropy_count = "" + # get entropy count + f1.ioctl(0x80045200, entropy_count) + } + end + + buf = '' + assert_nothing_raised do + fionread = 0x541B + File.open(__FILE__){|f1| + f1.ioctl(fionread, buf) + } + end + assert_equal(File.size(__FILE__), buf.unpack('i!')[0]) + end + + def test_ioctl_linux2 + return if /linux/ !~ RUBY_PLATFORM + return if /^i.?86|^x86_64/ !~ RUBY_PLATFORM + + return unless system('tty', '-s') # stdin is not a terminal + File.open('/dev/tty') { |f| + tiocgwinsz=0x5413 + winsize="" + assert_nothing_raised { + f.ioctl(tiocgwinsz, winsize) + } + } + end + + def test_setpos + mkcdtmpdir { + File.open("tmp.txt", "w") {|f| + f.puts "a" + f.puts "bc" + f.puts "def" + } + pos1 = pos2 = pos3 = nil + File.open("tmp.txt") {|f| + assert_equal("a\n", f.gets) + pos1 = f.pos + assert_equal("bc\n", f.gets) + pos2 = f.pos + assert_equal("def\n", f.gets) + pos3 = f.pos + assert_equal(nil, f.gets) + } + File.open("tmp.txt") {|f| + f.pos = pos1 + assert_equal("bc\n", f.gets) + assert_equal("def\n", f.gets) + assert_equal(nil, f.gets) + } + File.open("tmp.txt") {|f| + f.pos = pos2 + assert_equal("def\n", f.gets) + assert_equal(nil, f.gets) + } + File.open("tmp.txt") {|f| + f.pos = pos3 + assert_equal(nil, f.gets) + } + } + end + + def test_std_fileno + assert_equal(0, STDIN.fileno) + assert_equal(1, STDOUT.fileno) + assert_equal(2, STDERR.fileno) + assert_equal(0, $stdin.fileno) + assert_equal(1, $stdout.fileno) + assert_equal(2, $stderr.fileno) + end + + def test_io_select_with_many_files + bug8080 = '[ruby-core:53349]' + + assert_normal_exit %q{ + require "tempfile" + + # try to raise RLIM_NOFILE to >FD_SETSIZE + # Unfortunately, ruby export FD_SETSIZE. then we assume it's 1024. + fd_setsize = 1024 + + begin + Process.setrlimit(Process::RLIMIT_NOFILE, fd_setsize+10) + rescue =>e + # Process::RLIMIT_NOFILE couldn't be raised. skip the test + exit 0 + end + + tempfiles = [] + (0..fd_setsize+1).map {|i| + tempfiles << Tempfile.open("test_io_select_with_many_files") + } + + IO.select(tempfiles) + }, bug8080 + end + + def test_read_32bit_boundary + bug8431 = '[ruby-core:55098] [Bug #8431]' + make_tempfile {|t| + assert_separately(["-", bug8431, t.path], <<-"end;") + msg = ARGV.shift + f = open(ARGV[0], "rb") + f.seek(0xffff_ffff) + assert_nil(f.read(1), msg) + end; + } + end if /mswin|mingw/ =~ RUBY_PLATFORM + + def test_write_32bit_boundary + bug8431 = '[ruby-core:55098] [Bug #8431]' + make_tempfile {|t| + assert_separately(["-", bug8431, t.path], <<-"end;", timeout: 30) + msg = ARGV.shift + f = open(ARGV[0], "wb") + f.seek(0xffff_ffff) + begin + # this will consume very long time or fail by ENOSPC on a + # filesystem which sparse file is not supported + f.write('1') + rescue SystemCallError + else + assert_equal(0x1_0000_0000, f.tell, msg) + end + end; + } + end if /mswin|mingw/ =~ RUBY_PLATFORM end diff --git a/test/ruby/test_io_m17n.rb b/test/ruby/test_io_m17n.rb index 560cd03..c22f665 100644 --- a/test/ruby/test_io_m17n.rb +++ b/test/ruby/test_io_m17n.rb @@ -2067,7 +2067,17 @@ EOT open("a", "wb") {|f| f.puts "a"} open("a", "rt") {|f| f.getc} } - assert(c.ascii_only?, "should be ascii_only #{bug4557}") + assert(c.ascii_only?, bug4557) + end + + def test_getc_conversion + bug8516 = '[ruby-core:55444] [Bug #8516]' + c = with_tmpdir { + open("a", "wb") {|f| f.putc "\xe1"} + open("a", "r:iso-8859-1:utf-8") {|f| f.getc} + } + refute(c.ascii_only?, bug8516) + assert_equal(1, c.size, bug8516) end def test_default_mode_on_dosish @@ -2363,6 +2373,22 @@ EOT } end if /mswin|mingw/ =~ RUBY_PLATFORM + def test_pos_with_buffer_end_cr + bug6401 = '[ruby-core:44874]' + with_tmpdir { + # Read buffer size is 8191. This generates '\r' at 8191. + lines = ["X" * 8187, "X"] + generate_file("tmp", lines.join("\r\n") + "\r\n") + + open("tmp", "r") do |f| + lines.each do |line| + f.pos + assert_equal(line, f.readline.chomp, bug6401) + end + end + } + end if /mswin|mingw/ =~ RUBY_PLATFORM + def test_read_crlf_and_eof bug6271 = '[ruby-core:44189]' with_tmpdir { diff --git a/test/ruby/test_literal.rb b/test/ruby/test_literal.rb index bb3f50d..e7a7c76 100644 --- a/test/ruby/test_literal.rb +++ b/test/ruby/test_literal.rb @@ -79,9 +79,15 @@ class TestRubyLiteral < Test::Unit::TestCase assert_equal "\x13", "\c\x33" assert_equal "\x13", "\C-\x33" assert_equal "\xB3", "\M-\x33" - assert_equal "\\\u201c", eval(%["\\\u{201c}"]), bug6069 - assert_equal "\\\u201c".encode("euc-jp"), eval(%["\\\u{201c}"].encode("euc-jp")), bug6069 - assert_equal "\\\u201c".encode("iso-8859-13"), eval(%["\\\u{201c}"].encode("iso-8859-13")), bug6069 + assert_equal "\u201c", eval(%["\\\u{201c}"]), bug5262 + assert_equal "\u201c".encode("euc-jp"), eval(%["\\\u{201c}"].encode("euc-jp")), bug5262 + assert_equal "\u201c".encode("iso-8859-13"), eval(%["\\\u{201c}"].encode("iso-8859-13")), bug5262 + assert_equal "\\\u201c", eval(%['\\\u{201c}']), bug6069 + assert_equal "\\\u201c".encode("euc-jp"), eval(%['\\\u{201c}'].encode("euc-jp")), bug6069 + assert_equal "\\\u201c".encode("iso-8859-13"), eval(%['\\\u{201c}'].encode("iso-8859-13")), bug6069 + assert_equal "\u201c", eval(%[?\\\u{201c}]), bug6069 + assert_equal "\u201c".encode("euc-jp"), eval(%[?\\\u{201c}].encode("euc-jp")), bug6069 + assert_equal "\u201c".encode("iso-8859-13"), eval(%[?\\\u{201c}].encode("iso-8859-13")), bug6069 end def test_dstring diff --git a/test/ruby/test_m17n.rb b/test/ruby/test_m17n.rb index 3553f3a..699c815 100644 --- a/test/ruby/test_m17n.rb +++ b/test/ruby/test_m17n.rb @@ -1369,6 +1369,14 @@ class TestM17N < Test::Unit::TestCase assert_equal(true, s.valid_encoding?) s << "\xff".force_encoding("utf-16be") assert_equal(false, s.valid_encoding?, bug4018) + + bug6190 = '[ruby-core:43557]' + s = "\xe9" + s = s.encode("utf-8", "utf-8") + assert_equal(false, s.valid_encoding?, bug6190) + s = "\xe9" + s.encode!("utf-8", "utf-8") + assert_equal(false, s.valid_encoding?, bug6190) end def test_getbyte diff --git a/test/ruby/test_m17n_comb.rb b/test/ruby/test_m17n_comb.rb index 79016af..6eec6a6 100644 --- a/test/ruby/test_m17n_comb.rb +++ b/test/ruby/test_m17n_comb.rb @@ -777,7 +777,17 @@ class TestM17NComb < Test::Unit::TestCase end def test_str_crypt + begin + # glibc 2.16 or later denies salt contained other than [0-9A-Za-z./] #7312 + glibcver = `#{RbConfig::CONFIG["libdir"]}/libc.so.6`[/\AGNU C Library.*version ([0-9.]+)/, 1].split('.').map(&:to_i) + strict_crypt = (glibcver <=> [2, 16]) > -1 + rescue + end + combination(STRINGS, STRINGS) {|str, salt| + if strict_crypt + next unless salt.ascii_only? && /\A[0-9a-zA-Z.\/]+\z/ =~ salt + end if a(salt).length < 2 assert_raise(ArgumentError) { str.crypt(salt) } next diff --git a/test/ruby/test_marshal.rb b/test/ruby/test_marshal.rb index 7ec6959..0f3f794 100644 --- a/test/ruby/test_marshal.rb +++ b/test/ruby/test_marshal.rb @@ -483,4 +483,22 @@ class TestMarshal < Test::Unit::TestCase assert_equal(Rational(1, 2), Marshal.load("\x04\bU:\rRational[\ai\x06i\a")) assert_raise(ArgumentError){Marshal.load("\x04\bU:\rRational[\bi\x00i\x00i\x00")} end + + class TestClass + end + + module TestModule + end + + def test_marshal_load_should_not_taint_classes + bug7325 = '[ruby-core:49198]' + for c in [TestClass, TestModule] + assert(!c.tainted?) + assert(!c.untrusted?) + c2 = Marshal.load(Marshal.dump(c).taint.untrust) + assert_same(c, c2) + assert(!c.tainted?, bug7325) + assert(!c.untrusted?, bug7325) + end + end end diff --git a/test/ruby/test_method.rb b/test/ruby/test_method.rb index 2cc0de5..ea6c5f2 100644 --- a/test/ruby/test_method.rb +++ b/test/ruby/test_method.rb @@ -460,4 +460,16 @@ class TestMethod < Test::Unit::TestCase assert_nothing_raised { v.instance_eval { mv2 } } assert_nothing_raised { v.instance_eval { mv3 } } end + + def test_bound_method_entry + bug6171 = '[ruby-core:43383]' + assert_ruby_status([], <<-EOC, bug6171) + class Bug6171 + def initialize(target) + define_singleton_method(:reverse, target.method(:reverse).to_proc) + end + end + 1000.times {p = Bug6171.new('test'); 10000.times {p.reverse}} + EOC + end end diff --git a/test/ruby/test_module.rb b/test/ruby/test_module.rb index 6176f48..6673852 100644 --- a/test/ruby/test_module.rb +++ b/test/ruby/test_module.rb @@ -1220,4 +1220,24 @@ class TestModule < Test::Unit::TestCase INPUT assert_in_out_err([], src, ["NameError"], []) end + + def test_include_module_with_constants_invalidates_method_cache + assert_in_out_err([], <<-RUBY, %w(123 456), []) + A = 123 + + class Foo + def self.a + A + end + end + + module M + A = 456 + end + + puts Foo.a + Foo.send(:include, M) + puts Foo.a + RUBY + end end diff --git a/test/ruby/test_pack.rb b/test/ruby/test_pack.rb index 6ce16a2..c862215 100644 --- a/test/ruby/test_pack.rb +++ b/test/ruby/test_pack.rb @@ -612,6 +612,18 @@ class TestPack < Test::Unit::TestCase assert_equal([0x100000000], "\220\200\200\200\000".unpack("w"), [0x100000000]) end + + def test_pack_unpack_M + assert_equal(["pre123after"], "pre=31=32=33after".unpack("M")) + assert_equal(["preafter"], "pre=\nafter".unpack("M")) + assert_equal(["preafter"], "pre=\r\nafter".unpack("M")) + assert_equal(["pre="], "pre=".unpack("M")) + assert_equal(["pre=\r"], "pre=\r".unpack("M")) + assert_equal(["pre=hoge"], "pre=hoge".unpack("M")) + assert_equal(["pre==31after"], "pre==31after".unpack("M")) + assert_equal(["pre===31after"], "pre===31after".unpack("M")) + end + def test_modify_under_safe4 s = "foo" assert_raise(SecurityError) do diff --git a/test/ruby/test_proc.rb b/test/ruby/test_proc.rb index 3cac94a..7560ce9 100644 --- a/test/ruby/test_proc.rb +++ b/test/ruby/test_proc.rb @@ -1,4 +1,5 @@ require 'test/unit' +require_relative 'envutil' class TestProc < Test::Unit::TestCase def setup @@ -140,6 +141,14 @@ class TestProc < Test::Unit::TestCase method(:m2).to_proc end + def m1(var) + var + end + + def m_block_given? + m1(block_given?) + end + # [yarv-dev:777] block made by Method#to_proc def test_method_to_proc b = block() @@ -147,6 +156,37 @@ class TestProc < Test::Unit::TestCase assert_instance_of(Binding, b.binding, '[ruby-core:25589]') end + def test_block_given_method + m = method(:m_block_given?) + assert(!m.call, "without block") + assert(m.call {}, "with block") + assert(!m.call, "without block second") + end + + def test_block_given_method_to_proc + bug8341 = '[Bug #8341]' + m = method(:m_block_given?).to_proc + assert(!m.call, "#{bug8341} without block") + assert(m.call {}, "#{bug8341} with block") + assert(!m.call, "#{bug8341} without block second") + end + + def test_block_persist_between_calls + bug8341 = '[Bug #8341]' + o = Object.new + def o.m1(top=true) + if top + [block_given?, @m.call(false)] + else + block_given? + end + end + m = o.method(:m1).to_proc + o.instance_variable_set(:@m, m) + assert_equal([true, false], m.call {}, "#{bug8341} nested with block") + assert_equal([false, false], m.call, "#{bug8341} nested without block") + end + def test_curry b = proc {|x, y, z| (x||0) + (y||0) + (z||0) } assert_equal(6, b.curry[1][2][3]) @@ -818,4 +858,14 @@ class TestProc < Test::Unit::TestCase assert_equal('zot', o.method(:foo).to_proc.() {'zot'}, bug3792) } end + + def test_overriden_lambda + bug8345 = '[ruby-core:54687] [Bug #8345]' + assert_normal_exit('def lambda; end; method(:puts).to_proc', bug8345) + end + + def test_overriden_proc + bug8345 = '[ruby-core:54688] [Bug #8345]' + assert_normal_exit('def proc; end; ->{}.curry', bug8345) + end end diff --git a/test/ruby/test_rand.rb b/test/ruby/test_rand.rb index 67b6df8..c713981 100644 --- a/test/ruby/test_rand.rb +++ b/test/ruby/test_rand.rb @@ -415,14 +415,43 @@ END def test_fork_shuffle pid = fork do - (1..10).to_a.shuffle - raise 'default seed is not set' if srand == 0 + (1..10).to_a.shuffle + raise 'default seed is not set' if srand == 0 end p2, st = Process.waitpid2(pid) assert(st.success?, "#{st.inspect}") rescue NotImplementedError, ArgumentError end + def assert_fork_status(n, mesg, &block) + IO.pipe do |r, w| + (1..n).map do + p1 = fork {w.puts(block.call.to_s)} + _, st = Process.waitpid2(p1) + assert_send([st, :success?], mesg) + r.gets.strip + end + end + end + + def test_rand_reseed_on_fork + bug5661 = '[ruby-core:41209]' + + assert_fork_status(1, bug5661) {Random.rand(4)} + r1, r2 = *assert_fork_status(2, bug5661) {Random.rand} + assert_not_equal(r1, r2, bug5661) + + assert_fork_status(1, bug5661) {rand(4)} + r1, r2 = *assert_fork_status(2, bug5661) {rand} + assert_not_equal(r1, r2, bug5661) + + stable = Random.new + assert_fork_status(1, bug5661) {stable.rand(4)} + r1, r2 = *assert_fork_status(2, bug5661) {stable.rand} + assert_equal(r1, r2, bug5661) + rescue NotImplementedError + end + def test_seed bug3104 = '[ruby-core:29292]' rand_1 = Random.new(-1).rand diff --git a/test/ruby/test_regexp.rb b/test/ruby/test_regexp.rb index 3c1662e..3073a98 100644 --- a/test/ruby/test_regexp.rb +++ b/test/ruby/test_regexp.rb @@ -498,17 +498,17 @@ class TestRegexp < Test::Unit::TestCase assert(m.tainted?) end - def check(re, ss, fs = []) + def check(re, ss, fs = [], msg = nil) re = Regexp.new(re) unless re.is_a?(Regexp) ss = [ss] unless ss.is_a?(Array) ss.each do |e, s| s ||= e - assert_match(re, s) + assert_match(re, s, msg) m = re.match(s) - assert_equal(e, m[0]) + assert_equal(e, m[0], msg) end fs = [fs] unless fs.is_a?(Array) - fs.each {|s| assert_no_match(re, s) } + fs.each {|s| assert_no_match(re, s, msg) } end def failcheck(re) @@ -688,7 +688,7 @@ class TestRegexp < Test::Unit::TestCase check(/\A[a-b-]\z/, %w(a b -), ["", "c"]) check('\A[a-b-&&\w]\z', %w(a b), ["", "-"]) check('\A[a-b-&&\W]\z', "-", ["", "a", "b"]) - check('\A[a-c-e]\z', %w(a b c e), %w(- d)) # is it OK? + check('\A[a-c-e]\z', %w(a b c e -), %w(d)) check(/\A[a-f&&[^b-c]&&[^e]]\z/, %w(a d f), %w(b c e g 0)) check(/\A[[^b-c]&&[^e]&&a-f]\z/, %w(a d f), %w(b c e g 0)) check(/\A[\n\r\t]\z/, ["\n", "\r", "\t"]) @@ -867,4 +867,10 @@ class TestRegexp < Test::Unit::TestCase assert_match(/invalid hex escape/, error.message) assert_equal(1, error.message.scan(/.*invalid .*escape.*/i).size, bug3539) end + + def test_raw_hyphen_and_tk_char_type_after_range + bug6853 = '[ruby-core:47115]' + # use Regexp.new instead of literal to ignore a parser warning. + check(Regexp.new('[0-1-\\s]'), [' ', '-'], ['2', 'a'], bug6853) + end end diff --git a/test/ruby/test_require.rb b/test/ruby/test_require.rb index 96b1551..58a9ee2 100644 --- a/test/ruby/test_require.rb +++ b/test/ruby/test_require.rb @@ -339,4 +339,21 @@ class TestRequire < Test::Unit::TestCase [], /\$LOADED_FEATURES is frozen; cannot append feature \(RuntimeError\)$/, bug3756) end + + def test_loaded_features_encoding + bug6377 = '[ruby-core:44750]' + loadpath = $:.dup + features = $".dup + $".clear + $:.clear + Dir.mktmpdir {|tmp| + $: << tmp + open(File.join(tmp, "foo.rb"), "w") {} + require "foo" + assert_not_equal(Encoding::ASCII_8BIT, $"[0].encoding, bug6377) + } + ensure + $:.replace(loadpath) + $".replace(features) + end end diff --git a/test/ruby/test_rubyoptions.rb b/test/ruby/test_rubyoptions.rb index 339999a..5533ac2 100644 --- a/test/ruby/test_rubyoptions.rb +++ b/test/ruby/test_rubyoptions.rb @@ -489,6 +489,8 @@ class TestRubyOptions < Test::Unit::TestCase assert_in_out_err(["-we", "1.times do\n a=1\nend"], "", [], [], feature3446) assert_in_out_err(["-we", "def foo\n 1.times do\n a=1\n end\nend"], "", [], ["-e:3: warning: assigned but unused variable - a"], feature3446) assert_in_out_err(["-we", "def foo\n"" 1.times do |a| end\n""end"], "", [], []) + bug7408 = '[ruby-core:49659]' + assert_in_out_err(["-we", "def foo\n a=1\n :a\nend"], "", [], ["-e:2: warning: assigned but unused variable - a"], bug7408) end def test_shadowing_variable @@ -553,4 +555,14 @@ class TestRubyOptions < Test::Unit::TestCase assert_in_out_err(["-C", dir, a], "", [], /LoadError/, bug3851) end end + + def test_pflag_gsub + bug7157 = '[ruby-core:47967]' + assert_in_out_err(['-p', '-e', 'gsub(/t.*/){"TEST"}'], %[test], %w[TEST], [], bug7157) + end + + def test_pflag_sub + bug7157 = '[ruby-core:47967]' + assert_in_out_err(['-p', '-e', 'sub(/t.*/){"TEST"}'], %[test], %w[TEST], [], bug7157) + end end diff --git a/test/ruby/test_string.rb b/test/ruby/test_string.rb index 4d9d172..6185e23 100644 --- a/test/ruby/test_string.rb +++ b/test/ruby/test_string.rb @@ -1995,5 +1995,9 @@ class TestString < Test::Unit::TestCase assert_equal(u("\x81\x82"), "\u3042".byteslice(1..2)) assert_equal(u("\x82")+("\u3042"*9), ("\u3042"*10).byteslice(2, 28)) + + bug7954 = '[ruby-dev:47108]' + assert_equal(false, "\u3042".byteslice(0, 2).valid_encoding?) + assert_equal(false, ("\u3042"*10).byteslice(0, 20).valid_encoding?) end end diff --git a/test/ruby/test_symbol.rb b/test/ruby/test_symbol.rb index c98f954..23c50e6 100644 --- a/test/ruby/test_symbol.rb +++ b/test/ruby/test_symbol.rb @@ -33,7 +33,7 @@ class TestSymbol < Test::Unit::TestCase assert_inspect_evaled(':foo') assert_inspect_evaled(':foo!') assert_inspect_evaled(':bar?') - assert_inspect_evaled(':<<') + assert_inspect_evaled(":<<") assert_inspect_evaled(':>>') assert_inspect_evaled(':<=') assert_inspect_evaled(':>=') @@ -102,6 +102,33 @@ class TestSymbol < Test::Unit::TestCase assert_raise(ArgumentError) { :foo.to_proc.call } end + def m_block_given? + block_given? + end + + def m2_block_given?(m = nil) + if m + [block_given?, m.call(self)] + else + block_given? + end + end + + def test_block_given_to_proc + bug8531 = '[Bug #8531]' + m = :m_block_given?.to_proc + assert(!m.call(self), "#{bug8531} without block") + assert(m.call(self) {}, "#{bug8531} with block") + assert(!m.call(self), "#{bug8531} without block second") + end + + def test_block_persist_between_calls + bug8531 = '[Bug #8531]' + m2 = :m2_block_given?.to_proc + assert_equal([true, false], m2.call(self, m2) {}, "#{bug8531} nested with block") + assert_equal([false, false], m2.call(self, m2), "#{bug8531} nested without block") + end + def test_succ assert_equal(:fop, :foo.succ) end diff --git a/test/ruby/test_syntax.rb b/test/ruby/test_syntax.rb index bd60c8a..d924679 100644 --- a/test/ruby/test_syntax.rb +++ b/test/ruby/test_syntax.rb @@ -1,21 +1,24 @@ require 'test/unit' class TestSyntax < Test::Unit::TestCase - def valid_syntax?(code, fname) + def assert_valid_syntax(code, fname, mesg = fname) code = code.dup.force_encoding("ascii-8bit") code.sub!(/\A(?:\xef\xbb\xbf)?(\s*\#.*$)*(\n)?/n) { "#$&#{"\n" if $1 && !$2}BEGIN{throw tag, :ok}\n" } code.force_encoding("us-ascii") - catch {|tag| eval(code, binding, fname, 0)} - rescue SyntaxError - false + verbose, $VERBOSE = $VERBOSE, nil + assert_nothing_raised(SyntaxError, mesg) do + assert_equal(:ok, catch {|tag| eval(code, binding, fname, 0)}, mesg) + end + ensure + $VERBOSE = verbose end def test_syntax assert_nothing_raised(Exception) do for script in Dir[File.expand_path("../../../{lib,sample,ext,test}/**/*.rb", __FILE__)].sort - assert(valid_syntax?(IO::read(script), script), script) + assert_valid_syntax(IO::read(script), script) end end end @@ -52,6 +55,11 @@ class TestSyntax < Test::Unit::TestCase f.close! end + def test_reserved_method_no_args + bug6403 = '[ruby-dev:45626]' + assert_valid_syntax("def self; :foo; end", __FILE__, bug6403) + end + private def make_tmpsrc(f, src) diff --git a/test/ruby/test_time.rb b/test/ruby/test_time.rb index a1f060e..0317214 100644 --- a/test/ruby/test_time.rb +++ b/test/ruby/test_time.rb @@ -14,6 +14,20 @@ class TestTime < Test::Unit::TestCase $VERBOSE = @verbose end + def no_leap_seconds? + # 1972-06-30T23:59:60Z is the first leap second. + Time.utc(1972, 7, 1, 0, 0, 0) - Time.utc(1972, 6, 30, 23, 59, 59) == 1 + end + + def get_t2000 + if no_leap_seconds? + # Sat Jan 01 00:00:00 UTC 2000 + Time.at(946684800).gmtime + else + Time.utc(2000, 1, 1) + end + end + def test_new assert_equal(Time.utc(2000,2,10), Time.new(2000,2,10, 11,0,0, 3600*11)) assert_equal(Time.utc(2000,2,10), Time.new(2000,2,9, 13,0,0, -3600*11)) @@ -324,6 +338,7 @@ class TestTime < Test::Unit::TestCase end assert_raise(ArgumentError) { Time.gm(2000, 1, 1, 0, 0, -(2**31), :foo, :foo) } o = Object.new + def o.to_int; 0; end def o.to_r; nil; end assert_raise(TypeError) { Time.gm(2000, 1, 1, 0, 0, o, :foo, :foo) } def o.to_r; ""; end @@ -377,6 +392,15 @@ class TestTime < Test::Unit::TestCase assert_kind_of(Integer, T2000.hash) end + def test_reinitialize + bug8099 = '[ruby-core:53436] [Bug #8099]' + t2000 = get_t2000 + assert_raise(TypeError, bug8099) { + t2000.send(:initialize, 2013, 03, 14) + } + assert_equal(get_t2000, t2000, bug8099) + end + def test_init_copy assert_equal(T2000, T2000.dup) assert_raise(TypeError) do @@ -659,6 +683,38 @@ class TestTime < Test::Unit::TestCase bug4457 = '[ruby-dev:43285]' assert_raise(Errno::ERANGE, bug4457) {Time.now.strftime('%8192z')} + + bug4458 = '[ruby-dev:43287]' + t = T2000.getlocal("+09:00") + assert_equal(" +900", t.strftime("%_10z"), bug4458) + assert_equal("+000000900", t.strftime("%10z"), bug4458) + assert_equal(" +9:00", t.strftime("%_:10z"), bug4458) + assert_equal("+000009:00", t.strftime("%:10z"), bug4458) + assert_equal(" +9:00:00", t.strftime("%_::10z"), bug4458) + assert_equal("+009:00:00", t.strftime("%::10z"), bug4458) + t = T2000.getlocal("-05:00") + assert_equal(" -500", t.strftime("%_10z"), bug4458) + assert_equal("-000000500", t.strftime("%10z"), bug4458) + assert_equal(" -5:00", t.strftime("%_:10z"), bug4458) + assert_equal("-000005:00", t.strftime("%:10z"), bug4458) + assert_equal(" -5:00:00", t.strftime("%_::10z"), bug4458) + assert_equal("-005:00:00", t.strftime("%::10z"), bug4458) + + bug6323 = '[ruby-core:44447]' + t = T2000.getlocal("+00:36") + assert_equal(" +036", t.strftime("%_10z"), bug6323) + assert_equal("+000000036", t.strftime("%10z"), bug6323) + assert_equal(" +0:36", t.strftime("%_:10z"), bug6323) + assert_equal("+000000:36", t.strftime("%:10z"), bug6323) + assert_equal(" +0:36:00", t.strftime("%_::10z"), bug6323) + assert_equal("+000:36:00", t.strftime("%::10z"), bug6323) + t = T2000.getlocal("-00:55") + assert_equal(" -055", t.strftime("%_10z"), bug6323) + assert_equal("-000000055", t.strftime("%10z"), bug6323) + assert_equal(" -0:55", t.strftime("%_:10z"), bug6323) + assert_equal("-000000:55", t.strftime("%:10z"), bug6323) + assert_equal(" -0:55:00", t.strftime("%_::10z"), bug6323) + assert_equal("-000:55:00", t.strftime("%::10z"), bug6323) end def test_delegate diff --git a/test/rubygems/test_gem_installer.rb b/test/rubygems/test_gem_installer.rb index d40fbc9..9b36120 100644 --- a/test/rubygems/test_gem_installer.rb +++ b/test/rubygems/test_gem_installer.rb @@ -747,7 +747,8 @@ load Gem.bin_path('a', 'executable', version) exe = File.join @gemhome, 'bin', 'executable' - ARGV.unshift "\xE4pfel".force_encoding("UTF-8") + extra_arg = "\xE4pfel".force_encoding("UTF-8") + ARGV.unshift extra_arg begin Gem::Specification.reset @@ -756,7 +757,7 @@ load Gem.bin_path('a', 'executable', version) instance_eval File.read(exe) end ensure - ARGV.shift if ARGV.first == "\xE4pfel" + ARGV.shift if ARGV.first == extra_arg end assert_match(/ran executable/, e.message) diff --git a/test/socket/test_socket.rb b/test/socket/test_socket.rb index f433be8..f693a62 100644 --- a/test/socket/test_socket.rb +++ b/test/socket/test_socket.rb @@ -275,8 +275,32 @@ class TestSocket < Test::Unit::TestCase Socket.udp_server_sockets(0) {|sockets| famlies = {} - sockets.each {|s| famlies[s.local_address.afamily] = true } - ip_addrs.reject! {|ai| !famlies[ai.afamily] } + sockets.each {|s| famlies[s.local_address.afamily] = s } + ip_addrs.reject! {|ai| + s = famlies[ai.afamily] + next true unless s + case RUBY_PLATFORM + when /linux/ + if ai.ip_address.include?('%') and + (`uname -r`[/[0-9.]+/].split('.').map(&:to_i) <=> [2,6,18]) <= 0 + # Cent OS 5.6 (2.6.18-238.19.1.el5xen) doesn't correctly work + # sendmsg with pktinfo for link-local ipv6 addresses + next true + end + when /freebsd/ + if ifr_name = ai.ip_address[/%(.*)/, 1] + # FreeBSD 9.0 with default setting (ipv6_activate_all_interfaces + # is not YES) sets IFDISABLED to interfaces which don't have + # global IPv6 address. + # Link-local IPv6 addresses on those interfaces don't work. + ulSIOCGIFINFO_IN6 = -1068996244 + bIFDISABLED = 4 + in6_ifreq = ifr_name + s.ioctl(ulSIOCGIFINFO_IN6, in6_ifreq) + next true if in6_ifreq.unpack('A16L6').last[bIFDISABLED-1] == 1 + end + end + } skipped = false begin port = sockets.first.local_address.ip_port @@ -290,12 +314,6 @@ class TestSocket < Test::Unit::TestCase } ip_addrs.each {|ai| - if /linux/ =~ RUBY_PLATFORM && ai.ip_address.include?('%') && - (`uname -r`[/[0-9.]+/].split('.').map(&:to_i) <=> [2,6,18]) <= 0 - # Cent OS 5.6 (2.6.18-238.19.1.el5xen) doesn't correctly work - # sendmsg with pktinfo for link-local ipv6 addresses - next - end Addrinfo.udp(ai.ip_address, port).connect {|s| msg1 = "<<<#{ai.inspect}>>>" s.sendmsg msg1 diff --git a/test/socket/test_unix.rb b/test/socket/test_unix.rb index b4c4592..3559eb8 100644 --- a/test/socket/test_unix.rb +++ b/test/socket/test_unix.rb @@ -324,8 +324,11 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase assert_raise(ArgumentError) { UNIXServer.new("a" * 300) } end - def test_nul - assert_raise(ArgumentError) { Socket.sockaddr_un("a\0b") } + def test_abstract_namespace + return if /linux/ !~ RUBY_PLATFORM + addr = Socket.pack_sockaddr_un("\0foo") + assert_match(/\0foo\z/, addr) + assert_equal("\0foo", Socket.unpack_sockaddr_un(addr)) end def test_dgram_pair @@ -507,4 +510,69 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase } end + def test_abstract_unix_server + return if /linux/ !~ RUBY_PLATFORM + name = "\0ruby-test_unix" + s0 = nil + UNIXServer.open(name) {|s| + assert_equal(name, s.local_address.unix_path) + s0 = s + UNIXSocket.open(name) {|c| + sock = s.accept + begin + assert_equal(name, c.remote_address.unix_path) + ensure + sock.close + end + } + } + assert(s0.closed?) + end + + def test_abstract_unix_socket_econnrefused + return if /linux/ !~ RUBY_PLATFORM + name = "\0ruby-test_unix" + assert_raise(Errno::ECONNREFUSED) do + UNIXSocket.open(name) {} + end + end + + def test_abstract_unix_server_socket + return if /linux/ !~ RUBY_PLATFORM + name = "\0ruby-test_unix" + s0 = nil + Socket.unix_server_socket(name) {|s| + assert_equal(name, s.local_address.unix_path) + s0 = s + Socket.unix(name) {|c| + sock, = s.accept + begin + assert_equal(name, c.remote_address.unix_path) + ensure + sock.close + end + } + } + assert(s0.closed?) + end + + def test_autobind + return if /linux/ !~ RUBY_PLATFORM + s0 = nil + Socket.unix_server_socket("") {|s| + name = s.local_address.unix_path + assert_match(/\A\0[0-9a-f]{5}\z/, name) + s0 = s + Socket.unix(name) {|c| + sock, = s.accept + begin + assert_equal(name, c.remote_address.unix_path) + ensure + sock.close + end + } + } + assert(s0.closed?) + end + end if defined?(UNIXSocket) && /cygwin/ !~ RUBY_PLATFORM diff --git a/test/uri/test_ftp.rb b/test/uri/test_ftp.rb index 0d76c44..cc6843e 100644 --- a/test/uri/test_ftp.rb +++ b/test/uri/test_ftp.rb @@ -27,6 +27,10 @@ class TestFTP < Test::Unit::TestCase assert_equal('pass', url.password) end + def test_parse_invalid + assert_raise(InvalidURIError){URI.parse('ftp:example')} + end + def test_paths # If you think what's below is wrong, please read RubyForge bug 2055, # RFC 1738 section 3.2.2, and RFC 2396. diff --git a/test/webrick/test_cgi.rb b/test/webrick/test_cgi.rb index 1185316..d930c26 100644 --- a/test/webrick/test_cgi.rb +++ b/test/webrick/test_cgi.rb @@ -14,6 +14,7 @@ class TestWEBrickCGI < Test::Unit::TestCase def req.meta_vars meta = super meta["RUBYLIB"] = $:.join(File::PATH_SEPARATOR) + meta[RbConfig::CONFIG['LIBPATHENV']] = ENV[RbConfig::CONFIG['LIBPATHENV']] if RbConfig::CONFIG['LIBPATHENV'] return meta end }, diff --git a/test/webrick/test_filehandler.rb b/test/webrick/test_filehandler.rb index bcdb3df..cc27b34 100644 --- a/test/webrick/test_filehandler.rb +++ b/test/webrick/test_filehandler.rb @@ -252,6 +252,7 @@ class WEBrick::TestFileHandler < Test::Unit::TestCase def req.meta_vars meta = super meta["RUBYLIB"] = $:.join(File::PATH_SEPARATOR) + meta[RbConfig::CONFIG['LIBPATHENV']] = ENV[RbConfig::CONFIG['LIBPATHENV']] if RbConfig::CONFIG['LIBPATHENV'] return meta end }, diff --git a/test/win32ole/test_err_in_callback.rb b/test/win32ole/test_err_in_callback.rb index 11c29a8..d39ea12 100644 --- a/test/win32ole/test_err_in_callback.rb +++ b/test/win32ole/test_err_in_callback.rb @@ -9,17 +9,21 @@ rescue LoadError end if defined?(WIN32OLE) require 'mkmf' + require 'pathname' require 'test/unit' + require 'tmpdir' class TestErrInCallBack < Test::Unit::TestCase def setup @ruby = nil if File.exist?("./" + CONFIG["RUBY_INSTALL_NAME"] + CONFIG["EXEEXT"]) sep = File::ALT_SEPARATOR || "/" @ruby = "." + sep + CONFIG["RUBY_INSTALL_NAME"] + cwd = Pathname.new(File.expand_path('.')) @iopt = $:.map {|e| - " -I " + e + " -I " + (Pathname.new(e).relative_path_from(cwd).to_s rescue e) }.join("") - @script = File.join(File.dirname(__FILE__), "err_in_callback.rb") + script = File.join(File.dirname(__FILE__), "err_in_callback.rb") + @script = Pathname.new(script).relative_path_from(cwd).to_s rescue script end end @@ -35,18 +39,17 @@ if defined?(WIN32OLE) def test_err_in_callback skip "'ADODB.Connection' is not available" unless available_adodb? if @ruby - cmd = "#{@ruby} -v #{@iopt} #{@script} > test_err_in_callback.log 2>&1" - system(cmd) - str = "" - open("test_err_in_callback.log") {|ifs| - str = ifs.read - } - assert_match(/NameError/, str) + Dir.mktmpdir do |tmpdir| + logfile = File.join(tmpdir, "test_err_in_callback.log") + cmd = "#{@ruby} -v #{@iopt} #{@script} > #{logfile.gsub(%r(/), '\\')} 2>&1" + result = system(cmd) + str = "" + open(logfile) {|ifs| + str = ifs.read + } + assert_match(/NameError/, str) + end end end - - def teardown - File.unlink("test_err_in_callback.log") if File.exist?("test_err_in_callback.log") - end end end diff --git a/test/win32ole/test_win32ole.rb b/test/win32ole/test_win32ole.rb index 8d72272..5fbfbde 100644 --- a/test/win32ole/test_win32ole.rb +++ b/test/win32ole/test_win32ole.rb @@ -351,8 +351,9 @@ if defined?(WIN32OLE) WIN32OLE.codepage = cp file = fso.opentextfile(fname, 2, true) + test_str = [0x3042].pack("U*").encode("UTF-16LE") begin - file.write [0x3042].pack("U*").force_encoding("UTF-8") + file.write test_str.force_encoding("UTF-16") ensure file.close end @@ -360,7 +361,7 @@ if defined?(WIN32OLE) open(fname, "r:ascii-8bit") {|ifs| str = ifs.read } - assert_equal("\202\240", str) + assert_equal(test_str.force_encoding("ascii-8bit"), str) # This test fail if codepage 20932 (euc) is not installed. begin @@ -371,14 +372,14 @@ if defined?(WIN32OLE) WIN32OLE.codepage = cp file = fso.opentextfile(fname, 2, true) begin - file.write [164, 162].pack("c*").force_encoding("EUC-JP") + file.write [164, 162].pack("c*").force_encoding("UTF-16") ensure file.close end open(fname, "r:ascii-8bit") {|ifs| str = ifs.read } - assert_equal("\202\240", str) + assert_equal("\244\242", str) end ensure diff --git a/test/win32ole/test_win32ole_method.rb b/test/win32ole/test_win32ole_method.rb index e4f38ea..2c24004 100644 --- a/test/win32ole/test_win32ole_method.rb +++ b/test/win32ole/test_win32ole_method.rb @@ -109,7 +109,7 @@ if defined?(WIN32OLE_METHOD) end def is_ruby64? - /mswin64|mingw64/ =~ RUBY_PLATFORM + /mswin64|x64-mingw/ =~ RUBY_PLATFORM end def test_offset_vtbl diff --git a/test/win32ole/test_win32ole_variant.rb b/test/win32ole/test_win32ole_variant.rb index 2b34d27..832d943 100644 --- a/test/win32ole/test_win32ole_variant.rb +++ b/test/win32ole/test_win32ole_variant.rb @@ -12,6 +12,14 @@ end if defined?(WIN32OLE_VARIANT) class TestWIN32OLE_VARIANT < Test::Unit::TestCase + def setup + @orglocale = WIN32OLE.locale + WIN32OLE.locale = 0x0409 # set locale US-Eng + end + + def teardown + WIN32OLE.locale = @orglocale + end def test_s_new obj = WIN32OLE_VARIANT.new('foo') @@ -395,17 +403,13 @@ if defined?(WIN32OLE_VARIANT) def test_conversion_str2cy begin - begin - WIN32OLE.locale = 0x0411 # set locale Japanese - rescue WIN32OLERuntimeError - STDERR.puts("\n#{__FILE__}:#{__LINE__}:#{self.class.name}.test_conversion_str2cy is skipped(Japanese locale is not installed)") - end - if WIN32OLE.locale == 0x0411 - obj = WIN32OLE_VARIANT.new("\\10,000", WIN32OLE::VARIANT::VT_CY) - assert_equal("10000", obj.value) - end - ensure - WIN32OLE.locale = WIN32OLE::LOCALE_SYSTEM_DEFAULT + WIN32OLE.locale = 0x0411 # set locale Japanese + rescue WIN32OLERuntimeError + skip("Japanese locale is not installed") + end + if WIN32OLE.locale == 0x0411 + obj = WIN32OLE_VARIANT.new("\\10,000", WIN32OLE::VARIANT::VT_CY) + assert_equal("10000", obj.value) end end diff --git a/test/zlib/test_zlib.rb b/test/zlib/test_zlib.rb index 37781bc..529c3f4 100644 --- a/test/zlib/test_zlib.rb +++ b/test/zlib/test_zlib.rb @@ -195,6 +195,29 @@ if defined? Zlib z << "foo" # ??? end + def test_inflate_dictionary + dictionary = "foo" + + deflate = Zlib::Deflate.new + deflate.set_dictionary dictionary + compressed = deflate.deflate "foofoofoo", Zlib::FINISH + deflate.close + + out = nil + inflate = Zlib::Inflate.new + + begin + out = inflate.inflate compressed + + flunk "Zlib::NeedDict was not raised" + rescue Zlib::NeedDict + inflate.set_dictionary dictionary + out = inflate.inflate "" + end + + assert_equal "foofoofoo", out + end + def test_sync z = Zlib::Deflate.new s = z.deflate("foo" * 1000, Zlib::FULL_FLUSH) |