diff options
Diffstat (limited to 'spec/ruby/core')
403 files changed, 7775 insertions, 8298 deletions
diff --git a/spec/ruby/core/array/collect_spec.rb b/spec/ruby/core/array/collect_spec.rb index 43a539f805..bdee5c240a 100644 --- a/spec/ruby/core/array/collect_spec.rb +++ b/spec/ruby/core/array/collect_spec.rb @@ -1,143 +1,13 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative '../enumerable/shared/enumeratorized' -require_relative 'shared/iterable_and_tolerating_size_increasing' describe "Array#collect" do - it "returns a copy of array with each element replaced by the value returned by block" do - a = ['a', 'b', 'c', 'd'] - b = a.collect { |i| i + '!' } - b.should == ["a!", "b!", "c!", "d!"] - b.should_not.equal? a + it "is an alias of Array#map" do + Array.instance_method(:collect).should == Array.instance_method(:map) end - - it "does not return subclass instance" do - ArraySpecs::MyArray[1, 2, 3].collect { |x| x + 1 }.should.instance_of?(Array) - end - - it "does not change self" do - a = ['a', 'b', 'c', 'd'] - a.collect { |i| i + '!' } - a.should == ['a', 'b', 'c', 'd'] - end - - it "returns the evaluated value of block if it broke in the block" do - a = ['a', 'b', 'c', 'd'] - b = a.collect {|i| - if i == 'c' - break 0 - else - i + '!' - end - } - b.should == 0 - end - - it "returns an Enumerator when no block given" do - a = [1, 2, 3] - a.collect.should.instance_of?(Enumerator) - end - - it "raises an ArgumentError when no block and with arguments" do - a = [1, 2, 3] - -> { - a.collect(:foo) - }.should.raise(ArgumentError) - end - - before :each do - @object = [1, 2, 3, 4] - end - it_behaves_like :enumeratorized_with_origin_size, :collect - - it_behaves_like :array_iterable_and_tolerating_size_increasing, :collect end describe "Array#collect!" do - it "replaces each element with the value returned by block" do - a = [7, 9, 3, 5] - a.collect! { |i| i - 1 }.should.equal?(a) - a.should == [6, 8, 2, 4] - end - - it "returns self" do - a = [1, 2, 3, 4, 5] - b = a.collect! {|i| i+1 } - a.should.equal? b - end - - it "returns the evaluated value of block but its contents is partially modified, if it broke in the block" do - a = ['a', 'b', 'c', 'd'] - b = a.collect! {|i| - if i == 'c' - break 0 - else - i + '!' - end - } - b.should == 0 - a.should == ['a!', 'b!', 'c', 'd'] + it "is an alias of Array#map!" do + Array.instance_method(:collect!).should == Array.instance_method(:map!) end - - it "returns an Enumerator when no block given, and the enumerator can modify the original array" do - a = [1, 2, 3] - enum = a.collect! - enum.should.instance_of?(Enumerator) - enum.each{|i| "#{i}!" } - a.should == ["1!", "2!", "3!"] - end - - describe "when frozen" do - it "raises a FrozenError" do - -> { ArraySpecs.frozen_array.collect! {} }.should.raise(FrozenError) - end - - it "raises a FrozenError when empty" do - -> { ArraySpecs.empty_frozen_array.collect! {} }.should.raise(FrozenError) - end - - it "raises a FrozenError when calling #each on the returned Enumerator" do - enumerator = ArraySpecs.frozen_array.collect! - -> { enumerator.each {|x| x } }.should.raise(FrozenError) - end - - it "raises a FrozenError when calling #each on the returned Enumerator when empty" do - enumerator = ArraySpecs.empty_frozen_array.collect! - -> { enumerator.each {|x| x } }.should.raise(FrozenError) - end - end - - it "does not truncate the array is the block raises an exception" do - a = [1, 2, 3] - begin - a.collect! { raise StandardError, 'Oops' } - rescue - end - - a.should == [1, 2, 3] - end - - it "only changes elements before error is raised, keeping the element which raised an error." do - a = [1, 2, 3, 4] - begin - a.collect! do |e| - case e - when 1 then -1 - when 2 then -2 - when 3 then raise StandardError, 'Oops' - else 0 - end - end - rescue StandardError - end - - a.should == [-1, -2, 3, 4] - end - - before :each do - @object = [1, 2, 3, 4] - end - it_behaves_like :enumeratorized_with_origin_size, :collect! - - it_behaves_like :array_iterable_and_tolerating_size_increasing, :collect! end diff --git a/spec/ruby/core/array/length_spec.rb b/spec/ruby/core/array/length_spec.rb index 74b2eb3a08..e45abb2138 100644 --- a/spec/ruby/core/array/length_spec.rb +++ b/spec/ruby/core/array/length_spec.rb @@ -1,14 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' describe "Array#length" do - it "returns the number of elements" do - [].length.should == 0 - [1, 2, 3].length.should == 3 - end - - it "properly handles recursive arrays" do - ArraySpecs.empty_recursive_array.length.should == 1 - ArraySpecs.recursive_array.length.should == 8 + it "is an alias of Array#size" do + Array.instance_method(:length).should == Array.instance_method(:size) end end diff --git a/spec/ruby/core/array/map_spec.rb b/spec/ruby/core/array/map_spec.rb index f5e88c8624..0cc394663a 100644 --- a/spec/ruby/core/array/map_spec.rb +++ b/spec/ruby/core/array/map_spec.rb @@ -1,13 +1,143 @@ require_relative '../../spec_helper' +require_relative 'fixtures/classes' +require_relative '../enumerable/shared/enumeratorized' +require_relative 'shared/iterable_and_tolerating_size_increasing' describe "Array#map" do - it "is an alias of Array#collect" do - Array.instance_method(:map).should == Array.instance_method(:collect) + it "returns a copy of array with each element replaced by the value returned by block" do + a = ['a', 'b', 'c', 'd'] + b = a.map { |i| i + '!' } + b.should == ["a!", "b!", "c!", "d!"] + b.should_not.equal? a end + + it "does not return subclass instance" do + ArraySpecs::MyArray[1, 2, 3].map { |x| x + 1 }.should.instance_of?(Array) + end + + it "does not change self" do + a = ['a', 'b', 'c', 'd'] + a.map { |i| i + '!' } + a.should == ['a', 'b', 'c', 'd'] + end + + it "returns the evaluated value of block if it broke in the block" do + a = ['a', 'b', 'c', 'd'] + b = a.map {|i| + if i == 'c' + break 0 + else + i + '!' + end + } + b.should == 0 + end + + it "returns an Enumerator when no block given" do + a = [1, 2, 3] + a.map.should.instance_of?(Enumerator) + end + + it "raises an ArgumentError when no block and with arguments" do + a = [1, 2, 3] + -> { + a.map(:foo) + }.should.raise(ArgumentError) + end + + before :each do + @object = [1, 2, 3, 4] + end + it_behaves_like :enumeratorized_with_origin_size, :map + + it_behaves_like :array_iterable_and_tolerating_size_increasing, :map end describe "Array#map!" do - it "is an alias of Array#collect!" do - Array.instance_method(:map!).should == Array.instance_method(:collect!) + it "replaces each element with the value returned by block" do + a = [7, 9, 3, 5] + a.map! { |i| i - 1 }.should.equal?(a) + a.should == [6, 8, 2, 4] + end + + it "returns self" do + a = [1, 2, 3, 4, 5] + b = a.map! {|i| i+1 } + a.should.equal? b + end + + it "returns the evaluated value of block but its contents is partially modified, if it broke in the block" do + a = ['a', 'b', 'c', 'd'] + b = a.map! {|i| + if i == 'c' + break 0 + else + i + '!' + end + } + b.should == 0 + a.should == ['a!', 'b!', 'c', 'd'] end + + it "returns an Enumerator when no block given, and the enumerator can modify the original array" do + a = [1, 2, 3] + enum = a.map! + enum.should.instance_of?(Enumerator) + enum.each{|i| "#{i}!" } + a.should == ["1!", "2!", "3!"] + end + + describe "when frozen" do + it "raises a FrozenError" do + -> { ArraySpecs.frozen_array.map! {} }.should.raise(FrozenError) + end + + it "raises a FrozenError when empty" do + -> { ArraySpecs.empty_frozen_array.map! {} }.should.raise(FrozenError) + end + + it "raises a FrozenError when calling #each on the returned Enumerator" do + enumerator = ArraySpecs.frozen_array.map! + -> { enumerator.each {|x| x } }.should.raise(FrozenError) + end + + it "raises a FrozenError when calling #each on the returned Enumerator when empty" do + enumerator = ArraySpecs.empty_frozen_array.map! + -> { enumerator.each {|x| x } }.should.raise(FrozenError) + end + end + + it "does not truncate the array is the block raises an exception" do + a = [1, 2, 3] + begin + a.map! { raise StandardError, 'Oops' } + rescue + end + + a.should == [1, 2, 3] + end + + it "only changes elements before error is raised, keeping the element which raised an error." do + a = [1, 2, 3, 4] + begin + a.map! do |e| + case e + when 1 then -1 + when 2 then -2 + when 3 then raise StandardError, 'Oops' + else 0 + end + end + rescue StandardError + end + + a.should == [-1, -2, 3, 4] + end + + before :each do + @object = [1, 2, 3, 4] + end + it_behaves_like :enumeratorized_with_origin_size, :map! + + it_behaves_like :array_iterable_and_tolerating_size_increasing, :map! end diff --git a/spec/ruby/core/array/size_spec.rb b/spec/ruby/core/array/size_spec.rb index 83e8969012..710754ed62 100644 --- a/spec/ruby/core/array/size_spec.rb +++ b/spec/ruby/core/array/size_spec.rb @@ -1,7 +1,14 @@ require_relative '../../spec_helper' +require_relative 'fixtures/classes' describe "Array#size" do - it "is an alias of Array#length" do - Array.instance_method(:size).should == Array.instance_method(:length) + it "returns the number of elements" do + [].size.should == 0 + [1, 2, 3].size.should == 3 + end + + it "properly handles recursive arrays" do + ArraySpecs.empty_recursive_array.size.should == 1 + ArraySpecs.recursive_array.size.should == 8 end end diff --git a/spec/ruby/core/basicobject/equal_spec.rb b/spec/ruby/core/basicobject/equal_spec.rb index c0f41dc0c0..f27f0d7aca 100644 --- a/spec/ruby/core/basicobject/equal_spec.rb +++ b/spec/ruby/core/basicobject/equal_spec.rb @@ -1,54 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/kernel/equal' describe "BasicObject#equal?" do - it "is a public instance method" do - BasicObject.public_instance_methods(false).should.include?(:equal?) - end - - it_behaves_like :object_equal, :equal? - - it "is unaffected by overriding __id__" do - o1 = mock("object") - o2 = mock("object") - suppress_warning { - def o1.__id__; 10; end - def o2.__id__; 10; end - } - o1.equal?(o2).should == false - end - - it "is unaffected by overriding object_id" do - o1 = mock("object") - o1.stub!(:object_id).and_return(10) - o2 = mock("object") - o2.stub!(:object_id).and_return(10) - o1.equal?(o2).should == false - end - - it "is unaffected by overriding ==" do - # different objects, overriding == to return true - o1 = mock("object") - o1.stub!(:==).and_return(true) - o2 = mock("object") - o1.equal?(o2).should == false - - # same objects, overriding == to return false - o3 = mock("object") - o3.stub!(:==).and_return(false) - o3.equal?(o3).should == true - end - - it "is unaffected by overriding eql?" do - # different objects, overriding eql? to return true - o1 = mock("object") - o1.stub!(:eql?).and_return(true) - o2 = mock("object") - o1.equal?(o2).should == false - - # same objects, overriding eql? to return false - o3 = mock("object") - o3.stub!(:eql?).and_return(false) - o3.equal?(o3).should == true + it "is an alias of BasicObject#==" do + BasicObject.instance_method(:equal?).should == BasicObject.instance_method(:==) end end diff --git a/spec/ruby/core/basicobject/equal_value_spec.rb b/spec/ruby/core/basicobject/equal_value_spec.rb index eb951a8305..15755a44a2 100644 --- a/spec/ruby/core/basicobject/equal_value_spec.rb +++ b/spec/ruby/core/basicobject/equal_value_spec.rb @@ -7,4 +7,48 @@ describe "BasicObject#==" do end it_behaves_like :object_equal, :== + + it "is unaffected by overriding __id__" do + o1 = mock("object") + o2 = mock("object") + suppress_warning { + def o1.__id__; 10; end + def o2.__id__; 10; end + } + (o1 == o2).should == false + end + + it "is unaffected by overriding object_id" do + o1 = mock("object") + o1.stub!(:object_id).and_return(10) + o2 = mock("object") + o2.stub!(:object_id).and_return(10) + (o1 == o2).should == false + end + + it "is unaffected by overriding equal?" do + # different objects, overriding equal? to return true + o1 = mock("object") + o1.stub!(:equal?).and_return(true) + o2 = mock("object") + (o1 == o2).should == false + + # same objects, overriding equal? to return false + o3 = mock("object") + o3.stub!(:equal?).and_return(false) + (o3 == o3).should == true + end + + it "is unaffected by overriding eql?" do + # different objects, overriding eql? to return true + o1 = mock("object") + o1.stub!(:eql?).and_return(true) + o2 = mock("object") + (o1 == o2).should == false + + # same objects, overriding eql? to return false + o3 = mock("object") + o3.stub!(:eql?).and_return(false) + (o3 == o3).should == true + end end diff --git a/spec/ruby/core/complex/rect_spec.rb b/spec/ruby/core/complex/rect_spec.rb index 72f2bf9930..bf3467c611 100644 --- a/spec/ruby/core/complex/rect_spec.rb +++ b/spec/ruby/core/complex/rect_spec.rb @@ -7,7 +7,7 @@ describe "Complex#rect" do end describe "Complex.rect" do - it "is an alias of Complex#rectangular" do + it "is an alias of Complex.rectangular" do Complex.method(:rect).should == Complex.method(:rectangular) end end diff --git a/spec/ruby/core/data/inspect_spec.rb b/spec/ruby/core/data/inspect_spec.rb index 6c97a719e3..e5b9689ca5 100644 --- a/spec/ruby/core/data/inspect_spec.rb +++ b/spec/ruby/core/data/inspect_spec.rb @@ -2,62 +2,7 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' describe "Data#inspect" do - it "returns a string representation showing members and values" do - a = DataSpecs::Measure.new(42, "km") - a.inspect.should == '#<data DataSpecs::Measure amount=42, unit="km">' - end - - it "returns a string representation without the class name for anonymous structs" do - Data.define(:a).new("").inspect.should == '#<data a="">' - end - - it "returns a string representation without the class name for structs nested in anonymous classes" do - c = Class.new - c.class_eval <<~DOC - Foo = Data.define(:a) - DOC - - c::Foo.new("").inspect.should == '#<data a="">' - end - - it "returns a string representation without the class name for structs nested in anonymous modules" do - m = Module.new - m.class_eval <<~DOC - Foo = Data.define(:a) - DOC - - m::Foo.new("").inspect.should == '#<data a="">' - end - - it "does not call #name method" do - struct = DataSpecs::MeasureWithOverriddenName.new(42, "km") - struct.inspect.should == '#<data DataSpecs::MeasureWithOverriddenName amount=42, unit="km">' - end - - it "does not call #name method when struct is anonymous" do - klass = Class.new(DataSpecs::Measure) do - def self.name - "A" - end - end - struct = klass.new(42, "km") - struct.inspect.should == '#<data amount=42, unit="km">' - end - - context "recursive structure" do - it "returns string representation with recursive attribute replaced with ..." do - a = DataSpecs::Measure.allocate - a.send(:initialize, amount: 42, unit: a) - - a.inspect.should == "#<data DataSpecs::Measure amount=42, unit=#<data DataSpecs::Measure:...>>" - end - - it "returns string representation with recursive attribute replaced with ... when an anonymous class" do - klass = Class.new(DataSpecs::Measure) - a = klass.allocate - a.send(:initialize, amount: 42, unit: a) - - a.inspect.should =~ /#<data amount=42, unit=#<data #<Class:0x.+?>:\.\.\.>>/ - end + it "is an alias of Data#to_s" do + DataSpecs::Measure.instance_method(:inspect).should == DataSpecs::Measure.instance_method(:to_s) end end diff --git a/spec/ruby/core/data/to_s_spec.rb b/spec/ruby/core/data/to_s_spec.rb index a552e4659b..e436c21109 100644 --- a/spec/ruby/core/data/to_s_spec.rb +++ b/spec/ruby/core/data/to_s_spec.rb @@ -2,8 +2,62 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' describe "Data#to_s" do - it "is an alias of Data#inspect" do + it "returns a string representation showing members and values" do a = DataSpecs::Measure.new(42, "km") - a.method(:to_s).should == a.method(:inspect) + a.to_s.should == '#<data DataSpecs::Measure amount=42, unit="km">' + end + + it "returns a string representation without the class name for anonymous structs" do + Data.define(:a).new("").to_s.should == '#<data a="">' + end + + it "returns a string representation without the class name for structs nested in anonymous classes" do + c = Class.new + c.class_eval <<~DOC + Foo = Data.define(:a) + DOC + + c::Foo.new("").to_s.should == '#<data a="">' + end + + it "returns a string representation without the class name for structs nested in anonymous modules" do + m = Module.new + m.class_eval <<~DOC + Foo = Data.define(:a) + DOC + + m::Foo.new("").to_s.should == '#<data a="">' + end + + it "does not call #name method" do + struct = DataSpecs::MeasureWithOverriddenName.new(42, "km") + struct.to_s.should == '#<data DataSpecs::MeasureWithOverriddenName amount=42, unit="km">' + end + + it "does not call #name method when struct is anonymous" do + klass = Class.new(DataSpecs::Measure) do + def self.name + "A" + end + end + struct = klass.new(42, "km") + struct.to_s.should == '#<data amount=42, unit="km">' + end + + context "recursive structure" do + it "returns string representation with recursive attribute replaced with ..." do + a = DataSpecs::Measure.allocate + a.send(:initialize, amount: 42, unit: a) + + a.to_s.should == "#<data DataSpecs::Measure amount=42, unit=#<data DataSpecs::Measure:...>>" + end + + it "returns string representation with recursive attribute replaced with ... when an anonymous class" do + klass = Class.new(DataSpecs::Measure) + a = klass.allocate + a.send(:initialize, amount: 42, unit: a) + + a.to_s.should =~ /#<data amount=42, unit=#<data #<Class:0x.+?>:\.\.\.>>/ + end end end diff --git a/spec/ruby/core/dir/delete_spec.rb b/spec/ruby/core/dir/delete_spec.rb index a0020788ca..2dbd461c94 100644 --- a/spec/ruby/core/dir/delete_spec.rb +++ b/spec/ruby/core/dir/delete_spec.rb @@ -1,6 +1,5 @@ require_relative '../../spec_helper' require_relative 'fixtures/common' -require_relative 'shared/delete' describe "Dir.delete" do before :all do @@ -11,5 +10,55 @@ describe "Dir.delete" do DirSpecs.delete_mock_dirs end - it_behaves_like :dir_delete, :delete + before :each do + DirSpecs.rmdir_dirs true + end + + after :each do + DirSpecs.rmdir_dirs false + end + + it "removes empty directories" do + Dir.delete(DirSpecs.mock_rmdir("empty")).should == 0 + end + + it "calls #to_path on non-String arguments" do + p = mock('path') + p.should_receive(:to_path).and_return(DirSpecs.mock_rmdir("empty")) + Dir.delete(p) + end + + it "raises an Errno::ENOTEMPTY when trying to remove a nonempty directory" do + -> do + Dir.delete DirSpecs.mock_rmdir("nonempty") + end.should.raise(Errno::ENOTEMPTY) + end + + it "raises an Errno::ENOENT when trying to remove a non-existing directory" do + -> do + Dir.delete DirSpecs.nonexistent + end.should.raise(Errno::ENOENT) + end + + it "raises an Errno::ENOTDIR when trying to remove a non-directory" do + file = DirSpecs.mock_rmdir("nonempty/regular") + touch(file) + -> do + Dir.delete file + end.should.raise(Errno::ENOTDIR) + end + + # this won't work on Windows, since chmod(0000) does not remove all permissions + platform_is_not :windows do + as_user do + it "raises an Errno::EACCES if lacking adequate permissions to remove the directory" do + parent = DirSpecs.mock_rmdir("noperm") + child = DirSpecs.mock_rmdir("noperm", "child") + File.chmod(0000, parent) + -> do + Dir.delete child + end.should.raise(Errno::EACCES) + end + end + end end diff --git a/spec/ruby/core/dir/path_spec.rb b/spec/ruby/core/dir/path_spec.rb index 02ddd2cd42..e506db1222 100644 --- a/spec/ruby/core/dir/path_spec.rb +++ b/spec/ruby/core/dir/path_spec.rb @@ -1,37 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/common' describe "Dir#path" do - before :all do - DirSpecs.create_mock_dirs - end - - after :all do - DirSpecs.delete_mock_dirs - end - - it "returns the path that was supplied to .new or .open" do - dir = Dir.open DirSpecs.mock_dir - begin - dir.path.should == DirSpecs.mock_dir - ensure - dir.close rescue nil - end - end - - it "returns the path even when called on a closed Dir instance" do - dir = Dir.open DirSpecs.mock_dir - dir.close - dir.path.should == DirSpecs.mock_dir - end - - it "returns a String with the same encoding as the argument to .open" do - path = DirSpecs.mock_dir.force_encoding Encoding::IBM866 - dir = Dir.open path - begin - dir.path.encoding.should.equal?(Encoding::IBM866) - ensure - dir.close - end + it "is an alias of Dir#to_path" do + Dir.instance_method(:path).should == Dir.instance_method(:to_path) end end diff --git a/spec/ruby/core/dir/pos_spec.rb b/spec/ruby/core/dir/pos_spec.rb index f8ca06d778..1e364fbe3c 100644 --- a/spec/ruby/core/dir/pos_spec.rb +++ b/spec/ruby/core/dir/pos_spec.rb @@ -1,10 +1,42 @@ require_relative '../../spec_helper' require_relative 'fixtures/common' +require_relative 'shared/closed' require_relative 'shared/pos' describe "Dir#pos" do - it "is an alias of Dir#tell" do - Dir.instance_method(:pos).should == Dir.instance_method(:tell) + before :all do + DirSpecs.create_mock_dirs + end + + after :all do + DirSpecs.delete_mock_dirs + end + + it_behaves_like :dir_closed, :pos + + before :each do + @dir = Dir.open DirSpecs.mock_dir + end + + after :each do + @dir.close rescue nil + end + + it "returns an Integer representing the current position in the directory" do + @dir.pos.should.is_a?(Integer) + @dir.pos.should.is_a?(Integer) + @dir.pos.should.is_a?(Integer) + end + + it "returns a different Integer if moved from previous position" do + a = @dir.pos + @dir.read + b = @dir.pos + + a.should.is_a?(Integer) + b.should.is_a?(Integer) + + a.should_not == b end end diff --git a/spec/ruby/core/dir/rmdir_spec.rb b/spec/ruby/core/dir/rmdir_spec.rb index 08cd1a5bc6..c31067ca29 100644 --- a/spec/ruby/core/dir/rmdir_spec.rb +++ b/spec/ruby/core/dir/rmdir_spec.rb @@ -1,15 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/common' -require_relative 'shared/delete' describe "Dir.rmdir" do - before :all do - DirSpecs.create_mock_dirs + it "is an alias of Dir.delete" do + Dir.method(:rmdir).should == Dir.method(:delete) end - - after :all do - DirSpecs.delete_mock_dirs - end - - it_behaves_like :dir_delete, :rmdir end diff --git a/spec/ruby/core/dir/shared/delete.rb b/spec/ruby/core/dir/shared/delete.rb deleted file mode 100644 index ba013e8615..0000000000 --- a/spec/ruby/core/dir/shared/delete.rb +++ /dev/null @@ -1,53 +0,0 @@ -describe :dir_delete, shared: true do - before :each do - DirSpecs.rmdir_dirs true - end - - after :each do - DirSpecs.rmdir_dirs false - end - - it "removes empty directories" do - Dir.send(@method, DirSpecs.mock_rmdir("empty")).should == 0 - end - - it "calls #to_path on non-String arguments" do - p = mock('path') - p.should_receive(:to_path).and_return(DirSpecs.mock_rmdir("empty")) - Dir.send(@method, p) - end - - it "raises an Errno::ENOTEMPTY when trying to remove a nonempty directory" do - -> do - Dir.send @method, DirSpecs.mock_rmdir("nonempty") - end.should.raise(Errno::ENOTEMPTY) - end - - it "raises an Errno::ENOENT when trying to remove a non-existing directory" do - -> do - Dir.send @method, DirSpecs.nonexistent - end.should.raise(Errno::ENOENT) - end - - it "raises an Errno::ENOTDIR when trying to remove a non-directory" do - file = DirSpecs.mock_rmdir("nonempty/regular") - touch(file) - -> do - Dir.send @method, file - end.should.raise(Errno::ENOTDIR) - end - - # this won't work on Windows, since chmod(0000) does not remove all permissions - platform_is_not :windows do - as_user do - it "raises an Errno::EACCES if lacking adequate permissions to remove the directory" do - parent = DirSpecs.mock_rmdir("noperm") - child = DirSpecs.mock_rmdir("noperm", "child") - File.chmod(0000, parent) - -> do - Dir.send @method, child - end.should.raise(Errno::EACCES) - end - end - end -end diff --git a/spec/ruby/core/dir/tell_spec.rb b/spec/ruby/core/dir/tell_spec.rb index dcbb40438f..04f92a8ade 100644 --- a/spec/ruby/core/dir/tell_spec.rb +++ b/spec/ruby/core/dir/tell_spec.rb @@ -1,41 +1,9 @@ require_relative '../../spec_helper' require_relative 'fixtures/common' -require_relative 'shared/closed' require_relative 'shared/pos' describe "Dir#tell" do - before :all do - DirSpecs.create_mock_dirs - end - - after :all do - DirSpecs.delete_mock_dirs - end - - it_behaves_like :dir_closed, :tell - - before :each do - @dir = Dir.open DirSpecs.mock_dir - end - - after :each do - @dir.close rescue nil - end - - it "returns an Integer representing the current position in the directory" do - @dir.tell.should.is_a?(Integer) - @dir.tell.should.is_a?(Integer) - @dir.tell.should.is_a?(Integer) - end - - it "returns a different Integer if moved from previous position" do - a = @dir.tell - @dir.read - b = @dir.tell - - a.should.is_a?(Integer) - b.should.is_a?(Integer) - - a.should_not == b + it "is an alias of Dir#pos" do + Dir.instance_method(:tell).should == Dir.instance_method(:pos) end end diff --git a/spec/ruby/core/dir/to_path_spec.rb b/spec/ruby/core/dir/to_path_spec.rb index 2ed533e757..43e349c50e 100644 --- a/spec/ruby/core/dir/to_path_spec.rb +++ b/spec/ruby/core/dir/to_path_spec.rb @@ -1,7 +1,37 @@ require_relative '../../spec_helper' +require_relative 'fixtures/common' describe "Dir#to_path" do - it "is an alias of Dir#path" do - Dir.instance_method(:to_path).should == Dir.instance_method(:path) + before :all do + DirSpecs.create_mock_dirs + end + + after :all do + DirSpecs.delete_mock_dirs + end + + it "returns the to_path that was supplied to .new or .open" do + dir = Dir.open DirSpecs.mock_dir + begin + dir.to_path.should == DirSpecs.mock_dir + ensure + dir.close rescue nil + end + end + + it "returns the to_path even when called on a closed Dir instance" do + dir = Dir.open DirSpecs.mock_dir + dir.close + dir.to_path.should == DirSpecs.mock_dir + end + + it "returns a String with the same encoding as the argument to .open" do + to_path = DirSpecs.mock_dir.force_encoding Encoding::IBM866 + dir = Dir.open to_path + begin + dir.to_path.encoding.should.equal?(Encoding::IBM866) + ensure + dir.close + end end end diff --git a/spec/ruby/core/dir/unlink_spec.rb b/spec/ruby/core/dir/unlink_spec.rb index 79027e020c..d9cd1b1a87 100644 --- a/spec/ruby/core/dir/unlink_spec.rb +++ b/spec/ruby/core/dir/unlink_spec.rb @@ -1,15 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/common' -require_relative 'shared/delete' describe "Dir.unlink" do - before :all do - DirSpecs.create_mock_dirs + it "is an alias of Dir.delete" do + Dir.method(:unlink).should == Dir.method(:delete) end - - after :all do - DirSpecs.delete_mock_dirs - end - - it_behaves_like :dir_delete, :unlink end diff --git a/spec/ruby/core/encoding/converter/asciicompat_encoding_spec.rb b/spec/ruby/core/encoding/converter/asciicompat_encoding_spec.rb index 07c7a88356..7fa867a57e 100644 --- a/spec/ruby/core/encoding/converter/asciicompat_encoding_spec.rb +++ b/spec/ruby/core/encoding/converter/asciicompat_encoding_spec.rb @@ -1,11 +1,6 @@ require_relative '../../../spec_helper' describe "Encoding::Converter.asciicompat_encoding" do - it "accepts an encoding name as a String argument" do - -> { Encoding::Converter.asciicompat_encoding('UTF-8') }. - should_not raise_error - end - it "coerces non-String/Encoding objects with #to_str" do str = mock('string') str.should_receive(:to_str).at_least(1).times.and_return('string') @@ -13,9 +8,8 @@ describe "Encoding::Converter.asciicompat_encoding" do end it "accepts an Encoding object as an argument" do - Encoding::Converter. - asciicompat_encoding(Encoding.find("ISO-2022-JP")). - should == Encoding::Converter.asciicompat_encoding("ISO-2022-JP") + Encoding::Converter.asciicompat_encoding(Encoding.find("ISO-2022-JP")).should == + Encoding::Converter.asciicompat_encoding("ISO-2022-JP") end it "returns a corresponding ASCII compatible encoding for ASCII-incompatible encodings" do diff --git a/spec/ruby/core/enumerable/collect_concat_spec.rb b/spec/ruby/core/enumerable/collect_concat_spec.rb index 59317cfe34..5024aaddab 100644 --- a/spec/ruby/core/enumerable/collect_concat_spec.rb +++ b/spec/ruby/core/enumerable/collect_concat_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/collect_concat' describe "Enumerable#collect_concat" do - it_behaves_like :enumerable_collect_concat, :collect_concat + it "is an alias of Enumerable#flat_map" do + Enumerable.instance_method(:collect_concat).should == Enumerable.instance_method(:flat_map) + end end diff --git a/spec/ruby/core/enumerable/collect_spec.rb b/spec/ruby/core/enumerable/collect_spec.rb index cfa2895cce..319b1b263d 100644 --- a/spec/ruby/core/enumerable/collect_spec.rb +++ b/spec/ruby/core/enumerable/collect_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/collect' describe "Enumerable#collect" do - it_behaves_like :enumerable_collect, :collect + it "is an alias of Enumerable#map" do + Enumerable.instance_method(:collect).should == Enumerable.instance_method(:map) + end end diff --git a/spec/ruby/core/enumerable/detect_spec.rb b/spec/ruby/core/enumerable/detect_spec.rb index 6959aadc44..0669c50c58 100644 --- a/spec/ruby/core/enumerable/detect_spec.rb +++ b/spec/ruby/core/enumerable/detect_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/find' describe "Enumerable#detect" do - it_behaves_like :enumerable_find, :detect + it "is an alias of Enumerable#find" do + Enumerable.instance_method(:detect).should == Enumerable.instance_method(:find) + end end diff --git a/spec/ruby/core/enumerable/entries_spec.rb b/spec/ruby/core/enumerable/entries_spec.rb index 2de4fc756a..8cb29b7b47 100644 --- a/spec/ruby/core/enumerable/entries_spec.rb +++ b/spec/ruby/core/enumerable/entries_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/entries' describe "Enumerable#entries" do - it_behaves_like :enumerable_entries, :entries + it "is an alias of Enumerable#to_a" do + Enumerable.instance_method(:entries).should == Enumerable.instance_method(:to_a) + end end diff --git a/spec/ruby/core/enumerable/filter_spec.rb b/spec/ruby/core/enumerable/filter_spec.rb index 1c3a7e9ff5..d075b39396 100644 --- a/spec/ruby/core/enumerable/filter_spec.rb +++ b/spec/ruby/core/enumerable/filter_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/find_all' describe "Enumerable#filter" do - it_behaves_like :enumerable_find_all, :filter + it "is an alias of Enumerable#select" do + Enumerable.instance_method(:filter).should == Enumerable.instance_method(:select) + end end diff --git a/spec/ruby/core/enumerable/find_all_spec.rb b/spec/ruby/core/enumerable/find_all_spec.rb index 9cd635f247..1095a19569 100644 --- a/spec/ruby/core/enumerable/find_all_spec.rb +++ b/spec/ruby/core/enumerable/find_all_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/find_all' describe "Enumerable#find_all" do - it_behaves_like :enumerable_find_all, :find_all + it "is an alias of Enumerable#select" do + Enumerable.instance_method(:find_all).should == Enumerable.instance_method(:select) + end end diff --git a/spec/ruby/core/enumerable/find_spec.rb b/spec/ruby/core/enumerable/find_spec.rb index 5ddebc05f8..4ac4b75c47 100644 --- a/spec/ruby/core/enumerable/find_spec.rb +++ b/spec/ruby/core/enumerable/find_spec.rb @@ -1,7 +1,78 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/find' +require_relative 'shared/enumerable_enumeratorized' describe "Enumerable#find" do - it_behaves_like :enumerable_find, :find + before :each do + ScratchPad.record [] + @elements = [2, 4, 6, 8, 10] + @numerous = EnumerableSpecs::Numerous.new(*@elements) + @empty = [] + end + + it "passes each entry in enum to block while block when block is false" do + visited_elements = [] + @numerous.find do |element| + visited_elements << element + false + end + visited_elements.should == @elements + end + + it "returns nil when the block is false and there is no ifnone proc given" do + @numerous.find {|e| false }.should == nil + end + + it "returns the first element for which the block is not false" do + @elements.each do |element| + @numerous.find {|e| e > element - 1 }.should == element + end + end + + it "returns the value of the ifnone proc if the block is false" do + fail_proc = -> { "cheeseburgers" } + @numerous.find(fail_proc) {|e| false }.should == "cheeseburgers" + end + + it "doesn't call the ifnone proc if an element is found" do + fail_proc = -> { raise "This shouldn't have been called" } + @numerous.find(fail_proc) {|e| e == @elements.first }.should == 2 + end + + it "calls the ifnone proc only once when the block is false" do + times = 0 + fail_proc = -> { times += 1; raise if times > 1; "cheeseburgers" } + @numerous.find(fail_proc) {|e| false }.should == "cheeseburgers" + end + + it "calls the ifnone proc when there are no elements" do + fail_proc = -> { "yay" } + @empty.find(fail_proc) {|e| true}.should == "yay" + end + + it "ignores the ifnone argument when nil" do + @numerous.find(nil) {|e| false }.should == nil + end + + it "passes through the values yielded by #each_with_index" do + [:a, :b].each_with_index.find { |x, i| ScratchPad << [x, i]; nil } + ScratchPad.recorded.should == [[:a, 0], [:b, 1]] + end + + it "returns an enumerator when no block given" do + @numerous.find.should.instance_of?(Enumerator) + end + + it "passes the ifnone proc to the enumerator" do + times = 0 + fail_proc = -> { times += 1; raise if times > 1; "cheeseburgers" } + @numerous.find(fail_proc).each {|e| false }.should == "cheeseburgers" + end + + it "gathers whole arrays as elements when each yields multiple" do + multi = EnumerableSpecs::YieldsMulti.new + multi.find {|e| e == [1, 2] }.should == [1, 2] + end + + it_behaves_like :enumerable_enumeratorized_with_unknown_size, :find end diff --git a/spec/ruby/core/enumerable/flat_map_spec.rb b/spec/ruby/core/enumerable/flat_map_spec.rb index bd07eab6c5..ef50cb2696 100644 --- a/spec/ruby/core/enumerable/flat_map_spec.rb +++ b/spec/ruby/core/enumerable/flat_map_spec.rb @@ -1,7 +1,56 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/collect_concat' +require_relative 'shared/enumerable_enumeratorized' describe "Enumerable#flat_map" do - it_behaves_like :enumerable_collect_concat, :flat_map + it "yields elements to the block and flattens one level" do + numerous = EnumerableSpecs::Numerous.new(1, [2, 3], [4, [5, 6]], {foo: :bar}) + numerous.flat_map { |i| i }.should == [1, 2, 3, 4, [5, 6], {foo: :bar}] + end + + it "appends non-Array elements that do not define #to_ary" do + obj = mock("to_ary undefined") + + numerous = EnumerableSpecs::Numerous.new(1, obj, 2) + numerous.flat_map { |i| i }.should == [1, obj, 2] + end + + it "concatenates the result of calling #to_ary if it returns an Array" do + obj = mock("to_ary defined") + obj.should_receive(:to_ary).and_return([:a, :b]) + + numerous = EnumerableSpecs::Numerous.new(1, obj, 2) + numerous.flat_map { |i| i }.should == [1, :a, :b, 2] + end + + it "does not call #to_a" do + obj = mock("to_ary undefined") + obj.should_not_receive(:to_a) + + numerous = EnumerableSpecs::Numerous.new(1, obj, 2) + numerous.flat_map { |i| i }.should == [1, obj, 2] + end + + it "appends an element that defines #to_ary that returns nil" do + obj = mock("to_ary defined") + obj.should_receive(:to_ary).and_return(nil) + + numerous = EnumerableSpecs::Numerous.new(1, obj, 2) + numerous.flat_map { |i| i }.should == [1, obj, 2] + end + + it "raises a TypeError if an element defining #to_ary does not return an Array or nil" do + obj = mock("to_ary defined") + obj.should_receive(:to_ary).and_return("array") + + -> { [1, obj, 3].flat_map { |i| i } }.should.raise(TypeError) + end + + it "returns an enumerator when no block given" do + enum = EnumerableSpecs::Numerous.new(1, 2).flat_map + enum.should.instance_of?(Enumerator) + enum.each{ |i| [i] * i }.should == [1, 2, 2] + end + + it_behaves_like :enumerable_enumeratorized_with_origin_size, :flat_map end diff --git a/spec/ruby/core/enumerable/include_spec.rb b/spec/ruby/core/enumerable/include_spec.rb index dab1b04451..d59b351486 100644 --- a/spec/ruby/core/enumerable/include_spec.rb +++ b/spec/ruby/core/enumerable/include_spec.rb @@ -1,7 +1,36 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/include' describe "Enumerable#include?" do - it_behaves_like :enumerable_include, :include? + it "returns true if any element == argument for numbers" do + class EnumerableSpecIncludeP; def ==(obj) obj == 5; end; end + + elements = (0..5).to_a + EnumerableSpecs::Numerous.new(*elements).include?(5).should == true + EnumerableSpecs::Numerous.new(*elements).include?(10).should == false + EnumerableSpecs::Numerous.new(*elements).include?(EnumerableSpecIncludeP.new).should == true + end + + it "returns true if any element == argument for other objects" do + class EnumerableSpecIncludeP11; def ==(obj); obj == '11'; end; end + + elements = ('0'..'5').to_a + [EnumerableSpecIncludeP11.new] + EnumerableSpecs::Numerous.new(*elements).include?('5').should == true + EnumerableSpecs::Numerous.new(*elements).include?('10').should == false + EnumerableSpecs::Numerous.new(*elements).include?(EnumerableSpecIncludeP11.new).should == true + EnumerableSpecs::Numerous.new(*elements).include?('11').should == true + end + + + it "returns true if any member of enum equals obj when == compare different classes (legacy rubycon)" do + # equality is tested with == + EnumerableSpecs::Numerous.new(2,4,6,8,10).include?(2.0).should == true + EnumerableSpecs::Numerous.new(2,4,[6,8],10).include?([6, 8]).should == true + EnumerableSpecs::Numerous.new(2,4,[6,8],10).include?([6.0, 8.0]).should == true + end + + it "gathers whole arrays as elements when each yields multiple" do + multi = EnumerableSpecs::YieldsMulti.new + multi.include?([1,2]).should == true + end end diff --git a/spec/ruby/core/enumerable/inject_spec.rb b/spec/ruby/core/enumerable/inject_spec.rb index e1fe216144..10de321395 100644 --- a/spec/ruby/core/enumerable/inject_spec.rb +++ b/spec/ruby/core/enumerable/inject_spec.rb @@ -1,7 +1,144 @@ require_relative '../../spec_helper' +require_relative '../array/shared/iterable_and_tolerating_size_increasing' require_relative 'fixtures/classes' -require_relative 'shared/inject' describe "Enumerable#inject" do - it_behaves_like :enumerable_inject, :inject + it "with argument takes a block with an accumulator (with argument as initial value) and the current element. Value of block becomes new accumulator" do + a = [] + EnumerableSpecs::Numerous.new.inject(0) { |memo, i| a << [memo, i]; i } + a.should == [[0, 2], [2, 5], [5, 3], [3, 6], [6, 1], [1, 4]] + EnumerableSpecs::EachDefiner.new(true, true, true).inject(nil) {|result, i| i && result}.should == nil + end + + it "produces an array of the accumulator and the argument when given a block with a *arg" do + a = [] + [1,2].inject(0) {|*args| a << args; args[0] + args[1]} + a.should == [[0, 1], [1, 2]] + end + + it "can take two argument" do + EnumerableSpecs::Numerous.new(1, 2, 3).inject(10, :-).should == 4 + EnumerableSpecs::Numerous.new(1, 2, 3).inject(10, "-").should == 4 + + [1, 2, 3].inject(10, :-).should == 4 + [1, 2, 3].inject(10, "-").should == 4 + end + + it "converts non-Symbol method name argument to String with #to_str if two arguments" do + name = Object.new + def name.to_str; "-"; end + + EnumerableSpecs::Numerous.new(1, 2, 3).inject(10, name).should == 4 + [1, 2, 3].inject(10, name).should == 4 + end + + it "raises TypeError when the second argument is not Symbol or String and it cannot be converted to String if two arguments" do + -> { EnumerableSpecs::Numerous.new(1, 2, 3).inject(10, Object.new) }.should.raise(TypeError, /is not a symbol nor a string/) + -> { [1, 2, 3].inject(10, Object.new) }.should.raise(TypeError, /is not a symbol nor a string/) + end + + it "ignores the block if two arguments" do + -> { + EnumerableSpecs::Numerous.new(1, 2, 3).inject(10, :-) { raise "we never get here"}.should == 4 + }.should complain(/#{__FILE__}:#{__LINE__-1}: warning: given block not used/, verbose: true) + + -> { + [1, 2, 3].inject(10, :-) { raise "we never get here"}.should == 4 + }.should complain(/#{__FILE__}:#{__LINE__-1}: warning: given block not used/, verbose: true) + end + + it "does not warn when given a Symbol with $VERBOSE true" do + -> { + [1, 2].inject(0, :+) + [1, 2].inject(:+) + EnumerableSpecs::Numerous.new(1, 2).inject(0, :+) + EnumerableSpecs::Numerous.new(1, 2).inject(:+) + }.should_not complain(verbose: true) + end + + it "can take a symbol argument" do + EnumerableSpecs::Numerous.new(10, 1, 2, 3).inject(:-).should == 4 + [10, 1, 2, 3].inject(:-).should == 4 + end + + it "can take a String argument" do + EnumerableSpecs::Numerous.new(10, 1, 2, 3).inject("-").should == 4 + [10, 1, 2, 3].inject("-").should == 4 + end + + it "converts non-Symbol method name argument to String with #to_str" do + name = Object.new + def name.to_str; "-"; end + + EnumerableSpecs::Numerous.new(10, 1, 2, 3).inject(name).should == 4 + [10, 1, 2, 3].inject(name).should == 4 + end + + it "raises TypeError when passed not Symbol or String method name argument and it cannot be converted to String" do + -> { EnumerableSpecs::Numerous.new(10, 1, 2, 3).inject(Object.new) }.should.raise(TypeError, /is not a symbol nor a string/) + -> { [10, 1, 2, 3].inject(Object.new) }.should.raise(TypeError, /is not a symbol nor a string/) + end + + it "without argument takes a block with an accumulator (with first element as initial value) and the current element. Value of block becomes new accumulator" do + a = [] + EnumerableSpecs::Numerous.new.inject { |memo, i| a << [memo, i]; i } + a.should == [[2, 5], [5, 3], [3, 6], [6, 1], [1, 4]] + end + + it "gathers whole arrays as elements when each yields multiple" do + multi = EnumerableSpecs::YieldsMulti.new + multi.inject([]) {|acc, e| acc << e }.should == [[1, 2], [3, 4, 5], [6, 7, 8, 9]] + end + + it "with inject arguments(legacy rubycon)" do + # with inject argument + EnumerableSpecs::EachDefiner.new().inject(1) {|acc,x| 999 }.should == 1 + EnumerableSpecs::EachDefiner.new(2).inject(1) {|acc,x| 999 }.should == 999 + EnumerableSpecs::EachDefiner.new(2).inject(1) {|acc,x| acc }.should == 1 + EnumerableSpecs::EachDefiner.new(2).inject(1) {|acc,x| x }.should == 2 + + EnumerableSpecs::EachDefiner.new(1,2,3,4).inject(100) {|acc,x| acc + x }.should == 110 + EnumerableSpecs::EachDefiner.new(1,2,3,4).inject(100) {|acc,x| acc * x }.should == 2400 + + EnumerableSpecs::EachDefiner.new('a','b','c').inject("z") {|result, i| i+result}.should == "cbaz" + end + + it "without inject arguments(legacy rubycon)" do + # no inject argument + EnumerableSpecs::EachDefiner.new(2).inject {|acc,x| 999 }.should == 2 + EnumerableSpecs::EachDefiner.new(2).inject {|acc,x| acc }.should == 2 + EnumerableSpecs::EachDefiner.new(2).inject {|acc,x| x }.should == 2 + + EnumerableSpecs::EachDefiner.new(1,2,3,4).inject {|acc,x| acc + x }.should == 10 + EnumerableSpecs::EachDefiner.new(1,2,3,4).inject {|acc,x| acc * x }.should == 24 + + EnumerableSpecs::EachDefiner.new('a','b','c').inject {|result, i| i+result}.should == "cba" + EnumerableSpecs::EachDefiner.new(3, 4, 5).inject {|result, i| result*i}.should == 60 + EnumerableSpecs::EachDefiner.new([1], 2, 'a','b').inject {|r,i| r<<i}.should == [1, 2, 'a', 'b'] + end + + it "returns nil when fails(legacy rubycon)" do + EnumerableSpecs::EachDefiner.new().inject {|acc,x| 999 }.should == nil + end + + it "tolerates increasing a collection size during iterating Array" do + array = [:a, :b, :c] + ScratchPad.record [] + i = 0 + + array.inject(nil) do |_, e| + ScratchPad << e + array << i if i < 100 + i += 1 + end + + actual = ScratchPad.recorded + expected = [:a, :b, :c] + (0..99).to_a + actual.sort_by(&:to_s).should == expected.sort_by(&:to_s) + end + + it "raises an ArgumentError when no parameters or block is given" do + -> { [1,2].inject }.should.raise(ArgumentError) + -> { {one: 1, two: 2}.inject }.should.raise(ArgumentError) + end end diff --git a/spec/ruby/core/enumerable/map_spec.rb b/spec/ruby/core/enumerable/map_spec.rb index 98a70781cf..e6447f5c23 100644 --- a/spec/ruby/core/enumerable/map_spec.rb +++ b/spec/ruby/core/enumerable/map_spec.rb @@ -1,7 +1,109 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/collect' +require_relative 'shared/enumerable_enumeratorized' describe "Enumerable#map" do - it_behaves_like :enumerable_collect, :map + before :each do + ScratchPad.record [] + end + + it "returns a new array with the results of passing each element to block" do + entries = [0, 1, 3, 4, 5, 6] + numerous = EnumerableSpecs::Numerous.new(*entries) + numerous.map { |i| i % 2 }.should == [0, 1, 1, 0, 1, 0] + numerous.map { |i| i }.should == entries + end + + it "passes through the values yielded by #each_with_index" do + [:a, :b].each_with_index.map { |x, i| ScratchPad << [x, i]; nil } + ScratchPad.recorded.should == [[:a, 0], [:b, 1]] + end + + it "gathers initial args as elements when each yields multiple" do + multi = EnumerableSpecs::YieldsMulti.new + multi.map {|e| e}.should == [1,3,6] + end + + it "only yields increasing values for a Range" do + (1..0).map { |x| x }.should == [] + (1..1).map { |x| x }.should == [1] + (1..2).map { |x| x }.should == [1, 2] + end + + it "returns an enumerator when no block given" do + enum = EnumerableSpecs::Numerous.new.map + enum.should.instance_of?(Enumerator) + enum.each { |i| -i }.should == [-2, -5, -3, -6, -1, -4] + end + + it "reports the same arity as the given block" do + entries = [0, 1, 3, 4, 5, 6] + numerous = EnumerableSpecs::Numerous.new(*entries) + + def numerous.each(&block) + ScratchPad << block.arity + super + end + + numerous.map { |a, b| a % 2 }.should == [0, 1, 1, 0, 1, 0] + ScratchPad.recorded.should == [2] + ScratchPad.clear + ScratchPad.record [] + numerous.map { |i| i }.should == entries + ScratchPad.recorded.should == [1] + end + + it "yields an Array of 2 elements for a Hash when block arity is 1" do + c = Class.new do + def register(a) + ScratchPad << a + end + end + m = c.new.method(:register) + + ScratchPad.record [] + { 1 => 'a', 2 => 'b' }.map(&m) + ScratchPad.recorded.should == [[1, 'a'], [2, 'b']] + end + + it "yields 2 arguments for a Hash when block arity is 2" do + c = Class.new do + def register(a, b) + ScratchPad << [a, b] + end + end + m = c.new.method(:register) + + ScratchPad.record [] + { 1 => 'a', 2 => 'b' }.map(&m) + ScratchPad.recorded.should == [[1, 'a'], [2, 'b']] + end + + it "raises an error for a Hash when an arity enforcing block of arity >2 is passed in" do + c = Class.new do + def register(a, b, c) + end + end + m = c.new.method(:register) + + -> do + { 1 => 'a', 2 => 'b' }.map(&m) + end.should.raise(ArgumentError) + end + + it "calls the each method on sub-classes" do + c = Class.new(Hash) do + def each + ScratchPad << 'in each' + super + end + end + h = c.new + h[1] = 'a' + ScratchPad.record [] + h.map { |k,v| v } + ScratchPad.recorded.should == ['in each'] + end + + it_behaves_like :enumerable_enumeratorized_with_origin_size, :map end diff --git a/spec/ruby/core/enumerable/member_spec.rb b/spec/ruby/core/enumerable/member_spec.rb index 1fe3cebd28..be06880ebb 100644 --- a/spec/ruby/core/enumerable/member_spec.rb +++ b/spec/ruby/core/enumerable/member_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/include' describe "Enumerable#member?" do - it_behaves_like :enumerable_include, :member? + it "is an alias of Enumerable#include?" do + Enumerable.instance_method(:member?).should == Enumerable.instance_method(:include?) + end end diff --git a/spec/ruby/core/enumerable/reduce_spec.rb b/spec/ruby/core/enumerable/reduce_spec.rb index bc8691c1b0..40452b66a1 100644 --- a/spec/ruby/core/enumerable/reduce_spec.rb +++ b/spec/ruby/core/enumerable/reduce_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/inject' describe "Enumerable#reduce" do - it_behaves_like :enumerable_inject, :reduce + it "is an alias of Enumerable#inject" do + Enumerable.instance_method(:reduce).should == Enumerable.instance_method(:inject) + end end diff --git a/spec/ruby/core/enumerable/select_spec.rb b/spec/ruby/core/enumerable/select_spec.rb index 7fc61926f9..a53c228a44 100644 --- a/spec/ruby/core/enumerable/select_spec.rb +++ b/spec/ruby/core/enumerable/select_spec.rb @@ -1,7 +1,33 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/find_all' +require_relative 'shared/enumerable_enumeratorized' describe "Enumerable#select" do - it_behaves_like :enumerable_find_all, :select + before :each do + ScratchPad.record [] + @elements = (1..10).to_a + @numerous = EnumerableSpecs::Numerous.new(*@elements) + end + + it "returns all elements for which the block is not false" do + @numerous.select {|i| i % 3 == 0 }.should == [3, 6, 9] + @numerous.select {|i| true }.should == @elements + @numerous.select {|i| false }.should == [] + end + + it "returns an enumerator when no block given" do + @numerous.select.should.instance_of?(Enumerator) + end + + it "passes through the values yielded by #each_with_index" do + [:a, :b].each_with_index.select { |x, i| ScratchPad << [x, i] } + ScratchPad.recorded.should == [[:a, 0], [:b, 1]] + end + + it "gathers whole arrays as elements when each yields multiple" do + multi = EnumerableSpecs::YieldsMulti.new + multi.select {|e| e == [3, 4, 5] }.should == [[3, 4, 5]] + end + + it_behaves_like :enumerable_enumeratorized_with_origin_size, :select end diff --git a/spec/ruby/core/enumerable/shared/collect.rb b/spec/ruby/core/enumerable/shared/collect.rb deleted file mode 100644 index 4696d32454..0000000000 --- a/spec/ruby/core/enumerable/shared/collect.rb +++ /dev/null @@ -1,107 +0,0 @@ -require_relative 'enumerable_enumeratorized' - -describe :enumerable_collect, shared: true do - before :each do - ScratchPad.record [] - end - - it "returns a new array with the results of passing each element to block" do - entries = [0, 1, 3, 4, 5, 6] - numerous = EnumerableSpecs::Numerous.new(*entries) - numerous.send(@method) { |i| i % 2 }.should == [0, 1, 1, 0, 1, 0] - numerous.send(@method) { |i| i }.should == entries - end - - it "passes through the values yielded by #each_with_index" do - [:a, :b].each_with_index.send(@method) { |x, i| ScratchPad << [x, i]; nil } - ScratchPad.recorded.should == [[:a, 0], [:b, 1]] - end - - it "gathers initial args as elements when each yields multiple" do - multi = EnumerableSpecs::YieldsMulti.new - multi.send(@method) {|e| e}.should == [1,3,6] - end - - it "only yields increasing values for a Range" do - (1..0).send(@method) { |x| x }.should == [] - (1..1).send(@method) { |x| x }.should == [1] - (1..2).send(@method) { |x| x }.should == [1, 2] - end - - it "returns an enumerator when no block given" do - enum = EnumerableSpecs::Numerous.new.send(@method) - enum.should.instance_of?(Enumerator) - enum.each { |i| -i }.should == [-2, -5, -3, -6, -1, -4] - end - - it "reports the same arity as the given block" do - entries = [0, 1, 3, 4, 5, 6] - numerous = EnumerableSpecs::Numerous.new(*entries) - - def numerous.each(&block) - ScratchPad << block.arity - super - end - - numerous.send(@method) { |a, b| a % 2 }.should == [0, 1, 1, 0, 1, 0] - ScratchPad.recorded.should == [2] - ScratchPad.clear - ScratchPad.record [] - numerous.send(@method) { |i| i }.should == entries - ScratchPad.recorded.should == [1] - end - - it "yields an Array of 2 elements for a Hash when block arity is 1" do - c = Class.new do - def register(a) - ScratchPad << a - end - end - m = c.new.method(:register) - - ScratchPad.record [] - { 1 => 'a', 2 => 'b' }.map(&m) - ScratchPad.recorded.should == [[1, 'a'], [2, 'b']] - end - - it "yields 2 arguments for a Hash when block arity is 2" do - c = Class.new do - def register(a, b) - ScratchPad << [a, b] - end - end - m = c.new.method(:register) - - ScratchPad.record [] - { 1 => 'a', 2 => 'b' }.map(&m) - ScratchPad.recorded.should == [[1, 'a'], [2, 'b']] - end - - it "raises an error for a Hash when an arity enforcing block of arity >2 is passed in" do - c = Class.new do - def register(a, b, c) - end - end - m = c.new.method(:register) - - -> do - { 1 => 'a', 2 => 'b' }.map(&m) - end.should.raise(ArgumentError) - end - - it "calls the each method on sub-classes" do - c = Class.new(Hash) do - def each - ScratchPad << 'in each' - super - end - end - h = c.new - h[1] = 'a' - ScratchPad.record [] - h.send(@method) { |k,v| v } - ScratchPad.recorded.should == ['in each'] - end - - it_should_behave_like :enumerable_enumeratorized_with_origin_size -end diff --git a/spec/ruby/core/enumerable/shared/collect_concat.rb b/spec/ruby/core/enumerable/shared/collect_concat.rb deleted file mode 100644 index 1694e3fdce..0000000000 --- a/spec/ruby/core/enumerable/shared/collect_concat.rb +++ /dev/null @@ -1,54 +0,0 @@ -require_relative 'enumerable_enumeratorized' - -describe :enumerable_collect_concat, shared: true do - it "yields elements to the block and flattens one level" do - numerous = EnumerableSpecs::Numerous.new(1, [2, 3], [4, [5, 6]], {foo: :bar}) - numerous.send(@method) { |i| i }.should == [1, 2, 3, 4, [5, 6], {foo: :bar}] - end - - it "appends non-Array elements that do not define #to_ary" do - obj = mock("to_ary undefined") - - numerous = EnumerableSpecs::Numerous.new(1, obj, 2) - numerous.send(@method) { |i| i }.should == [1, obj, 2] - end - - it "concatenates the result of calling #to_ary if it returns an Array" do - obj = mock("to_ary defined") - obj.should_receive(:to_ary).and_return([:a, :b]) - - numerous = EnumerableSpecs::Numerous.new(1, obj, 2) - numerous.send(@method) { |i| i }.should == [1, :a, :b, 2] - end - - it "does not call #to_a" do - obj = mock("to_ary undefined") - obj.should_not_receive(:to_a) - - numerous = EnumerableSpecs::Numerous.new(1, obj, 2) - numerous.send(@method) { |i| i }.should == [1, obj, 2] - end - - it "appends an element that defines #to_ary that returns nil" do - obj = mock("to_ary defined") - obj.should_receive(:to_ary).and_return(nil) - - numerous = EnumerableSpecs::Numerous.new(1, obj, 2) - numerous.send(@method) { |i| i }.should == [1, obj, 2] - end - - it "raises a TypeError if an element defining #to_ary does not return an Array or nil" do - obj = mock("to_ary defined") - obj.should_receive(:to_ary).and_return("array") - - -> { [1, obj, 3].send(@method) { |i| i } }.should.raise(TypeError) - end - - it "returns an enumerator when no block given" do - enum = EnumerableSpecs::Numerous.new(1, 2).send(@method) - enum.should.instance_of?(Enumerator) - enum.each{ |i| [i] * i }.should == [1, 2, 2] - end - - it_should_behave_like :enumerable_enumeratorized_with_origin_size -end diff --git a/spec/ruby/core/enumerable/shared/entries.rb b/spec/ruby/core/enumerable/shared/entries.rb deleted file mode 100644 index e32eb23d2a..0000000000 --- a/spec/ruby/core/enumerable/shared/entries.rb +++ /dev/null @@ -1,16 +0,0 @@ -describe :enumerable_entries, shared: true do - it "returns an array containing the elements" do - numerous = EnumerableSpecs::Numerous.new(1, nil, 'a', 2, false, true) - numerous.send(@method).should == [1, nil, "a", 2, false, true] - end - - it "passes through the values yielded by #each_with_index" do - [:a, :b].each_with_index.send(@method).should == [[:a, 0], [:b, 1]] - end - - it "passes arguments to each" do - count = EnumerableSpecs::EachCounter.new(1, 2, 3) - count.send(@method, :hello, "world").should == [1, 2, 3] - count.arguments_passed.should == [:hello, "world"] - end -end diff --git a/spec/ruby/core/enumerable/shared/find.rb b/spec/ruby/core/enumerable/shared/find.rb deleted file mode 100644 index cdff640415..0000000000 --- a/spec/ruby/core/enumerable/shared/find.rb +++ /dev/null @@ -1,77 +0,0 @@ -require_relative 'enumerable_enumeratorized' - -describe :enumerable_find, shared: true do - # #detect and #find are aliases, so we only need one function - before :each do - ScratchPad.record [] - @elements = [2, 4, 6, 8, 10] - @numerous = EnumerableSpecs::Numerous.new(*@elements) - @empty = [] - end - - it "passes each entry in enum to block while block when block is false" do - visited_elements = [] - @numerous.send(@method) do |element| - visited_elements << element - false - end - visited_elements.should == @elements - end - - it "returns nil when the block is false and there is no ifnone proc given" do - @numerous.send(@method) {|e| false }.should == nil - end - - it "returns the first element for which the block is not false" do - @elements.each do |element| - @numerous.send(@method) {|e| e > element - 1 }.should == element - end - end - - it "returns the value of the ifnone proc if the block is false" do - fail_proc = -> { "cheeseburgers" } - @numerous.send(@method, fail_proc) {|e| false }.should == "cheeseburgers" - end - - it "doesn't call the ifnone proc if an element is found" do - fail_proc = -> { raise "This shouldn't have been called" } - @numerous.send(@method, fail_proc) {|e| e == @elements.first }.should == 2 - end - - it "calls the ifnone proc only once when the block is false" do - times = 0 - fail_proc = -> { times += 1; raise if times > 1; "cheeseburgers" } - @numerous.send(@method, fail_proc) {|e| false }.should == "cheeseburgers" - end - - it "calls the ifnone proc when there are no elements" do - fail_proc = -> { "yay" } - @empty.send(@method, fail_proc) {|e| true}.should == "yay" - end - - it "ignores the ifnone argument when nil" do - @numerous.send(@method, nil) {|e| false }.should == nil - end - - it "passes through the values yielded by #each_with_index" do - [:a, :b].each_with_index.send(@method) { |x, i| ScratchPad << [x, i]; nil } - ScratchPad.recorded.should == [[:a, 0], [:b, 1]] - end - - it "returns an enumerator when no block given" do - @numerous.send(@method).should.instance_of?(Enumerator) - end - - it "passes the ifnone proc to the enumerator" do - times = 0 - fail_proc = -> { times += 1; raise if times > 1; "cheeseburgers" } - @numerous.send(@method, fail_proc).each {|e| false }.should == "cheeseburgers" - end - - it "gathers whole arrays as elements when each yields multiple" do - multi = EnumerableSpecs::YieldsMulti.new - multi.send(@method) {|e| e == [1, 2] }.should == [1, 2] - end - - it_should_behave_like :enumerable_enumeratorized_with_unknown_size -end diff --git a/spec/ruby/core/enumerable/shared/find_all.rb b/spec/ruby/core/enumerable/shared/find_all.rb deleted file mode 100644 index 27f01de6e0..0000000000 --- a/spec/ruby/core/enumerable/shared/find_all.rb +++ /dev/null @@ -1,31 +0,0 @@ -require_relative 'enumerable_enumeratorized' - -describe :enumerable_find_all, shared: true do - before :each do - ScratchPad.record [] - @elements = (1..10).to_a - @numerous = EnumerableSpecs::Numerous.new(*@elements) - end - - it "returns all elements for which the block is not false" do - @numerous.send(@method) {|i| i % 3 == 0 }.should == [3, 6, 9] - @numerous.send(@method) {|i| true }.should == @elements - @numerous.send(@method) {|i| false }.should == [] - end - - it "returns an enumerator when no block given" do - @numerous.send(@method).should.instance_of?(Enumerator) - end - - it "passes through the values yielded by #each_with_index" do - [:a, :b].each_with_index.send(@method) { |x, i| ScratchPad << [x, i] } - ScratchPad.recorded.should == [[:a, 0], [:b, 1]] - end - - it "gathers whole arrays as elements when each yields multiple" do - multi = EnumerableSpecs::YieldsMulti.new - multi.send(@method) {|e| e == [3, 4, 5] }.should == [[3, 4, 5]] - end - - it_should_behave_like :enumerable_enumeratorized_with_origin_size -end diff --git a/spec/ruby/core/enumerable/shared/include.rb b/spec/ruby/core/enumerable/shared/include.rb deleted file mode 100644 index ea250f032b..0000000000 --- a/spec/ruby/core/enumerable/shared/include.rb +++ /dev/null @@ -1,34 +0,0 @@ -describe :enumerable_include, shared: true do - it "returns true if any element == argument for numbers" do - class EnumerableSpecIncludeP; def ==(obj) obj == 5; end; end - - elements = (0..5).to_a - EnumerableSpecs::Numerous.new(*elements).send(@method,5).should == true - EnumerableSpecs::Numerous.new(*elements).send(@method,10).should == false - EnumerableSpecs::Numerous.new(*elements).send(@method,EnumerableSpecIncludeP.new).should == true - end - - it "returns true if any element == argument for other objects" do - class EnumerableSpecIncludeP11; def ==(obj); obj == '11'; end; end - - elements = ('0'..'5').to_a + [EnumerableSpecIncludeP11.new] - EnumerableSpecs::Numerous.new(*elements).send(@method,'5').should == true - EnumerableSpecs::Numerous.new(*elements).send(@method,'10').should == false - EnumerableSpecs::Numerous.new(*elements).send(@method,EnumerableSpecIncludeP11.new).should == true - EnumerableSpecs::Numerous.new(*elements).send(@method,'11').should == true - end - - - it "returns true if any member of enum equals obj when == compare different classes (legacy rubycon)" do - # equality is tested with == - EnumerableSpecs::Numerous.new(2,4,6,8,10).send(@method, 2.0).should == true - EnumerableSpecs::Numerous.new(2,4,[6,8],10).send(@method, [6, 8]).should == true - EnumerableSpecs::Numerous.new(2,4,[6,8],10).send(@method, [6.0, 8.0]).should == true - end - - it "gathers whole arrays as elements when each yields multiple" do - multi = EnumerableSpecs::YieldsMulti.new - multi.send(@method, [1,2]).should == true - end - -end diff --git a/spec/ruby/core/enumerable/shared/inject.rb b/spec/ruby/core/enumerable/shared/inject.rb deleted file mode 100644 index 7da4f0ca99..0000000000 --- a/spec/ruby/core/enumerable/shared/inject.rb +++ /dev/null @@ -1,142 +0,0 @@ -require_relative '../../array/shared/iterable_and_tolerating_size_increasing' - -describe :enumerable_inject, shared: true do - it "with argument takes a block with an accumulator (with argument as initial value) and the current element. Value of block becomes new accumulator" do - a = [] - EnumerableSpecs::Numerous.new.send(@method, 0) { |memo, i| a << [memo, i]; i } - a.should == [[0, 2], [2, 5], [5, 3], [3, 6], [6, 1], [1, 4]] - EnumerableSpecs::EachDefiner.new(true, true, true).send(@method, nil) {|result, i| i && result}.should == nil - end - - it "produces an array of the accumulator and the argument when given a block with a *arg" do - a = [] - [1,2].send(@method, 0) {|*args| a << args; args[0] + args[1]} - a.should == [[0, 1], [1, 2]] - end - - it "can take two argument" do - EnumerableSpecs::Numerous.new(1, 2, 3).send(@method, 10, :-).should == 4 - EnumerableSpecs::Numerous.new(1, 2, 3).send(@method, 10, "-").should == 4 - - [1, 2, 3].send(@method, 10, :-).should == 4 - [1, 2, 3].send(@method, 10, "-").should == 4 - end - - it "converts non-Symbol method name argument to String with #to_str if two arguments" do - name = Object.new - def name.to_str; "-"; end - - EnumerableSpecs::Numerous.new(1, 2, 3).send(@method, 10, name).should == 4 - [1, 2, 3].send(@method, 10, name).should == 4 - end - - it "raises TypeError when the second argument is not Symbol or String and it cannot be converted to String if two arguments" do - -> { EnumerableSpecs::Numerous.new(1, 2, 3).send(@method, 10, Object.new) }.should.raise(TypeError, /is not a symbol nor a string/) - -> { [1, 2, 3].send(@method, 10, Object.new) }.should.raise(TypeError, /is not a symbol nor a string/) - end - - it "ignores the block if two arguments" do - -> { - EnumerableSpecs::Numerous.new(1, 2, 3).send(@method, 10, :-) { raise "we never get here"}.should == 4 - }.should complain(/#{__FILE__}:#{__LINE__-1}: warning: given block not used/, verbose: true) - - -> { - [1, 2, 3].send(@method, 10, :-) { raise "we never get here"}.should == 4 - }.should complain(/#{__FILE__}:#{__LINE__-1}: warning: given block not used/, verbose: true) - end - - it "does not warn when given a Symbol with $VERBOSE true" do - -> { - [1, 2].send(@method, 0, :+) - [1, 2].send(@method, :+) - EnumerableSpecs::Numerous.new(1, 2).send(@method, 0, :+) - EnumerableSpecs::Numerous.new(1, 2).send(@method, :+) - }.should_not complain(verbose: true) - end - - it "can take a symbol argument" do - EnumerableSpecs::Numerous.new(10, 1, 2, 3).send(@method, :-).should == 4 - [10, 1, 2, 3].send(@method, :-).should == 4 - end - - it "can take a String argument" do - EnumerableSpecs::Numerous.new(10, 1, 2, 3).send(@method, "-").should == 4 - [10, 1, 2, 3].send(@method, "-").should == 4 - end - - it "converts non-Symbol method name argument to String with #to_str" do - name = Object.new - def name.to_str; "-"; end - - EnumerableSpecs::Numerous.new(10, 1, 2, 3).send(@method, name).should == 4 - [10, 1, 2, 3].send(@method, name).should == 4 - end - - it "raises TypeError when passed not Symbol or String method name argument and it cannot be converted to String" do - -> { EnumerableSpecs::Numerous.new(10, 1, 2, 3).send(@method, Object.new) }.should.raise(TypeError, /is not a symbol nor a string/) - -> { [10, 1, 2, 3].send(@method, Object.new) }.should.raise(TypeError, /is not a symbol nor a string/) - end - - it "without argument takes a block with an accumulator (with first element as initial value) and the current element. Value of block becomes new accumulator" do - a = [] - EnumerableSpecs::Numerous.new.send(@method) { |memo, i| a << [memo, i]; i } - a.should == [[2, 5], [5, 3], [3, 6], [6, 1], [1, 4]] - end - - it "gathers whole arrays as elements when each yields multiple" do - multi = EnumerableSpecs::YieldsMulti.new - multi.send(@method, []) {|acc, e| acc << e }.should == [[1, 2], [3, 4, 5], [6, 7, 8, 9]] - end - - it "with inject arguments(legacy rubycon)" do - # with inject argument - EnumerableSpecs::EachDefiner.new().send(@method, 1) {|acc,x| 999 }.should == 1 - EnumerableSpecs::EachDefiner.new(2).send(@method, 1) {|acc,x| 999 }.should == 999 - EnumerableSpecs::EachDefiner.new(2).send(@method, 1) {|acc,x| acc }.should == 1 - EnumerableSpecs::EachDefiner.new(2).send(@method, 1) {|acc,x| x }.should == 2 - - EnumerableSpecs::EachDefiner.new(1,2,3,4).send(@method, 100) {|acc,x| acc + x }.should == 110 - EnumerableSpecs::EachDefiner.new(1,2,3,4).send(@method, 100) {|acc,x| acc * x }.should == 2400 - - EnumerableSpecs::EachDefiner.new('a','b','c').send(@method, "z") {|result, i| i+result}.should == "cbaz" - end - - it "without inject arguments(legacy rubycon)" do - # no inject argument - EnumerableSpecs::EachDefiner.new(2).send(@method) {|acc,x| 999 }.should == 2 - EnumerableSpecs::EachDefiner.new(2).send(@method) {|acc,x| acc }.should == 2 - EnumerableSpecs::EachDefiner.new(2).send(@method) {|acc,x| x }.should == 2 - - EnumerableSpecs::EachDefiner.new(1,2,3,4).send(@method) {|acc,x| acc + x }.should == 10 - EnumerableSpecs::EachDefiner.new(1,2,3,4).send(@method) {|acc,x| acc * x }.should == 24 - - EnumerableSpecs::EachDefiner.new('a','b','c').send(@method) {|result, i| i+result}.should == "cba" - EnumerableSpecs::EachDefiner.new(3, 4, 5).send(@method) {|result, i| result*i}.should == 60 - EnumerableSpecs::EachDefiner.new([1], 2, 'a','b').send(@method){|r,i| r<<i}.should == [1, 2, 'a', 'b'] - end - - it "returns nil when fails(legacy rubycon)" do - EnumerableSpecs::EachDefiner.new().send(@method) {|acc,x| 999 }.should == nil - end - - it "tolerates increasing a collection size during iterating Array" do - array = [:a, :b, :c] - ScratchPad.record [] - i = 0 - - array.send(@method, nil) do |_, e| - ScratchPad << e - array << i if i < 100 - i += 1 - end - - actual = ScratchPad.recorded - expected = [:a, :b, :c] + (0..99).to_a - actual.sort_by(&:to_s).should == expected.sort_by(&:to_s) - end - - it "raises an ArgumentError when no parameters or block is given" do - -> { [1,2].send(@method) }.should.raise(ArgumentError) - -> { {one: 1, two: 2}.send(@method) }.should.raise(ArgumentError) - end -end diff --git a/spec/ruby/core/enumerable/to_a_spec.rb b/spec/ruby/core/enumerable/to_a_spec.rb index 723f922574..f1796070f0 100644 --- a/spec/ruby/core/enumerable/to_a_spec.rb +++ b/spec/ruby/core/enumerable/to_a_spec.rb @@ -1,7 +1,19 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/entries' describe "Enumerable#to_a" do - it_behaves_like :enumerable_entries, :to_a + it "returns an array containing the elements" do + numerous = EnumerableSpecs::Numerous.new(1, nil, 'a', 2, false, true) + numerous.to_a.should == [1, nil, "a", 2, false, true] + end + + it "passes through the values yielded by #each_with_index" do + [:a, :b].each_with_index.to_a.should == [[:a, 0], [:b, 1]] + end + + it "passes arguments to each" do + count = EnumerableSpecs::EachCounter.new(1, 2, 3) + count.to_a(:hello, "world").should == [1, 2, 3] + count.arguments_passed.should == [:hello, "world"] + end end diff --git a/spec/ruby/core/enumerator/each_spec.rb b/spec/ruby/core/enumerator/each_spec.rb index 03be53fe05..64912b98b6 100644 --- a/spec/ruby/core/enumerator/each_spec.rb +++ b/spec/ruby/core/enumerator/each_spec.rb @@ -1,6 +1,21 @@ require_relative '../../spec_helper' +require_relative 'shared/each' describe "Enumerator#each" do + describe "passing source-yielded arguments to the block" do + before :each do + @object = -> e { e } + end + it_behaves_like :enum_each, nil + end + + describe "passing source-yielded arguments to the block (lazy)" do + before :each do + @object = -> e { e.lazy } + end + it_behaves_like :enum_each, nil + end + before :each do object_each_with_arguments = Object.new def object_each_with_arguments.each_with_arguments(arg, *args) diff --git a/spec/ruby/core/enumerator/each_with_object_spec.rb b/spec/ruby/core/enumerator/each_with_object_spec.rb index 84a45ae89d..0e0a4496f4 100644 --- a/spec/ruby/core/enumerator/each_with_object_spec.rb +++ b/spec/ruby/core/enumerator/each_with_object_spec.rb @@ -1,6 +1,42 @@ require_relative '../../spec_helper' -require_relative 'shared/with_object' describe "Enumerator#each_with_object" do - it_behaves_like :enum_with_object, :each_with_object + before :each do + @enum = [:a, :b].to_enum + @memo = '' + @block_params = @enum.each_with_object(@memo).to_a + end + + it "receives an argument" do + @enum.method(:each_with_object).arity.should == 1 + end + + context "with block" do + it "returns the given object" do + ret = @enum.each_with_object(@memo) do |elm, memo| + # nothing + end + ret.should.equal?(@memo) + end + + context "the block parameter" do + it "passes each element to first parameter" do + @block_params[0][0].should.equal?(:a) + @block_params[1][0].should.equal?(:b) + end + + it "passes the given object to last parameter" do + @block_params[0][1].should.equal?(@memo) + @block_params[1][1].should.equal?(@memo) + end + end + end + + context "without block" do + it "returns new Enumerator" do + ret = @enum.each_with_object(@memo) + ret.should.instance_of?(Enumerator) + ret.should_not.equal?(@enum) + end + end end diff --git a/spec/ruby/core/enumerator/enum_for_spec.rb b/spec/ruby/core/enumerator/enum_for_spec.rb deleted file mode 100644 index fbdf98545a..0000000000 --- a/spec/ruby/core/enumerator/enum_for_spec.rb +++ /dev/null @@ -1,6 +0,0 @@ -require_relative '../../spec_helper' -require_relative 'shared/enum_for' - -describe "Enumerator#enum_for" do - it_behaves_like :enum_for, :enum_for -end diff --git a/spec/ruby/core/enumerator/lazy/collect_concat_spec.rb b/spec/ruby/core/enumerator/lazy/collect_concat_spec.rb index 8765bb2190..d9fd576e43 100644 --- a/spec/ruby/core/enumerator/lazy/collect_concat_spec.rb +++ b/spec/ruby/core/enumerator/lazy/collect_concat_spec.rb @@ -1,8 +1,8 @@ -# -*- encoding: us-ascii -*- - require_relative '../../../spec_helper' -require_relative 'shared/collect_concat' describe "Enumerator::Lazy#collect_concat" do - it_behaves_like :enumerator_lazy_collect_concat, :collect_concat + it "is an alias of Enumerator::Lazy#flat_map" do + Enumerator::Lazy.instance_method(:collect_concat).should == + Enumerator::Lazy.instance_method(:flat_map) + end end diff --git a/spec/ruby/core/enumerator/lazy/collect_spec.rb b/spec/ruby/core/enumerator/lazy/collect_spec.rb index 14b79ce16d..53a477e053 100644 --- a/spec/ruby/core/enumerator/lazy/collect_spec.rb +++ b/spec/ruby/core/enumerator/lazy/collect_spec.rb @@ -1,8 +1,8 @@ -# -*- encoding: us-ascii -*- - require_relative '../../../spec_helper' -require_relative 'shared/collect' describe "Enumerator::Lazy#collect" do - it_behaves_like :enumerator_lazy_collect, :collect + it "is an alias of Enumerator::Lazy#map" do + Enumerator::Lazy.instance_method(:collect).should == + Enumerator::Lazy.instance_method(:map) + end end diff --git a/spec/ruby/core/enumerator/lazy/enum_for_spec.rb b/spec/ruby/core/enumerator/lazy/enum_for_spec.rb index 7e7783f6f1..b40c5d9915 100644 --- a/spec/ruby/core/enumerator/lazy/enum_for_spec.rb +++ b/spec/ruby/core/enumerator/lazy/enum_for_spec.rb @@ -1,8 +1,8 @@ -# -*- encoding: us-ascii -*- - require_relative '../../../spec_helper' -require_relative 'shared/to_enum' describe "Enumerator::Lazy#enum_for" do - it_behaves_like :enumerator_lazy_to_enum, :enum_for + it "is an alias of Enumerator::Lazy#to_enum" do + Enumerator::Lazy.instance_method(:enum_for).should == + Enumerator::Lazy.instance_method(:to_enum) + end end diff --git a/spec/ruby/core/enumerator/lazy/filter_spec.rb b/spec/ruby/core/enumerator/lazy/filter_spec.rb index 43128241e0..3ca5376faa 100644 --- a/spec/ruby/core/enumerator/lazy/filter_spec.rb +++ b/spec/ruby/core/enumerator/lazy/filter_spec.rb @@ -1,6 +1,8 @@ require_relative '../../../spec_helper' -require_relative 'shared/select' describe "Enumerator::Lazy#filter" do - it_behaves_like :enumerator_lazy_select, :filter + it "is an alias of Enumerator::Lazy#select" do + Enumerator::Lazy.instance_method(:filter).should == + Enumerator::Lazy.instance_method(:select) + end end diff --git a/spec/ruby/core/enumerator/lazy/find_all_spec.rb b/spec/ruby/core/enumerator/lazy/find_all_spec.rb index 8b05c53803..64930dc61b 100644 --- a/spec/ruby/core/enumerator/lazy/find_all_spec.rb +++ b/spec/ruby/core/enumerator/lazy/find_all_spec.rb @@ -1,8 +1,8 @@ -# -*- encoding: us-ascii -*- - require_relative '../../../spec_helper' -require_relative 'shared/select' describe "Enumerator::Lazy#find_all" do - it_behaves_like :enumerator_lazy_select, :find_all + it "is an alias of Enumerator::Lazy#select" do + Enumerator::Lazy.instance_method(:find_all).should == + Enumerator::Lazy.instance_method(:select) + end end diff --git a/spec/ruby/core/enumerator/lazy/flat_map_spec.rb b/spec/ruby/core/enumerator/lazy/flat_map_spec.rb index 5dcaa8bfa1..609bf95b9e 100644 --- a/spec/ruby/core/enumerator/lazy/flat_map_spec.rb +++ b/spec/ruby/core/enumerator/lazy/flat_map_spec.rb @@ -1,10 +1,78 @@ -# -*- encoding: us-ascii -*- - require_relative '../../../spec_helper' -require_relative 'shared/collect_concat' +require_relative 'fixtures/classes' describe "Enumerator::Lazy#flat_map" do - it_behaves_like :enumerator_lazy_collect_concat, :flat_map + before :each do + @yieldsmixed = EnumeratorLazySpecs::YieldsMixed.new.to_enum.lazy + @eventsmixed = EnumeratorLazySpecs::EventsMixed.new.to_enum.lazy + ScratchPad.record [] + end + + after :each do + ScratchPad.clear + end + + it "returns a new instance of Enumerator::Lazy" do + ret = @yieldsmixed.flat_map {} + ret.should.instance_of?(Enumerator::Lazy) + ret.should_not.equal?(@yieldsmixed) + end + + it "sets #size to nil" do + Enumerator::Lazy.new(Object.new, 100) {}.flat_map { true }.size.should == nil + end + + describe "when the returned lazy enumerator is evaluated by Enumerable#first" do + it "stops after specified times" do + (0..Float::INFINITY).lazy.flat_map { |n| (n * 10).to_s }.first(6).should == %w[0 10 20 30 40 50] + + @eventsmixed.flat_map {}.first(1) + ScratchPad.recorded.should == [:before_yield] + end + + it "flattens elements when the given block returned an array or responding to .each and .force" do + (0..Float::INFINITY).lazy.flat_map { |n| (n * 10).to_s.chars }.first(6).should == %w[0 1 0 2 0 3] + (0..Float::INFINITY).lazy.flat_map { |n| (n * 10).to_s.each_char }.first(6).all? { |o| o.instance_of? Enumerator }.should == true + (0..Float::INFINITY).lazy.flat_map { |n| (n * 10).to_s.each_char.lazy }.first(6).should == %w[0 1 0 2 0 3] + end + end + + it "calls the block with initial values when yield with multiple arguments" do + yields = [] + @yieldsmixed.flat_map { |v| yields << v }.force + yields.should == EnumeratorLazySpecs::YieldsMixed.initial_yields + end + + it "raises an ArgumentError when not given a block" do + -> { @yieldsmixed.flat_map }.should.raise(ArgumentError) + end + + describe "on a nested Lazy" do + it "sets #size to nil" do + Enumerator::Lazy.new(Object.new, 100) {}.take(50) {}.flat_map {}.size.should == nil + end + + describe "when the returned lazy enumerator is evaluated by Enumerable#first" do + it "stops after specified times" do + (0..Float::INFINITY).lazy.map {|n| n * 10 }.flat_map { |n| n.to_s }.first(6).should == %w[0 10 20 30 40 50] + + @eventsmixed.flat_map {}.flat_map {}.first(1) + ScratchPad.recorded.should == [:before_yield] + end + + it "flattens elements when the given block returned an array or responding to .each and .force" do + (0..Float::INFINITY).lazy.map {|n| n * 10 }.flat_map { |n| n.to_s.chars }.first(6).should == %w[0 1 0 2 0 3] + (0..Float::INFINITY).lazy.map {|n| n * 10 }.flat_map { |n| n.to_s.each_char }.first(6).all? { |o| o.instance_of? Enumerator }.should == true + (0..Float::INFINITY).lazy.map {|n| n * 10 }.flat_map { |n| n.to_s.each_char.lazy }.first(6).should == %w[0 1 0 2 0 3] + end + end + end + + it "works with an infinite enumerable" do + s = 0..Float::INFINITY + s.lazy.flat_map { |n| [-n, +n] }.first(200).should == + s.first(100).flat_map { |n| [-n, +n] }.to_a + end it "properly unwraps nested yields" do s = Enumerator.new do |y| loop do y << [1, 2] end end diff --git a/spec/ruby/core/enumerator/lazy/map_spec.rb b/spec/ruby/core/enumerator/lazy/map_spec.rb index 5cb998f5f7..2c7f8efab8 100644 --- a/spec/ruby/core/enumerator/lazy/map_spec.rb +++ b/spec/ruby/core/enumerator/lazy/map_spec.rb @@ -1,10 +1,62 @@ -# -*- encoding: us-ascii -*- - require_relative '../../../spec_helper' -require_relative 'shared/collect' +require_relative 'fixtures/classes' describe "Enumerator::Lazy#map" do - it_behaves_like :enumerator_lazy_collect, :map + before :each do + @yieldsmixed = EnumeratorLazySpecs::YieldsMixed.new.to_enum.lazy + @eventsmixed = EnumeratorLazySpecs::EventsMixed.new.to_enum.lazy + ScratchPad.record [] + end + + after :each do + ScratchPad.clear + end + + it "returns a new instance of Enumerator::Lazy" do + ret = @yieldsmixed.map {} + ret.should.instance_of?(Enumerator::Lazy) + ret.should_not.equal?(@yieldsmixed) + end + + it "keeps size" do + Enumerator::Lazy.new(Object.new, 100) {}.map {}.size.should == 100 + end + + describe "when the returned lazy enumerator is evaluated by Enumerable#first" do + it "stops after specified times" do + (0..Float::INFINITY).lazy.map(&:succ).first(3).should == [1, 2, 3] + + @eventsmixed.map {}.first(1) + ScratchPad.recorded.should == [:before_yield] + end + end + + it "calls the block with initial values when yield with multiple arguments" do + yields = [] + @yieldsmixed.map { |v| yields << v }.force + yields.should == EnumeratorLazySpecs::YieldsMixed.initial_yields + end + + describe "on a nested Lazy" do + it "keeps size" do + Enumerator::Lazy.new(Object.new, 100) {}.map {}.map {}.size.should == 100 + end + + describe "when the returned lazy enumerator is evaluated by Enumerable#first" do + it "stops after specified times" do + (0..Float::INFINITY).lazy.map(&:succ).map(&:succ).first(3).should == [2, 3, 4] + + @eventsmixed.map {}.map {}.first(1) + ScratchPad.recorded.should == [:before_yield] + end + end + end + + it "works with an infinite enumerable" do + s = 0..Float::INFINITY + s.lazy.map { |n| n }.first(100).should == + s.first(100).map { |n| n }.to_a + end it "doesn't unwrap Arrays" do Enumerator.new {|y| y.yield([1])}.lazy.to_a.should == [[1]] diff --git a/spec/ruby/core/enumerator/lazy/select_spec.rb b/spec/ruby/core/enumerator/lazy/select_spec.rb index 3773d8f0a8..29c8f1bd80 100644 --- a/spec/ruby/core/enumerator/lazy/select_spec.rb +++ b/spec/ruby/core/enumerator/lazy/select_spec.rb @@ -1,10 +1,66 @@ -# -*- encoding: us-ascii -*- - require_relative '../../../spec_helper' -require_relative 'shared/select' +require_relative 'fixtures/classes' describe "Enumerator::Lazy#select" do - it_behaves_like :enumerator_lazy_select, :select + before :each do + @yieldsmixed = EnumeratorLazySpecs::YieldsMixed.new.to_enum.lazy + @eventsmixed = EnumeratorLazySpecs::EventsMixed.new.to_enum.lazy + ScratchPad.record [] + end + + after :each do + ScratchPad.clear + end + + it "returns a new instance of Enumerator::Lazy" do + ret = @yieldsmixed.select {} + ret.should.instance_of?(Enumerator::Lazy) + ret.should_not.equal?(@yieldsmixed) + end + + it "sets #size to nil" do + Enumerator::Lazy.new(Object.new, 100) {}.select { true }.size.should == nil + end + + describe "when the returned lazy enumerator is evaluated by Enumerable#first" do + it "stops after specified times" do + (0..Float::INFINITY).lazy.select(&:even?).first(3).should == [0, 2, 4] + + @eventsmixed.select { true }.first(1) + ScratchPad.recorded.should == [:before_yield] + end + end + + it "calls the block with a gathered array when yield with multiple arguments" do + yields = [] + @yieldsmixed.select { |v| yields << v }.force + yields.should == EnumeratorLazySpecs::YieldsMixed.gathered_yields + end + + it "raises an ArgumentError when not given a block" do + -> { @yieldsmixed.select }.should.raise(ArgumentError) + end + + describe "on a nested Lazy" do + it "sets #size to nil" do + Enumerator::Lazy.new(Object.new, 100) {}.take(50) {}.select { true }.size.should == nil + end + + describe "when the returned lazy enumerator is evaluated by Enumerable#first" do + it "stops after specified times" do + (0..Float::INFINITY).lazy.select { |n| n > 5 }.select(&:even?).first(3).should == [6, 8, 10] + + @eventsmixed.select { true }.select { true }.first(1) + ScratchPad.recorded.should == [:before_yield] + end + end + end + + it "works with an infinite enumerable" do + s = 0..Float::INFINITY + s.lazy.select { |n| true }.first(100).should == + s.first(100).select { |n| true } + end it "doesn't pre-evaluate the next element" do eval_count = 0 diff --git a/spec/ruby/core/enumerator/lazy/shared/collect.rb b/spec/ruby/core/enumerator/lazy/shared/collect.rb deleted file mode 100644 index 0ed04c8e02..0000000000 --- a/spec/ruby/core/enumerator/lazy/shared/collect.rb +++ /dev/null @@ -1,62 +0,0 @@ -# -*- encoding: us-ascii -*- - -require_relative '../../../../spec_helper' -require_relative '../fixtures/classes' - -describe :enumerator_lazy_collect, shared: true do - before :each do - @yieldsmixed = EnumeratorLazySpecs::YieldsMixed.new.to_enum.lazy - @eventsmixed = EnumeratorLazySpecs::EventsMixed.new.to_enum.lazy - ScratchPad.record [] - end - - after :each do - ScratchPad.clear - end - - it "returns a new instance of Enumerator::Lazy" do - ret = @yieldsmixed.send(@method) {} - ret.should.instance_of?(Enumerator::Lazy) - ret.should_not.equal?(@yieldsmixed) - end - - it "keeps size" do - Enumerator::Lazy.new(Object.new, 100) {}.send(@method) {}.size.should == 100 - end - - describe "when the returned lazy enumerator is evaluated by Enumerable#first" do - it "stops after specified times" do - (0..Float::INFINITY).lazy.send(@method, &:succ).first(3).should == [1, 2, 3] - - @eventsmixed.send(@method) {}.first(1) - ScratchPad.recorded.should == [:before_yield] - end - end - - it "calls the block with initial values when yield with multiple arguments" do - yields = [] - @yieldsmixed.send(@method) { |v| yields << v }.force - yields.should == EnumeratorLazySpecs::YieldsMixed.initial_yields - end - - describe "on a nested Lazy" do - it "keeps size" do - Enumerator::Lazy.new(Object.new, 100) {}.send(@method) {}.send(@method) {}.size.should == 100 - end - - describe "when the returned lazy enumerator is evaluated by Enumerable#first" do - it "stops after specified times" do - (0..Float::INFINITY).lazy.send(@method, &:succ).send(@method, &:succ).first(3).should == [2, 3, 4] - - @eventsmixed.send(@method) {}.send(@method) {}.first(1) - ScratchPad.recorded.should == [:before_yield] - end - end - end - - it "works with an infinite enumerable" do - s = 0..Float::INFINITY - s.lazy.send(@method) { |n| n }.first(100).should == - s.first(100).send(@method) { |n| n }.to_a - end -end diff --git a/spec/ruby/core/enumerator/lazy/shared/collect_concat.rb b/spec/ruby/core/enumerator/lazy/shared/collect_concat.rb deleted file mode 100644 index 685e6d0594..0000000000 --- a/spec/ruby/core/enumerator/lazy/shared/collect_concat.rb +++ /dev/null @@ -1,78 +0,0 @@ -# -*- encoding: us-ascii -*- - -require_relative '../../../../spec_helper' -require_relative '../fixtures/classes' - -describe :enumerator_lazy_collect_concat, shared: true do - before :each do - @yieldsmixed = EnumeratorLazySpecs::YieldsMixed.new.to_enum.lazy - @eventsmixed = EnumeratorLazySpecs::EventsMixed.new.to_enum.lazy - ScratchPad.record [] - end - - after :each do - ScratchPad.clear - end - - it "returns a new instance of Enumerator::Lazy" do - ret = @yieldsmixed.send(@method) {} - ret.should.instance_of?(Enumerator::Lazy) - ret.should_not.equal?(@yieldsmixed) - end - - it "sets #size to nil" do - Enumerator::Lazy.new(Object.new, 100) {}.send(@method) { true }.size.should == nil - end - - describe "when the returned lazy enumerator is evaluated by Enumerable#first" do - it "stops after specified times" do - (0..Float::INFINITY).lazy.send(@method) { |n| (n * 10).to_s }.first(6).should == %w[0 10 20 30 40 50] - - @eventsmixed.send(@method) {}.first(1) - ScratchPad.recorded.should == [:before_yield] - end - - it "flattens elements when the given block returned an array or responding to .each and .force" do - (0..Float::INFINITY).lazy.send(@method) { |n| (n * 10).to_s.chars }.first(6).should == %w[0 1 0 2 0 3] - (0..Float::INFINITY).lazy.send(@method) { |n| (n * 10).to_s.each_char }.first(6).all? { |o| o.instance_of? Enumerator }.should == true - (0..Float::INFINITY).lazy.send(@method) { |n| (n * 10).to_s.each_char.lazy }.first(6).should == %w[0 1 0 2 0 3] - end - end - - it "calls the block with initial values when yield with multiple arguments" do - yields = [] - @yieldsmixed.send(@method) { |v| yields << v }.force - yields.should == EnumeratorLazySpecs::YieldsMixed.initial_yields - end - - it "raises an ArgumentError when not given a block" do - -> { @yieldsmixed.send(@method) }.should.raise(ArgumentError) - end - - describe "on a nested Lazy" do - it "sets #size to nil" do - Enumerator::Lazy.new(Object.new, 100) {}.take(50) {}.send(@method) {}.size.should == nil - end - - describe "when the returned lazy enumerator is evaluated by Enumerable#first" do - it "stops after specified times" do - (0..Float::INFINITY).lazy.map {|n| n * 10 }.send(@method) { |n| n.to_s }.first(6).should == %w[0 10 20 30 40 50] - - @eventsmixed.send(@method) {}.send(@method) {}.first(1) - ScratchPad.recorded.should == [:before_yield] - end - - it "flattens elements when the given block returned an array or responding to .each and .force" do - (0..Float::INFINITY).lazy.map {|n| n * 10 }.send(@method) { |n| n.to_s.chars }.first(6).should == %w[0 1 0 2 0 3] - (0..Float::INFINITY).lazy.map {|n| n * 10 }.send(@method) { |n| n.to_s.each_char }.first(6).all? { |o| o.instance_of? Enumerator }.should == true - (0..Float::INFINITY).lazy.map {|n| n * 10 }.send(@method) { |n| n.to_s.each_char.lazy }.first(6).should == %w[0 1 0 2 0 3] - end - end - end - - it "works with an infinite enumerable" do - s = 0..Float::INFINITY - s.lazy.send(@method) { |n| [-n, +n] }.first(200).should == - s.first(100).send(@method) { |n| [-n, +n] }.to_a - end -end diff --git a/spec/ruby/core/enumerator/lazy/shared/select.rb b/spec/ruby/core/enumerator/lazy/shared/select.rb deleted file mode 100644 index 2d15176620..0000000000 --- a/spec/ruby/core/enumerator/lazy/shared/select.rb +++ /dev/null @@ -1,66 +0,0 @@ -# -*- encoding: us-ascii -*- - -require_relative '../../../../spec_helper' -require_relative '../fixtures/classes' - -describe :enumerator_lazy_select, shared: true do - before :each do - @yieldsmixed = EnumeratorLazySpecs::YieldsMixed.new.to_enum.lazy - @eventsmixed = EnumeratorLazySpecs::EventsMixed.new.to_enum.lazy - ScratchPad.record [] - end - - after :each do - ScratchPad.clear - end - - it "returns a new instance of Enumerator::Lazy" do - ret = @yieldsmixed.send(@method) {} - ret.should.instance_of?(Enumerator::Lazy) - ret.should_not.equal?(@yieldsmixed) - end - - it "sets #size to nil" do - Enumerator::Lazy.new(Object.new, 100) {}.send(@method) { true }.size.should == nil - end - - describe "when the returned lazy enumerator is evaluated by Enumerable#first" do - it "stops after specified times" do - (0..Float::INFINITY).lazy.send(@method, &:even?).first(3).should == [0, 2, 4] - - @eventsmixed.send(@method) { true }.first(1) - ScratchPad.recorded.should == [:before_yield] - end - end - - it "calls the block with a gathered array when yield with multiple arguments" do - yields = [] - @yieldsmixed.send(@method) { |v| yields << v }.force - yields.should == EnumeratorLazySpecs::YieldsMixed.gathered_yields - end - - it "raises an ArgumentError when not given a block" do - -> { @yieldsmixed.send(@method) }.should.raise(ArgumentError) - end - - describe "on a nested Lazy" do - it "sets #size to nil" do - Enumerator::Lazy.new(Object.new, 100) {}.take(50) {}.send(@method) { true }.size.should == nil - end - - describe "when the returned lazy enumerator is evaluated by Enumerable#first" do - it "stops after specified times" do - (0..Float::INFINITY).lazy.send(@method) { |n| n > 5 }.send(@method, &:even?).first(3).should == [6, 8, 10] - - @eventsmixed.send(@method) { true }.send(@method) { true }.first(1) - ScratchPad.recorded.should == [:before_yield] - end - end - end - - it "works with an infinite enumerable" do - s = 0..Float::INFINITY - s.lazy.send(@method) { |n| true }.first(100).should == - s.first(100).send(@method) { |n| true } - end -end diff --git a/spec/ruby/core/enumerator/lazy/shared/to_enum.rb b/spec/ruby/core/enumerator/lazy/shared/to_enum.rb deleted file mode 100644 index 75b9aefe8c..0000000000 --- a/spec/ruby/core/enumerator/lazy/shared/to_enum.rb +++ /dev/null @@ -1,55 +0,0 @@ -# -*- encoding: us-ascii -*- - -require_relative '../../../../spec_helper' - -describe :enumerator_lazy_to_enum, shared: true do - before :each do - @infinite = (0..Float::INFINITY).lazy - end - - it "requires multiple arguments" do - Enumerator::Lazy.instance_method(@method).arity.should < 0 - end - - it "returns a new instance of Enumerator::Lazy" do - ret = @infinite.send @method - ret.should.instance_of?(Enumerator::Lazy) - ret.should_not.equal?(@infinite) - end - - it "sets #size to nil when not given a block" do - Enumerator::Lazy.new(Object.new, 100) {}.send(@method).size.should == nil - end - - it "sets given block to size when given a block" do - Enumerator::Lazy.new(Object.new, 100) {}.send(@method) { 30 }.size.should == 30 - end - - it "generates a lazy enumerator from the given name" do - @infinite.send(@method, :with_index, 10).first(3).should == [[0, 10], [1, 11], [2, 12]] - end - - it "passes given arguments to wrapped method" do - @infinite.send(@method, :each_slice, 2).map { |assoc| assoc.first * assoc.last }.first(4).should == [0, 6, 20, 42] - end - - it "used by some parent's methods though returning Lazy" do - { each_with_index: [], - with_index: [], - cycle: [1], - each_with_object: [Object.new], - with_object: [Object.new], - each_slice: [2], - each_entry: [], - each_cons: [2] - }.each_pair do |method, args| - @infinite.send(method, *args).should.instance_of?(Enumerator::Lazy) - end - end - - it "works with an infinite enumerable" do - s = 0..Float::INFINITY - s.lazy.send(@method, :with_index).first(100).should == - s.first(100).to_enum.send(@method, :with_index).to_a - end -end diff --git a/spec/ruby/core/enumerator/lazy/to_enum_spec.rb b/spec/ruby/core/enumerator/lazy/to_enum_spec.rb index 210e5294b7..c0233d60fa 100644 --- a/spec/ruby/core/enumerator/lazy/to_enum_spec.rb +++ b/spec/ruby/core/enumerator/lazy/to_enum_spec.rb @@ -1,8 +1,54 @@ -# -*- encoding: us-ascii -*- - require_relative '../../../spec_helper' -require_relative 'shared/to_enum' +require_relative 'fixtures/classes' describe "Enumerator::Lazy#to_enum" do - it_behaves_like :enumerator_lazy_to_enum, :to_enum + before :each do + @infinite = (0..Float::INFINITY).lazy + end + + it "requires multiple arguments" do + Enumerator::Lazy.instance_method(:to_enum).arity.should < 0 + end + + it "returns a new instance of Enumerator::Lazy" do + ret = @infinite.to_enum + ret.should.instance_of?(Enumerator::Lazy) + ret.should_not.equal?(@infinite) + end + + it "sets #size to nil when not given a block" do + Enumerator::Lazy.new(Object.new, 100) {}.to_enum.size.should == nil + end + + it "sets given block to size when given a block" do + Enumerator::Lazy.new(Object.new, 100) {}.to_enum { 30 }.size.should == 30 + end + + it "generates a lazy enumerator from the given name" do + @infinite.to_enum(:with_index, 10).first(3).should == [[0, 10], [1, 11], [2, 12]] + end + + it "passes given arguments to wrapped method" do + @infinite.to_enum(:each_slice, 2).map { |assoc| assoc.first * assoc.last }.first(4).should == [0, 6, 20, 42] + end + + it "used by some parent's methods though returning Lazy" do + { each_with_index: [], + with_index: [], + cycle: [1], + each_with_object: [Object.new], + with_object: [Object.new], + each_slice: [2], + each_entry: [], + each_cons: [2] + }.each_pair do |method, args| + @infinite.send(method, *args).should.instance_of?(Enumerator::Lazy) + end + end + + it "works with an infinite enumerable" do + s = 0..Float::INFINITY + s.lazy.to_enum(:with_index).first(100).should == + s.first(100).to_enum.to_enum(:with_index).to_a + end end diff --git a/spec/ruby/core/enumerator/shared/each.rb b/spec/ruby/core/enumerator/shared/each.rb new file mode 100644 index 0000000000..18ca773207 --- /dev/null +++ b/spec/ruby/core/enumerator/shared/each.rb @@ -0,0 +1,46 @@ +# #each passes source-yielded values to the block by ordinary block arity +# (rb_yield_values2 semantics in CRuby), unlike the Enumerable collection methods +# which pack them via rb_enum_values_pack() (see enumerable/shared/value_packing.rb). +describe :enum_each, shared: true do + # @object must be set to a Proc that wraps an Enumerator into the receiver + # under test (e.g. -> e { e } for Enumerator#each, -> e { e.lazy } for Lazy#each). + describe "with a source that yields multiple values" do + before :each do + @enum = @object.call(Enumerator.new { |y| y.yield 1, 2; y.yield 3, 4 }) + end + + it "yields the first value to a single-argument block" do + collected = [] + @enum.each { |x| collected << x } + collected.should == [1, 3] + end + + it "yields each value to a multi-argument block" do + collected = [] + @enum.each { |x, y| collected << [x, y] } + collected.should == [[1, 2], [3, 4]] + end + + it "gathers the values for a splat block" do + collected = [] + @enum.each { |*args| collected << args } + collected.should == [[1, 2], [3, 4]] + end + end + + describe "with a source that yields a single value" do + it "yields the value to a single-argument block" do + collected = [] + @object.call(Enumerator.new { |y| y.yield 7; y.yield 8 }).each { |x| collected << x } + collected.should == [7, 8] + end + end + + describe "with a source that yields no value" do + it "yields nil to a single-argument block" do + collected = [] + @object.call(Enumerator.new { |y| y.yield; y.yield }).each { |x| collected << x } + collected.should == [nil, nil] + end + end +end diff --git a/spec/ruby/core/enumerator/shared/enum_for.rb b/spec/ruby/core/enumerator/shared/enum_for.rb deleted file mode 100644 index 4388103ecf..0000000000 --- a/spec/ruby/core/enumerator/shared/enum_for.rb +++ /dev/null @@ -1,57 +0,0 @@ -describe :enum_for, shared: true do - it "is defined in Kernel" do - Kernel.method_defined?(@method).should == true - end - - it "returns a new enumerator" do - "abc".send(@method).should.instance_of?(Enumerator) - end - - it "defaults the first argument to :each" do - enum = [1,2].send(@method) - enum.map { |v| v }.should == [1,2].each { |v| v } - end - - it "sets regexp matches in the caller" do - "wawa".send(@method, :scan, /./).map {|o| $& }.should == ["w", "a", "w", "a"] - a = [] - "wawa".send(@method, :scan, /./).each {|o| a << $& } - a.should == ["w", "a", "w", "a"] - end - - it "exposes multi-arg yields as an array" do - o = Object.new - def o.each - yield :a - yield :b1, :b2 - yield [:c] - yield :d1, :d2 - yield :e1, :e2, :e3 - end - - enum = o.send(@method) - enum.next.should == :a - enum.next.should == [:b1, :b2] - enum.next.should == [:c] - enum.next.should == [:d1, :d2] - enum.next.should == [:e1, :e2, :e3] - end - - it "uses the passed block's value to calculate the size of the enumerator" do - Object.new.enum_for { 100 }.size.should == 100 - end - - it "defers the evaluation of the passed block until #size is called" do - ScratchPad.record [] - - enum = Object.new.enum_for do - ScratchPad << :called - 100 - end - - ScratchPad.recorded.should.empty? - - enum.size - ScratchPad.recorded.should == [:called] - end -end diff --git a/spec/ruby/core/enumerator/shared/with_object.rb b/spec/ruby/core/enumerator/shared/with_object.rb deleted file mode 100644 index 50d4f24eb3..0000000000 --- a/spec/ruby/core/enumerator/shared/with_object.rb +++ /dev/null @@ -1,42 +0,0 @@ -require_relative '../../../spec_helper' - -describe :enum_with_object, shared: true do - before :each do - @enum = [:a, :b].to_enum - @memo = '' - @block_params = @enum.send(@method, @memo).to_a - end - - it "receives an argument" do - @enum.method(@method).arity.should == 1 - end - - context "with block" do - it "returns the given object" do - ret = @enum.send(@method, @memo) do |elm, memo| - # nothing - end - ret.should.equal?(@memo) - end - - context "the block parameter" do - it "passes each element to first parameter" do - @block_params[0][0].should.equal?(:a) - @block_params[1][0].should.equal?(:b) - end - - it "passes the given object to last parameter" do - @block_params[0][1].should.equal?(@memo) - @block_params[1][1].should.equal?(@memo) - end - end - end - - context "without block" do - it "returns new Enumerator" do - ret = @enum.send(@method, @memo) - ret.should.instance_of?(Enumerator) - ret.should_not.equal?(@enum) - end - end -end diff --git a/spec/ruby/core/enumerator/to_enum_spec.rb b/spec/ruby/core/enumerator/to_enum_spec.rb deleted file mode 100644 index 7fb73d0c3c..0000000000 --- a/spec/ruby/core/enumerator/to_enum_spec.rb +++ /dev/null @@ -1,6 +0,0 @@ -require_relative '../../spec_helper' -require_relative 'shared/enum_for' - -describe "Enumerator#to_enum" do - it_behaves_like :enum_for, :to_enum -end diff --git a/spec/ruby/core/enumerator/with_object_spec.rb b/spec/ruby/core/enumerator/with_object_spec.rb index 58031fd765..790be66a11 100644 --- a/spec/ruby/core/enumerator/with_object_spec.rb +++ b/spec/ruby/core/enumerator/with_object_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/with_object' describe "Enumerator#with_object" do - it_behaves_like :enum_with_object, :with_object + it "is an alias of Enumerator#each_with_object" do + Enumerator.instance_method(:with_object).should == Enumerator.instance_method(:each_with_object) + end end diff --git a/spec/ruby/core/env/each_pair_spec.rb b/spec/ruby/core/env/each_pair_spec.rb index 2d7ed5faa0..1acd2fbb00 100644 --- a/spec/ruby/core/env/each_pair_spec.rb +++ b/spec/ruby/core/env/each_pair_spec.rb @@ -1,6 +1,63 @@ require_relative 'spec_helper' -require_relative 'shared/each' +require_relative '../enumerable/shared/enumeratorized' describe "ENV.each_pair" do - it_behaves_like :env_each, :each_pair + it "returns each pair" do + orig = ENV.to_hash + e = [] + begin + ENV.clear + ENV["foo"] = "bar" + ENV["baz"] = "boo" + ENV.each_pair { |k, v| e << [k, v] }.should.equal?(ENV) + e.should.include?(["foo", "bar"]) + e.should.include?(["baz", "boo"]) + ensure + ENV.replace orig + end + end + + it "returns an Enumerator if called without a block" do + enum = ENV.each_pair + enum.should.instance_of?(Enumerator) + enum.each do |name, value| + ENV[name].should == value + end + end + + it_behaves_like :enumeratorized_with_origin_size, :each_pair, ENV + + describe "with encoding" do + before :each do + @external = Encoding.default_external + @internal = Encoding.default_internal + + Encoding.default_external = Encoding::BINARY + end + + after :each do + Encoding.default_external = @external + Encoding.default_internal = @internal + end + + it "uses the locale encoding when Encoding.default_internal is nil" do + Encoding.default_internal = nil + + ENV.each_pair do |key, value| + key.should.be_locale_env + value.should.be_locale_env + end + end + + it "transcodes from the locale encoding to Encoding.default_internal if set" do + Encoding.default_internal = internal = Encoding::IBM437 + + ENV.each_pair do |key, value| + key.encoding.should.equal?(internal) + if value.ascii_only? + value.encoding.should.equal?(internal) + end + end + end + end end diff --git a/spec/ruby/core/env/each_spec.rb b/spec/ruby/core/env/each_spec.rb index d1e06f55b6..166a0b4fc8 100644 --- a/spec/ruby/core/env/each_spec.rb +++ b/spec/ruby/core/env/each_spec.rb @@ -1,6 +1,7 @@ require_relative 'spec_helper' -require_relative 'shared/each' describe "ENV.each" do - it_behaves_like :env_each, :each + it "is an alias of ENV.each_pair" do + ENV.method(:each).should == ENV.method(:each_pair) + end end diff --git a/spec/ruby/core/env/element_set_spec.rb b/spec/ruby/core/env/element_set_spec.rb index 26dfee1ade..ca5d468009 100644 --- a/spec/ruby/core/env/element_set_spec.rb +++ b/spec/ruby/core/env/element_set_spec.rb @@ -1,6 +1,62 @@ require_relative '../../spec_helper' -require_relative 'shared/store' describe "ENV.[]=" do - it_behaves_like :env_store, :[]= + before :each do + @saved_foo = ENV["foo"] + end + + after :each do + ENV["foo"] = @saved_foo + end + + it "sets the environment variable to the given value" do + ENV["foo"] = "bar" + ENV["foo"].should == "bar" + end + + it "returns the value" do + value = "bar" + ENV.send(:[]=, "foo", value).should.equal?(value) + end + + it "deletes the environment variable when the value is nil" do + ENV["foo"] = "bar" + ENV["foo"] = nil + ENV.key?("foo").should == false + end + + it "coerces the key argument with #to_str" do + k = mock("key") + k.should_receive(:to_str).and_return("foo") + ENV[k] = "bar" + ENV["foo"].should == "bar" + end + + it "coerces the value argument with #to_str" do + v = mock("value") + v.should_receive(:to_str).and_return("bar") + ENV["foo"] = v + ENV["foo"].should == "bar" + end + + it "raises TypeError when the key is not coercible to String" do + -> { ENV[Object.new] = "bar" }.should.raise(TypeError, "no implicit conversion of Object into String") + end + + it "raises TypeError when the value is not coercible to String" do + -> { ENV["foo"] = Object.new }.should.raise(TypeError, "no implicit conversion of Object into String") + end + + it "raises Errno::EINVAL when the key contains the '=' character" do + -> { ENV["foo="] = "bar" }.should.raise(Errno::EINVAL) + end + + it "raises Errno::EINVAL when the key is an empty string" do + -> { ENV[""] = "bar" }.should.raise(Errno::EINVAL) + end + + it "does nothing when the key is not a valid environment variable key and the value is nil" do + ENV["foo="] = nil + ENV.key?("foo=").should == false + end end diff --git a/spec/ruby/core/env/filter_spec.rb b/spec/ruby/core/env/filter_spec.rb index 52f8b79a0b..54997bfda1 100644 --- a/spec/ruby/core/env/filter_spec.rb +++ b/spec/ruby/core/env/filter_spec.rb @@ -1,13 +1,13 @@ require_relative '../../spec_helper' -require_relative '../enumerable/shared/enumeratorized' -require_relative 'shared/select' describe "ENV.filter!" do - it_behaves_like :env_select!, :filter! - it_behaves_like :enumeratorized_with_origin_size, :filter!, ENV + it "is an alias of ENV.select!" do + ENV.method(:filter!).should == ENV.method(:select!) + end end describe "ENV.filter" do - it_behaves_like :env_select, :filter - it_behaves_like :enumeratorized_with_origin_size, :filter, ENV + it "is an alias of ENV.select" do + ENV.method(:filter).should == ENV.method(:select) + end end diff --git a/spec/ruby/core/env/has_key_spec.rb b/spec/ruby/core/env/has_key_spec.rb index 798668105d..7feeec8dfa 100644 --- a/spec/ruby/core/env/has_key_spec.rb +++ b/spec/ruby/core/env/has_key_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/include' describe "ENV.has_key?" do - it_behaves_like :env_include, :has_key? + it "is an alias of ENV.include?" do + ENV.method(:has_key?).should == ENV.method(:include?) + end end diff --git a/spec/ruby/core/env/has_value_spec.rb b/spec/ruby/core/env/has_value_spec.rb index a2bf3eb877..b76ec0dc5d 100644 --- a/spec/ruby/core/env/has_value_spec.rb +++ b/spec/ruby/core/env/has_value_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/value' describe "ENV.has_value?" do - it_behaves_like :env_value, :has_value? + it "is an alias of ENV.value?" do + ENV.method(:has_value?).should == ENV.method(:value?) + end end diff --git a/spec/ruby/core/env/include_spec.rb b/spec/ruby/core/env/include_spec.rb index 3975f095ac..8e68aa3bfd 100644 --- a/spec/ruby/core/env/include_spec.rb +++ b/spec/ruby/core/env/include_spec.rb @@ -1,6 +1,32 @@ require_relative '../../spec_helper' -require_relative 'shared/include' describe "ENV.include?" do - it_behaves_like :env_include, :include? + before :each do + @saved_foo = ENV["foo"] + end + + after :each do + ENV["foo"] = @saved_foo + end + + it "returns true if ENV has the key" do + ENV["foo"] = "bar" + ENV.include?( "foo").should == true + end + + it "returns false if ENV doesn't include the key" do + ENV.delete("foo") + ENV.include?( "foo").should == false + end + + it "coerces the key with #to_str" do + ENV["foo"] = "bar" + k = mock('key') + k.should_receive(:to_str).and_return("foo") + ENV.include?( k).should == true + end + + it "raises TypeError if the argument is not a String and does not respond to #to_str" do + -> { ENV.include?( Object.new) }.should.raise(TypeError, "no implicit conversion of Object into String") + end end diff --git a/spec/ruby/core/env/key_spec.rb b/spec/ruby/core/env/key_spec.rb index 677cf35216..56f5f609a7 100644 --- a/spec/ruby/core/env/key_spec.rb +++ b/spec/ruby/core/env/key_spec.rb @@ -1,8 +1,9 @@ require_relative '../../spec_helper' -require_relative 'shared/include' describe "ENV.key?" do - it_behaves_like :env_include, :key? + it "is an alias of ENV.include?" do + ENV.method(:key?).should == ENV.method(:include?) + end end describe "ENV.key" do diff --git a/spec/ruby/core/env/length_spec.rb b/spec/ruby/core/env/length_spec.rb index c6f9062892..6baac6f7a4 100644 --- a/spec/ruby/core/env/length_spec.rb +++ b/spec/ruby/core/env/length_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/length' describe "ENV.length" do - it_behaves_like :env_length, :length + it "is an alias of ENV.size" do + ENV.method(:length).should == ENV.method(:size) + end end diff --git a/spec/ruby/core/env/member_spec.rb b/spec/ruby/core/env/member_spec.rb index 9119022ae5..f062d41190 100644 --- a/spec/ruby/core/env/member_spec.rb +++ b/spec/ruby/core/env/member_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/include' describe "ENV.member?" do - it_behaves_like :env_include, :member? + it "is an alias of ENV.include?" do + ENV.method(:member?).should == ENV.method(:include?) + end end diff --git a/spec/ruby/core/env/merge_spec.rb b/spec/ruby/core/env/merge_spec.rb index f10662cf79..78231afbb2 100644 --- a/spec/ruby/core/env/merge_spec.rb +++ b/spec/ruby/core/env/merge_spec.rb @@ -1,6 +1,106 @@ require_relative '../../spec_helper' -require_relative 'shared/update' describe "ENV.merge!" do - it_behaves_like :env_update, :merge! + before :each do + @saved_foo = ENV["foo"] + @saved_bar = ENV["bar"] + end + + after :each do + ENV["foo"] = @saved_foo + ENV["bar"] = @saved_bar + end + + it "adds the parameter hash to ENV, returning ENV" do + ENV.merge!("foo" => "0", "bar" => "1").should.equal?(ENV) + ENV["foo"].should == "0" + ENV["bar"].should == "1" + end + + it "adds the multiple parameter hashes to ENV, returning ENV" do + ENV.merge!({"foo" => "multi1"}, {"bar" => "multi2"}).should.equal?(ENV) + ENV["foo"].should == "multi1" + ENV["bar"].should == "multi2" + end + + it "returns ENV when no block given" do + ENV.merge!({"foo" => "0", "bar" => "1"}).should.equal?(ENV) + end + + it "yields key, the old value and the new value when replacing an entry" do + ENV.merge!({"foo" => "0", "bar" => "3"}) + a = [] + ENV.merge!({"foo" => "1", "bar" => "4"}) do |key, old, new| + a << [key, old, new] + new + end + a[0].should == ["foo", "0", "1"] + a[1].should == ["bar", "3", "4"] + end + + it "yields key, the old value and the new value when replacing an entry" do + ENV.merge!({"foo" => "0", "bar" => "3"}) + ENV.merge!({"foo" => "1", "bar" => "4"}) do |key, old, new| + (new.to_i + 1).to_s + end + ENV["foo"].should == "2" + ENV["bar"].should == "5" + end + + # BUG: https://bugs.ruby-lang.org/issues/16192 + it "does not evaluate the block when the name is new" do + ENV.delete("bar") + ENV.merge!({"foo" => "0"}) + ENV.merge!("bar" => "1") { |key, old, new| fail "Should not get here" } + ENV["bar"].should == "1" + end + + # BUG: https://bugs.ruby-lang.org/issues/16192 + it "does not use the block's return value as the value when the name is new" do + ENV.delete("bar") + ENV.merge!({"foo" => "0"}) + ENV.merge!("bar" => "1") { |key, old, new| "Should not use this value" } + ENV["foo"].should == "0" + ENV["bar"].should == "1" + end + + it "returns ENV when block given" do + ENV.merge!({"foo" => "0", "bar" => "1"}){}.should.equal?(ENV) + end + + it "raises TypeError when a name is not coercible to String" do + -> { ENV.merge!(Object.new => "0") }.should.raise(TypeError, "no implicit conversion of Object into String") + end + + it "raises TypeError when a value is not coercible to String" do + -> { ENV.merge!("foo" => Object.new) }.should.raise(TypeError, "no implicit conversion of Object into String") + end + + it "raises Errno::EINVAL when a name contains the '=' character" do + -> { ENV.merge!("foo=" => "bar") }.should.raise(Errno::EINVAL) + end + + it "raises Errno::EINVAL when a name is an empty string" do + -> { ENV.merge!("" => "bar") }.should.raise(Errno::EINVAL) + end + + it "updates good data preceding an error" do + ENV["foo"] = "0" + begin + ENV.merge!({"foo" => "2", Object.new => "1"}) + rescue TypeError + ensure + ENV["foo"].should == "2" + end + end + + it "does not update good data following an error" do + ENV["foo"] = "0" + begin + ENV.merge!({Object.new => "1", "foo" => "2"}) + rescue TypeError + ensure + ENV["foo"].should == "0" + end + end end diff --git a/spec/ruby/core/env/select_spec.rb b/spec/ruby/core/env/select_spec.rb index c3a76f4434..2b92d61551 100644 --- a/spec/ruby/core/env/select_spec.rb +++ b/spec/ruby/core/env/select_spec.rb @@ -1,13 +1,68 @@ require_relative '../../spec_helper' require_relative '../enumerable/shared/enumeratorized' -require_relative 'shared/select' describe "ENV.select!" do - it_behaves_like :env_select!, :select! it_behaves_like :enumeratorized_with_origin_size, :select!, ENV + + before :each do + @saved_foo = ENV["foo"] + end + + after :each do + ENV["foo"] = @saved_foo + end + + it "removes environment variables for which the block returns false" do + ENV["foo"] = "bar" + ENV.select! { |k, v| k != "foo" } + ENV["foo"].should == nil + end + + it "returns self if any changes were made" do + ENV["foo"] = "bar" + (ENV.select! { |k, v| k != "foo" }).should == ENV + end + + it "returns nil if no changes were made" do + (ENV.select! { true }).should == nil + end + + it "returns an Enumerator if called without a block" do + ENV.select!.should.instance_of?(Enumerator) + end + + it "selects via the enumerator" do + enum = ENV.select! + ENV["foo"] = "bar" + enum.each { |k, v| k != "foo" } + ENV["foo"].should == nil + end end describe "ENV.select" do - it_behaves_like :env_select, :select it_behaves_like :enumeratorized_with_origin_size, :select, ENV + + before :each do + @saved_foo = ENV["foo"] + end + + after :each do + ENV["foo"] = @saved_foo + end + + it "returns a Hash of names and values for which block returns true" do + ENV["foo"] = "bar" + (ENV.select { |k, v| k == "foo" }).should == { "foo" => "bar" } + end + + it "returns an Enumerator when no block is given" do + enum = ENV.select + enum.should.instance_of?(Enumerator) + end + + it "selects via the enumerator" do + enum = ENV.select + ENV["foo"] = "bar" + enum.each { |k, v| k == "foo" }.should == { "foo" => "bar"} + end end diff --git a/spec/ruby/core/env/shared/each.rb b/spec/ruby/core/env/shared/each.rb deleted file mode 100644 index 0661ca924c..0000000000 --- a/spec/ruby/core/env/shared/each.rb +++ /dev/null @@ -1,65 +0,0 @@ -require_relative '../../enumerable/shared/enumeratorized' - -describe :env_each, shared: true do - it "returns each pair" do - orig = ENV.to_hash - e = [] - begin - ENV.clear - ENV["foo"] = "bar" - ENV["baz"] = "boo" - ENV.send(@method) { |k, v| e << [k, v] }.should.equal?(ENV) - e.should.include?(["foo", "bar"]) - e.should.include?(["baz", "boo"]) - ensure - ENV.replace orig - end - end - - it "returns an Enumerator if called without a block" do - enum = ENV.send(@method) - enum.should.instance_of?(Enumerator) - enum.each do |name, value| - ENV[name].should == value - end - end - - before :all do - @object = ENV - end - it_should_behave_like :enumeratorized_with_origin_size - - describe "with encoding" do - before :each do - @external = Encoding.default_external - @internal = Encoding.default_internal - - Encoding.default_external = Encoding::BINARY - end - - after :each do - Encoding.default_external = @external - Encoding.default_internal = @internal - end - - it "uses the locale encoding when Encoding.default_internal is nil" do - Encoding.default_internal = nil - - ENV.send(@method) do |key, value| - key.should.be_locale_env - value.should.be_locale_env - end - end - - it "transcodes from the locale encoding to Encoding.default_internal if set" do - Encoding.default_internal = internal = Encoding::IBM437 - - ENV.send(@method) do |key, value| - key.encoding.should.equal?(internal) - if value.ascii_only? - value.encoding.should.equal?(internal) - end - end - end - end -end diff --git a/spec/ruby/core/env/shared/include.rb b/spec/ruby/core/env/shared/include.rb deleted file mode 100644 index ceca02e3eb..0000000000 --- a/spec/ruby/core/env/shared/include.rb +++ /dev/null @@ -1,30 +0,0 @@ -describe :env_include, shared: true do - before :each do - @saved_foo = ENV["foo"] - end - - after :each do - ENV["foo"] = @saved_foo - end - - it "returns true if ENV has the key" do - ENV["foo"] = "bar" - ENV.send(@method, "foo").should == true - end - - it "returns false if ENV doesn't include the key" do - ENV.delete("foo") - ENV.send(@method, "foo").should == false - end - - it "coerces the key with #to_str" do - ENV["foo"] = "bar" - k = mock('key') - k.should_receive(:to_str).and_return("foo") - ENV.send(@method, k).should == true - end - - it "raises TypeError if the argument is not a String and does not respond to #to_str" do - -> { ENV.send(@method, Object.new) }.should.raise(TypeError, "no implicit conversion of Object into String") - end -end diff --git a/spec/ruby/core/env/shared/length.rb b/spec/ruby/core/env/shared/length.rb deleted file mode 100644 index 6d788a3f4a..0000000000 --- a/spec/ruby/core/env/shared/length.rb +++ /dev/null @@ -1,13 +0,0 @@ -describe :env_length, shared: true do - it "returns the number of ENV entries" do - orig = ENV.to_hash - begin - ENV.clear - ENV["foo"] = "bar" - ENV["baz"] = "boo" - ENV.send(@method).should == 2 - ensure - ENV.replace orig - end - end -end diff --git a/spec/ruby/core/env/shared/select.rb b/spec/ruby/core/env/shared/select.rb deleted file mode 100644 index 8ec648a637..0000000000 --- a/spec/ruby/core/env/shared/select.rb +++ /dev/null @@ -1,61 +0,0 @@ -describe :env_select, shared: true do - before :each do - @saved_foo = ENV["foo"] - end - - after :each do - ENV["foo"] = @saved_foo - end - - it "returns a Hash of names and values for which block return true" do - ENV["foo"] = "bar" - (ENV.send(@method) { |k, v| k == "foo" }).should == { "foo" => "bar" } - end - - it "returns an Enumerator when no block is given" do - enum = ENV.send(@method) - enum.should.instance_of?(Enumerator) - end - - it "selects via the enumerator" do - enum = ENV.send(@method) - ENV["foo"] = "bar" - enum.each { |k, v| k == "foo" }.should == { "foo" => "bar"} - end -end - -describe :env_select!, shared: true do - before :each do - @saved_foo = ENV["foo"] - end - - after :each do - ENV["foo"] = @saved_foo - end - - it "removes environment variables for which the block returns true" do - ENV["foo"] = "bar" - ENV.send(@method) { |k, v| k != "foo" } - ENV["foo"].should == nil - end - - it "returns self if any changes were made" do - ENV["foo"] = "bar" - (ENV.send(@method) { |k, v| k != "foo" }).should == ENV - end - - it "returns nil if no changes were made" do - (ENV.send(@method) { true }).should == nil - end - - it "returns an Enumerator if called without a block" do - ENV.send(@method).should.instance_of?(Enumerator) - end - - it "selects via the enumerator" do - enum = ENV.send(@method) - ENV["foo"] = "bar" - enum.each { |k, v| k != "foo" } - ENV["foo"].should == nil - end -end diff --git a/spec/ruby/core/env/shared/store.rb b/spec/ruby/core/env/shared/store.rb deleted file mode 100644 index 388208a8ac..0000000000 --- a/spec/ruby/core/env/shared/store.rb +++ /dev/null @@ -1,60 +0,0 @@ -describe :env_store, shared: true do - before :each do - @saved_foo = ENV["foo"] - end - - after :each do - ENV["foo"] = @saved_foo - end - - it "sets the environment variable to the given value" do - ENV.send(@method, "foo", "bar") - ENV["foo"].should == "bar" - end - - it "returns the value" do - value = "bar" - ENV.send(@method, "foo", value).should.equal?(value) - end - - it "deletes the environment variable when the value is nil" do - ENV["foo"] = "bar" - ENV.send(@method, "foo", nil) - ENV.key?("foo").should == false - end - - it "coerces the key argument with #to_str" do - k = mock("key") - k.should_receive(:to_str).and_return("foo") - ENV.send(@method, k, "bar") - ENV["foo"].should == "bar" - end - - it "coerces the value argument with #to_str" do - v = mock("value") - v.should_receive(:to_str).and_return("bar") - ENV.send(@method, "foo", v) - ENV["foo"].should == "bar" - end - - it "raises TypeError when the key is not coercible to String" do - -> { ENV.send(@method, Object.new, "bar") }.should.raise(TypeError, "no implicit conversion of Object into String") - end - - it "raises TypeError when the value is not coercible to String" do - -> { ENV.send(@method, "foo", Object.new) }.should.raise(TypeError, "no implicit conversion of Object into String") - end - - it "raises Errno::EINVAL when the key contains the '=' character" do - -> { ENV.send(@method, "foo=", "bar") }.should.raise(Errno::EINVAL) - end - - it "raises Errno::EINVAL when the key is an empty string" do - -> { ENV.send(@method, "", "bar") }.should.raise(Errno::EINVAL) - end - - it "does nothing when the key is not a valid environment variable key and the value is nil" do - ENV.send(@method, "foo=", nil) - ENV.key?("foo=").should == false - end -end diff --git a/spec/ruby/core/env/shared/update.rb b/spec/ruby/core/env/shared/update.rb deleted file mode 100644 index 112cc2505d..0000000000 --- a/spec/ruby/core/env/shared/update.rb +++ /dev/null @@ -1,104 +0,0 @@ -describe :env_update, shared: true do - before :each do - @saved_foo = ENV["foo"] - @saved_bar = ENV["bar"] - end - - after :each do - ENV["foo"] = @saved_foo - ENV["bar"] = @saved_bar - end - - it "adds the parameter hash to ENV, returning ENV" do - ENV.send(@method, "foo" => "0", "bar" => "1").should.equal?(ENV) - ENV["foo"].should == "0" - ENV["bar"].should == "1" - end - - it "adds the multiple parameter hashes to ENV, returning ENV" do - ENV.send(@method, {"foo" => "multi1"}, {"bar" => "multi2"}).should.equal?(ENV) - ENV["foo"].should == "multi1" - ENV["bar"].should == "multi2" - end - - it "returns ENV when no block given" do - ENV.send(@method, {"foo" => "0", "bar" => "1"}).should.equal?(ENV) - end - - it "yields key, the old value and the new value when replacing an entry" do - ENV.send @method, {"foo" => "0", "bar" => "3"} - a = [] - ENV.send @method, {"foo" => "1", "bar" => "4"} do |key, old, new| - a << [key, old, new] - new - end - a[0].should == ["foo", "0", "1"] - a[1].should == ["bar", "3", "4"] - end - - it "yields key, the old value and the new value when replacing an entry" do - ENV.send @method, {"foo" => "0", "bar" => "3"} - ENV.send @method, {"foo" => "1", "bar" => "4"} do |key, old, new| - (new.to_i + 1).to_s - end - ENV["foo"].should == "2" - ENV["bar"].should == "5" - end - - # BUG: https://bugs.ruby-lang.org/issues/16192 - it "does not evaluate the block when the name is new" do - ENV.delete("bar") - ENV.send @method, {"foo" => "0"} - ENV.send(@method, "bar" => "1") { |key, old, new| fail "Should not get here" } - ENV["bar"].should == "1" - end - - # BUG: https://bugs.ruby-lang.org/issues/16192 - it "does not use the block's return value as the value when the name is new" do - ENV.delete("bar") - ENV.send @method, {"foo" => "0"} - ENV.send(@method, "bar" => "1") { |key, old, new| "Should not use this value" } - ENV["foo"].should == "0" - ENV["bar"].should == "1" - end - - it "returns ENV when block given" do - ENV.send(@method, {"foo" => "0", "bar" => "1"}){}.should.equal?(ENV) - end - - it "raises TypeError when a name is not coercible to String" do - -> { ENV.send @method, Object.new => "0" }.should.raise(TypeError, "no implicit conversion of Object into String") - end - - it "raises TypeError when a value is not coercible to String" do - -> { ENV.send @method, "foo" => Object.new }.should.raise(TypeError, "no implicit conversion of Object into String") - end - - it "raises Errno::EINVAL when a name contains the '=' character" do - -> { ENV.send(@method, "foo=" => "bar") }.should.raise(Errno::EINVAL) - end - - it "raises Errno::EINVAL when a name is an empty string" do - -> { ENV.send(@method, "" => "bar") }.should.raise(Errno::EINVAL) - end - - it "updates good data preceding an error" do - ENV["foo"] = "0" - begin - ENV.send @method, {"foo" => "2", Object.new => "1"} - rescue TypeError - ensure - ENV["foo"].should == "2" - end - end - - it "does not update good data following an error" do - ENV["foo"] = "0" - begin - ENV.send @method, {Object.new => "1", "foo" => "2"} - rescue TypeError - ensure - ENV["foo"].should == "0" - end - end -end diff --git a/spec/ruby/core/env/shared/value.rb b/spec/ruby/core/env/shared/value.rb deleted file mode 100644 index c2b5025465..0000000000 --- a/spec/ruby/core/env/shared/value.rb +++ /dev/null @@ -1,29 +0,0 @@ -describe :env_value, shared: true do - before :each do - @saved_foo = ENV["foo"] - end - - after :each do - ENV["foo"] = @saved_foo - end - - it "returns true if ENV has the value" do - ENV["foo"] = "bar" - ENV.send(@method, "bar").should == true - end - - it "returns false if ENV doesn't have the value" do - ENV.send(@method, "foo").should == false - end - - it "coerces the value element with #to_str" do - ENV["foo"] = "bar" - v = mock('value') - v.should_receive(:to_str).and_return("bar") - ENV.send(@method, v).should == true - end - - it "returns nil if the argument is not a String and does not respond to #to_str" do - ENV.send(@method, Object.new).should == nil - end -end diff --git a/spec/ruby/core/env/size_spec.rb b/spec/ruby/core/env/size_spec.rb index 7c8072481e..9c6de20df6 100644 --- a/spec/ruby/core/env/size_spec.rb +++ b/spec/ruby/core/env/size_spec.rb @@ -1,6 +1,15 @@ require_relative '../../spec_helper' -require_relative 'shared/length' describe "ENV.size" do - it_behaves_like :env_length, :size + it "returns the number of ENV entries" do + orig = ENV.to_hash + begin + ENV.clear + ENV["foo"] = "bar" + ENV["baz"] = "boo" + ENV.size.should == 2 + ensure + ENV.replace orig + end + end end diff --git a/spec/ruby/core/env/store_spec.rb b/spec/ruby/core/env/store_spec.rb index b4700e0a96..a5fd7e1e26 100644 --- a/spec/ruby/core/env/store_spec.rb +++ b/spec/ruby/core/env/store_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/store' describe "ENV.store" do - it_behaves_like :env_store, :store + it "is an alias of ENV.[]=" do + ENV.method(:store).should == ENV.method(:[]=) + end end diff --git a/spec/ruby/core/env/update_spec.rb b/spec/ruby/core/env/update_spec.rb index 95a8a2eb49..44d05d617f 100644 --- a/spec/ruby/core/env/update_spec.rb +++ b/spec/ruby/core/env/update_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/update' describe "ENV.update" do - it_behaves_like :env_update, :update + it "is an alias of ENV.merge!" do + ENV.method(:update).should == ENV.method(:merge!) + end end diff --git a/spec/ruby/core/env/value_spec.rb b/spec/ruby/core/env/value_spec.rb index 906e86ab39..c732cfbd15 100644 --- a/spec/ruby/core/env/value_spec.rb +++ b/spec/ruby/core/env/value_spec.rb @@ -1,6 +1,31 @@ require_relative '../../spec_helper' -require_relative 'shared/value' describe "ENV.value?" do - it_behaves_like :env_value, :value? + before :each do + @saved_foo = ENV["foo"] + end + + after :each do + ENV["foo"] = @saved_foo + end + + it "returns true if ENV has the value" do + ENV["foo"] = "bar" + ENV.value?("bar").should == true + end + + it "returns false if ENV doesn't have the value" do + ENV.value?("foo").should == false + end + + it "coerces the value element with #to_str" do + ENV["foo"] = "bar" + v = mock('value') + v.should_receive(:to_str).and_return("bar") + ENV.value?(v).should == true + end + + it "returns nil if the argument is not a String and does not respond to #to_str" do + ENV.value?(Object.new).should == nil + end end diff --git a/spec/ruby/core/false/inspect_spec.rb b/spec/ruby/core/false/inspect_spec.rb index 4cbb55d434..70f4aa0159 100644 --- a/spec/ruby/core/false/inspect_spec.rb +++ b/spec/ruby/core/false/inspect_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' describe "FalseClass#inspect" do - it "returns the string 'false'" do - false.inspect.should == "false" + it "is an alias of FalseClass#to_s" do + false.method(:inspect).should == false.method(:to_s) end end diff --git a/spec/ruby/core/false/xor_spec.rb b/spec/ruby/core/false/xor_spec.rb index 1b87b9f412..d8432ca326 100644 --- a/spec/ruby/core/false/xor_spec.rb +++ b/spec/ruby/core/false/xor_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' describe "FalseClass#^" do - it "returns false if other is nil or false, otherwise true" do - (false ^ false).should == false - (false ^ true).should == true - (false ^ nil).should == false - (false ^ "").should == true - (false ^ mock('x')).should == true + it "is an alias of FalseClass#|" do + false.method(:^).should == false.method(:|) end end diff --git a/spec/ruby/core/fiber/scheduler_spec.rb b/spec/ruby/core/fiber/scheduler_spec.rb index 15a03c1479..2a517ba93b 100644 --- a/spec/ruby/core/fiber/scheduler_spec.rb +++ b/spec/ruby/core/fiber/scheduler_spec.rb @@ -1,8 +1,5 @@ require_relative '../../spec_helper' -require_relative 'shared/scheduler' - -require "fiber" describe "Fiber.scheduler" do - it_behaves_like :scheduler, :scheduler + it "is already tested in Fiber.set_scheduler" end diff --git a/spec/ruby/core/fiber/set_scheduler_spec.rb b/spec/ruby/core/fiber/set_scheduler_spec.rb index 82f6acbe86..b34aff8734 100644 --- a/spec/ruby/core/fiber/set_scheduler_spec.rb +++ b/spec/ruby/core/fiber/set_scheduler_spec.rb @@ -1,8 +1,55 @@ require_relative '../../spec_helper' -require_relative 'shared/scheduler' require "fiber" describe "Fiber.scheduler" do - it_behaves_like :scheduler, :set_scheduler + it "validates the scheduler for required methods" do + required_methods = [:block, :unblock, :kernel_sleep, :io_wait] + required_methods.each do |missing_method| + scheduler = Object.new + required_methods.difference([missing_method]).each do |method| + scheduler.define_singleton_method(method) {} + end + -> { + suppress_warning { Fiber.set_scheduler(scheduler) } + }.should.raise(ArgumentError, /Scheduler must implement ##{missing_method}/) + end + end + + it "can set and get the scheduler" do + required_methods = [:block, :unblock, :kernel_sleep, :io_wait] + scheduler = Object.new + required_methods.each do |method| + scheduler.define_singleton_method(method) {} + end + suppress_warning { Fiber.set_scheduler(scheduler) } + Fiber.scheduler.should == scheduler + end + + it "returns the scheduler after setting it" do + required_methods = [:block, :unblock, :kernel_sleep, :io_wait] + scheduler = Object.new + required_methods.each do |method| + scheduler.define_singleton_method(method) {} + end + result = suppress_warning { Fiber.set_scheduler(scheduler) } + result.should == scheduler + end + + it "can remove the scheduler" do + required_methods = [:block, :unblock, :kernel_sleep, :io_wait] + scheduler = Object.new + required_methods.each do |method| + scheduler.define_singleton_method(method) {} + end + suppress_warning { Fiber.set_scheduler(scheduler) } + Fiber.set_scheduler(nil) + Fiber.scheduler.should == nil + end + + it "can assign a nil scheduler multiple times" do + Fiber.set_scheduler(nil) + Fiber.set_scheduler(nil) + Fiber.scheduler.should == nil + end end diff --git a/spec/ruby/core/fiber/shared/scheduler.rb b/spec/ruby/core/fiber/shared/scheduler.rb deleted file mode 100644 index 04bdded53a..0000000000 --- a/spec/ruby/core/fiber/shared/scheduler.rb +++ /dev/null @@ -1,51 +0,0 @@ -describe :scheduler, shared: true do - it "validates the scheduler for required methods" do - required_methods = [:block, :unblock, :kernel_sleep, :io_wait] - required_methods.each do |missing_method| - scheduler = Object.new - required_methods.difference([missing_method]).each do |method| - scheduler.define_singleton_method(method) {} - end - -> { - suppress_warning { Fiber.set_scheduler(scheduler) } - }.should.raise(ArgumentError, /Scheduler must implement ##{missing_method}/) - end - end - - it "can set and get the scheduler" do - required_methods = [:block, :unblock, :kernel_sleep, :io_wait] - scheduler = Object.new - required_methods.each do |method| - scheduler.define_singleton_method(method) {} - end - suppress_warning { Fiber.set_scheduler(scheduler) } - Fiber.scheduler.should == scheduler - end - - it "returns the scheduler after setting it" do - required_methods = [:block, :unblock, :kernel_sleep, :io_wait] - scheduler = Object.new - required_methods.each do |method| - scheduler.define_singleton_method(method) {} - end - result = suppress_warning { Fiber.set_scheduler(scheduler) } - result.should == scheduler - end - - it "can remove the scheduler" do - required_methods = [:block, :unblock, :kernel_sleep, :io_wait] - scheduler = Object.new - required_methods.each do |method| - scheduler.define_singleton_method(method) {} - end - suppress_warning { Fiber.set_scheduler(scheduler) } - Fiber.set_scheduler(nil) - Fiber.scheduler.should == nil - end - - it "can assign a nil scheduler multiple times" do - Fiber.set_scheduler(nil) - Fiber.set_scheduler(nil) - Fiber.scheduler.should == nil - end -end diff --git a/spec/ruby/core/file/delete_spec.rb b/spec/ruby/core/file/delete_spec.rb index 4098499942..7149b8a37d 100644 --- a/spec/ruby/core/file/delete_spec.rb +++ b/spec/ruby/core/file/delete_spec.rb @@ -1,6 +1,63 @@ require_relative '../../spec_helper' -require_relative 'shared/unlink' describe "File.delete" do - it_behaves_like :file_unlink, :delete + before :each do + @file1 = tmp('test.txt') + @file2 = tmp('test2.txt') + + touch @file1 + touch @file2 + end + + after :each do + File.delete(@file1) if File.exist?(@file1) + File.delete(@file2) if File.exist?(@file2) + + @file1 = nil + @file2 = nil + end + + it "returns 0 when called without arguments" do + File.delete.should == 0 + end + + it "deletes a single file" do + File.delete(@file1).should == 1 + File.should_not.exist?(@file1) + end + + it "deletes multiple files" do + File.delete(@file1, @file2).should == 2 + File.should_not.exist?(@file1) + File.should_not.exist?(@file2) + end + + it "raises a TypeError if not passed a String type" do + -> { File.delete(1) }.should.raise(TypeError) + end + + it "raises an Errno::ENOENT when the given file doesn't exist" do + -> { File.delete('bogus') }.should.raise(Errno::ENOENT) + end + + it "coerces a given parameter into a string if possible" do + mock = mock("to_str") + mock.should_receive(:to_str).and_return(@file1) + File.delete(mock).should == 1 + end + + it "accepts an object that has a #to_path method" do + File.delete(mock_to_path(@file1)).should == 1 + end + + platform_is :windows do + it "allows deleting an open file with File::SHARE_DELETE" do + path = tmp("share_delete.txt") + File.open(path, mode: File::CREAT | File::WRONLY | File::BINARY | File::SHARE_DELETE) do |f| + File.should.exist?(path) + File.delete(path) + end + File.should_not.exist?(path) + end + end end diff --git a/spec/ruby/core/file/fnmatch_spec.rb b/spec/ruby/core/file/fnmatch_spec.rb index a1b7fa12b3..44a143bddc 100644 --- a/spec/ruby/core/file/fnmatch_spec.rb +++ b/spec/ruby/core/file/fnmatch_spec.rb @@ -1,10 +1,302 @@ require_relative '../../spec_helper' -require_relative 'shared/fnmatch' describe "File.fnmatch" do - it_behaves_like :file_fnmatch, :fnmatch + it "matches entire strings" do + File.fnmatch('cat', 'cat').should == true + end + + it "does not match partial strings" do + File.fnmatch('cat', 'category').should == false + end + + it "does not support { } patterns by default" do + File.fnmatch('c{at,ub}s', 'cats').should == false + File.fnmatch('c{at,ub}s', 'c{at,ub}s').should == true + end + + it "supports some { } patterns when File::FNM_EXTGLOB is passed" do + File.fnmatch("{a,b}", "a", File::FNM_EXTGLOB).should == true + File.fnmatch("{a,b}", "b", File::FNM_EXTGLOB).should == true + File.fnmatch("c{at,ub}s", "cats", File::FNM_EXTGLOB).should == true + File.fnmatch("c{at,ub}s", "cubs", File::FNM_EXTGLOB).should == true + File.fnmatch("-c{at,ub}s-", "-cats-", File::FNM_EXTGLOB).should == true + File.fnmatch("-c{at,ub}s-", "-cubs-", File::FNM_EXTGLOB).should == true + File.fnmatch("{a,b,c}{d,e,f}{g,h}", "adg", File::FNM_EXTGLOB).should == true + File.fnmatch("{a,b,c}{d,e,f}{g,h}", "bdg", File::FNM_EXTGLOB).should == true + File.fnmatch("{a,b,c}{d,e,f}{g,h}", "ceh", File::FNM_EXTGLOB).should == true + File.fnmatch("{aa,bb,cc,dd}", "aa", File::FNM_EXTGLOB).should == true + File.fnmatch("{aa,bb,cc,dd}", "bb", File::FNM_EXTGLOB).should == true + File.fnmatch("{aa,bb,cc,dd}", "cc", File::FNM_EXTGLOB).should == true + File.fnmatch("{aa,bb,cc,dd}", "dd", File::FNM_EXTGLOB).should == true + File.fnmatch("{1,5{a,b{c,d}}}", "1", File::FNM_EXTGLOB).should == true + File.fnmatch("{1,5{a,b{c,d}}}", "5a", File::FNM_EXTGLOB).should == true + File.fnmatch("{1,5{a,b{c,d}}}", "5bc", File::FNM_EXTGLOB).should == true + File.fnmatch("{1,5{a,b{c,d}}}", "5bd", File::FNM_EXTGLOB).should == true + File.fnmatch("\\\\{a\\,b,b\\}c}", "\\a,b", File::FNM_EXTGLOB).should == true + File.fnmatch("\\\\{a\\,b,b\\}c}", "\\b}c", File::FNM_EXTGLOB).should == true + end + + it "doesn't support some { } patterns even when File::FNM_EXTGLOB is passed" do + File.fnmatch("a{0..3}b", "a0b", File::FNM_EXTGLOB).should == false + File.fnmatch("a{0..3}b", "a1b", File::FNM_EXTGLOB).should == false + File.fnmatch("a{0..3}b", "a2b", File::FNM_EXTGLOB).should == false + File.fnmatch("a{0..3}b", "a3b", File::FNM_EXTGLOB).should == false + File.fnmatch("{0..12}", "0", File::FNM_EXTGLOB).should == false + File.fnmatch("{0..12}", "6", File::FNM_EXTGLOB).should == false + File.fnmatch("{0..12}", "12", File::FNM_EXTGLOB).should == false + File.fnmatch("{3..-2}", "3", File::FNM_EXTGLOB).should == false + File.fnmatch("{3..-2}", "0", File::FNM_EXTGLOB).should == false + File.fnmatch("{3..-2}", "-2", File::FNM_EXTGLOB).should == false + File.fnmatch("{a..g}", "a", File::FNM_EXTGLOB).should == false + File.fnmatch("{a..g}", "d", File::FNM_EXTGLOB).should == false + File.fnmatch("{a..g}", "g", File::FNM_EXTGLOB).should == false + File.fnmatch("{g..a}", "a", File::FNM_EXTGLOB).should == false + File.fnmatch("{g..a}", "d", File::FNM_EXTGLOB).should == false + File.fnmatch("{g..a}", "g", File::FNM_EXTGLOB).should == false + File.fnmatch("escaping: {{,\\,,\\},\\{}", "escaping: {", File::FNM_EXTGLOB).should == false + File.fnmatch("escaping: {{,\\,,\\},\\{}", "escaping: ,", File::FNM_EXTGLOB).should == false + File.fnmatch("escaping: {{,\\,,\\},\\{}", "escaping: }", File::FNM_EXTGLOB).should == false + File.fnmatch("escaping: {{,\\,,\\},\\{}", "escaping: {", File::FNM_EXTGLOB).should == false + end + + it "doesn't match an extra } when File::FNM_EXTGLOB is passed" do + File.fnmatch('c{at,ub}}s', 'cats', File::FNM_EXTGLOB).should == false + end + + it "matches when both FNM_EXTGLOB and FNM_PATHNAME are passed" do + File.fnmatch("?.md", "a.md", File::FNM_EXTGLOB | File::FNM_PATHNAME).should == true + end + + it "matches a single character for each ? character" do + File.fnmatch('c?t', 'cat').should == true + File.fnmatch('c??t', 'cat').should == false + end + + it "matches zero or more characters for each * character" do + File.fnmatch('c*', 'cats').should == true + File.fnmatch('c*t', 'c/a/b/t').should == true + end + + it "does not match unterminated range of characters" do + File.fnmatch('abc[de', 'abcd').should == false + end + + it "does not match unterminated range of characters as a literal" do + File.fnmatch('abc[de', 'abc[de').should == false + end + + it "matches ranges of characters using bracket expression (e.g. [a-z])" do + File.fnmatch('ca[a-z]', 'cat').should == true + end + + it "matches ranges of characters using bracket expression, taking case into account" do + File.fnmatch('[a-z]', 'D').should == false + File.fnmatch('[^a-z]', 'D').should == true + File.fnmatch('[A-Z]', 'd').should == false + File.fnmatch('[^A-Z]', 'd').should == true + File.fnmatch('[a-z]', 'D', File::FNM_CASEFOLD).should == true + end + + it "does not match characters outside of the range of the bracket expression" do + File.fnmatch('ca[x-z]', 'cat').should == false + File.fnmatch('/ca[s][s-t]/rul[a-b]/[z]he/[x-Z]orld', '/cats/rule/the/World').should == false + end + + it "matches ranges of characters using exclusive bracket expression (e.g. [^t] or [!t])" do + File.fnmatch('ca[^t]', 'cat').should == false + File.fnmatch('ca[^t]', 'cas').should == true + File.fnmatch('ca[!t]', 'cat').should == false + end + + it "matches characters with a case sensitive comparison" do + File.fnmatch('cat', 'CAT').should == false + end + + it "matches characters with case insensitive comparison when flags includes FNM_CASEFOLD" do + File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD).should == true + end + + platform_is_not :windows do + it "doesn't match case sensitive characters on platforms with case sensitive paths, when flags include FNM_SYSCASE" do + File.fnmatch('cat', 'CAT', File::FNM_SYSCASE).should == false + end + end + + platform_is :windows do + it "matches case sensitive characters on platforms with case insensitive paths, when flags include FNM_SYSCASE" do + File.fnmatch('cat', 'CAT', File::FNM_SYSCASE).should == true + end + end + + it "matches wildcard with characters when flags includes FNM_PATHNAME" do + File.fnmatch('*a', 'aa', File::FNM_PATHNAME).should == true + File.fnmatch('a*', 'aa', File::FNM_PATHNAME).should == true + File.fnmatch('a*', 'aaa', File::FNM_PATHNAME).should == true + File.fnmatch('*a', 'aaa', File::FNM_PATHNAME).should == true + end + + it "does not match '/' characters with ? or * when flags includes FNM_PATHNAME" do + File.fnmatch('?', '/', File::FNM_PATHNAME).should == false + File.fnmatch('*', '/', File::FNM_PATHNAME).should == false + end + + it "does not match '/' characters inside bracket expressions when flags includes FNM_PATHNAME" do + File.fnmatch('[/]', '/', File::FNM_PATHNAME).should == false + end + + it "matches literal ? or * in path when pattern includes \\? or \\*" do + File.fnmatch('\?', '?').should == true + File.fnmatch('\?', 'a').should == false + + File.fnmatch('\*', '*').should == true + File.fnmatch('\*', 'a').should == false + end + + it "matches literal character (e.g. 'a') in path when pattern includes escaped character (e.g. \\a)" do + File.fnmatch('\a', 'a').should == true + File.fnmatch('this\b', 'thisb').should == true + end + + it "matches '\\' characters in path when flags includes FNM_NOESCAPE" do + File.fnmatch('\a', '\a', File::FNM_NOESCAPE).should == true + File.fnmatch('\a', 'a', File::FNM_NOESCAPE).should == false + File.fnmatch('\[foo\]\[bar\]', '[foo][bar]', File::FNM_NOESCAPE).should == false + end + + it "escapes special characters inside bracket expression" do + File.fnmatch('[\?]', '?').should == true + File.fnmatch('[\*]', '*').should == true + end + + it "does not match leading periods in filenames with wildcards by default" do + File.should_not.fnmatch('*', '.profile') + File.should.fnmatch('*', 'home/.profile') + File.should.fnmatch('*/*', 'home/.profile') + File.should_not.fnmatch('*/*', 'dave/.profile', File::FNM_PATHNAME) + end + + it "matches patterns with leading periods to dotfiles" do + File.fnmatch('.*', '.profile').should == true + File.fnmatch('.*', '.profile', File::FNM_PATHNAME).should == true + File.fnmatch(".*file", "nondotfile").should == false + File.fnmatch(".*file", "nondotfile", File::FNM_PATHNAME).should == false + end + + it "does not match directories with leading periods by default with FNM_PATHNAME" do + File.fnmatch('.*', '.directory/nondotfile', File::FNM_PATHNAME).should == false + File.fnmatch('.*', '.directory/.profile', File::FNM_PATHNAME).should == false + File.fnmatch('.*', 'foo/.directory/nondotfile', File::FNM_PATHNAME).should == false + File.fnmatch('.*', 'foo/.directory/.profile', File::FNM_PATHNAME).should == false + File.fnmatch('**/.dotfile', '.dotsubdir/.dotfile', File::FNM_PATHNAME).should == false + end + + it "matches leading periods in filenames when flags includes FNM_DOTMATCH" do + File.fnmatch('*', '.profile', File::FNM_DOTMATCH).should == true + File.fnmatch('*', 'home/.profile', File::FNM_DOTMATCH).should == true + end + + it "matches multiple directories with ** and *" do + files = '**/*.rb' + File.fnmatch(files, 'main.rb').should == false + File.fnmatch(files, './main.rb').should == false + File.fnmatch(files, 'lib/song.rb').should == true + File.fnmatch('**.rb', 'main.rb').should == true + File.fnmatch('**.rb', './main.rb').should == false + File.fnmatch('**.rb', 'lib/song.rb').should == true + File.fnmatch('*', 'dave/.profile').should == true + end + + it "matches multiple directories with ** when flags includes File::FNM_PATHNAME" do + files = '**/*.rb' + flags = File::FNM_PATHNAME + + File.fnmatch(files, 'main.rb', flags).should == true + File.fnmatch(files, 'one/two/three/main.rb', flags).should == true + File.fnmatch(files, './main.rb', flags).should == false + + flags = File::FNM_PATHNAME | File::FNM_DOTMATCH + + File.fnmatch(files, './main.rb', flags).should == true + File.fnmatch(files, 'one/two/.main.rb', flags).should == true + + File.fnmatch("**/best/*", 'lib/my/best/song.rb').should == true + end + + it "returns false if '/' in pattern do not match '/' in path when flags includes FNM_PATHNAME" do + pattern = '*/*' + File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME).should == false + + pattern = '**/foo' + File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME).should == false + end + + it "returns true if '/' in pattern match '/' in path when flags includes FNM_PATHNAME" do + pattern = '*/*' + File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true + + pattern = '**/foo' + File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME).should == true + File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME).should == true + File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME).should == true + File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true + end + + it "has special handling for ./ when using * and FNM_PATHNAME" do + File.fnmatch('./*', '.', File::FNM_PATHNAME).should == false + File.fnmatch('./*', './', File::FNM_PATHNAME).should == true + File.fnmatch('./*/', './', File::FNM_PATHNAME).should == false + File.fnmatch('./**', './', File::FNM_PATHNAME).should == true + File.fnmatch('./**/', './', File::FNM_PATHNAME).should == true + File.fnmatch('./*', '.', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == false + File.fnmatch('./*', './', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true + File.fnmatch('./*/', './', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == false + File.fnmatch('./**', './', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true + File.fnmatch('./**/', './', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true + end + + it "matches **/* with FNM_PATHNAME to recurse directories" do + File.fnmatch('nested/**/*', 'nested/subdir', File::FNM_PATHNAME).should == true + File.fnmatch('nested/**/*', 'nested/subdir/file', File::FNM_PATHNAME).should == true + File.fnmatch('nested/**/*', 'nested/.dotsubdir', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true + File.fnmatch('nested/**/*', 'nested/.dotsubir/.dotfile', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true + end + + it "matches ** with FNM_PATHNAME only in current directory" do + File.fnmatch('nested/**', 'nested/subdir', File::FNM_PATHNAME).should == true + File.fnmatch('nested/**', 'nested/subdir/file', File::FNM_PATHNAME).should == false + File.fnmatch('nested/**', 'nested/.dotsubdir', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true + File.fnmatch('nested/**', 'nested/.dotsubir/.dotfile', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == false + end + + it "accepts an object that has a #to_path method" do + File.fnmatch('\*', mock_to_path('a')).should == false + end + + it "raises a TypeError if the first and second arguments are not string-like" do + -> { File.fnmatch(nil, nil, 0, 0) }.should.raise(ArgumentError) + -> { File.fnmatch(1, 'some/thing') }.should.raise(TypeError) + -> { File.fnmatch('some/thing', 1) }.should.raise(TypeError) + -> { File.fnmatch(1, 1) }.should.raise(TypeError) + end + + it "raises a TypeError if the third argument is not an Integer" do + -> { File.fnmatch("*/place", "path/to/file", "flags") }.should.raise(TypeError) + -> { File.fnmatch("*/place", "path/to/file", nil) }.should.raise(TypeError) + end + + it "does not raise a TypeError if the third argument can be coerced to an Integer" do + flags = mock("flags") + flags.should_receive(:to_int).and_return(10) + -> { File.fnmatch("*/place", "path/to/file", flags) }.should_not.raise + end + + it "matches multibyte characters" do + File.fnmatch("*/ä/ø/ñ", "a/ä/ø/ñ").should == true + end end describe "File.fnmatch?" do - it_behaves_like :file_fnmatch, :fnmatch? + it "is an alias of File.fnmatch" do + File.method(:fnmatch?).should == File.method(:fnmatch) + end end diff --git a/spec/ruby/core/file/path_spec.rb b/spec/ruby/core/file/path_spec.rb index ce78dbeede..f3b9b56dbe 100644 --- a/spec/ruby/core/file/path_spec.rb +++ b/spec/ruby/core/file/path_spec.rb @@ -1,8 +1,9 @@ require_relative '../../spec_helper' -require_relative 'shared/path' describe "File#path" do - it_behaves_like :file_path, :path + it "is an alias of File#to_path" do + File.instance_method(:path).should == File.instance_method(:to_path) + end end describe "File.path" do diff --git a/spec/ruby/core/file/shared/fnmatch.rb b/spec/ruby/core/file/shared/fnmatch.rb deleted file mode 100644 index b9140d027d..0000000000 --- a/spec/ruby/core/file/shared/fnmatch.rb +++ /dev/null @@ -1,294 +0,0 @@ -describe :file_fnmatch, shared: true do - it "matches entire strings" do - File.send(@method, 'cat', 'cat').should == true - end - - it "does not match partial strings" do - File.send(@method, 'cat', 'category').should == false - end - - it "does not support { } patterns by default" do - File.send(@method, 'c{at,ub}s', 'cats').should == false - File.send(@method, 'c{at,ub}s', 'c{at,ub}s').should == true - end - - it "supports some { } patterns when File::FNM_EXTGLOB is passed" do - File.send(@method, "{a,b}", "a", File::FNM_EXTGLOB).should == true - File.send(@method, "{a,b}", "b", File::FNM_EXTGLOB).should == true - File.send(@method, "c{at,ub}s", "cats", File::FNM_EXTGLOB).should == true - File.send(@method, "c{at,ub}s", "cubs", File::FNM_EXTGLOB).should == true - File.send(@method, "-c{at,ub}s-", "-cats-", File::FNM_EXTGLOB).should == true - File.send(@method, "-c{at,ub}s-", "-cubs-", File::FNM_EXTGLOB).should == true - File.send(@method, "{a,b,c}{d,e,f}{g,h}", "adg", File::FNM_EXTGLOB).should == true - File.send(@method, "{a,b,c}{d,e,f}{g,h}", "bdg", File::FNM_EXTGLOB).should == true - File.send(@method, "{a,b,c}{d,e,f}{g,h}", "ceh", File::FNM_EXTGLOB).should == true - File.send(@method, "{aa,bb,cc,dd}", "aa", File::FNM_EXTGLOB).should == true - File.send(@method, "{aa,bb,cc,dd}", "bb", File::FNM_EXTGLOB).should == true - File.send(@method, "{aa,bb,cc,dd}", "cc", File::FNM_EXTGLOB).should == true - File.send(@method, "{aa,bb,cc,dd}", "dd", File::FNM_EXTGLOB).should == true - File.send(@method, "{1,5{a,b{c,d}}}", "1", File::FNM_EXTGLOB).should == true - File.send(@method, "{1,5{a,b{c,d}}}", "5a", File::FNM_EXTGLOB).should == true - File.send(@method, "{1,5{a,b{c,d}}}", "5bc", File::FNM_EXTGLOB).should == true - File.send(@method, "{1,5{a,b{c,d}}}", "5bd", File::FNM_EXTGLOB).should == true - File.send(@method, "\\\\{a\\,b,b\\}c}", "\\a,b", File::FNM_EXTGLOB).should == true - File.send(@method, "\\\\{a\\,b,b\\}c}", "\\b}c", File::FNM_EXTGLOB).should == true - end - - it "doesn't support some { } patterns even when File::FNM_EXTGLOB is passed" do - File.send(@method, "a{0..3}b", "a0b", File::FNM_EXTGLOB).should == false - File.send(@method, "a{0..3}b", "a1b", File::FNM_EXTGLOB).should == false - File.send(@method, "a{0..3}b", "a2b", File::FNM_EXTGLOB).should == false - File.send(@method, "a{0..3}b", "a3b", File::FNM_EXTGLOB).should == false - File.send(@method, "{0..12}", "0", File::FNM_EXTGLOB).should == false - File.send(@method, "{0..12}", "6", File::FNM_EXTGLOB).should == false - File.send(@method, "{0..12}", "12", File::FNM_EXTGLOB).should == false - File.send(@method, "{3..-2}", "3", File::FNM_EXTGLOB).should == false - File.send(@method, "{3..-2}", "0", File::FNM_EXTGLOB).should == false - File.send(@method, "{3..-2}", "-2", File::FNM_EXTGLOB).should == false - File.send(@method, "{a..g}", "a", File::FNM_EXTGLOB).should == false - File.send(@method, "{a..g}", "d", File::FNM_EXTGLOB).should == false - File.send(@method, "{a..g}", "g", File::FNM_EXTGLOB).should == false - File.send(@method, "{g..a}", "a", File::FNM_EXTGLOB).should == false - File.send(@method, "{g..a}", "d", File::FNM_EXTGLOB).should == false - File.send(@method, "{g..a}", "g", File::FNM_EXTGLOB).should == false - File.send(@method, "escaping: {{,\\,,\\},\\{}", "escaping: {", File::FNM_EXTGLOB).should == false - File.send(@method, "escaping: {{,\\,,\\},\\{}", "escaping: ,", File::FNM_EXTGLOB).should == false - File.send(@method, "escaping: {{,\\,,\\},\\{}", "escaping: }", File::FNM_EXTGLOB).should == false - File.send(@method, "escaping: {{,\\,,\\},\\{}", "escaping: {", File::FNM_EXTGLOB).should == false - end - - it "doesn't match an extra } when File::FNM_EXTGLOB is passed" do - File.send(@method, 'c{at,ub}}s', 'cats', File::FNM_EXTGLOB).should == false - end - - it "matches when both FNM_EXTGLOB and FNM_PATHNAME are passed" do - File.send(@method, "?.md", "a.md", File::FNM_EXTGLOB | File::FNM_PATHNAME).should == true - end - - it "matches a single character for each ? character" do - File.send(@method, 'c?t', 'cat').should == true - File.send(@method, 'c??t', 'cat').should == false - end - - it "matches zero or more characters for each * character" do - File.send(@method, 'c*', 'cats').should == true - File.send(@method, 'c*t', 'c/a/b/t').should == true - end - - it "does not match unterminated range of characters" do - File.send(@method, 'abc[de', 'abcd').should == false - end - - it "does not match unterminated range of characters as a literal" do - File.send(@method, 'abc[de', 'abc[de').should == false - end - - it "matches ranges of characters using bracket expression (e.g. [a-z])" do - File.send(@method, 'ca[a-z]', 'cat').should == true - end - - it "matches ranges of characters using bracket expression, taking case into account" do - File.send(@method, '[a-z]', 'D').should == false - File.send(@method, '[^a-z]', 'D').should == true - File.send(@method, '[A-Z]', 'd').should == false - File.send(@method, '[^A-Z]', 'd').should == true - File.send(@method, '[a-z]', 'D', File::FNM_CASEFOLD).should == true - end - - it "does not match characters outside of the range of the bracket expression" do - File.send(@method, 'ca[x-z]', 'cat').should == false - File.send(@method, '/ca[s][s-t]/rul[a-b]/[z]he/[x-Z]orld', '/cats/rule/the/World').should == false - end - - it "matches ranges of characters using exclusive bracket expression (e.g. [^t] or [!t])" do - File.send(@method, 'ca[^t]', 'cat').should == false - File.send(@method, 'ca[^t]', 'cas').should == true - File.send(@method, 'ca[!t]', 'cat').should == false - end - - it "matches characters with a case sensitive comparison" do - File.send(@method, 'cat', 'CAT').should == false - end - - it "matches characters with case insensitive comparison when flags includes FNM_CASEFOLD" do - File.send(@method, 'cat', 'CAT', File::FNM_CASEFOLD).should == true - end - - platform_is_not :windows do - it "doesn't match case sensitive characters on platforms with case sensitive paths, when flags include FNM_SYSCASE" do - File.send(@method, 'cat', 'CAT', File::FNM_SYSCASE).should == false - end - end - - platform_is :windows do - it "matches case sensitive characters on platforms with case insensitive paths, when flags include FNM_SYSCASE" do - File.send(@method, 'cat', 'CAT', File::FNM_SYSCASE).should == true - end - end - - it "matches wildcard with characters when flags includes FNM_PATHNAME" do - File.send(@method, '*a', 'aa', File::FNM_PATHNAME).should == true - File.send(@method, 'a*', 'aa', File::FNM_PATHNAME).should == true - File.send(@method, 'a*', 'aaa', File::FNM_PATHNAME).should == true - File.send(@method, '*a', 'aaa', File::FNM_PATHNAME).should == true - end - - it "does not match '/' characters with ? or * when flags includes FNM_PATHNAME" do - File.send(@method, '?', '/', File::FNM_PATHNAME).should == false - File.send(@method, '*', '/', File::FNM_PATHNAME).should == false - end - - it "does not match '/' characters inside bracket expressions when flags includes FNM_PATHNAME" do - File.send(@method, '[/]', '/', File::FNM_PATHNAME).should == false - end - - it "matches literal ? or * in path when pattern includes \\? or \\*" do - File.send(@method, '\?', '?').should == true - File.send(@method, '\?', 'a').should == false - - File.send(@method, '\*', '*').should == true - File.send(@method, '\*', 'a').should == false - end - - it "matches literal character (e.g. 'a') in path when pattern includes escaped character (e.g. \\a)" do - File.send(@method, '\a', 'a').should == true - File.send(@method, 'this\b', 'thisb').should == true - end - - it "matches '\\' characters in path when flags includes FNM_NOESACPE" do - File.send(@method, '\a', '\a', File::FNM_NOESCAPE).should == true - File.send(@method, '\a', 'a', File::FNM_NOESCAPE).should == false - File.send(@method, '\[foo\]\[bar\]', '[foo][bar]', File::FNM_NOESCAPE).should == false - end - - it "escapes special characters inside bracket expression" do - File.send(@method, '[\?]', '?').should == true - File.send(@method, '[\*]', '*').should == true - end - - it "does not match leading periods in filenames with wildcards by default" do - File.should_not.send(@method, '*', '.profile') - File.should.send(@method, '*', 'home/.profile') - File.should.send(@method, '*/*', 'home/.profile') - File.should_not.send(@method, '*/*', 'dave/.profile', File::FNM_PATHNAME) - end - - it "matches patterns with leading periods to dotfiles" do - File.send(@method, '.*', '.profile').should == true - File.send(@method, '.*', '.profile', File::FNM_PATHNAME).should == true - File.send(@method, ".*file", "nondotfile").should == false - File.send(@method, ".*file", "nondotfile", File::FNM_PATHNAME).should == false - end - - it "does not match directories with leading periods by default with FNM_PATHNAME" do - File.send(@method, '.*', '.directory/nondotfile', File::FNM_PATHNAME).should == false - File.send(@method, '.*', '.directory/.profile', File::FNM_PATHNAME).should == false - File.send(@method, '.*', 'foo/.directory/nondotfile', File::FNM_PATHNAME).should == false - File.send(@method, '.*', 'foo/.directory/.profile', File::FNM_PATHNAME).should == false - File.send(@method, '**/.dotfile', '.dotsubdir/.dotfile', File::FNM_PATHNAME).should == false - end - - it "matches leading periods in filenames when flags includes FNM_DOTMATCH" do - File.send(@method, '*', '.profile', File::FNM_DOTMATCH).should == true - File.send(@method, '*', 'home/.profile', File::FNM_DOTMATCH).should == true - end - - it "matches multiple directories with ** and *" do - files = '**/*.rb' - File.send(@method, files, 'main.rb').should == false - File.send(@method, files, './main.rb').should == false - File.send(@method, files, 'lib/song.rb').should == true - File.send(@method, '**.rb', 'main.rb').should == true - File.send(@method, '**.rb', './main.rb').should == false - File.send(@method, '**.rb', 'lib/song.rb').should == true - File.send(@method, '*', 'dave/.profile').should == true - end - - it "matches multiple directories with ** when flags includes File::FNM_PATHNAME" do - files = '**/*.rb' - flags = File::FNM_PATHNAME - - File.send(@method, files, 'main.rb', flags).should == true - File.send(@method, files, 'one/two/three/main.rb', flags).should == true - File.send(@method, files, './main.rb', flags).should == false - - flags = File::FNM_PATHNAME | File::FNM_DOTMATCH - - File.send(@method, files, './main.rb', flags).should == true - File.send(@method, files, 'one/two/.main.rb', flags).should == true - - File.send(@method, "**/best/*", 'lib/my/best/song.rb').should == true - end - - it "returns false if '/' in pattern do not match '/' in path when flags includes FNM_PATHNAME" do - pattern = '*/*' - File.send(@method, pattern, 'dave/.profile', File::FNM_PATHNAME).should == false - - pattern = '**/foo' - File.send(@method, pattern, 'a/.b/c/foo', File::FNM_PATHNAME).should == false - end - - it "returns true if '/' in pattern match '/' in path when flags includes FNM_PATHNAME" do - pattern = '*/*' - File.send(@method, pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true - - pattern = '**/foo' - File.send(@method, pattern, 'a/b/c/foo', File::FNM_PATHNAME).should == true - File.send(@method, pattern, '/a/b/c/foo', File::FNM_PATHNAME).should == true - File.send(@method, pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME).should == true - File.send(@method, pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true - end - - it "has special handling for ./ when using * and FNM_PATHNAME" do - File.send(@method, './*', '.', File::FNM_PATHNAME).should == false - File.send(@method, './*', './', File::FNM_PATHNAME).should == true - File.send(@method, './*/', './', File::FNM_PATHNAME).should == false - File.send(@method, './**', './', File::FNM_PATHNAME).should == true - File.send(@method, './**/', './', File::FNM_PATHNAME).should == true - File.send(@method, './*', '.', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == false - File.send(@method, './*', './', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true - File.send(@method, './*/', './', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == false - File.send(@method, './**', './', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true - File.send(@method, './**/', './', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true - end - - it "matches **/* with FNM_PATHNAME to recurse directories" do - File.send(@method, 'nested/**/*', 'nested/subdir', File::FNM_PATHNAME).should == true - File.send(@method, 'nested/**/*', 'nested/subdir/file', File::FNM_PATHNAME).should == true - File.send(@method, 'nested/**/*', 'nested/.dotsubdir', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true - File.send(@method, 'nested/**/*', 'nested/.dotsubir/.dotfile', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true - end - - it "matches ** with FNM_PATHNAME only in current directory" do - File.send(@method, 'nested/**', 'nested/subdir', File::FNM_PATHNAME).should == true - File.send(@method, 'nested/**', 'nested/subdir/file', File::FNM_PATHNAME).should == false - File.send(@method, 'nested/**', 'nested/.dotsubdir', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == true - File.send(@method, 'nested/**', 'nested/.dotsubir/.dotfile', File::FNM_PATHNAME | File::FNM_DOTMATCH).should == false - end - - it "accepts an object that has a #to_path method" do - File.send(@method, '\*', mock_to_path('a')).should == false - end - - it "raises a TypeError if the first and second arguments are not string-like" do - -> { File.send(@method, nil, nil, 0, 0) }.should.raise(ArgumentError) - -> { File.send(@method, 1, 'some/thing') }.should.raise(TypeError) - -> { File.send(@method, 'some/thing', 1) }.should.raise(TypeError) - -> { File.send(@method, 1, 1) }.should.raise(TypeError) - end - - it "raises a TypeError if the third argument is not an Integer" do - -> { File.send(@method, "*/place", "path/to/file", "flags") }.should.raise(TypeError) - -> { File.send(@method, "*/place", "path/to/file", nil) }.should.raise(TypeError) - end - - it "does not raise a TypeError if the third argument can be coerced to an Integer" do - flags = mock("flags") - flags.should_receive(:to_int).and_return(10) - -> { File.send(@method, "*/place", "path/to/file", flags) }.should_not.raise - end - - it "matches multibyte characters" do - File.fnmatch("*/ä/ø/ñ", "a/ä/ø/ñ").should == true - end -end diff --git a/spec/ruby/core/file/shared/path.rb b/spec/ruby/core/file/shared/path.rb deleted file mode 100644 index 6c6f7d4234..0000000000 --- a/spec/ruby/core/file/shared/path.rb +++ /dev/null @@ -1,82 +0,0 @@ -describe :file_path, shared: true do - before :each do - @path = tmp("file_to_path") - @name = File.basename(@path) - touch @path - end - - after :each do - @file.close if @file and !@file.closed? - rm_r @path - end - - it "returns a String" do - @file = File.new @path - @file.send(@method).should.instance_of?(String) - end - - it "returns a different String on every call" do - @file = File.new @path - path1 = @file.send(@method) - path2 = @file.send(@method) - path1.should == path2 - path1.should_not.equal?(path2) - end - - it "returns a mutable String" do - @file = File.new @path.dup.freeze - path = @file.send(@method) - path.should == @path - path.should_not.frozen? - path << "test" - @file.send(@method).should == @path - end - - it "calls to_str on argument and returns exact value" do - path = mock('path') - path.should_receive(:to_str).and_return(@path) - @file = File.new path - @file.send(@method).should == @path - end - - it "does not normalise the path it returns" do - Dir.chdir(tmp("")) do - unorm = "./#{@name}" - @file = File.new unorm - @file.send(@method).should == unorm - end - end - - it "does not canonicalize the path it returns" do - dir = File.basename tmp("") - path = "#{tmp("")}../#{dir}/#{@name}" - @file = File.new path - @file.send(@method).should == path - end - - it "does not absolute-ise the path it returns" do - Dir.chdir(tmp("")) do - @file = File.new @name - @file.send(@method).should == @name - end - end - - it "preserves the encoding of the path" do - path = @path.force_encoding("euc-jp") - @file = File.new path - @file.send(@method).encoding.should == Encoding.find("euc-jp") - end - - platform_is :linux do - guard -> { defined?(File::TMPFILE) } do - before :each do - @dir = tmp("tmpfilespec") - mkdir_p @dir - end - - after :each do - rm_r @dir - end - end - end -end diff --git a/spec/ruby/core/file/shared/unlink.rb b/spec/ruby/core/file/shared/unlink.rb deleted file mode 100644 index 0032907ba2..0000000000 --- a/spec/ruby/core/file/shared/unlink.rb +++ /dev/null @@ -1,61 +0,0 @@ -describe :file_unlink, shared: true do - before :each do - @file1 = tmp('test.txt') - @file2 = tmp('test2.txt') - - touch @file1 - touch @file2 - end - - after :each do - File.send(@method, @file1) if File.exist?(@file1) - File.send(@method, @file2) if File.exist?(@file2) - - @file1 = nil - @file2 = nil - end - - it "returns 0 when called without arguments" do - File.send(@method).should == 0 - end - - it "deletes a single file" do - File.send(@method, @file1).should == 1 - File.should_not.exist?(@file1) - end - - it "deletes multiple files" do - File.send(@method, @file1, @file2).should == 2 - File.should_not.exist?(@file1) - File.should_not.exist?(@file2) - end - - it "raises a TypeError if not passed a String type" do - -> { File.send(@method, 1) }.should.raise(TypeError) - end - - it "raises an Errno::ENOENT when the given file doesn't exist" do - -> { File.send(@method, 'bogus') }.should.raise(Errno::ENOENT) - end - - it "coerces a given parameter into a string if possible" do - mock = mock("to_str") - mock.should_receive(:to_str).and_return(@file1) - File.send(@method, mock).should == 1 - end - - it "accepts an object that has a #to_path method" do - File.send(@method, mock_to_path(@file1)).should == 1 - end - - platform_is :windows do - it "allows deleting an open file with File::SHARE_DELETE" do - path = tmp("share_delete.txt") - File.open(path, mode: File::CREAT | File::WRONLY | File::BINARY | File::SHARE_DELETE) do |f| - File.should.exist?(path) - File.send(@method, path) - end - File.should_not.exist?(path) - end - end -end diff --git a/spec/ruby/core/file/sticky_spec.rb b/spec/ruby/core/file/sticky_spec.rb index 5f7b2d93eb..782541abf3 100644 --- a/spec/ruby/core/file/sticky_spec.rb +++ b/spec/ruby/core/file/sticky_spec.rb @@ -41,7 +41,7 @@ describe "File.sticky?" do touch(filename) stat = File.stat(filename) mode = stat.mode - raise_error(Errno::EFTYPE){File.chmod(mode|01000, filename)} + -> { File.chmod(mode|01000, filename) }.should.raise(Errno::EFTYPE) File.sticky?(filename).should == false rm_r filename diff --git a/spec/ruby/core/file/to_path_spec.rb b/spec/ruby/core/file/to_path_spec.rb index 6d168a065c..b968d3b2b9 100644 --- a/spec/ruby/core/file/to_path_spec.rb +++ b/spec/ruby/core/file/to_path_spec.rb @@ -1,6 +1,84 @@ require_relative '../../spec_helper' -require_relative 'shared/path' describe "File#to_path" do - it_behaves_like :file_path, :to_path + before :each do + @path = tmp("file_to_path") + @name = File.basename(@path) + touch @path + end + + after :each do + @file.close if @file and !@file.closed? + rm_r @path + end + + it "returns a String" do + @file = File.new @path + @file.to_path.should.instance_of?(String) + end + + it "returns a different String on every call" do + @file = File.new @path + path1 = @file.to_path + path2 = @file.to_path + path1.should == path2 + path1.should_not.equal?(path2) + end + + it "returns a mutable String" do + @file = File.new @path.dup.freeze + path = @file.to_path + path.should == @path + path.should_not.frozen? + path << "test" + @file.to_path.should == @path + end + + it "calls to_str on argument and returns exact value" do + path = mock('path') + path.should_receive(:to_str).and_return(@path) + @file = File.new path + @file.to_path.should == @path + end + + it "does not normalise the path it returns" do + Dir.chdir(tmp("")) do + unorm = "./#{@name}" + @file = File.new unorm + @file.to_path.should == unorm + end + end + + it "does not canonicalize the path it returns" do + dir = File.basename tmp("") + path = "#{tmp("")}../#{dir}/#{@name}" + @file = File.new path + @file.to_path.should == path + end + + it "does not absolute-ise the path it returns" do + Dir.chdir(tmp("")) do + @file = File.new @name + @file.to_path.should == @name + end + end + + it "preserves the encoding of the path" do + path = @path.force_encoding("euc-jp") + @file = File.new path + @file.to_path.encoding.should == Encoding.find("euc-jp") + end + + platform_is :linux do + guard -> { defined?(File::TMPFILE) } do + before :each do + @dir = tmp("tmpfilespec") + mkdir_p @dir + end + + after :each do + rm_r @dir + end + end + end end diff --git a/spec/ruby/core/file/unlink_spec.rb b/spec/ruby/core/file/unlink_spec.rb index 28872d55ed..db0c08f3ae 100644 --- a/spec/ruby/core/file/unlink_spec.rb +++ b/spec/ruby/core/file/unlink_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/unlink' describe "File.unlink" do - it_behaves_like :file_unlink, :unlink + it "is an alias of File.delete" do + File.method(:unlink).should == File.method(:delete) + end end diff --git a/spec/ruby/core/file/zero_spec.rb b/spec/ruby/core/file/zero_spec.rb index 01c7505ef2..09b0decf48 100644 --- a/spec/ruby/core/file/zero_spec.rb +++ b/spec/ruby/core/file/zero_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/file/zero' describe "File.zero?" do - it_behaves_like :file_zero, :zero?, File - it_behaves_like :file_zero_missing, :zero?, File + it "is an alias of File.empty?" do + File.method(:zero?).should == File.method(:empty?) + end end diff --git a/spec/ruby/core/filetest/empty_spec.rb b/spec/ruby/core/filetest/empty_spec.rb new file mode 100644 index 0000000000..2c7fbe0dcd --- /dev/null +++ b/spec/ruby/core/filetest/empty_spec.rb @@ -0,0 +1,7 @@ +require_relative '../../spec_helper' +require_relative '../../shared/file/zero' + +describe "FileTest.empty?" do + it_behaves_like :file_zero, :empty?, FileTest + it_behaves_like :file_zero_missing, :empty?, FileTest +end diff --git a/spec/ruby/core/filetest/zero_spec.rb b/spec/ruby/core/filetest/zero_spec.rb index 92cab67f1b..de024c25ff 100644 --- a/spec/ruby/core/filetest/zero_spec.rb +++ b/spec/ruby/core/filetest/zero_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/file/zero' describe "FileTest.zero?" do - it_behaves_like :file_zero, :zero?, FileTest - it_behaves_like :file_zero_missing, :zero?, FileTest + it "is an alias of FileTest.empty?" do + FileTest.method(:zero?).should == FileTest.method(:empty?) + end end diff --git a/spec/ruby/core/float/angle_spec.rb b/spec/ruby/core/float/angle_spec.rb index c07249aa97..ac182c5b73 100644 --- a/spec/ruby/core/float/angle_spec.rb +++ b/spec/ruby/core/float/angle_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/arg' describe "Float#angle" do - it_behaves_like :float_arg, :angle + it "is an alias of Float#arg" do + Float.instance_method(:angle).should == Float.instance_method(:arg) + end end diff --git a/spec/ruby/core/float/arg_spec.rb b/spec/ruby/core/float/arg_spec.rb index d3a50668f8..c9c602bbf6 100644 --- a/spec/ruby/core/float/arg_spec.rb +++ b/spec/ruby/core/float/arg_spec.rb @@ -1,6 +1,38 @@ require_relative '../../spec_helper' -require_relative 'shared/arg' describe "Float#arg" do - it_behaves_like :float_arg, :arg + it "returns NaN if NaN" do + f = nan_value + f.arg.nan?.should == true + end + + it "returns self if NaN" do + f = nan_value + f.arg.should.equal?(f) + end + + it "returns 0 if positive" do + 1.0.arg.should == 0 + end + + it "returns 0 if +0.0" do + 0.0.arg.should == 0 + end + + it "returns 0 if +Infinity" do + infinity_value.arg.should == 0 + end + + it "returns Pi if negative" do + (-1.0).arg.should == Math::PI + end + + # This was established in r23960 + it "returns Pi if -0.0" do + (-0.0).arg.should == Math::PI + end + + it "returns Pi if -Infinity" do + (-infinity_value).arg.should == Math::PI + end end diff --git a/spec/ruby/core/float/case_compare_spec.rb b/spec/ruby/core/float/case_compare_spec.rb index b902fbea18..c82803642d 100644 --- a/spec/ruby/core/float/case_compare_spec.rb +++ b/spec/ruby/core/float/case_compare_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/equal' describe "Float#===" do - it_behaves_like :float_equal, :=== + it "is an alias of Float#==" do + Float.instance_method(:===).should == Float.instance_method(:==) + end end diff --git a/spec/ruby/core/float/equal_value_spec.rb b/spec/ruby/core/float/equal_value_spec.rb index 03eea5108e..37d0e162d3 100644 --- a/spec/ruby/core/float/equal_value_spec.rb +++ b/spec/ruby/core/float/equal_value_spec.rb @@ -1,6 +1,40 @@ require_relative '../../spec_helper' -require_relative 'shared/equal' describe "Float#==" do - it_behaves_like :float_equal, :== + it "returns true if self has the same value as other" do + (1.0 == 1).should == true + (2.71828 == 1.428).should == false + (-4.2 == 4.2).should == false + end + + it "calls 'other == self' if coercion fails" do + x = mock('other') + def x.==(other) + 2.0 == other + end + + (1.0 == x).should == false + (2.0 == x).should == true + end + + it "returns false if one side is NaN" do + [1.0, 42, bignum_value].each { |n| + (nan_value == n).should == false + (n == nan_value).should == false + } + end + + it "handles positive infinity" do + [1.0, 42, bignum_value].each { |n| + (infinity_value == n).should == false + (n == infinity_value).should == false + } + end + + it "handles negative infinity" do + [1.0, 42, bignum_value].each { |n| + ((-infinity_value) == n).should == false + (n == -infinity_value).should == false + } + end end diff --git a/spec/ruby/core/float/fdiv_spec.rb b/spec/ruby/core/float/fdiv_spec.rb index be25ee283b..8a3ead4880 100644 --- a/spec/ruby/core/float/fdiv_spec.rb +++ b/spec/ruby/core/float/fdiv_spec.rb @@ -1,6 +1,61 @@ require_relative '../../spec_helper' -require_relative 'shared/quo' describe "Float#fdiv" do - it_behaves_like :float_quo, :fdiv + it "performs floating-point division between self and an Integer" do + 8.9.fdiv(7).should == 1.2714285714285716 + end + + it "performs floating-point division between self and an Integer" do + 8.9.fdiv(9999999999999**9).should == 8.900000000008011e-117 + end + + it "performs floating-point division between self and a Float" do + 2827.22.fdiv(872.111111).should == 3.2418116961704433 + end + + it "returns NaN when the argument is NaN" do + -1819.999999.fdiv(nan_value).nan?.should == true + 11109.1981271.fdiv(nan_value).nan?.should == true + end + + it "returns Infinity when the argument is 0.0" do + 2827.22.fdiv(0.0).infinite?.should == 1 + end + + it "returns -Infinity when the argument is 0.0 and self is negative" do + -48229.282.fdiv(0.0).infinite?.should == -1 + end + + it "returns Infinity when the argument is 0" do + 2827.22.fdiv(0).infinite?.should == 1 + end + + it "returns -Infinity when the argument is 0 and self is negative" do + -48229.282.fdiv(0).infinite?.should == -1 + end + + it "returns 0.0 when the argument is Infinity" do + 47292.2821.fdiv(infinity_value).should == 0.0 + end + + it "returns -0.0 when the argument is -Infinity" do + 1.9999918.fdiv(-infinity_value).should == -0.0 + end + + it "performs floating-point division between self and a Rational" do + 74620.09.fdiv(Rational(2,3)).should == 111930.135 + end + + it "performs floating-point division between self and a Complex" do + 74620.09.fdiv(Complex(8,2)).should == Complex( + 8778.834117647059, -2194.7085294117646) + end + + it "raises a TypeError when argument isn't numeric" do + -> { 27292.2.fdiv(mock('non-numeric')) }.should.raise(TypeError) + end + + it "raises an ArgumentError when passed multiple arguments" do + -> { 272.221.fdiv(6,0.2) }.should.raise(ArgumentError) + end end diff --git a/spec/ruby/core/float/inspect_spec.rb b/spec/ruby/core/float/inspect_spec.rb index 4be1927d84..3827167c17 100644 --- a/spec/ruby/core/float/inspect_spec.rb +++ b/spec/ruby/core/float/inspect_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/to_s' describe "Float#inspect" do - it_behaves_like :float_to_s, :inspect + it "is an alias of Float#to_s" do + Float.instance_method(:inspect).should == Float.instance_method(:to_s) + end end diff --git a/spec/ruby/core/float/magnitude_spec.rb b/spec/ruby/core/float/magnitude_spec.rb index 7cdd8ef28a..4a753267e0 100644 --- a/spec/ruby/core/float/magnitude_spec.rb +++ b/spec/ruby/core/float/magnitude_spec.rb @@ -2,5 +2,13 @@ require_relative "../../spec_helper" require_relative 'shared/abs' describe "Float#magnitude" do - it_behaves_like :float_abs, :magnitude + ruby_version_is ""..."3.4" do + it_behaves_like :float_abs, :magnitude + end + + ruby_version_is "3.4" do + it "is an alias of Float#abs" do + Float.instance_method(:magnitude).should == Float.instance_method(:abs) + end + end end diff --git a/spec/ruby/core/float/modulo_spec.rb b/spec/ruby/core/float/modulo_spec.rb index 8ae80a0b05..8b7aedf822 100644 --- a/spec/ruby/core/float/modulo_spec.rb +++ b/spec/ruby/core/float/modulo_spec.rb @@ -1,10 +1,56 @@ require_relative '../../spec_helper' -require_relative 'shared/modulo' describe "Float#%" do - it_behaves_like :float_modulo, :% + it "returns self modulo other" do + (6543.21 % 137).should be_close(104.21, TOLERANCE) + (5667.19 % bignum_value).should be_close(5667.19, TOLERANCE) + (6543.21 % 137.24).should be_close(92.9299999999996, TOLERANCE) + + (-1.0 % 1).should == 0 + end + + it "returns self when modulus is +Infinity" do + (4.2 % Float::INFINITY).should == 4.2 + end + + it "returns -Infinity when modulus is -Infinity" do + (4.2 % -Float::INFINITY).should == -Float::INFINITY + end + + it "returns NaN when called on NaN or Infinities" do + (Float::NAN % 42).should.nan? + (Float::INFINITY % 42).should.nan? + (-Float::INFINITY % 42).should.nan? + end + + it "returns NaN when modulus is NaN" do + (4.2 % Float::NAN).should.nan? + end + + it "returns -0.0 when called on -0.0 with a non zero modulus" do + r = -0.0 % 42 + r.should == 0 + (1/r).should < 0 + + r = -0.0 % Float::INFINITY + r.should == 0 + (1/r).should < 0 + end + + it "tries to coerce the modulus" do + obj = mock("modulus") + obj.should_receive(:coerce).with(1.25).and_return([1.25, 0.5]) + (1.25 % obj).should == 0.25 + end + + it "raises a ZeroDivisionError if other is zero" do + -> { 1.0 % 0 }.should.raise(ZeroDivisionError) + -> { 1.0 % 0.0 }.should.raise(ZeroDivisionError) + end end describe "Float#modulo" do - it_behaves_like :float_modulo, :modulo + it "is an alias of Float#%" do + Float.instance_method(:modulo).should == Float.instance_method(:%) + end end diff --git a/spec/ruby/core/float/phase_spec.rb b/spec/ruby/core/float/phase_spec.rb index 2aa84024b4..ad112ac9fe 100644 --- a/spec/ruby/core/float/phase_spec.rb +++ b/spec/ruby/core/float/phase_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/arg' describe "Float#phase" do - it_behaves_like :float_arg, :phase + it "is an alias of Float#arg" do + Float.instance_method(:phase).should == Float.instance_method(:arg) + end end diff --git a/spec/ruby/core/float/quo_spec.rb b/spec/ruby/core/float/quo_spec.rb index b5c64f9d87..0e9a7a0a0c 100644 --- a/spec/ruby/core/float/quo_spec.rb +++ b/spec/ruby/core/float/quo_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/quo' describe "Float#quo" do - it_behaves_like :float_quo, :quo + it "is an alias of Float#fdiv" do + Float.instance_method(:quo).should == Float.instance_method(:fdiv) + end end diff --git a/spec/ruby/core/float/shared/arg.rb b/spec/ruby/core/float/shared/arg.rb deleted file mode 100644 index de0024313d..0000000000 --- a/spec/ruby/core/float/shared/arg.rb +++ /dev/null @@ -1,36 +0,0 @@ -describe :float_arg, shared: true do - it "returns NaN if NaN" do - f = nan_value - f.send(@method).nan?.should == true - end - - it "returns self if NaN" do - f = nan_value - f.send(@method).should.equal?(f) - end - - it "returns 0 if positive" do - 1.0.send(@method).should == 0 - end - - it "returns 0 if +0.0" do - 0.0.send(@method).should == 0 - end - - it "returns 0 if +Infinity" do - infinity_value.send(@method).should == 0 - end - - it "returns Pi if negative" do - (-1.0).send(@method).should == Math::PI - end - - # This was established in r23960 - it "returns Pi if -0.0" do - (-0.0).send(@method).should == Math::PI - end - - it "returns Pi if -Infinity" do - (-infinity_value).send(@method).should == Math::PI - end -end diff --git a/spec/ruby/core/float/shared/equal.rb b/spec/ruby/core/float/shared/equal.rb deleted file mode 100644 index 4d524e1cf2..0000000000 --- a/spec/ruby/core/float/shared/equal.rb +++ /dev/null @@ -1,38 +0,0 @@ -describe :float_equal, shared: true do - it "returns true if self has the same value as other" do - 1.0.send(@method, 1).should == true - 2.71828.send(@method, 1.428).should == false - -4.2.send(@method, 4.2).should == false - end - - it "calls 'other == self' if coercion fails" do - x = mock('other') - def x.==(other) - 2.0 == other - end - - 1.0.send(@method, x).should == false - 2.0.send(@method, x).should == true - end - - it "returns false if one side is NaN" do - [1.0, 42, bignum_value].each { |n| - (nan_value.send(@method, n)).should == false - (n.send(@method, nan_value)).should == false - } - end - - it "handles positive infinity" do - [1.0, 42, bignum_value].each { |n| - (infinity_value.send(@method, n)).should == false - (n.send(@method, infinity_value)).should == false - } - end - - it "handles negative infinity" do - [1.0, 42, bignum_value].each { |n| - ((-infinity_value).send(@method, n)).should == false - (n.send(@method, -infinity_value)).should == false - } - end -end diff --git a/spec/ruby/core/float/shared/modulo.rb b/spec/ruby/core/float/shared/modulo.rb deleted file mode 100644 index 1efee1476d..0000000000 --- a/spec/ruby/core/float/shared/modulo.rb +++ /dev/null @@ -1,48 +0,0 @@ -describe :float_modulo, shared: true do - it "returns self modulo other" do - 6543.21.send(@method, 137).should be_close(104.21, TOLERANCE) - 5667.19.send(@method, bignum_value).should be_close(5667.19, TOLERANCE) - 6543.21.send(@method, 137.24).should be_close(92.9299999999996, TOLERANCE) - - -1.0.send(@method, 1).should == 0 - end - - it "returns self when modulus is +Infinity" do - 4.2.send(@method, Float::INFINITY).should == 4.2 - end - - it "returns -Infinity when modulus is -Infinity" do - 4.2.send(@method, -Float::INFINITY).should == -Float::INFINITY - end - - it "returns NaN when called on NaN or Infinities" do - Float::NAN.send(@method, 42).should.nan? - Float::INFINITY.send(@method, 42).should.nan? - (-Float::INFINITY).send(@method, 42).should.nan? - end - - it "returns NaN when modulus is NaN" do - 4.2.send(@method, Float::NAN).should.nan? - end - - it "returns -0.0 when called on -0.0 with a non zero modulus" do - r = (-0.0).send(@method, 42) - r.should == 0 - (1/r).should < 0 - - r = (-0.0).send(@method, Float::INFINITY) - r.should == 0 - (1/r).should < 0 - end - - it "tries to coerce the modulus" do - obj = mock("modulus") - obj.should_receive(:coerce).with(1.25).and_return([1.25, 0.5]) - (1.25 % obj).should == 0.25 - end - - it "raises a ZeroDivisionError if other is zero" do - -> { 1.0.send(@method, 0) }.should.raise(ZeroDivisionError) - -> { 1.0.send(@method, 0.0) }.should.raise(ZeroDivisionError) - end -end diff --git a/spec/ruby/core/float/shared/quo.rb b/spec/ruby/core/float/shared/quo.rb deleted file mode 100644 index 930187aaf7..0000000000 --- a/spec/ruby/core/float/shared/quo.rb +++ /dev/null @@ -1,59 +0,0 @@ -describe :float_quo, shared: true do - it "performs floating-point division between self and an Integer" do - 8.9.send(@method, 7).should == 1.2714285714285716 - end - - it "performs floating-point division between self and an Integer" do - 8.9.send(@method, 9999999999999**9).should == 8.900000000008011e-117 - end - - it "performs floating-point division between self and a Float" do - 2827.22.send(@method, 872.111111).should == 3.2418116961704433 - end - - it "returns NaN when the argument is NaN" do - -1819.999999.send(@method, nan_value).nan?.should == true - 11109.1981271.send(@method, nan_value).nan?.should == true - end - - it "returns Infinity when the argument is 0.0" do - 2827.22.send(@method, 0.0).infinite?.should == 1 - end - - it "returns -Infinity when the argument is 0.0 and self is negative" do - -48229.282.send(@method, 0.0).infinite?.should == -1 - end - - it "returns Infinity when the argument is 0" do - 2827.22.send(@method, 0).infinite?.should == 1 - end - - it "returns -Infinity when the argument is 0 and self is negative" do - -48229.282.send(@method, 0).infinite?.should == -1 - end - - it "returns 0.0 when the argument is Infinity" do - 47292.2821.send(@method, infinity_value).should == 0.0 - end - - it "returns -0.0 when the argument is -Infinity" do - 1.9999918.send(@method, -infinity_value).should == -0.0 - end - - it "performs floating-point division between self and a Rational" do - 74620.09.send(@method, Rational(2,3)).should == 111930.135 - end - - it "performs floating-point division between self and a Complex" do - 74620.09.send(@method, Complex(8,2)).should == Complex( - 8778.834117647059, -2194.7085294117646) - end - - it "raises a TypeError when argument isn't numeric" do - -> { 27292.2.send(@method, mock('non-numeric')) }.should.raise(TypeError) - end - - it "raises an ArgumentError when passed multiple arguments" do - -> { 272.221.send(@method, 6,0.2) }.should.raise(ArgumentError) - end -end diff --git a/spec/ruby/core/float/shared/to_s.rb b/spec/ruby/core/float/shared/to_s.rb deleted file mode 100644 index 81ffdd9e81..0000000000 --- a/spec/ruby/core/float/shared/to_s.rb +++ /dev/null @@ -1,308 +0,0 @@ -describe :float_to_s, shared: true do - it "returns 'NaN' for NaN" do - nan_value().send(@method).should == 'NaN' - end - - it "returns 'Infinity' for positive infinity" do - infinity_value().send(@method).should == 'Infinity' - end - - it "returns '-Infinity' for negative infinity" do - (-infinity_value()).send(@method).should == '-Infinity' - end - - it "returns '0.0' for 0.0" do - 0.0.send(@method).should == "0.0" - end - - platform_is_not :openbsd do - it "emits '-' for -0.0" do - -0.0.send(@method).should == "-0.0" - end - end - - it "emits a '-' for negative values" do - -3.14.send(@method).should == "-3.14" - end - - it "emits a trailing '.0' for a whole number" do - 50.0.send(@method).should == "50.0" - end - - it "emits a trailing '.0' for the mantissa in e format" do - 1.0e20.send(@method).should == "1.0e+20" - end - - it "uses non-e format for a positive value with fractional part having 5 significant figures" do - 0.0001.send(@method).should == "0.0001" - end - - it "uses non-e format for a negative value with fractional part having 5 significant figures" do - -0.0001.send(@method).should == "-0.0001" - end - - it "uses e format for a positive value with fractional part having 6 significant figures" do - 0.00001.send(@method).should == "1.0e-05" - end - - it "uses e format for a negative value with fractional part having 6 significant figures" do - -0.00001.send(@method).should == "-1.0e-05" - end - - it "uses non-e format for a positive value with whole part having 15 significant figures" do - 10000000000000.0.send(@method).should == "10000000000000.0" - end - - it "uses non-e format for a negative value with whole part having 15 significant figures" do - -10000000000000.0.send(@method).should == "-10000000000000.0" - end - - it "uses non-e format for a positive value with whole part having 16 significant figures" do - 100000000000000.0.send(@method).should == "100000000000000.0" - end - - it "uses non-e format for a negative value with whole part having 16 significant figures" do - -100000000000000.0.send(@method).should == "-100000000000000.0" - end - - it "uses e format for a positive value with whole part having 18 significant figures" do - 10000000000000000.0.send(@method).should == "1.0e+16" - end - - it "uses e format for a negative value with whole part having 18 significant figures" do - -10000000000000000.0.send(@method).should == "-1.0e+16" - end - - it "uses e format for a positive value with whole part having 17 significant figures" do - 1000000000000000.0.send(@method).should == "1.0e+15" - end - - it "uses e format for a negative value with whole part having 17 significant figures" do - -1000000000000000.0.send(@method).should == "-1.0e+15" - end - - # #3273 - it "outputs the minimal, unique form necessary to recreate the value" do - value = 0.21611564636388508 - string = "0.21611564636388508" - - value.send(@method).should == string - string.to_f.should == value - end - - it "outputs the minimal, unique form to represent the value" do - 0.56.send(@method).should == "0.56" - end - - describe "matches" do - it "random examples in all ranges" do - # 50.times do - # bytes = (0...8).map { rand(256) } - # string = bytes.pack('C8') - # float = string.unpack('D').first - # puts "#{'%.20g' % float}.send(@method).should == #{float.send(@method).inspect}" - # end - - 2.5540217314354050325e+163.send(@method).should == "2.554021731435405e+163" - 2.5492588360356597544e-172.send(@method).should == "2.5492588360356598e-172" - 1.742770260934704852e-82.send(@method).should == "1.7427702609347049e-82" - 6.2108093676180883209e-104.send(@method).should == "6.210809367618088e-104" - -3.3448803488331067402e-143.send(@method).should == "-3.3448803488331067e-143" - -2.2740074343500832557e-168.send(@method).should == "-2.2740074343500833e-168" - 7.0587971678048535732e+191.send(@method).should == "7.058797167804854e+191" - -284438.88327586348169.send(@method).should == "-284438.8832758635" - 3.953272468476091301e+105.send(@method).should == "3.9532724684760913e+105" - -3.6361359552959847853e+100.send(@method).should == "-3.636135955295985e+100" - -1.3222325865575206185e-31.send(@method).should == "-1.3222325865575206e-31" - 1.1440138916932761366e+130.send(@method).should == "1.1440138916932761e+130" - 4.8750891560387561157e-286.send(@method).should == "4.875089156038756e-286" - 5.6101113356591453525e-257.send(@method).should == "5.610111335659145e-257" - -3.829644279545809575e-100.send(@method).should == "-3.8296442795458096e-100" - 1.5342839401396406117e-194.send(@method).should == "1.5342839401396406e-194" - 2.2284972755169921402e-144.send(@method).should == "2.228497275516992e-144" - 2.1825655917065601737e-61.send(@method).should == "2.1825655917065602e-61" - -2.6672271363524338322e-62.send(@method).should == "-2.667227136352434e-62" - -1.9257995160119059415e+21.send(@method).should == "-1.925799516011906e+21" - -8.9096732962887121718e-198.send(@method).should == "-8.909673296288712e-198" - 2.0202075376548644959e-90.send(@method).should == "2.0202075376548645e-90" - -7.7341602581786258961e-266.send(@method).should == "-7.734160258178626e-266" - 3.5134482598733635046e+98.send(@method).should == "3.5134482598733635e+98" - -2.124411722371029134e+154.send(@method).should == "-2.124411722371029e+154" - -4.573908787355718687e+110.send(@method).should == "-4.573908787355719e+110" - -1.9344425934170969879e-232.send(@method).should == "-1.934442593417097e-232" - -1.3274227399979271095e+171.send(@method).should == "-1.3274227399979271e+171" - 9.3495270482104442383e-283.send(@method).should == "9.349527048210444e-283" - -4.2046059371986483233e+307.send(@method).should == "-4.2046059371986483e+307" - 3.6133547278583543004e-117.send(@method).should == "3.613354727858354e-117" - 4.9247416523566613499e-08.send(@method).should == "4.9247416523566613e-08" - 1.6936145488250064007e-71.send(@method).should == "1.6936145488250064e-71" - 2.4455483206829433098e+96.send(@method).should == "2.4455483206829433e+96" - 7.9797449851436455384e+124.send(@method).should == "7.979744985143646e+124" - -1.3873689634457876774e-129.send(@method).should == "-1.3873689634457877e-129" - 3.9761102037533483075e+284.send(@method).should == "3.976110203753348e+284" - -4.2819791952139402486e-303.send(@method).should == "-4.28197919521394e-303" - -5.7981017546689831298e-116.send(@method).should == "-5.798101754668983e-116" - -3.953266497860534199e-28.send(@method).should == "-3.953266497860534e-28" - -2.0659852720290440959e-243.send(@method).should == "-2.065985272029044e-243" - 8.9670488995878688018e-05.send(@method).should == "8.967048899587869e-05" - -1.2317943708113061768e-98.send(@method).should == "-1.2317943708113062e-98" - -3.8930768307633080463e+248.send(@method).should == "-3.893076830763308e+248" - 6.5854032671803925627e-239.send(@method).should == "6.5854032671803926e-239" - 4.6257022188980878952e+177.send(@method).should == "4.625702218898088e+177" - -1.9397155125507235603e-187.send(@method).should == "-1.9397155125507236e-187" - 8.5752156951245705056e+117.send(@method).should == "8.57521569512457e+117" - -2.4784875958162501671e-132.send(@method).should == "-2.4784875958162502e-132" - -4.4125691841230058457e-203.send(@method).should == "-4.412569184123006e-203" - end - - it "random examples in human ranges" do - # 50.times do - # formatted = '' - # rand(1..3).times do - # formatted << rand(10).to_s - # end - # formatted << '.' - # rand(1..9).times do - # formatted << rand(10).to_s - # end - # float = formatted.to_f - # puts "#{'%.20f' % float}.send(@method).should == #{float.send(@method).inspect}" - # end - - 5.17869899999999994122.send(@method).should == "5.178699" - 905.62695729999995819526.send(@method).should == "905.6269573" - 62.75999999999999801048.send(@method).should == "62.76" - 6.93856795800000014651.send(@method).should == "6.938567958" - 4.95999999999999996447.send(@method).should == "4.96" - 32.77993899999999882766.send(@method).should == "32.779939" - 544.12756779999995160324.send(@method).should == "544.1275678" - 66.25801119999999855281.send(@method).should == "66.2580112" - 7.90000000000000035527.send(@method).should == "7.9" - 5.93100000000000004974.send(@method).should == "5.931" - 5.21229313600000043749.send(@method).should == "5.212293136" - 503.44173809000000119340.send(@method).should == "503.44173809" - 79.26000000000000511591.send(@method).should == "79.26" - 8.51524999999999998579.send(@method).should == "8.51525" - 174.00000000000000000000.send(@method).should == "174.0" - 50.39580000000000126192.send(@method).should == "50.3958" - 35.28999999999999914735.send(@method).should == "35.29" - 5.43136675399999990788.send(@method).should == "5.431366754" - 654.07680000000004838512.send(@method).should == "654.0768" - 6.07423700000000010846.send(@method).should == "6.074237" - 102.25779799999999397642.send(@method).should == "102.257798" - 5.08129999999999970584.send(@method).should == "5.0813" - 6.00000000000000000000.send(@method).should == "6.0" - 8.30000000000000071054.send(@method).should == "8.3" - 32.68345999999999662577.send(@method).should == "32.68346" - 581.11170000000004165486.send(@method).should == "581.1117" - 76.31342999999999676675.send(@method).should == "76.31343" - 438.30826000000001840817.send(@method).should == "438.30826" - 482.06631994000002805478.send(@method).should == "482.06631994" - 55.92721026899999969828.send(@method).should == "55.927210269" - 4.00000000000000000000.send(@method).should == "4.0" - 55.86693999999999959982.send(@method).should == "55.86694" - 787.98299999999994724931.send(@method).should == "787.983" - 5.73810511000000023074.send(@method).should == "5.73810511" - 74.51926810000000500622.send(@method).should == "74.5192681" - 892.89999999999997726263.send(@method).should == "892.9" - 68.27299999999999613465.send(@method).should == "68.273" - 904.10000000000002273737.send(@method).should == "904.1" - 5.23200000000000020606.send(@method).should == "5.232" - 4.09628000000000014325.send(@method).should == "4.09628" - 46.05152633699999853434.send(@method).should == "46.051526337" - 142.12884990599999923688.send(@method).should == "142.128849906" - 3.83057023500000015659.send(@method).should == "3.830570235" - 11.81684594699999912848.send(@method).should == "11.816845947" - 80.50000000000000000000.send(@method).should == "80.5" - 382.18215010000000120272.send(@method).should == "382.1821501" - 55.38444606899999911320.send(@method).should == "55.384446069" - 5.78000000000000024869.send(@method).should == "5.78" - 2.88244999999999995666.send(@method).should == "2.88245" - 43.27709999999999723741.send(@method).should == "43.2771" - end - - it "random values from divisions" do - (1.0 / 7).send(@method).should == "0.14285714285714285" - - # 50.times do - # a = rand(10) - # b = rand(10) - # c = rand(10) - # d = rand(10) - # expression = "#{a}.#{b} / #{c}.#{d}" - # puts " (#{expression}).send(@method).should == #{eval(expression).send(@method).inspect}" - # end - - (1.1 / 7.1).send(@method).should == "0.15492957746478875" - (6.5 / 8.8).send(@method).should == "0.7386363636363635" - (4.8 / 4.3).send(@method).should == "1.1162790697674418" - (4.0 / 1.9).send(@method).should == "2.1052631578947367" - (9.1 / 0.8).send(@method).should == "11.374999999999998" - (5.3 / 7.5).send(@method).should == "0.7066666666666667" - (2.8 / 1.8).send(@method).should == "1.5555555555555554" - (2.1 / 2.5).send(@method).should == "0.8400000000000001" - (3.5 / 6.0).send(@method).should == "0.5833333333333334" - (4.6 / 0.3).send(@method).should == "15.333333333333332" - (0.6 / 2.4).send(@method).should == "0.25" - (1.3 / 9.1).send(@method).should == "0.14285714285714288" - (0.3 / 5.0).send(@method).should == "0.06" - (5.0 / 4.2).send(@method).should == "1.1904761904761905" - (3.0 / 2.0).send(@method).should == "1.5" - (6.3 / 2.0).send(@method).should == "3.15" - (5.4 / 6.0).send(@method).should == "0.9" - (9.6 / 8.1).send(@method).should == "1.1851851851851851" - (8.7 / 1.6).send(@method).should == "5.437499999999999" - (1.9 / 7.8).send(@method).should == "0.24358974358974358" - (0.5 / 2.1).send(@method).should == "0.23809523809523808" - (9.3 / 5.8).send(@method).should == "1.6034482758620692" - (2.7 / 8.0).send(@method).should == "0.3375" - (9.7 / 7.8).send(@method).should == "1.2435897435897436" - (8.1 / 2.4).send(@method).should == "3.375" - (7.7 / 2.7).send(@method).should == "2.8518518518518516" - (7.9 / 1.7).send(@method).should == "4.647058823529412" - (6.5 / 8.2).send(@method).should == "0.7926829268292683" - (7.8 / 9.6).send(@method).should == "0.8125" - (2.2 / 4.6).send(@method).should == "0.47826086956521746" - (0.0 / 1.0).send(@method).should == "0.0" - (8.3 / 2.9).send(@method).should == "2.8620689655172415" - (3.1 / 6.1).send(@method).should == "0.5081967213114754" - (2.8 / 7.8).send(@method).should == "0.358974358974359" - (8.0 / 0.1).send(@method).should == "80.0" - (1.7 / 6.4).send(@method).should == "0.265625" - (1.8 / 5.4).send(@method).should == "0.3333333333333333" - (8.0 / 5.8).send(@method).should == "1.3793103448275863" - (5.2 / 4.1).send(@method).should == "1.2682926829268295" - (9.8 / 5.8).send(@method).should == "1.6896551724137934" - (5.4 / 9.5).send(@method).should == "0.5684210526315789" - (8.4 / 4.9).send(@method).should == "1.7142857142857142" - (1.7 / 3.5).send(@method).should == "0.4857142857142857" - (1.2 / 5.1).send(@method).should == "0.23529411764705882" - (1.4 / 2.0).send(@method).should == "0.7" - (4.8 / 8.0).send(@method).should == "0.6" - (9.0 / 2.5).send(@method).should == "3.6" - (0.2 / 0.6).send(@method).should == "0.33333333333333337" - (7.8 / 5.2).send(@method).should == "1.5" - (9.5 / 5.5).send(@method).should == "1.7272727272727273" - end - end - - describe 'encoding' do - before :each do - @internal = Encoding.default_internal - end - - after :each do - Encoding.default_internal = @internal - end - - it "returns a String in US-ASCII encoding when Encoding.default_internal is nil" do - Encoding.default_internal = nil - 1.23.send(@method).encoding.should.equal?(Encoding::US_ASCII) - end - - it "returns a String in US-ASCII encoding when Encoding.default_internal is not nil" do - Encoding.default_internal = Encoding::IBM437 - 5.47.send(@method).encoding.should.equal?(Encoding::US_ASCII) - end - end -end diff --git a/spec/ruby/core/float/to_int_spec.rb b/spec/ruby/core/float/to_int_spec.rb index 084a58b431..ff70d508ff 100644 --- a/spec/ruby/core/float/to_int_spec.rb +++ b/spec/ruby/core/float/to_int_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/to_i' describe "Float#to_int" do - it_behaves_like :float_to_i, :to_int + it "is an alias of Float#to_i" do + Float.instance_method(:to_int).should == Float.instance_method(:to_i) + end end diff --git a/spec/ruby/core/float/to_s_spec.rb b/spec/ruby/core/float/to_s_spec.rb index 6727a883f8..3fd64581c2 100644 --- a/spec/ruby/core/float/to_s_spec.rb +++ b/spec/ruby/core/float/to_s_spec.rb @@ -1,6 +1,310 @@ require_relative '../../spec_helper' -require_relative 'shared/to_s' describe "Float#to_s" do - it_behaves_like :float_to_s, :to_s + it "returns 'NaN' for NaN" do + nan_value().to_s.should == 'NaN' + end + + it "returns 'Infinity' for positive infinity" do + infinity_value().to_s.should == 'Infinity' + end + + it "returns '-Infinity' for negative infinity" do + (-infinity_value()).to_s.should == '-Infinity' + end + + it "returns '0.0' for 0.0" do + 0.0.to_s.should == "0.0" + end + + platform_is_not :openbsd do + it "emits '-' for -0.0" do + -0.0.to_s.should == "-0.0" + end + end + + it "emits a '-' for negative values" do + -3.14.to_s.should == "-3.14" + end + + it "emits a trailing '.0' for a whole number" do + 50.0.to_s.should == "50.0" + end + + it "emits a trailing '.0' for the mantissa in e format" do + 1.0e20.to_s.should == "1.0e+20" + end + + it "uses non-e format for a positive value with fractional part having 5 significant figures" do + 0.0001.to_s.should == "0.0001" + end + + it "uses non-e format for a negative value with fractional part having 5 significant figures" do + -0.0001.to_s.should == "-0.0001" + end + + it "uses e format for a positive value with fractional part having 6 significant figures" do + 0.00001.to_s.should == "1.0e-05" + end + + it "uses e format for a negative value with fractional part having 6 significant figures" do + -0.00001.to_s.should == "-1.0e-05" + end + + it "uses non-e format for a positive value with whole part having 15 significant figures" do + 10000000000000.0.to_s.should == "10000000000000.0" + end + + it "uses non-e format for a negative value with whole part having 15 significant figures" do + -10000000000000.0.to_s.should == "-10000000000000.0" + end + + it "uses non-e format for a positive value with whole part having 16 significant figures" do + 100000000000000.0.to_s.should == "100000000000000.0" + end + + it "uses non-e format for a negative value with whole part having 16 significant figures" do + -100000000000000.0.to_s.should == "-100000000000000.0" + end + + it "uses e format for a positive value with whole part having 18 significant figures" do + 10000000000000000.0.to_s.should == "1.0e+16" + end + + it "uses e format for a negative value with whole part having 18 significant figures" do + -10000000000000000.0.to_s.should == "-1.0e+16" + end + + it "uses e format for a positive value with whole part having 17 significant figures" do + 1000000000000000.0.to_s.should == "1.0e+15" + end + + it "uses e format for a negative value with whole part having 17 significant figures" do + -1000000000000000.0.to_s.should == "-1.0e+15" + end + + # #3273 + it "outputs the minimal, unique form necessary to recreate the value" do + value = 0.21611564636388508 + string = "0.21611564636388508" + + value.to_s.should == string + string.to_f.should == value + end + + it "outputs the minimal, unique form to represent the value" do + 0.56.to_s.should == "0.56" + end + + describe "matches" do + it "random examples in all ranges" do + # 50.times do + # bytes = (0...8).map { rand(256) } + # string = bytes.pack('C8') + # float = string.unpack('D').first + # puts "#{'%.20g' % float}.to_s.should == #{float.to_s.inspect}" + # end + + 2.5540217314354050325e+163.to_s.should == "2.554021731435405e+163" + 2.5492588360356597544e-172.to_s.should == "2.5492588360356598e-172" + 1.742770260934704852e-82.to_s.should == "1.7427702609347049e-82" + 6.2108093676180883209e-104.to_s.should == "6.210809367618088e-104" + -3.3448803488331067402e-143.to_s.should == "-3.3448803488331067e-143" + -2.2740074343500832557e-168.to_s.should == "-2.2740074343500833e-168" + 7.0587971678048535732e+191.to_s.should == "7.058797167804854e+191" + -284438.88327586348169.to_s.should == "-284438.8832758635" + 3.953272468476091301e+105.to_s.should == "3.9532724684760913e+105" + -3.6361359552959847853e+100.to_s.should == "-3.636135955295985e+100" + -1.3222325865575206185e-31.to_s.should == "-1.3222325865575206e-31" + 1.1440138916932761366e+130.to_s.should == "1.1440138916932761e+130" + 4.8750891560387561157e-286.to_s.should == "4.875089156038756e-286" + 5.6101113356591453525e-257.to_s.should == "5.610111335659145e-257" + -3.829644279545809575e-100.to_s.should == "-3.8296442795458096e-100" + 1.5342839401396406117e-194.to_s.should == "1.5342839401396406e-194" + 2.2284972755169921402e-144.to_s.should == "2.228497275516992e-144" + 2.1825655917065601737e-61.to_s.should == "2.1825655917065602e-61" + -2.6672271363524338322e-62.to_s.should == "-2.667227136352434e-62" + -1.9257995160119059415e+21.to_s.should == "-1.925799516011906e+21" + -8.9096732962887121718e-198.to_s.should == "-8.909673296288712e-198" + 2.0202075376548644959e-90.to_s.should == "2.0202075376548645e-90" + -7.7341602581786258961e-266.to_s.should == "-7.734160258178626e-266" + 3.5134482598733635046e+98.to_s.should == "3.5134482598733635e+98" + -2.124411722371029134e+154.to_s.should == "-2.124411722371029e+154" + -4.573908787355718687e+110.to_s.should == "-4.573908787355719e+110" + -1.9344425934170969879e-232.to_s.should == "-1.934442593417097e-232" + -1.3274227399979271095e+171.to_s.should == "-1.3274227399979271e+171" + 9.3495270482104442383e-283.to_s.should == "9.349527048210444e-283" + -4.2046059371986483233e+307.to_s.should == "-4.2046059371986483e+307" + 3.6133547278583543004e-117.to_s.should == "3.613354727858354e-117" + 4.9247416523566613499e-08.to_s.should == "4.9247416523566613e-08" + 1.6936145488250064007e-71.to_s.should == "1.6936145488250064e-71" + 2.4455483206829433098e+96.to_s.should == "2.4455483206829433e+96" + 7.9797449851436455384e+124.to_s.should == "7.979744985143646e+124" + -1.3873689634457876774e-129.to_s.should == "-1.3873689634457877e-129" + 3.9761102037533483075e+284.to_s.should == "3.976110203753348e+284" + -4.2819791952139402486e-303.to_s.should == "-4.28197919521394e-303" + -5.7981017546689831298e-116.to_s.should == "-5.798101754668983e-116" + -3.953266497860534199e-28.to_s.should == "-3.953266497860534e-28" + -2.0659852720290440959e-243.to_s.should == "-2.065985272029044e-243" + 8.9670488995878688018e-05.to_s.should == "8.967048899587869e-05" + -1.2317943708113061768e-98.to_s.should == "-1.2317943708113062e-98" + -3.8930768307633080463e+248.to_s.should == "-3.893076830763308e+248" + 6.5854032671803925627e-239.to_s.should == "6.5854032671803926e-239" + 4.6257022188980878952e+177.to_s.should == "4.625702218898088e+177" + -1.9397155125507235603e-187.to_s.should == "-1.9397155125507236e-187" + 8.5752156951245705056e+117.to_s.should == "8.57521569512457e+117" + -2.4784875958162501671e-132.to_s.should == "-2.4784875958162502e-132" + -4.4125691841230058457e-203.to_s.should == "-4.412569184123006e-203" + end + + it "random examples in human ranges" do + # 50.times do + # formatted = '' + # rand(1..3).times do + # formatted << rand(10).to_s + # end + # formatted << '.' + # rand(1..9).times do + # formatted << rand(10).to_s + # end + # float = formatted.to_f + # puts "#{'%.20f' % float}.to_s.should == #{float.to_s.inspect}" + # end + + 5.17869899999999994122.to_s.should == "5.178699" + 905.62695729999995819526.to_s.should == "905.6269573" + 62.75999999999999801048.to_s.should == "62.76" + 6.93856795800000014651.to_s.should == "6.938567958" + 4.95999999999999996447.to_s.should == "4.96" + 32.77993899999999882766.to_s.should == "32.779939" + 544.12756779999995160324.to_s.should == "544.1275678" + 66.25801119999999855281.to_s.should == "66.2580112" + 7.90000000000000035527.to_s.should == "7.9" + 5.93100000000000004974.to_s.should == "5.931" + 5.21229313600000043749.to_s.should == "5.212293136" + 503.44173809000000119340.to_s.should == "503.44173809" + 79.26000000000000511591.to_s.should == "79.26" + 8.51524999999999998579.to_s.should == "8.51525" + 174.00000000000000000000.to_s.should == "174.0" + 50.39580000000000126192.to_s.should == "50.3958" + 35.28999999999999914735.to_s.should == "35.29" + 5.43136675399999990788.to_s.should == "5.431366754" + 654.07680000000004838512.to_s.should == "654.0768" + 6.07423700000000010846.to_s.should == "6.074237" + 102.25779799999999397642.to_s.should == "102.257798" + 5.08129999999999970584.to_s.should == "5.0813" + 6.00000000000000000000.to_s.should == "6.0" + 8.30000000000000071054.to_s.should == "8.3" + 32.68345999999999662577.to_s.should == "32.68346" + 581.11170000000004165486.to_s.should == "581.1117" + 76.31342999999999676675.to_s.should == "76.31343" + 438.30826000000001840817.to_s.should == "438.30826" + 482.06631994000002805478.to_s.should == "482.06631994" + 55.92721026899999969828.to_s.should == "55.927210269" + 4.00000000000000000000.to_s.should == "4.0" + 55.86693999999999959982.to_s.should == "55.86694" + 787.98299999999994724931.to_s.should == "787.983" + 5.73810511000000023074.to_s.should == "5.73810511" + 74.51926810000000500622.to_s.should == "74.5192681" + 892.89999999999997726263.to_s.should == "892.9" + 68.27299999999999613465.to_s.should == "68.273" + 904.10000000000002273737.to_s.should == "904.1" + 5.23200000000000020606.to_s.should == "5.232" + 4.09628000000000014325.to_s.should == "4.09628" + 46.05152633699999853434.to_s.should == "46.051526337" + 142.12884990599999923688.to_s.should == "142.128849906" + 3.83057023500000015659.to_s.should == "3.830570235" + 11.81684594699999912848.to_s.should == "11.816845947" + 80.50000000000000000000.to_s.should == "80.5" + 382.18215010000000120272.to_s.should == "382.1821501" + 55.38444606899999911320.to_s.should == "55.384446069" + 5.78000000000000024869.to_s.should == "5.78" + 2.88244999999999995666.to_s.should == "2.88245" + 43.27709999999999723741.to_s.should == "43.2771" + end + + it "random values from divisions" do + (1.0 / 7).to_s.should == "0.14285714285714285" + + # 50.times do + # a = rand(10) + # b = rand(10) + # c = rand(10) + # d = rand(10) + # expression = "#{a}.#{b} / #{c}.#{d}" + # puts " (#{expression}).to_s.should == #{eval(expression).to_s.inspect}" + # end + + (1.1 / 7.1).to_s.should == "0.15492957746478875" + (6.5 / 8.8).to_s.should == "0.7386363636363635" + (4.8 / 4.3).to_s.should == "1.1162790697674418" + (4.0 / 1.9).to_s.should == "2.1052631578947367" + (9.1 / 0.8).to_s.should == "11.374999999999998" + (5.3 / 7.5).to_s.should == "0.7066666666666667" + (2.8 / 1.8).to_s.should == "1.5555555555555554" + (2.1 / 2.5).to_s.should == "0.8400000000000001" + (3.5 / 6.0).to_s.should == "0.5833333333333334" + (4.6 / 0.3).to_s.should == "15.333333333333332" + (0.6 / 2.4).to_s.should == "0.25" + (1.3 / 9.1).to_s.should == "0.14285714285714288" + (0.3 / 5.0).to_s.should == "0.06" + (5.0 / 4.2).to_s.should == "1.1904761904761905" + (3.0 / 2.0).to_s.should == "1.5" + (6.3 / 2.0).to_s.should == "3.15" + (5.4 / 6.0).to_s.should == "0.9" + (9.6 / 8.1).to_s.should == "1.1851851851851851" + (8.7 / 1.6).to_s.should == "5.437499999999999" + (1.9 / 7.8).to_s.should == "0.24358974358974358" + (0.5 / 2.1).to_s.should == "0.23809523809523808" + (9.3 / 5.8).to_s.should == "1.6034482758620692" + (2.7 / 8.0).to_s.should == "0.3375" + (9.7 / 7.8).to_s.should == "1.2435897435897436" + (8.1 / 2.4).to_s.should == "3.375" + (7.7 / 2.7).to_s.should == "2.8518518518518516" + (7.9 / 1.7).to_s.should == "4.647058823529412" + (6.5 / 8.2).to_s.should == "0.7926829268292683" + (7.8 / 9.6).to_s.should == "0.8125" + (2.2 / 4.6).to_s.should == "0.47826086956521746" + (0.0 / 1.0).to_s.should == "0.0" + (8.3 / 2.9).to_s.should == "2.8620689655172415" + (3.1 / 6.1).to_s.should == "0.5081967213114754" + (2.8 / 7.8).to_s.should == "0.358974358974359" + (8.0 / 0.1).to_s.should == "80.0" + (1.7 / 6.4).to_s.should == "0.265625" + (1.8 / 5.4).to_s.should == "0.3333333333333333" + (8.0 / 5.8).to_s.should == "1.3793103448275863" + (5.2 / 4.1).to_s.should == "1.2682926829268295" + (9.8 / 5.8).to_s.should == "1.6896551724137934" + (5.4 / 9.5).to_s.should == "0.5684210526315789" + (8.4 / 4.9).to_s.should == "1.7142857142857142" + (1.7 / 3.5).to_s.should == "0.4857142857142857" + (1.2 / 5.1).to_s.should == "0.23529411764705882" + (1.4 / 2.0).to_s.should == "0.7" + (4.8 / 8.0).to_s.should == "0.6" + (9.0 / 2.5).to_s.should == "3.6" + (0.2 / 0.6).to_s.should == "0.33333333333333337" + (7.8 / 5.2).to_s.should == "1.5" + (9.5 / 5.5).to_s.should == "1.7272727272727273" + end + end + + describe 'encoding' do + before :each do + @internal = Encoding.default_internal + end + + after :each do + Encoding.default_internal = @internal + end + + it "returns a String in US-ASCII encoding when Encoding.default_internal is nil" do + Encoding.default_internal = nil + 1.23.to_s.encoding.should.equal?(Encoding::US_ASCII) + end + + it "returns a String in US-ASCII encoding when Encoding.default_internal is not nil" do + Encoding.default_internal = Encoding::IBM437 + 5.47.to_s.encoding.should.equal?(Encoding::US_ASCII) + end + end end diff --git a/spec/ruby/core/hash/has_value_spec.rb b/spec/ruby/core/hash/has_value_spec.rb index d40e52ebfd..95b8390a66 100644 --- a/spec/ruby/core/hash/has_value_spec.rb +++ b/spec/ruby/core/hash/has_value_spec.rb @@ -1,16 +1,7 @@ require_relative '../../spec_helper' describe "Hash#has_value?" do - it "returns true if the value exists in the hash" do - { a: :b }.has_value?(:a).should == false - { 1 => 2 }.has_value?(2).should == true - h = Hash.new(5) - h.has_value?(5).should == false - h = Hash.new { 5 } - h.has_value?(5).should == false - end - - it "uses == semantics for comparing values" do - { 5 => 2.0 }.has_value?(2).should == true + it "is an alias of Hash#value?" do + Hash.instance_method(:has_value?).should == Hash.instance_method(:value?) end end diff --git a/spec/ruby/core/hash/merge_spec.rb b/spec/ruby/core/hash/merge_spec.rb index 9e566fcee9..7a444f7f25 100644 --- a/spec/ruby/core/hash/merge_spec.rb +++ b/spec/ruby/core/hash/merge_spec.rb @@ -117,7 +117,78 @@ describe "Hash#merge" do end describe "Hash#merge!" do - it "is an alias of Hash#update" do - Hash.instance_method(:merge!).should == Hash.instance_method(:update) + it "adds the entries from other, overwriting duplicate keys. Returns self" do + h = { _1: 'a', _2: '3' } + h.merge!(_1: '9', _9: 2).should.equal?(h) + h.should == { _1: "9", _2: "3", _9: 2 } + end + + it "sets any duplicate key to the value of block if passed a block" do + h1 = { a: 2, b: -1 } + h2 = { a: -2, c: 1 } + h1.merge!(h2) { |k,x,y| 3.14 }.should.equal?(h1) + h1.should == { c: 1, b: -1, a: 3.14 } + + h1.merge!(h1) { nil } + h1.should == { a: nil, b: nil, c: nil } + end + + it "tries to convert the passed argument to a hash using #to_hash" do + obj = mock('{1=>2}') + obj.should_receive(:to_hash).and_return({ 1 => 2 }) + { 3 => 4 }.merge!(obj).should == { 1 => 2, 3 => 4 } + end + + it "does not call to_hash on hash subclasses" do + { 3 => 4 }.merge!(HashSpecs::ToHashHash[1 => 2]).should == { 1 => 2, 3 => 4 } + end + + it "processes entries with same order as merge()" do + h = { 1 => 2, 3 => 4, 5 => 6, "x" => nil, nil => 5, [] => [] } + merge_bang_pairs = [] + merge_pairs = [] + h.merge(h) { |*arg| merge_pairs << arg } + h.merge!(h) { |*arg| merge_bang_pairs << arg } + merge_bang_pairs.should == merge_pairs + end + + it "raises a FrozenError on a frozen instance that is modified" do + -> do + HashSpecs.frozen_hash.merge!(1 => 2) + end.should.raise(FrozenError) + end + + it "checks frozen status before coercing an object with #to_hash" do + obj = mock("to_hash frozen") + # This is necessary because mock cleanup code cannot run on the frozen + # object. + def obj.to_hash() raise Exception, "should not receive #to_hash" end + obj.freeze + + -> { HashSpecs.frozen_hash.merge!(obj) }.should.raise(FrozenError) + end + + # see redmine #1571 + it "raises a FrozenError on a frozen instance that would not be modified" do + -> do + HashSpecs.frozen_hash.merge!(HashSpecs.empty_frozen_hash) + end.should.raise(FrozenError) + end + + it "does not raise an exception if changing the value of an existing key during iteration" do + hash = {1 => 2, 3 => 4, 5 => 6} + hash2 = {1 => :foo, 3 => :bar} + hash.each { hash.merge!(hash2) } + hash.should == {1 => :foo, 3 => :bar, 5 => 6} + end + + it "accepts multiple hashes" do + result = { a: 1 }.merge!({ b: 2 }, { c: 3 }, { d: 4 }) + result.should == { a: 1, b: 2, c: 3, d: 4 } + end + + it "accepts zero arguments" do + hash = { a: 1 } + hash.merge!.should.eql?(hash) end end diff --git a/spec/ruby/core/hash/update_spec.rb b/spec/ruby/core/hash/update_spec.rb index f3a3e6b4db..04070baad8 100644 --- a/spec/ruby/core/hash/update_spec.rb +++ b/spec/ruby/core/hash/update_spec.rb @@ -1,79 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' describe "Hash#update" do - it "adds the entries from other, overwriting duplicate keys. Returns self" do - h = { _1: 'a', _2: '3' } - h.update(_1: '9', _9: 2).should.equal?(h) - h.should == { _1: "9", _2: "3", _9: 2 } - end - - it "sets any duplicate key to the value of block if passed a block" do - h1 = { a: 2, b: -1 } - h2 = { a: -2, c: 1 } - h1.update(h2) { |k,x,y| 3.14 }.should.equal?(h1) - h1.should == { c: 1, b: -1, a: 3.14 } - - h1.update(h1) { nil } - h1.should == { a: nil, b: nil, c: nil } - end - - it "tries to convert the passed argument to a hash using #to_hash" do - obj = mock('{1=>2}') - obj.should_receive(:to_hash).and_return({ 1 => 2 }) - { 3 => 4 }.update(obj).should == { 1 => 2, 3 => 4 } - end - - it "does not call to_hash on hash subclasses" do - { 3 => 4 }.update(HashSpecs::ToHashHash[1 => 2]).should == { 1 => 2, 3 => 4 } - end - - it "processes entries with same order as merge()" do - h = { 1 => 2, 3 => 4, 5 => 6, "x" => nil, nil => 5, [] => [] } - merge_bang_pairs = [] - merge_pairs = [] - h.merge(h) { |*arg| merge_pairs << arg } - h.update(h) { |*arg| merge_bang_pairs << arg } - merge_bang_pairs.should == merge_pairs - end - - it "raises a FrozenError on a frozen instance that is modified" do - -> do - HashSpecs.frozen_hash.update(1 => 2) - end.should.raise(FrozenError) - end - - it "checks frozen status before coercing an object with #to_hash" do - obj = mock("to_hash frozen") - # This is necessary because mock cleanup code cannot run on the frozen - # object. - def obj.to_hash() raise Exception, "should not receive #to_hash" end - obj.freeze - - -> { HashSpecs.frozen_hash.update(obj) }.should.raise(FrozenError) - end - - # see redmine #1571 - it "raises a FrozenError on a frozen instance that would not be modified" do - -> do - HashSpecs.frozen_hash.update(HashSpecs.empty_frozen_hash) - end.should.raise(FrozenError) - end - - it "does not raise an exception if changing the value of an existing key during iteration" do - hash = {1 => 2, 3 => 4, 5 => 6} - hash2 = {1 => :foo, 3 => :bar} - hash.each { hash.update(hash2) } - hash.should == {1 => :foo, 3 => :bar, 5 => 6} - end - - it "accepts multiple hashes" do - result = { a: 1 }.update({ b: 2 }, { c: 3 }, { d: 4 }) - result.should == { a: 1, b: 2, c: 3, d: 4 } - end - - it "accepts zero arguments" do - hash = { a: 1 } - hash.update.should.eql?(hash) + it "is an alias of Hash#merge!" do + Hash.instance_method(:update).should == Hash.instance_method(:merge!) end end diff --git a/spec/ruby/core/hash/value_spec.rb b/spec/ruby/core/hash/value_spec.rb index 9cfbe576d2..8e4732480f 100644 --- a/spec/ruby/core/hash/value_spec.rb +++ b/spec/ruby/core/hash/value_spec.rb @@ -1,7 +1,16 @@ require_relative '../../spec_helper' describe "Hash#value?" do - it "is an alias of Hash#has_value?" do - Hash.instance_method(:value?).should == Hash.instance_method(:has_value?) + it "returns true if the value exists in the hash" do + { a: :b }.value?(:a).should == false + { 1 => 2 }.value?(2).should == true + h = Hash.new(5) + h.value?(5).should == false + h = Hash.new { 5 } + h.value?(5).should == false + end + + it "uses == semantics for comparing values" do + { 5 => 2.0 }.value?(2).should == true end end diff --git a/spec/ruby/core/integer/abs_spec.rb b/spec/ruby/core/integer/abs_spec.rb index c40356db12..768eebdce2 100644 --- a/spec/ruby/core/integer/abs_spec.rb +++ b/spec/ruby/core/integer/abs_spec.rb @@ -1,6 +1,20 @@ require_relative '../../spec_helper' -require_relative 'shared/abs' describe "Integer#abs" do - it_behaves_like :integer_abs, :abs + context "fixnum" do + it "returns self's absolute fixnum value" do + { 0 => [0, -0, +0], 2 => [2, -2, +2], 100 => [100, -100, +100] }.each do |key, values| + values.each do |value| + value.abs.should == key + end + end + end + end + + context "bignum" do + it "returns the absolute bignum value" do + bignum_value(39).abs.should == 18446744073709551655 + (-bignum_value(18)).abs.should == 18446744073709551634 + end + end end diff --git a/spec/ruby/core/integer/case_compare_spec.rb b/spec/ruby/core/integer/case_compare_spec.rb index e5dde2c64a..1e0c6cb411 100644 --- a/spec/ruby/core/integer/case_compare_spec.rb +++ b/spec/ruby/core/integer/case_compare_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/equal' describe "Integer#===" do - it_behaves_like :integer_equal, :=== + it "is an alias of Integer#==" do + Integer.instance_method(:===).should == Integer.instance_method(:==) + end end diff --git a/spec/ruby/core/integer/equal_value_spec.rb b/spec/ruby/core/integer/equal_value_spec.rb index 67a73713af..dc73552267 100644 --- a/spec/ruby/core/integer/equal_value_spec.rb +++ b/spec/ruby/core/integer/equal_value_spec.rb @@ -1,6 +1,65 @@ require_relative '../../spec_helper' -require_relative 'shared/equal' describe "Integer#==" do - it_behaves_like :integer_equal, :== + context "fixnum" do + it "returns true if self has the same value as other" do + (1 == 1).should == true + (9 == 5).should == false + + # Actually, these call Float#==, Integer#== etc. + (9 == 9.0).should == true + (9 == 9.01).should == false + + (10 == bignum_value).should == false + end + + it "calls 'other == self' if the given argument is not an Integer" do + (1 == '*').should == false + + obj = mock('one other') + obj.should_receive(:==).any_number_of_times.and_return(false) + (1 == obj).should == false + + obj = mock('another') + obj.should_receive(:==).any_number_of_times.and_return(true) + (2 == obj).should == true + end + end + + context "bignum" do + before :each do + @bignum = bignum_value + end + + it "returns true if self has the same value as the given argument" do + (@bignum == @bignum).should == true + (@bignum == @bignum.to_f).should == true + + (@bignum == @bignum + 1).should == false + ((@bignum + 1) == @bignum).should == false + + (@bignum == 9).should == false + (@bignum == 9.01).should == false + + (@bignum == bignum_value(10)).should == false + end + + it "calls 'other == self' if the given argument is not an Integer" do + obj = mock('not integer') + obj.should_receive(:==).and_return(true) + (@bignum == obj).should == true + end + + it "returns the result of 'other == self' as a boolean" do + obj = mock('not integer') + obj.should_receive(:==).exactly(2).times.and_return("woot", nil) + (@bignum == obj).should == true + (@bignum == obj).should == false + end + + it "does not lose precision when comparing with a Float" do + ((bignum_value(1) == bignum_value.to_f)).should == false + ((bignum_value == bignum_value.to_f)).should == true + end + end end diff --git a/spec/ruby/core/integer/inspect_spec.rb b/spec/ruby/core/integer/inspect_spec.rb new file mode 100644 index 0000000000..0b0d5cc7a9 --- /dev/null +++ b/spec/ruby/core/integer/inspect_spec.rb @@ -0,0 +1,7 @@ +require_relative '../../spec_helper' + +describe "Integer#inspect" do + it "is an alias of Integer#to_s" do + Integer.instance_method(:inspect).should == Integer.instance_method(:to_s) + end +end diff --git a/spec/ruby/core/integer/magnitude_spec.rb b/spec/ruby/core/integer/magnitude_spec.rb index 48cf1a8534..000e5be7f7 100644 --- a/spec/ruby/core/integer/magnitude_spec.rb +++ b/spec/ruby/core/integer/magnitude_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/abs' describe "Integer#magnitude" do - it_behaves_like :integer_abs, :magnitude + it "is an alias of Integer#abs" do + Integer.instance_method(:magnitude).should == Integer.instance_method(:abs) + end end diff --git a/spec/ruby/core/integer/modulo_spec.rb b/spec/ruby/core/integer/modulo_spec.rb index e263338e38..2680f49510 100644 --- a/spec/ruby/core/integer/modulo_spec.rb +++ b/spec/ruby/core/integer/modulo_spec.rb @@ -1,10 +1,122 @@ require_relative '../../spec_helper' -require_relative 'shared/modulo' describe "Integer#%" do - it_behaves_like :integer_modulo, :% + context "fixnum" do + it "returns the modulus obtained from dividing self by the given argument" do + # test all possible combinations: + # - integer/double/bignum argument + # - positive/negative argument + # - positive/negative self + # - self greater/smaller than argument + + (13 % 4).should == 1 + (4 % 13).should == 4 + + (13 % 4.0).should == 1 + (4 % 13.0).should == 4 + + (-200 % 256).should == 56 + (-1000 % 512).should == 24 + + (-200 % -256).should == -200 + (-1000 % -512).should == -488 + + (200 % -256).should == -56 + (1000 % -512).should == -24 + + (13 % -4.0).should == -3.0 + (4 % -13.0).should == -9.0 + + (-13 % -4.0).should == -1.0 + (-4 % -13.0).should == -4.0 + + (-13 % 4.0).should == 3.0 + (-4 % 13.0).should == 9.0 + + (1 % 2.0).should == 1.0 + (200 % bignum_value).should == 200 + + (4 % bignum_value(10)).should == 4 + (4 % -bignum_value(10)).should == -18446744073709551622 + (-4 % bignum_value(10)).should == 18446744073709551622 + (-4 % -bignum_value(10)).should == -4 + end + + it "raises a ZeroDivisionError when the given argument is 0" do + -> { 13 % 0 }.should.raise(ZeroDivisionError) + -> { 0 % 0 }.should.raise(ZeroDivisionError) + -> { -10 % 0 }.should.raise(ZeroDivisionError) + end + + it "raises a ZeroDivisionError when the given argument is 0 and a Float" do + -> { 0 % 0.0 }.should.raise(ZeroDivisionError) + -> { 10 % 0.0 }.should.raise(ZeroDivisionError) + -> { -10 % 0.0 }.should.raise(ZeroDivisionError) + end + + it "raises a TypeError when given a non-Integer" do + -> { + (obj = mock('10')).should_receive(:to_int).any_number_of_times.and_return(10) + 13 % obj + }.should.raise(TypeError) + -> { 13 % "10" }.should.raise(TypeError) + -> { 13 % :symbol }.should.raise(TypeError) + end + end + + context "bignum" do + before :each do + @bignum = bignum_value(10) + end + + it "returns the modulus obtained from dividing self by the given argument" do + # test all possible combinations: + # - integer/double/bignum argument + # - positive/negative argument + # - positive/negative self + # - self greater/smaller than argument + + (@bignum % 5).should == 1 + (@bignum % -5).should == -4 + (-@bignum % 5).should == 4 + (-@bignum % -5).should == -1 + + (@bignum % 2.22).should be_close(1.5603603603605034, TOLERANCE) + (@bignum % -2.22).should be_close(-0.6596396396394968, TOLERANCE) + (-@bignum % 2.22).should be_close(0.6596396396394968, TOLERANCE) + (-@bignum % -2.22).should be_close(-1.5603603603605034, TOLERANCE) + + (@bignum % (@bignum + 10)).should == 18446744073709551626 + (@bignum % -(@bignum + 10)).should == -10 + (-@bignum % (@bignum + 10)).should == 10 + (-@bignum % -(@bignum + 10)).should == -18446744073709551626 + + ((@bignum + 10) % @bignum).should == 10 + ((@bignum + 10) % -@bignum).should == -18446744073709551616 + (-(@bignum + 10) % @bignum).should == 18446744073709551616 + (-(@bignum + 10) % -@bignum).should == -10 + end + + it "raises a ZeroDivisionError when the given argument is 0" do + -> { @bignum % 0 }.should.raise(ZeroDivisionError) + -> { -@bignum % 0 }.should.raise(ZeroDivisionError) + end + + it "raises a ZeroDivisionError when the given argument is 0 and a Float" do + -> { @bignum % 0.0 }.should.raise(ZeroDivisionError) + -> { -@bignum % 0.0 }.should.raise(ZeroDivisionError) + end + + it "raises a TypeError when given a non-Integer" do + -> { @bignum % mock('10') }.should.raise(TypeError) + -> { @bignum % "10" }.should.raise(TypeError) + -> { @bignum % :symbol }.should.raise(TypeError) + end + end end describe "Integer#modulo" do - it_behaves_like :integer_modulo, :modulo + it "is an alias of Integer#%" do + Integer.instance_method(:modulo).should == Integer.instance_method(:%) + end end diff --git a/spec/ruby/core/integer/next_spec.rb b/spec/ruby/core/integer/next_spec.rb index 63c4e67893..da54dec454 100644 --- a/spec/ruby/core/integer/next_spec.rb +++ b/spec/ruby/core/integer/next_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/next' describe "Integer#next" do - it_behaves_like :integer_next, :next + it "is an alias of Integer#succ" do + Integer.instance_method(:next).should == Integer.instance_method(:succ) + end end diff --git a/spec/ruby/core/integer/shared/abs.rb b/spec/ruby/core/integer/shared/abs.rb deleted file mode 100644 index 43844c9065..0000000000 --- a/spec/ruby/core/integer/shared/abs.rb +++ /dev/null @@ -1,18 +0,0 @@ -describe :integer_abs, shared: true do - context "fixnum" do - it "returns self's absolute fixnum value" do - { 0 => [0, -0, +0], 2 => [2, -2, +2], 100 => [100, -100, +100] }.each do |key, values| - values.each do |value| - value.send(@method).should == key - end - end - end - end - - context "bignum" do - it "returns the absolute bignum value" do - bignum_value(39).send(@method).should == 18446744073709551655 - (-bignum_value(18)).send(@method).should == 18446744073709551634 - end - end -end diff --git a/spec/ruby/core/integer/shared/equal.rb b/spec/ruby/core/integer/shared/equal.rb deleted file mode 100644 index c621ba3f81..0000000000 --- a/spec/ruby/core/integer/shared/equal.rb +++ /dev/null @@ -1,63 +0,0 @@ -describe :integer_equal, shared: true do - context "fixnum" do - it "returns true if self has the same value as other" do - 1.send(@method, 1).should == true - 9.send(@method, 5).should == false - - # Actually, these call Float#==, Integer#== etc. - 9.send(@method, 9.0).should == true - 9.send(@method, 9.01).should == false - - 10.send(@method, bignum_value).should == false - end - - it "calls 'other == self' if the given argument is not an Integer" do - 1.send(@method, '*').should == false - - obj = mock('one other') - obj.should_receive(:==).any_number_of_times.and_return(false) - 1.send(@method, obj).should == false - - obj = mock('another') - obj.should_receive(:==).any_number_of_times.and_return(true) - 2.send(@method, obj).should == true - end - end - - context "bignum" do - before :each do - @bignum = bignum_value - end - - it "returns true if self has the same value as the given argument" do - @bignum.send(@method, @bignum).should == true - @bignum.send(@method, @bignum.to_f).should == true - - @bignum.send(@method, @bignum + 1).should == false - (@bignum + 1).send(@method, @bignum).should == false - - @bignum.send(@method, 9).should == false - @bignum.send(@method, 9.01).should == false - - @bignum.send(@method, bignum_value(10)).should == false - end - - it "calls 'other == self' if the given argument is not an Integer" do - obj = mock('not integer') - obj.should_receive(:==).and_return(true) - @bignum.send(@method, obj).should == true - end - - it "returns the result of 'other == self' as a boolean" do - obj = mock('not integer') - obj.should_receive(:==).exactly(2).times.and_return("woot", nil) - @bignum.send(@method, obj).should == true - @bignum.send(@method, obj).should == false - end - - it "does not lose precision when comparing with a Float" do - (bignum_value(1).send(@method, bignum_value.to_f)).should == false - (bignum_value.send(@method, bignum_value.to_f)).should == true - end - end -end diff --git a/spec/ruby/core/integer/shared/modulo.rb b/spec/ruby/core/integer/shared/modulo.rb deleted file mode 100644 index d0b5e26ed5..0000000000 --- a/spec/ruby/core/integer/shared/modulo.rb +++ /dev/null @@ -1,114 +0,0 @@ -describe :integer_modulo, shared: true do - context "fixnum" do - it "returns the modulus obtained from dividing self by the given argument" do - # test all possible combinations: - # - integer/double/bignum argument - # - positive/negative argument - # - positive/negative self - # - self greater/smaller than argument - - 13.send(@method, 4).should == 1 - 4.send(@method, 13).should == 4 - - 13.send(@method, 4.0).should == 1 - 4.send(@method, 13.0).should == 4 - - (-200).send(@method, 256).should == 56 - (-1000).send(@method, 512).should == 24 - - (-200).send(@method, -256).should == -200 - (-1000).send(@method, -512).should == -488 - - (200).send(@method, -256).should == -56 - (1000).send(@method, -512).should == -24 - - 13.send(@method, -4.0).should == -3.0 - 4.send(@method, -13.0).should == -9.0 - - -13.send(@method, -4.0).should == -1.0 - -4.send(@method, -13.0).should == -4.0 - - -13.send(@method, 4.0).should == 3.0 - -4.send(@method, 13.0).should == 9.0 - - 1.send(@method, 2.0).should == 1.0 - 200.send(@method, bignum_value).should == 200 - - 4.send(@method, bignum_value(10)).should == 4 - 4.send(@method, -bignum_value(10)).should == -18446744073709551622 - -4.send(@method, bignum_value(10)).should == 18446744073709551622 - -4.send(@method, -bignum_value(10)).should == -4 - end - - it "raises a ZeroDivisionError when the given argument is 0" do - -> { 13.send(@method, 0) }.should.raise(ZeroDivisionError) - -> { 0.send(@method, 0) }.should.raise(ZeroDivisionError) - -> { -10.send(@method, 0) }.should.raise(ZeroDivisionError) - end - - it "raises a ZeroDivisionError when the given argument is 0 and a Float" do - -> { 0.send(@method, 0.0) }.should.raise(ZeroDivisionError) - -> { 10.send(@method, 0.0) }.should.raise(ZeroDivisionError) - -> { -10.send(@method, 0.0) }.should.raise(ZeroDivisionError) - end - - it "raises a TypeError when given a non-Integer" do - -> { - (obj = mock('10')).should_receive(:to_int).any_number_of_times.and_return(10) - 13.send(@method, obj) - }.should.raise(TypeError) - -> { 13.send(@method, "10") }.should.raise(TypeError) - -> { 13.send(@method, :symbol) }.should.raise(TypeError) - end - end - - context "bignum" do - before :each do - @bignum = bignum_value(10) - end - - it "returns the modulus obtained from dividing self by the given argument" do - # test all possible combinations: - # - integer/double/bignum argument - # - positive/negative argument - # - positive/negative self - # - self greater/smaller than argument - - @bignum.send(@method, 5).should == 1 - @bignum.send(@method, -5).should == -4 - (-@bignum).send(@method, 5).should == 4 - (-@bignum).send(@method, -5).should == -1 - - @bignum.send(@method, 2.22).should be_close(1.5603603603605034, TOLERANCE) - @bignum.send(@method, -2.22).should be_close(-0.6596396396394968, TOLERANCE) - (-@bignum).send(@method, 2.22).should be_close(0.6596396396394968, TOLERANCE) - (-@bignum).send(@method, -2.22).should be_close(-1.5603603603605034, TOLERANCE) - - @bignum.send(@method, @bignum + 10).should == 18446744073709551626 - @bignum.send(@method, -(@bignum + 10)).should == -10 - (-@bignum).send(@method, @bignum + 10).should == 10 - (-@bignum).send(@method, -(@bignum + 10)).should == -18446744073709551626 - - (@bignum + 10).send(@method, @bignum).should == 10 - (@bignum + 10).send(@method, -@bignum).should == -18446744073709551616 - (-(@bignum + 10)).send(@method, @bignum).should == 18446744073709551616 - (-(@bignum + 10)).send(@method, -@bignum).should == -10 - end - - it "raises a ZeroDivisionError when the given argument is 0" do - -> { @bignum.send(@method, 0) }.should.raise(ZeroDivisionError) - -> { (-@bignum).send(@method, 0) }.should.raise(ZeroDivisionError) - end - - it "raises a ZeroDivisionError when the given argument is 0 and a Float" do - -> { @bignum.send(@method, 0.0) }.should.raise(ZeroDivisionError) - -> { -@bignum.send(@method, 0.0) }.should.raise(ZeroDivisionError) - end - - it "raises a TypeError when given a non-Integer" do - -> { @bignum.send(@method, mock('10')) }.should.raise(TypeError) - -> { @bignum.send(@method, "10") }.should.raise(TypeError) - -> { @bignum.send(@method, :symbol) }.should.raise(TypeError) - end - end -end diff --git a/spec/ruby/core/integer/shared/next.rb b/spec/ruby/core/integer/shared/next.rb deleted file mode 100644 index 85b83d6965..0000000000 --- a/spec/ruby/core/integer/shared/next.rb +++ /dev/null @@ -1,25 +0,0 @@ -describe :integer_next, shared: true do - it "returns the next larger positive Fixnum" do - 2.send(@method).should == 3 - end - - it "returns the next larger negative Fixnum" do - (-2).send(@method).should == -1 - end - - it "returns the next larger positive Bignum" do - bignum_value.send(@method).should == bignum_value(1) - end - - it "returns the next larger negative Bignum" do - (-bignum_value(1)).send(@method).should == -bignum_value - end - - it "overflows a Fixnum to a Bignum" do - fixnum_max.send(@method).should == fixnum_max + 1 - end - - it "underflows a Bignum to a Fixnum" do - (fixnum_min - 1).send(@method).should == fixnum_min - end -end diff --git a/spec/ruby/core/integer/succ_spec.rb b/spec/ruby/core/integer/succ_spec.rb index 9ae9a14fe7..2201a4c76d 100644 --- a/spec/ruby/core/integer/succ_spec.rb +++ b/spec/ruby/core/integer/succ_spec.rb @@ -1,6 +1,27 @@ require_relative '../../spec_helper' -require_relative 'shared/next' describe "Integer#succ" do - it_behaves_like :integer_next, :succ + it "returns the next larger positive Fixnum" do + 2.succ.should == 3 + end + + it "returns the next larger negative Fixnum" do + (-2).succ.should == -1 + end + + it "returns the next larger positive Bignum" do + bignum_value.succ.should == bignum_value(1) + end + + it "returns the next larger negative Bignum" do + (-bignum_value(1)).succ.should == -bignum_value + end + + it "overflows a Fixnum to a Bignum" do + fixnum_max.succ.should == fixnum_max + 1 + end + + it "underflows a Bignum to a Fixnum" do + (fixnum_min - 1).succ.should == fixnum_min + end end diff --git a/spec/ruby/core/io/buffer/map_spec.rb b/spec/ruby/core/io/buffer/map_spec.rb index 4b28539ad8..97764c2dd7 100644 --- a/spec/ruby/core/io/buffer/map_spec.rb +++ b/spec/ruby/core/io/buffer/map_spec.rb @@ -73,30 +73,34 @@ describe "IO::Buffer.map" do @buffer.should.valid? end - guard -> { Process.respond_to?(:fork) } do - it "is shareable across processes" do - file_name = tmp("shared_buffer") - @file = File.open(file_name, "w+") - @file << "I'm private" - @file.rewind - @buffer = IO::Buffer.map(@file) - - IO.popen("-") do |child_pipe| - if child_pipe - # Synchronize on child's output. - child_pipe.readlines.first.chomp.should == @buffer.to_s - @buffer.get_string.should == "I'm shared!" - - @file.read.should == "I'm shared!" - else - @buffer.set_string("I'm shared!") - puts @buffer + # IO::Buffer.map seems not shareable across processes on OpenBSD. + # See https://rubyci.s3.amazonaws.com/openbsd-current/ruby-master/log/20260129T163005Z.fail.html.gz + platform_is_not :openbsd do + guard -> { Process.respond_to?(:fork) } do + it "is shareable across processes" do + file_name = tmp("shared_buffer") + @file = File.open(file_name, "w+") + @file << "I'm private" + @file.rewind + @buffer = IO::Buffer.map(@file) + + IO.popen("-") do |child_pipe| + if child_pipe + # Synchronize on child's output. + child_pipe.readlines.first.chomp.should == @buffer.to_s + @buffer.get_string.should == "I'm shared!" + + @file.read.should == "I'm shared!" + else + @buffer.set_string("I'm shared!") + puts @buffer + end + ensure + child_pipe&.close end ensure - child_pipe&.close + File.unlink(file_name) end - ensure - File.unlink(file_name) end end diff --git a/spec/ruby/core/io/each_char_spec.rb b/spec/ruby/core/io/each_char_spec.rb index 5d460a1e7c..7c1ca4f069 100644 --- a/spec/ruby/core/io/each_char_spec.rb +++ b/spec/ruby/core/io/each_char_spec.rb @@ -1,12 +1,75 @@ -# -*- encoding: utf-8 -*- require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/chars' describe "IO#each_char" do - it_behaves_like :io_chars, :each_char + before :each do + @io = IOSpecs.io_fixture "lines.txt" + ScratchPad.record [] + end + + after :each do + @io.close unless @io.closed? + end + + it "yields each character" do + @io.readline.should == "Voici la ligne une.\n" + + count = 0 + @io.each_char do |c| + ScratchPad << c + break if 4 < count += 1 + end + + ScratchPad.recorded.should == ["Q", "u", "i", " ", "è"] + end + + describe "when no block is given" do + it "returns an Enumerator" do + enum = @io.each_char + enum.should.instance_of?(Enumerator) + enum.first(5).should == ["V", "o", "i", "c", "i"] + end + + describe "returned Enumerator" do + describe "size" do + it "should return nil" do + @io.each_char.size.should == nil + end + end + end + end + + it "returns itself" do + @io.each_char { |c| }.should.equal?(@io) + end + + it "returns an enumerator for a closed stream" do + IOSpecs.closed_io.each_char.should.instance_of?(Enumerator) + end + + it "raises an IOError when an enumerator created on a closed stream is accessed" do + -> { IOSpecs.closed_io.each_char.first }.should.raise(IOError) + end + + it "raises IOError on closed stream" do + -> { IOSpecs.closed_io.each_char {} }.should.raise(IOError) + end end describe "IO#each_char" do - it_behaves_like :io_chars_empty, :each_char + before :each do + @name = tmp("io_each_char") + @io = new_io @name, "w+:utf-8" + ScratchPad.record [] + end + + after :each do + @io.close unless @io.closed? + rm_r @name + end + + it "does not yield any characters on an empty stream" do + @io.each_char { |c| ScratchPad << c } + ScratchPad.recorded.should == [] + end end diff --git a/spec/ruby/core/io/each_codepoint_spec.rb b/spec/ruby/core/io/each_codepoint_spec.rb index 26cc87fc0e..758a524986 100644 --- a/spec/ruby/core/io/each_codepoint_spec.rb +++ b/spec/ruby/core/io/each_codepoint_spec.rb @@ -1,10 +1,57 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/codepoints' # See redmine #1667 describe "IO#each_codepoint" do - it_behaves_like :io_codepoints, :each_codepoint + before :each do + @io = IOSpecs.io_fixture "lines.txt" + @enum = @io.each_codepoint + end + + after :each do + @io.close + end + + describe "when no block is given" do + it "returns an Enumerator" do + @enum.should.instance_of?(Enumerator) + end + + describe "returned Enumerator" do + describe "size" do + it "should return nil" do + @enum.size.should == nil + end + end + end + end + + it "yields each codepoint" do + @enum.first(25).should == [ + 86, 111, 105, 99, 105, 32, 108, 97, 32, 108, 105, 103, 110, + 101, 32, 117, 110, 101, 46, 10, 81, 117, 105, 32, 232 + ] + end + + it "yields each codepoint starting from the current position" do + @io.pos = 130 + @enum.to_a.should == [101, 32, 115, 105, 120, 46, 10] + end + + it "raises an error if reading invalid sequence" do + @io.pos = 60 # inside of a multibyte sequence + -> { @enum.first }.should.raise(ArgumentError) + end + + it "does not change $_" do + $_ = "test" + @enum.to_a + $_.should == "test" + end + + it "raises an IOError when self is not readable" do + -> { IOSpecs.closed_io.each_codepoint.to_a }.should.raise(IOError) + end end describe "IO#each_codepoint" do diff --git a/spec/ruby/core/io/each_line_spec.rb b/spec/ruby/core/io/each_line_spec.rb index 58d26b325d..bcda4040b8 100644 --- a/spec/ruby/core/io/each_line_spec.rb +++ b/spec/ruby/core/io/each_line_spec.rb @@ -1,11 +1,251 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/each' describe "IO#each_line" do - it_behaves_like :io_each, :each_line + before :each do + @io = IOSpecs.io_fixture "lines.txt" + ScratchPad.record [] + end + + after :each do + @io.close if @io + end + + describe "with no separator" do + it "yields each line to the passed block" do + @io.each_line { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.lines + end + + it "yields each line starting from the current position" do + @io.pos = 41 + @io.each_line { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.lines[2..-1] + end + + it "returns self" do + @io.each_line { |l| l }.should.equal?(@io) + end + + it "does not change $_" do + $_ = "test" + @io.each_line { |s| s } + $_.should == "test" + end + + it "raises an IOError when self is not readable" do + -> { IOSpecs.closed_io.each_line {} }.should.raise(IOError) + end + + it "makes line count accessible via lineno" do + @io.each_line { ScratchPad << @io.lineno } + ScratchPad.recorded.should == [ 1,2,3,4,5,6,7,8,9 ] + end + + it "makes line count accessible via $." do + @io.each_line { ScratchPad << $. } + ScratchPad.recorded.should == [ 1,2,3,4,5,6,7,8,9 ] + end + + describe "when no block is given" do + it "returns an Enumerator" do + enum = @io.each_line + enum.should.instance_of?(Enumerator) + + enum.each { |l| ScratchPad << l } + ScratchPad.recorded.should == IOSpecs.lines + end + + describe "returned Enumerator" do + describe "size" do + it "should return nil" do + @io.each_line.size.should == nil + end + end + end + end + end + + describe "with limit" do + describe "when limit is 0" do + it "raises an ArgumentError" do + # must pass block so Enumerator is evaluated and raises + -> { @io.each_line(0){} }.should.raise(ArgumentError) + end + end + + it "does not accept Integers that don't fit in a C off_t" do + -> { @io.each_line(2**128){} }.should.raise(RangeError) + end + end + + describe "when passed a String containing one space as a separator" do + it "uses the passed argument as the line separator" do + @io.each_line(" ") { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.lines_space_separator + end + + it "does not change $_" do + $_ = "test" + @io.each_line(" ") { |s| } + $_.should == "test" + end + + it "tries to convert the passed separator to a String using #to_str" do + obj = mock("to_str") + obj.stub!(:to_str).and_return(" ") + + @io.each_line(obj) { |l| ScratchPad << l } + ScratchPad.recorded.should == IOSpecs.lines_space_separator + end + end + + describe "when passed nil as a separator" do + it "yields self's content starting from the current position when the passed separator is nil" do + @io.pos = 100 + @io.each_line(nil) { |s| ScratchPad << s } + ScratchPad.recorded.should == ["qui a linha cinco.\nHere is line six.\n"] + end + end + + describe "when passed an empty String as a separator" do + it "yields each paragraph" do + @io.each_line("") { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.paragraphs + end + + it "discards leading newlines" do + @io.readline + @io.readline + @io.each_line("") { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.paragraphs[1..-1] + end + end + + describe "with both separator and limit" do + describe "when no block is given" do + it "returns an Enumerator" do + enum = @io.each_line(nil, 1024) + enum.should.instance_of?(Enumerator) + + enum.each { |l| ScratchPad << l } + ScratchPad.recorded.should == [IOSpecs.lines.join] + end + + describe "returned Enumerator" do + describe "size" do + it "should return nil" do + @io.each_line(nil, 1024).size.should == nil + end + end + end + end + + describe "when a block is given" do + it "accepts an empty block" do + @io.each_line(nil, 1024) {}.should.equal?(@io) + end + + describe "when passed nil as a separator" do + it "yields self's content starting from the current position when the passed separator is nil" do + @io.pos = 100 + @io.each_line(nil, 1024) { |s| ScratchPad << s } + ScratchPad.recorded.should == ["qui a linha cinco.\nHere is line six.\n"] + end + end + + describe "when passed an empty String as a separator" do + it "yields each paragraph" do + @io.each_line("", 1024) { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.paragraphs + end + + it "discards leading newlines" do + @io.readline + @io.readline + @io.each_line("", 1024) { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.paragraphs[1..-1] + end + end + end + end + + describe "when passed chomp" do + it "yields each line without trailing newline characters to the passed block" do + @io.each_line(chomp: true) { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.lines_without_newline_characters + end + + it "raises exception when options passed as Hash" do + -> { + @io.each_line({ chomp: true }) { |s| } + }.should.raise(TypeError) + + -> { + @io.each_line("\n", 1, { chomp: true }) { |s| } + }.should.raise(ArgumentError, "wrong number of arguments (given 3, expected 0..2)") + end + end + + describe "when passed chomp and a separator" do + it "yields each line without separator to the passed block" do + @io.each_line(" ", chomp: true) { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.lines_space_separator_without_trailing_spaces + end + end + + describe "when passed chomp and empty line as a separator" do + it "yields each paragraph without trailing new line characters" do + @io.each_line("", 1024, chomp: true) { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.paragraphs_without_trailing_new_line_characters + end + end + + describe "when passed chomp and nil as a separator" do + it "yields self's content" do + @io.pos = 100 + @io.each_line(nil, chomp: true) { |s| ScratchPad << s } + ScratchPad.recorded.should == ["qui a linha cinco.\nHere is line six.\n"] + end + end + + describe "when passed chomp, nil as a separator, and a limit" do + it "yields each line of limit size without truncating trailing new line character" do + # 43 - is a size of the 1st paragraph in the file + @io.each_line(nil, 43, chomp: true) { |s| ScratchPad << s } + + ScratchPad.recorded.should == [ + "Voici la ligne une.\nQui è la linea due.\n\n\n", + "Aquí está la línea tres.\n" + "Hier ist Zeile ", + "vier.\n\nEstá aqui a linha cinco.\nHere is li", + "ne six.\n" + ] + end + end + + describe "when passed too many arguments" do + it "raises ArgumentError" do + -> { + @io.each_line("", 1, "excess argument", chomp: true) {} + }.should.raise(ArgumentError) + end + end end describe "IO#each_line" do - it_behaves_like :io_each_default_separator, :each_line + before :each do + @io = IOSpecs.io_fixture "lines.txt" + ScratchPad.record [] + suppress_warning {@sep, $/ = $/, " "} + end + + after :each do + @io.close if @io + suppress_warning {$/ = @sep} + end + + it "uses $/ as the default line separator" do + @io.each_line { |s| ScratchPad << s } + ScratchPad.recorded.should == IOSpecs.lines_space_separator + end end diff --git a/spec/ruby/core/io/each_spec.rb b/spec/ruby/core/io/each_spec.rb index 91ecbd19c8..594052256e 100644 --- a/spec/ruby/core/io/each_spec.rb +++ b/spec/ruby/core/io/each_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/each' describe "IO#each" do - it_behaves_like :io_each, :each -end - -describe "IO#each" do - it_behaves_like :io_each_default_separator, :each + it "is an alias of IO#each_line" do + IO.instance_method(:each).should == IO.instance_method(:each_line) + end end diff --git a/spec/ruby/core/io/eof_spec.rb b/spec/ruby/core/io/eof_spec.rb index c8955abde0..561daa4ec3 100644 --- a/spec/ruby/core/io/eof_spec.rb +++ b/spec/ruby/core/io/eof_spec.rb @@ -105,3 +105,9 @@ describe "IO#eof?" do @r.should.eof? end end + +describe "IO#eof" do + it "is an alias of IO#eof?" do + IO.instance_method(:eof).should == IO.instance_method(:eof?) + end +end diff --git a/spec/ruby/core/io/foreach_spec.rb b/spec/ruby/core/io/foreach_spec.rb index 015988f9fb..ccd2f25517 100644 --- a/spec/ruby/core/io/foreach_spec.rb +++ b/spec/ruby/core/io/foreach_spec.rb @@ -28,7 +28,7 @@ describe "IO.foreach" do ScratchPad.recorded.should == ["hello\n", "line2\n"] end - platform_is_not :windows do + guard -> { Process.respond_to?(:fork) } do it "gets data from a fork when passed -" do parent_pid = $$ diff --git a/spec/ruby/core/io/isatty_spec.rb b/spec/ruby/core/io/isatty_spec.rb index 3b6c69b190..60b97d21be 100644 --- a/spec/ruby/core/io/isatty_spec.rb +++ b/spec/ruby/core/io/isatty_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/tty' describe "IO#isatty" do - it_behaves_like :io_tty, :isatty + it "is an alias of IO#tty?" do + IO.instance_method(:isatty).should == IO.instance_method(:tty?) + end end diff --git a/spec/ruby/core/io/pos_spec.rb b/spec/ruby/core/io/pos_spec.rb index e6cda2643d..bbe25ce97b 100644 --- a/spec/ruby/core/io/pos_spec.rb +++ b/spec/ruby/core/io/pos_spec.rb @@ -3,7 +3,37 @@ require_relative 'fixtures/classes' require_relative 'shared/pos' describe "IO#pos" do - it_behaves_like :io_pos, :pos + before :each do + @fname = tmp('test.txt') + File.open(@fname, 'w') { |f| f.write "123" } + end + + after :each do + rm_r @fname + end + + it "gets the offset" do + File.open @fname do |f| + f.pos.should == 0 + f.read 1 + f.pos.should == 1 + f.read 2 + f.pos.should == 3 + end + end + + it "raises IOError on closed stream" do + -> { IOSpecs.closed_io.pos }.should.raise(IOError) + end + + it "resets #eof?" do + open @fname do |io| + io.read 1 + io.read 1 + io.pos + io.should_not.eof? + end + end end describe "IO#pos=" do diff --git a/spec/ruby/core/io/read_spec.rb b/spec/ruby/core/io/read_spec.rb index dd787c9b60..5be969e280 100644 --- a/spec/ruby/core/io/read_spec.rb +++ b/spec/ruby/core/io/read_spec.rb @@ -163,7 +163,7 @@ ruby_version_is ""..."4.0" do end end - platform_is_not :windows do + guard -> { Process.respond_to?(:fork) } do it "opens a pipe to a fork if the rest is -" do str = nil suppress_warning do # https://bugs.ruby-lang.org/issues/19630 diff --git a/spec/ruby/core/io/readlines_spec.rb b/spec/ruby/core/io/readlines_spec.rb index 640e253200..d41d24d7d1 100644 --- a/spec/ruby/core/io/readlines_spec.rb +++ b/spec/ruby/core/io/readlines_spec.rb @@ -189,7 +189,7 @@ describe "IO.readlines" do lines.should == ["hello\n", "line2\n"] end - platform_is_not :windows do + guard -> { Process.respond_to?(:fork) } do it "gets data from a fork when passed -" do lines = nil suppress_warning do # https://bugs.ruby-lang.org/issues/19630 diff --git a/spec/ruby/core/io/shared/chars.rb b/spec/ruby/core/io/shared/chars.rb deleted file mode 100644 index efd4d5ee10..0000000000 --- a/spec/ruby/core/io/shared/chars.rb +++ /dev/null @@ -1,73 +0,0 @@ -# -*- encoding: utf-8 -*- -describe :io_chars, shared: true do - before :each do - @io = IOSpecs.io_fixture "lines.txt" - ScratchPad.record [] - end - - after :each do - @io.close unless @io.closed? - end - - it "yields each character" do - @io.readline.should == "Voici la ligne une.\n" - - count = 0 - @io.send(@method) do |c| - ScratchPad << c - break if 4 < count += 1 - end - - ScratchPad.recorded.should == ["Q", "u", "i", " ", "è"] - end - - describe "when no block is given" do - it "returns an Enumerator" do - enum = @io.send(@method) - enum.should.instance_of?(Enumerator) - enum.first(5).should == ["V", "o", "i", "c", "i"] - end - - describe "returned Enumerator" do - describe "size" do - it "should return nil" do - @io.send(@method).size.should == nil - end - end - end - end - - it "returns itself" do - @io.send(@method) { |c| }.should.equal?(@io) - end - - it "returns an enumerator for a closed stream" do - IOSpecs.closed_io.send(@method).should.instance_of?(Enumerator) - end - - it "raises an IOError when an enumerator created on a closed stream is accessed" do - -> { IOSpecs.closed_io.send(@method).first }.should.raise(IOError) - end - - it "raises IOError on closed stream" do - -> { IOSpecs.closed_io.send(@method) {} }.should.raise(IOError) - end -end - -describe :io_chars_empty, shared: true do - before :each do - @name = tmp("io_each_char") - @io = new_io @name, "w+:utf-8" - ScratchPad.record [] - end - - after :each do - @io.close unless @io.closed? - rm_r @name - end - - it "does not yield any characters on an empty stream" do - @io.send(@method) { |c| ScratchPad << c } - ScratchPad.recorded.should == [] - end -end diff --git a/spec/ruby/core/io/shared/codepoints.rb b/spec/ruby/core/io/shared/codepoints.rb deleted file mode 100644 index 21c756986f..0000000000 --- a/spec/ruby/core/io/shared/codepoints.rb +++ /dev/null @@ -1,54 +0,0 @@ -# -*- encoding: utf-8 -*- -require_relative '../fixtures/classes' - -describe :io_codepoints, shared: true do - before :each do - @io = IOSpecs.io_fixture "lines.txt" - @enum = @io.send(@method) - end - - after :each do - @io.close - end - - describe "when no block is given" do - it "returns an Enumerator" do - @enum.should.instance_of?(Enumerator) - end - - describe "returned Enumerator" do - describe "size" do - it "should return nil" do - @enum.size.should == nil - end - end - end - end - - it "yields each codepoint" do - @enum.first(25).should == [ - 86, 111, 105, 99, 105, 32, 108, 97, 32, 108, 105, 103, 110, - 101, 32, 117, 110, 101, 46, 10, 81, 117, 105, 32, 232 - ] - end - - it "yields each codepoint starting from the current position" do - @io.pos = 130 - @enum.to_a.should == [101, 32, 115, 105, 120, 46, 10] - end - - it "raises an error if reading invalid sequence" do - @io.pos = 60 # inside of a multibyte sequence - -> { @enum.first }.should.raise(ArgumentError) - end - - it "does not change $_" do - $_ = "test" - @enum.to_a - $_.should == "test" - end - - it "raises an IOError when self is not readable" do - -> { IOSpecs.closed_io.send(@method).to_a }.should.raise(IOError) - end -end diff --git a/spec/ruby/core/io/shared/each.rb b/spec/ruby/core/io/shared/each.rb deleted file mode 100644 index ae60c3506a..0000000000 --- a/spec/ruby/core/io/shared/each.rb +++ /dev/null @@ -1,251 +0,0 @@ -# -*- encoding: utf-8 -*- -require_relative '../fixtures/classes' - -describe :io_each, shared: true do - before :each do - @io = IOSpecs.io_fixture "lines.txt" - ScratchPad.record [] - end - - after :each do - @io.close if @io - end - - describe "with no separator" do - it "yields each line to the passed block" do - @io.send(@method) { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.lines - end - - it "yields each line starting from the current position" do - @io.pos = 41 - @io.send(@method) { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.lines[2..-1] - end - - it "returns self" do - @io.send(@method) { |l| l }.should.equal?(@io) - end - - it "does not change $_" do - $_ = "test" - @io.send(@method) { |s| s } - $_.should == "test" - end - - it "raises an IOError when self is not readable" do - -> { IOSpecs.closed_io.send(@method) {} }.should.raise(IOError) - end - - it "makes line count accessible via lineno" do - @io.send(@method) { ScratchPad << @io.lineno } - ScratchPad.recorded.should == [ 1,2,3,4,5,6,7,8,9 ] - end - - it "makes line count accessible via $." do - @io.send(@method) { ScratchPad << $. } - ScratchPad.recorded.should == [ 1,2,3,4,5,6,7,8,9 ] - end - - describe "when no block is given" do - it "returns an Enumerator" do - enum = @io.send(@method) - enum.should.instance_of?(Enumerator) - - enum.each { |l| ScratchPad << l } - ScratchPad.recorded.should == IOSpecs.lines - end - - describe "returned Enumerator" do - describe "size" do - it "should return nil" do - @io.send(@method).size.should == nil - end - end - end - end - end - - describe "with limit" do - describe "when limit is 0" do - it "raises an ArgumentError" do - # must pass block so Enumerator is evaluated and raises - -> { @io.send(@method, 0){} }.should.raise(ArgumentError) - end - end - - it "does not accept Integers that don't fit in a C off_t" do - -> { @io.send(@method, 2**128){} }.should.raise(RangeError) - end - end - - describe "when passed a String containing one space as a separator" do - it "uses the passed argument as the line separator" do - @io.send(@method, " ") { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.lines_space_separator - end - - it "does not change $_" do - $_ = "test" - @io.send(@method, " ") { |s| } - $_.should == "test" - end - - it "tries to convert the passed separator to a String using #to_str" do - obj = mock("to_str") - obj.stub!(:to_str).and_return(" ") - - @io.send(@method, obj) { |l| ScratchPad << l } - ScratchPad.recorded.should == IOSpecs.lines_space_separator - end - end - - describe "when passed nil as a separator" do - it "yields self's content starting from the current position when the passed separator is nil" do - @io.pos = 100 - @io.send(@method, nil) { |s| ScratchPad << s } - ScratchPad.recorded.should == ["qui a linha cinco.\nHere is line six.\n"] - end - end - - describe "when passed an empty String as a separator" do - it "yields each paragraph" do - @io.send(@method, "") { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.paragraphs - end - - it "discards leading newlines" do - @io.readline - @io.readline - @io.send(@method, "") { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.paragraphs[1..-1] - end - end - - describe "with both separator and limit" do - describe "when no block is given" do - it "returns an Enumerator" do - enum = @io.send(@method, nil, 1024) - enum.should.instance_of?(Enumerator) - - enum.each { |l| ScratchPad << l } - ScratchPad.recorded.should == [IOSpecs.lines.join] - end - - describe "returned Enumerator" do - describe "size" do - it "should return nil" do - @io.send(@method, nil, 1024).size.should == nil - end - end - end - end - - describe "when a block is given" do - it "accepts an empty block" do - @io.send(@method, nil, 1024) {}.should.equal?(@io) - end - - describe "when passed nil as a separator" do - it "yields self's content starting from the current position when the passed separator is nil" do - @io.pos = 100 - @io.send(@method, nil, 1024) { |s| ScratchPad << s } - ScratchPad.recorded.should == ["qui a linha cinco.\nHere is line six.\n"] - end - end - - describe "when passed an empty String as a separator" do - it "yields each paragraph" do - @io.send(@method, "", 1024) { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.paragraphs - end - - it "discards leading newlines" do - @io.readline - @io.readline - @io.send(@method, "", 1024) { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.paragraphs[1..-1] - end - end - end - end - - describe "when passed chomp" do - it "yields each line without trailing newline characters to the passed block" do - @io.send(@method, chomp: true) { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.lines_without_newline_characters - end - - it "raises exception when options passed as Hash" do - -> { - @io.send(@method, { chomp: true }) { |s| } - }.should.raise(TypeError) - - -> { - @io.send(@method, "\n", 1, { chomp: true }) { |s| } - }.should.raise(ArgumentError, "wrong number of arguments (given 3, expected 0..2)") - end - end - - describe "when passed chomp and a separator" do - it "yields each line without separator to the passed block" do - @io.send(@method, " ", chomp: true) { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.lines_space_separator_without_trailing_spaces - end - end - - describe "when passed chomp and empty line as a separator" do - it "yields each paragraph without trailing new line characters" do - @io.send(@method, "", 1024, chomp: true) { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.paragraphs_without_trailing_new_line_characters - end - end - - describe "when passed chomp and nil as a separator" do - it "yields self's content" do - @io.pos = 100 - @io.send(@method, nil, chomp: true) { |s| ScratchPad << s } - ScratchPad.recorded.should == ["qui a linha cinco.\nHere is line six.\n"] - end - end - - describe "when passed chomp, nil as a separator, and a limit" do - it "yields each line of limit size without truncating trailing new line character" do - # 43 - is a size of the 1st paragraph in the file - @io.send(@method, nil, 43, chomp: true) { |s| ScratchPad << s } - - ScratchPad.recorded.should == [ - "Voici la ligne une.\nQui è la linea due.\n\n\n", - "Aquí está la línea tres.\n" + "Hier ist Zeile ", - "vier.\n\nEstá aqui a linha cinco.\nHere is li", - "ne six.\n" - ] - end - end - - describe "when passed too many arguments" do - it "raises ArgumentError" do - -> { - @io.send(@method, "", 1, "excess argument", chomp: true) {} - }.should.raise(ArgumentError) - end - end -end - -describe :io_each_default_separator, shared: true do - before :each do - @io = IOSpecs.io_fixture "lines.txt" - ScratchPad.record [] - suppress_warning {@sep, $/ = $/, " "} - end - - after :each do - @io.close if @io - suppress_warning {$/ = @sep} - end - - it "uses $/ as the default line separator" do - @io.send(@method) { |s| ScratchPad << s } - ScratchPad.recorded.should == IOSpecs.lines_space_separator - end -end diff --git a/spec/ruby/core/io/shared/pos.rb b/spec/ruby/core/io/shared/pos.rb index f4d0405863..450058e159 100644 --- a/spec/ruby/core/io/shared/pos.rb +++ b/spec/ruby/core/io/shared/pos.rb @@ -1,37 +1,3 @@ -describe :io_pos, shared: true do - before :each do - @fname = tmp('test.txt') - File.open(@fname, 'w') { |f| f.write "123" } - end - - after :each do - rm_r @fname - end - - it "gets the offset" do - File.open @fname do |f| - f.send(@method).should == 0 - f.read 1 - f.send(@method).should == 1 - f.read 2 - f.send(@method).should == 3 - end - end - - it "raises IOError on closed stream" do - -> { IOSpecs.closed_io.send(@method) }.should.raise(IOError) - end - - it "resets #eof?" do - open @fname do |io| - io.read 1 - io.read 1 - io.send(@method) - io.should_not.eof? - end - end -end - describe :io_set_pos, shared: true do before :each do @fname = tmp('test.txt') diff --git a/spec/ruby/core/io/shared/tty.rb b/spec/ruby/core/io/shared/tty.rb deleted file mode 100644 index 1dc0e95739..0000000000 --- a/spec/ruby/core/io/shared/tty.rb +++ /dev/null @@ -1,24 +0,0 @@ -require_relative '../fixtures/classes' - -describe :io_tty, shared: true do - platform_is_not :windows do - it "returns true if this stream is a terminal device (TTY)" do - begin - # check to enabled tty - File.open('/dev/tty') {} - rescue Errno::ENXIO - skip "workaround for not configured environment like OS X" - else - File.open('/dev/tty') { |f| f.send(@method) }.should == true - end - end - end - - it "returns false if this stream is not a terminal device (TTY)" do - File.open(__FILE__) { |f| f.send(@method) }.should == false - end - - it "raises IOError on closed stream" do - -> { IOSpecs.closed_io.send @method }.should.raise(IOError) - end -end diff --git a/spec/ruby/core/io/tell_spec.rb b/spec/ruby/core/io/tell_spec.rb index 0d6c6b02d3..a6b51adc17 100644 --- a/spec/ruby/core/io/tell_spec.rb +++ b/spec/ruby/core/io/tell_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/pos' describe "IO#tell" do - it_behaves_like :io_pos, :tell + it "is an alias of IO#pos" do + IO.instance_method(:tell).should == IO.instance_method(:pos) + end end diff --git a/spec/ruby/core/io/to_i_spec.rb b/spec/ruby/core/io/to_i_spec.rb index 1d0cf2a1f6..b271112a81 100644 --- a/spec/ruby/core/io/to_i_spec.rb +++ b/spec/ruby/core/io/to_i_spec.rb @@ -1,12 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' describe "IO#to_i" do - it "returns the numeric file descriptor of the given IO object" do - $stdout.to_i.should == 1 - end - - it "raises IOError on closed stream" do - -> { IOSpecs.closed_io.to_i }.should.raise(IOError) + it "is an alias of IO#fileno" do + IO.instance_method(:to_i).should == IO.instance_method(:fileno) end end diff --git a/spec/ruby/core/io/to_path_spec.rb b/spec/ruby/core/io/to_path_spec.rb new file mode 100644 index 0000000000..ec6dffc115 --- /dev/null +++ b/spec/ruby/core/io/to_path_spec.rb @@ -0,0 +1,7 @@ +require_relative '../../spec_helper' + +describe "IO#to_path" do + it "is an alias of IO#path" do + IO.instance_method(:to_path).should == IO.instance_method(:path) + end +end diff --git a/spec/ruby/core/io/tty_spec.rb b/spec/ruby/core/io/tty_spec.rb index 3b76c6d2b8..e1848a1760 100644 --- a/spec/ruby/core/io/tty_spec.rb +++ b/spec/ruby/core/io/tty_spec.rb @@ -1,6 +1,25 @@ require_relative '../../spec_helper' -require_relative 'shared/tty' +require_relative 'fixtures/classes' describe "IO#tty?" do - it_behaves_like :io_tty, :tty? + platform_is_not :windows do + it "returns true if this stream is a terminal device (TTY)" do + begin + # check to enabled tty + File.open('/dev/tty') {} + rescue Errno::ENXIO + skip "workaround for not configured environment like OS X" + else + File.open('/dev/tty') { |f| f.tty? }.should == true + end + end + end + + it "returns false if this stream is not a terminal device (TTY)" do + File.open(__FILE__) { |f| f.tty? }.should == false + end + + it "raises IOError on closed stream" do + -> { IOSpecs.closed_io.tty? }.should.raise(IOError) + end end diff --git a/spec/ruby/core/kernel/clone_spec.rb b/spec/ruby/core/kernel/clone_spec.rb index 4ddb23d6e6..80e7a78abb 100644 --- a/spec/ruby/core/kernel/clone_spec.rb +++ b/spec/ruby/core/kernel/clone_spec.rb @@ -10,12 +10,6 @@ describe "Kernel#clone" do @obj = KernelSpecs::Duplicate.new 1, :a end - it "calls #initialize_copy on the new instance" do - clone = @obj.clone - ScratchPad.recorded.should_not == @obj.object_id - ScratchPad.recorded.should == clone.object_id - end - it "uses the internal allocator and does not call #allocate" do klass = Class.new instance = klass.new diff --git a/spec/ruby/core/kernel/dup_spec.rb b/spec/ruby/core/kernel/dup_spec.rb index 99de5e3732..fa4ca71476 100644 --- a/spec/ruby/core/kernel/dup_spec.rb +++ b/spec/ruby/core/kernel/dup_spec.rb @@ -10,12 +10,6 @@ describe "Kernel#dup" do @obj = KernelSpecs::Duplicate.new 1, :a end - it "calls #initialize_copy on the new instance" do - dup = @obj.dup - ScratchPad.recorded.should_not == @obj.object_id - ScratchPad.recorded.should == dup.object_id - end - it "uses the internal allocator and does not call #allocate" do klass = Class.new instance = klass.new diff --git a/spec/ruby/core/kernel/enum_for_spec.rb b/spec/ruby/core/kernel/enum_for_spec.rb index 0092e20468..ef0fb64e63 100644 --- a/spec/ruby/core/kernel/enum_for_spec.rb +++ b/spec/ruby/core/kernel/enum_for_spec.rb @@ -1,5 +1,7 @@ require_relative '../../spec_helper' describe "Kernel#enum_for" do - it "needs to be reviewed for spec completeness" + it "is an alias of Kernel#to_enum" do + Kernel.instance_method(:enum_for).should == Kernel.instance_method(:to_enum) + end end diff --git a/spec/ruby/core/kernel/fail_spec.rb b/spec/ruby/core/kernel/fail_spec.rb index ac379b67d5..2d117d26cd 100644 --- a/spec/ruby/core/kernel/fail_spec.rb +++ b/spec/ruby/core/kernel/fail_spec.rb @@ -1,42 +1,13 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' describe "Kernel#fail" do - it "is a private method" do - Kernel.private_instance_methods(false).should.include?(:fail) - end - - it "raises a RuntimeError" do - -> { fail }.should.raise(RuntimeError) - end - - it "accepts an Object with an exception method returning an Exception" do - obj = Object.new - def obj.exception(msg) - StandardError.new msg - end - -> { fail obj, "..." }.should.raise(StandardError, "...") - end - - it "instantiates the specified exception class" do - error_class = Class.new(RuntimeError) - -> { fail error_class }.should.raise(error_class) - end - - it "uses the specified message" do - -> { - begin - fail "the duck is not irish." - rescue => e - e.message.should == "the duck is not irish." - raise - else - raise Exception - end - }.should.raise(RuntimeError) + it "is an alias of Kernel#raise" do + Kernel.instance_method(:fail).should == Kernel.instance_method(:raise) end end describe "Kernel.fail" do - it "needs to be reviewed for spec completeness" + it "is an alias of Kernel.raise" do + Kernel.method(:fail).should == Kernel.method(:raise) + end end diff --git a/spec/ruby/core/kernel/format_spec.rb b/spec/ruby/core/kernel/format_spec.rb index 35c752b1ab..a311f3c3d7 100644 --- a/spec/ruby/core/kernel/format_spec.rb +++ b/spec/ruby/core/kernel/format_spec.rb @@ -1,47 +1,13 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -# NOTE: most specs are in sprintf_spec.rb, this is just an alias describe "Kernel#format" do - it "is a private method" do - Kernel.private_instance_methods(false).should.include?(:format) + it "is an alias of Kernel#sprintf" do + Kernel.instance_method(:format).should == Kernel.instance_method(:sprintf) end end describe "Kernel.format" do - it "is accessible as a module function" do - Kernel.format("%s", "hello").should == "hello" - end - - describe "when $VERBOSE is true" do - it "warns if too many arguments are passed" do - code = <<~RUBY - $VERBOSE = true - format("test", 1) - RUBY - - ruby_exe(code, args: "2>&1").should.include?("warning: too many arguments for format string") - end - - it "does not warns if too many keyword arguments are passed" do - code = <<~RUBY - $VERBOSE = true - format("test %{test}", test: 1, unused: 2) - RUBY - - ruby_exe(code, args: "2>&1").should_not.include?("warning") - end - - ruby_bug "#20593", ""..."3.4" do - it "doesn't warns if keyword arguments are passed and none are used" do - code = <<~RUBY - $VERBOSE = true - format("test", test: 1) - format("test", {}) - RUBY - - ruby_exe(code, args: "2>&1").should_not.include?("warning") - end - end + it "is an alias of Kernel.sprintf" do + Kernel.method(:format).should == Kernel.method(:sprintf) end end diff --git a/spec/ruby/core/kernel/is_a_spec.rb b/spec/ruby/core/kernel/is_a_spec.rb index bd8c96529a..ff36a769c7 100644 --- a/spec/ruby/core/kernel/is_a_spec.rb +++ b/spec/ruby/core/kernel/is_a_spec.rb @@ -1,6 +1,56 @@ require_relative '../../spec_helper' -require_relative 'shared/kind_of' +require_relative 'fixtures/classes' describe "Kernel#is_a?" do - it_behaves_like :kernel_kind_of, :is_a? + before :each do + @o = KernelSpecs::KindaClass.new + end + + it "returns true if given class is the object's class" do + @o.is_a?(KernelSpecs::KindaClass).should == true + end + + it "returns true if given class is an ancestor of the object's class" do + @o.is_a?(KernelSpecs::AncestorClass).should == true + @o.is_a?(String).should == true + @o.is_a?(Object).should == true + end + + it "returns false if the given class is not object's class nor an ancestor" do + @o.is_a?(Array).should == false + end + + it "returns true if given a Module that is included in object's class" do + @o.is_a?(KernelSpecs::MyModule).should == true + end + + it "returns true if given a Module that is included one of object's ancestors only" do + @o.is_a?(KernelSpecs::AncestorModule).should == true + end + + it "returns true if given a Module that object has been extended with" do + @o.is_a?(KernelSpecs::MyExtensionModule).should == true + end + + it "returns true if given a Module that object has been prepended with" do + @o.is_a?(KernelSpecs::MyPrependedModule).should == true + end + + it "returns false if given a Module not included nor prepended in object's class nor ancestors" do + @o.is_a?(KernelSpecs::SomeOtherModule).should == false + end + + it "raises a TypeError if given an object that is not a Class nor a Module" do + -> { @o.is_a?(1) }.should.raise(TypeError) + -> { @o.is_a?('KindaClass') }.should.raise(TypeError) + -> { @o.is_a?(:KindaClass) }.should.raise(TypeError) + -> { @o.is_a?(Object.new) }.should.raise(TypeError) + end + + it "does not take into account `class` method overriding" do + def @o.class; Integer; end + + @o.is_a?(Integer).should == false + @o.is_a?(KernelSpecs::KindaClass).should == true + end end diff --git a/spec/ruby/core/kernel/kind_of_spec.rb b/spec/ruby/core/kernel/kind_of_spec.rb index c988edccb5..7fcc72543d 100644 --- a/spec/ruby/core/kernel/kind_of_spec.rb +++ b/spec/ruby/core/kernel/kind_of_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/kind_of' describe "Kernel#kind_of?" do - it_behaves_like :kernel_kind_of, :kind_of? + it "is an alias of Kernel#is_a?" do + Kernel.instance_method(:kind_of?).should == Kernel.instance_method(:is_a?) + end end diff --git a/spec/ruby/core/kernel/require_relative_spec.rb b/spec/ruby/core/kernel/require_relative_spec.rb index 332045b200..b3ac1fc64c 100644 --- a/spec/ruby/core/kernel/require_relative_spec.rb +++ b/spec/ruby/core/kernel/require_relative_spec.rb @@ -109,9 +109,9 @@ describe "Kernel#require_relative with a relative path" do -> { require_relative(path) - }.should(raise_error(LoadError) { |e| + }.should.raise(LoadError) { |e| e.path.should == File.expand_path(path, @abs_dir) - }) + } end it "calls #to_str on non-String objects" do @@ -311,9 +311,9 @@ describe "Kernel#require_relative with an absolute path" do -> { require_relative(path) - }.should(raise_error(LoadError) { |e| + }.should.raise(LoadError) { |e| e.path.should == File.expand_path(path, @abs_dir) - }) + } end it "calls #to_str on non-String objects" do diff --git a/spec/ruby/core/kernel/shared/kind_of.rb b/spec/ruby/core/kernel/shared/kind_of.rb deleted file mode 100644 index a5e0eab08f..0000000000 --- a/spec/ruby/core/kernel/shared/kind_of.rb +++ /dev/null @@ -1,55 +0,0 @@ -require_relative '../fixtures/classes' - -describe :kernel_kind_of, shared: true do - before :each do - @o = KernelSpecs::KindaClass.new - end - - it "returns true if given class is the object's class" do - @o.send(@method, KernelSpecs::KindaClass).should == true - end - - it "returns true if given class is an ancestor of the object's class" do - @o.send(@method, KernelSpecs::AncestorClass).should == true - @o.send(@method, String).should == true - @o.send(@method, Object).should == true - end - - it "returns false if the given class is not object's class nor an ancestor" do - @o.send(@method, Array).should == false - end - - it "returns true if given a Module that is included in object's class" do - @o.send(@method, KernelSpecs::MyModule).should == true - end - - it "returns true if given a Module that is included one of object's ancestors only" do - @o.send(@method, KernelSpecs::AncestorModule).should == true - end - - it "returns true if given a Module that object has been extended with" do - @o.send(@method, KernelSpecs::MyExtensionModule).should == true - end - - it "returns true if given a Module that object has been prepended with" do - @o.send(@method, KernelSpecs::MyPrependedModule).should == true - end - - it "returns false if given a Module not included nor prepended in object's class nor ancestors" do - @o.send(@method, KernelSpecs::SomeOtherModule).should == false - end - - it "raises a TypeError if given an object that is not a Class nor a Module" do - -> { @o.send(@method, 1) }.should.raise(TypeError) - -> { @o.send(@method, 'KindaClass') }.should.raise(TypeError) - -> { @o.send(@method, :KindaClass) }.should.raise(TypeError) - -> { @o.send(@method, Object.new) }.should.raise(TypeError) - end - - it "does not take into account `class` method overriding" do - def @o.class; Integer; end - - @o.send(@method, Integer).should == false - @o.send(@method, KernelSpecs::KindaClass).should == true - end -end diff --git a/spec/ruby/core/kernel/shared/sprintf.rb b/spec/ruby/core/kernel/shared/sprintf.rb index b40bd95f59..e57334c5ab 100644 --- a/spec/ruby/core/kernel/shared/sprintf.rb +++ b/spec/ruby/core/kernel/shared/sprintf.rb @@ -1031,4 +1031,27 @@ describe :kernel_sprintf, shared: true do it "does not raise error when passed more arguments than needed" do sprintf("%s %d %c", "string", 2, "c", []).should == "string 2 c" end + + describe "when $VERBOSE is true" do + it "warns if too many arguments are passed" do + -> { + format("test", 1) + }.should complain(/too many arguments for format string/, verbose: true) + end + + it "does not warns if too many keyword arguments are passed" do + -> { + format("test %{test}", test: 1, unused: 2) + }.should_not complain(verbose: true) + end + + ruby_bug "#20593", ""..."3.4" do + it "doesn't warns if keyword arguments are passed and none are used" do + -> { + format("test", test: 1) + format("test", {}) + }.should_not complain(verbose: true) + end + end + end end diff --git a/spec/ruby/core/kernel/then_spec.rb b/spec/ruby/core/kernel/then_spec.rb index 8109a2960a..bda5a69662 100644 --- a/spec/ruby/core/kernel/then_spec.rb +++ b/spec/ruby/core/kernel/then_spec.rb @@ -2,5 +2,13 @@ require_relative '../../spec_helper' require_relative 'shared/then' describe "Kernel#then" do - it_behaves_like :kernel_then, :then + ruby_version_is ""..."3.4" do + it_behaves_like :kernel_then, :then + end + + ruby_version_is "3.4" do + it "is an alias of Kernel#yield_self" do + Kernel.instance_method(:then).should == Kernel.instance_method(:yield_self) + end + end end diff --git a/spec/ruby/core/kernel/to_enum_spec.rb b/spec/ruby/core/kernel/to_enum_spec.rb index 9d9945450f..1cee26b694 100644 --- a/spec/ruby/core/kernel/to_enum_spec.rb +++ b/spec/ruby/core/kernel/to_enum_spec.rb @@ -1,5 +1,59 @@ require_relative '../../spec_helper' describe "Kernel#to_enum" do - it "needs to be reviewed for spec completeness" + it "is defined in Kernel" do + Kernel.method_defined?(:to_enum).should == true + end + + it "returns a new enumerator" do + "abc".to_enum.should.instance_of?(Enumerator) + end + + it "defaults the first argument to :each" do + enum = [1,2].to_enum + enum.map { |v| v }.should == [1,2].each { |v| v } + end + + it "sets regexp matches in the caller" do + "wawa".to_enum(:scan, /./).map {|o| $& }.should == ["w", "a", "w", "a"] + a = [] + "wawa".to_enum(:scan, /./).each {|o| a << $& } + a.should == ["w", "a", "w", "a"] + end + + it "exposes multi-arg yields as an array" do + o = Object.new + def o.each + yield :a + yield :b1, :b2 + yield [:c] + yield :d1, :d2 + yield :e1, :e2, :e3 + end + + enum = o.to_enum + enum.next.should == :a + enum.next.should == [:b1, :b2] + enum.next.should == [:c] + enum.next.should == [:d1, :d2] + enum.next.should == [:e1, :e2, :e3] + end + + it "uses the passed block's value to calculate the size of the enumerator" do + Object.new.to_enum { 100 }.size.should == 100 + end + + it "defers the evaluation of the passed block until #size is called" do + ScratchPad.record [] + + enum = Object.new.to_enum do + ScratchPad << :called + 100 + end + + ScratchPad.recorded.should.empty? + + enum.size + ScratchPad.recorded.should == [:called] + end end diff --git a/spec/ruby/core/marshal/load_spec.rb b/spec/ruby/core/marshal/load_spec.rb index a5bdfbf520..f5a05f8e52 100644 --- a/spec/ruby/core/marshal/load_spec.rb +++ b/spec/ruby/core/marshal/load_spec.rb @@ -1,6 +1,1291 @@ +# encoding: binary require_relative '../../spec_helper' -require_relative 'shared/load' +require_relative 'fixtures/marshal_data' describe "Marshal.load" do - it_behaves_like :marshal_load, :load + before :all do + @num_self_class = 1 + end + + it "raises an ArgumentError when the dumped data is truncated" do + obj = {first: 1, second: 2, third: 3} + -> { Marshal.load(Marshal.dump(obj)[0, 5]) }.should.raise(ArgumentError, "marshal data too short") + end + + it "raises an ArgumentError when the argument is empty String" do + -> { Marshal.load("") }.should.raise(ArgumentError, "marshal data too short") + end + + it "raises an ArgumentError when the dumped class is missing" do + Object.send(:const_set, :KaBoom, Class.new) + kaboom = Marshal.dump(KaBoom.new) + Object.send(:remove_const, :KaBoom) + + -> { Marshal.load(kaboom) }.should.raise(ArgumentError) + end + + describe "when called with freeze: true" do + it "returns frozen strings" do + string = Marshal.load(Marshal.dump("foo"), freeze: true) + string.should == "foo" + string.should.frozen? + + utf8_string = "foo".encode(Encoding::UTF_8) + string = Marshal.load(Marshal.dump(utf8_string), freeze: true) + string.should == utf8_string + string.should.frozen? + end + + it "returns frozen arrays" do + array = Marshal.load(Marshal.dump([1, 2, 3]), freeze: true) + array.should == [1, 2, 3] + array.should.frozen? + end + + it "returns frozen hashes" do + hash = Marshal.load(Marshal.dump({foo: 42}), freeze: true) + hash.should == {foo: 42} + hash.should.frozen? + end + + it "returns frozen regexps" do + regexp = Marshal.load(Marshal.dump(/foo/), freeze: true) + regexp.should == /foo/ + regexp.should.frozen? + end + + it "returns frozen structs" do + struct = Marshal.load(Marshal.dump(MarshalSpec::StructToDump.new(1, 2)), freeze: true) + struct.should == MarshalSpec::StructToDump.new(1, 2) + struct.should.frozen? + end + + it "returns frozen objects" do + source_object = Object.new + + object = Marshal.load(Marshal.dump(source_object), freeze: true) + object.should.frozen? + end + + describe "deep freezing" do + it "returns hashes with frozen keys and values" do + key = Object.new + value = Object.new + source_object = {key => value} + + hash = Marshal.load(Marshal.dump(source_object), freeze: true) + hash.size.should == 1 + hash.keys[0].should.frozen? + hash.values[0].should.frozen? + end + + it "returns arrays with frozen elements" do + object = Object.new + source_object = [object] + + array = Marshal.load(Marshal.dump(source_object), freeze: true) + array.size.should == 1 + array[0].should.frozen? + end + + it "returns structs with frozen members" do + object1 = Object.new + object2 = Object.new + source_object = MarshalSpec::StructToDump.new(object1, object2) + + struct = Marshal.load(Marshal.dump(source_object), freeze: true) + struct.a.should.frozen? + struct.b.should.frozen? + end + + it "returns objects with frozen instance variables" do + source_object = Object.new + instance_variable = Object.new + source_object.instance_variable_set(:@a, instance_variable) + + object = Marshal.load(Marshal.dump(source_object), freeze: true) + object.instance_variable_get(:@a).should != nil + object.instance_variable_get(:@a).should.frozen? + end + + it "deduplicates frozen strings" do + source_object = ["foo" + "bar", "foobar"] + object = Marshal.load(Marshal.dump(source_object), freeze: true) + + object[0].should.equal?(object[1]) + end + end + + it "does not freeze modules" do + object = Marshal.load(Marshal.dump(Kernel), freeze: true) + object.should_not.frozen? + Kernel.should_not.frozen? + end + + it "does not freeze classes" do + object = Marshal.load(Marshal.dump(Object), freeze: true) + object.should_not.frozen? + Object.should_not.frozen? + end + + it "does freeze extended objects" do + object = Marshal.load("\x04\be:\x0FEnumerableo:\vObject\x00", freeze: true) + object.should.frozen? + end + + it "does freeze extended objects with instance variables" do + object = Marshal.load("\x04\be:\x0FEnumerableo:\vObject\x06:\n@ivarT", freeze: true) + object.should.frozen? + end + + it "returns frozen object having #_dump method" do + object = Marshal.load(Marshal.dump(UserDefined.new), freeze: true) + object.should.frozen? + end + + it "returns frozen object responding to #marshal_dump and #marshal_load" do + object = Marshal.load(Marshal.dump(UserMarshal.new), freeze: true) + object.should.frozen? + end + + it "returns frozen object extended by a module" do + object = Object.new + object.extend(MarshalSpec::ModuleToExtendBy) + + object = Marshal.load(Marshal.dump(object), freeze: true) + object.should.frozen? + end + + it "does not call freeze method" do + object = MarshalSpec::ObjectWithFreezeRaisingException.new + object = Marshal.load(Marshal.dump(object), freeze: true) + object.should.frozen? + end + + it "returns frozen object even if object does not respond to freeze method" do + object = MarshalSpec::ObjectWithoutFreeze.new + object = Marshal.load(Marshal.dump(object), freeze: true) + object.should.frozen? + end + + it "returns a frozen object when is an instance of String/Array/Regexp/Hash subclass and has instance variables" do + source_object = UserString.new + source_object.instance_variable_set(:@foo, "bar") + + object = Marshal.load(Marshal.dump(source_object), freeze: true) + object.should.frozen? + end + + describe "when called with a proc" do + it "call the proc with frozen objects" do + arr = [] + s = +'hi' + s.instance_variable_set(:@foo, 5) + st = Struct.new("Brittle", :a).new + st.instance_variable_set(:@clue, 'none') + st.a = 0.0 + h = Hash.new('def') + h['nine'] = 9 + a = [:a, :b, :c] + a.instance_variable_set(:@two, 2) + obj = [s, 10, s, s, st, a] + obj.instance_variable_set(:@zoo, 'ant') + proc = Proc.new { |o| arr << o; o} + + Marshal.load( + "\x04\bI[\vI\"\ahi\a:\x06EF:\t@fooi\ni\x0F@\x06@\x06IS:\x14Struct::Brittle\x06:\x06af\x060\x06:\n@clueI\"\tnone\x06;\x00FI[\b;\b:\x06b:\x06c\x06:\t@twoi\a\x06:\t@zooI\"\bant\x06;\x00F", + proc, + freeze: true, + ) + + arr.should == [ + false, 5, "hi", 10, "hi", "hi", 0.0, false, "none", st, + :b, :c, 2, a, false, "ant", ["hi", 10, "hi", "hi", st, [:a, :b, :c]], + ] + + arr.each do |v| + v.should.frozen? + end + + Struct.send(:remove_const, :Brittle) + end + + it "does not freeze the object returned by the proc" do + string = Marshal.load(Marshal.dump("foo"), proc { |o| o.upcase }, freeze: true) + string.should == "FOO" + string.should_not.frozen? + end + end + end + + describe "when called with a proc" do + it "call the proc with fully initialized strings" do + utf8_string = "foo".encode(Encoding::UTF_8) + Marshal.load(Marshal.dump(utf8_string), proc { |arg| + if arg.is_a?(String) + arg.should == utf8_string + arg.encoding.should == Encoding::UTF_8 + end + arg + }) + end + + it "no longer mutate the object after it was passed to the proc" do + string = Marshal.load(Marshal.dump("foo"), :freeze.to_proc) + string.should.frozen? + end + + it "call the proc with extended objects" do + objs = [] + obj = Marshal.load("\x04\be:\x0FEnumerableo:\vObject\x00", Proc.new { |o| objs << o; o }) + objs.should == [obj] + end + + it "returns the value of the proc" do + Marshal.load(Marshal.dump([1,2]), proc { [3,4] }).should == [3,4] + end + + it "calls the proc for recursively visited data" do + a = [1] + a << a + ret = [] + Marshal.load(Marshal.dump(a), proc { |arg| ret << arg.inspect; arg }) + ret[0].should == 1.inspect + ret[1].should == a.inspect + ret.size.should == 2 + end + + it "loads an Array with proc" do + arr = [] + s = +'hi' + s.instance_variable_set(:@foo, 5) + st = Struct.new("Brittle", :a).new + st.instance_variable_set(:@clue, 'none') + st.a = 0.0 + h = Hash.new('def') + h['nine'] = 9 + a = [:a, :b, :c] + a.instance_variable_set(:@two, 2) + obj = [s, 10, s, s, st, a] + obj.instance_variable_set(:@zoo, 'ant') + proc = Proc.new { |o| arr << o.dup; o} + + Marshal.load("\x04\bI[\vI\"\ahi\a:\x06EF:\t@fooi\ni\x0F@\x06@\x06IS:\x14Struct::Brittle\x06:\x06af\x060\x06:\n@clueI\"\tnone\x06;\x00FI[\b;\b:\x06b:\x06c\x06:\t@twoi\a\x06:\t@zooI\"\bant\x06;\x00F", proc) + + arr.should == [ + false, 5, "hi", 10, "hi", "hi", 0.0, false, "none", st, + :b, :c, 2, a, false, "ant", ["hi", 10, "hi", "hi", st, [:a, :b, :c]], + ] + Struct.send(:remove_const, :Brittle) + end + end + + describe "when called with nil for the proc argument" do + it "behaves as if no proc argument was passed" do + a = [1] + a << a + b = Marshal.load(Marshal.dump(a), nil) + b.should == a + end + end + + describe "when called on objects with custom _dump methods" do + it "does not set instance variables of an object with user-defined _dump/_load" do + # this string represents: <#UserPreviouslyDefinedWithInitializedIvar @field2=7 @field1=6> + dump_str = "\004\bu:-UserPreviouslyDefinedWithInitializedIvar\a:\f@field2i\f:\f@field1i\v" + + UserPreviouslyDefinedWithInitializedIvar.should_receive(:_load).and_return(UserPreviouslyDefinedWithInitializedIvar.new) + marshaled_obj = Marshal.load(dump_str) + + marshaled_obj.should.instance_of?(UserPreviouslyDefinedWithInitializedIvar) + marshaled_obj.field1.should == nil + marshaled_obj.field2.should == nil + end + + it "loads the String in non US-ASCII and non UTF-8 encoding" do + source_object = UserDefinedString.new("a".encode("windows-1251")) + object = Marshal.load(Marshal.dump(source_object)) + object.string.should == "a".encode("windows-1251") + end + + it "loads the String in multibyte encoding" do + source_object = UserDefinedString.new("a".encode("utf-32le")) + object = Marshal.load(Marshal.dump(source_object)) + object.string.should == "a".encode("utf-32le") + end + + describe "that returns an immediate value" do + it "loads an array containing an instance of the object, followed by multiple instances of another object" do + str = "string" + + # this string represents: [<#UserDefinedImmediate A>, <#String "string">, <#String "string">] + marshaled_obj = Marshal.load("\004\b[\bu:\031UserDefinedImmediate\000\"\vstring@\a") + + marshaled_obj.should == [nil, str, str] + end + + it "loads any structure with multiple references to the same object, followed by multiple instances of another object" do + str = "string" + + # this string represents: {a: <#UserDefinedImmediate A>, b: <#UserDefinedImmediate A>, c: <#String "string">, d: <#String "string">} + hash_dump = "\x04\b{\t:\x06aIu:\x19UserDefinedImmediate\x00\x06:\x06ET:\x06b@\x06:\x06cI\"\vstring\x06;\aT:\x06d@\a" + + marshaled_obj = Marshal.load(hash_dump) + marshaled_obj.should == {a: nil, b: nil, c: str, d: str} + + # this string represents: [<#UserDefinedImmediate A>, <#UserDefinedImmediate A>, <#String "string">, <#String "string">] + array_dump = "\x04\b[\tIu:\x19UserDefinedImmediate\x00\x06:\x06ET@\x06I\"\vstring\x06;\x06T@\a" + + marshaled_obj = Marshal.load(array_dump) + marshaled_obj.should == [nil, nil, str, str] + end + + it "loads an array containing references to multiple instances of the object, followed by multiple instances of another object" do + str = "string" + + # this string represents: [<#UserDefinedImmediate A>, <#UserDefinedImmediate B>, <#String "string">, <#String "string">] + array_dump = "\x04\b[\tIu:\x19UserDefinedImmediate\x00\x06:\x06ETIu;\x00\x00\x06;\x06TI\"\vstring\x06;\x06T@\b" + + marshaled_obj = Marshal.load(array_dump) + marshaled_obj.should == [nil, nil, str, str] + end + end + end + + it "loads an array containing objects having _dump method, and with proc" do + arr = [] + myproc = Proc.new { |o| arr << o.dup; o } + o1 = UserDefined.new; + o2 = UserDefinedWithIvar.new + obj = [o1, o2, o1, o2] + + Marshal.load("\x04\b[\tu:\x10UserDefined\x18\x04\b[\aI\"\nstuff\x06:\x06EF@\x06u:\x18UserDefinedWithIvar>\x04\b[\bI\"\nstuff\a:\x06EF:\t@foo:\x18UserDefinedWithIvarI\"\tmore\x06;\x00F@\a@\x06@\a", myproc) + + arr[0].should == o1 + arr[1].should == o2 + arr[2].should == obj + arr.size.should == 3 + end + + it "loads an array containing objects having marshal_dump method, and with proc" do + arr = [] + proc = Proc.new { |o| arr << o.dup; o } + o1 = UserMarshal.new + o2 = UserMarshalWithIvar.new + + Marshal.load("\004\b[\tU:\020UserMarshal\"\nstuffU:\030UserMarshalWithIvar[\006\"\fmy data@\006@\b", proc) + + arr[0].should == 'stuff' + arr[1].should == o1 + arr[2].should == 'my data' + arr[3].should == ['my data'] + arr[4].should == o2 + arr[5].should == [o1, o2, o1, o2] + + arr.size.should == 6 + end + + it "assigns classes to nested subclasses of Array correctly" do + arr = ArraySub.new(ArraySub.new) + arr_dump = Marshal.dump(arr) + Marshal.load(arr_dump).class.should == ArraySub + end + + it "loads subclasses of Array with overridden << and push correctly" do + arr = ArraySubPush.new + arr[0] = '1' + arr_dump = Marshal.dump(arr) + Marshal.load(arr_dump).should == arr + end + + it "raises a TypeError with bad Marshal version" do + marshal_data = +'\xff\xff' + marshal_data[0] = (Marshal::MAJOR_VERSION).chr + marshal_data[1] = (Marshal::MINOR_VERSION + 1).chr + + -> { Marshal.load(marshal_data) }.should.raise(TypeError) + + marshal_data = +'\xff\xff' + marshal_data[0] = (Marshal::MAJOR_VERSION - 1).chr + marshal_data[1] = (Marshal::MINOR_VERSION).chr + + -> { Marshal.load(marshal_data) }.should.raise(TypeError) + end + + it "raises EOFError on loading an empty file" do + temp_file = tmp("marshal.rubyspec.tmp.#{Process.pid}") + file = File.new(temp_file, "w+") + begin + -> { Marshal.load(file) }.should.raise(EOFError) + ensure + file.close + rm_r temp_file + end + end + + # Note: Ruby 1.9 should be compatible with older marshal format + MarshalSpec::DATA.each do |description, (object, marshal, attributes)| + it "loads a #{description}" do + Marshal.load(marshal).should == object + end + end + + MarshalSpec::DATA_19.each do |description, (object, marshal, attributes)| + it "loads a #{description}" do + Marshal.load(marshal).should == object + end + end + + describe "for an Array" do + it "loads an array containing the same objects" do + s = 'oh' + b = 'hi' + r = // + d = [b, :no, s, :go] + c = String + f = 1.0 + + o1 = UserMarshalWithIvar.new; o2 = UserMarshal.new + + obj = [:so, 'hello', 100, :so, :so, d, :so, o2, :so, :no, o2, + :go, c, nil, Struct::Pyramid.new, f, :go, :no, s, b, r, + :so, 'huh', o1, true, b, b, 99, r, b, s, :so, f, c, :no, o1, d] + + Marshal.load("\004\b[*:\aso\"\nhelloii;\000;\000[\t\"\ahi:\ano\"\aoh:\ago;\000U:\020UserMarshal\"\nstuff;\000;\006@\n;\ac\vString0S:\024Struct::Pyramid\000f\0061;\a;\006@\t@\b/\000\000;\000\"\bhuhU:\030UserMarshalWithIvar[\006\"\fmy dataT@\b@\bih@\017@\b@\t;\000@\016@\f;\006@\021@\a").should == + obj + end + + it "loads an array having ivar" do + s = +'well' + s.instance_variable_set(:@foo, 10) + obj = ['5', s, 'hi'].extend(Meths, MethsMore) + obj.instance_variable_set(:@mix, s) + new_obj = Marshal.load("\004\bI[\b\"\0065I\"\twell\006:\t@fooi\017\"\ahi\006:\t@mix@\a") + new_obj.should == obj + new_obj.instance_variable_get(:@mix).should.equal? new_obj[1] + new_obj[1].instance_variable_get(:@foo).should == 10 + end + + it "loads an extended Array object containing a user-marshaled object" do + obj = [UserMarshal.new, UserMarshal.new].extend(Meths) + dump = "\x04\be:\nMeths[\ao:\x10UserMarshal\x06:\n@dataI\"\nstuff\x06:\x06ETo;\x06\x06;\aI\"\nstuff\x06;\bT" + new_obj = Marshal.load(dump) + + new_obj.should == obj + obj_ancestors = class << obj; ancestors[1..-1]; end + new_obj_ancestors = class << new_obj; ancestors[1..-1]; end + obj_ancestors.should == new_obj_ancestors + end + end + + describe "for a Hash" do + it "loads an extended_user_hash with a parameter to initialize" do + obj = UserHashInitParams.new(:abc).extend(Meths) + + new_obj = Marshal.load("\004\bIe:\nMethsC:\027UserHashInitParams{\000\006:\a@a:\babc") + + new_obj.should == obj + new_obj_metaclass_ancestors = class << new_obj; ancestors; end + new_obj_metaclass_ancestors[@num_self_class].should == Meths + new_obj_metaclass_ancestors[@num_self_class+1].should == UserHashInitParams + end + + it "loads an extended hash object containing a user-marshaled object" do + obj = {a: UserMarshal.new}.extend(Meths) + + new_obj = Marshal.load("\004\be:\nMeths{\006:\006aU:\020UserMarshal\"\nstuff") + + new_obj.should == obj + new_obj_metaclass_ancestors = class << new_obj; ancestors; end + new_obj_metaclass_ancestors[@num_self_class].should == Meths + new_obj_metaclass_ancestors[@num_self_class+1].should == Hash + end + + it "preserves hash ivars when hash contains a string having ivar" do + s = +'string' + s.instance_variable_set :@string_ivar, 'string ivar' + h = { key: s } + h.instance_variable_set :@hash_ivar, 'hash ivar' + + unmarshalled = Marshal.load(Marshal.dump(h)) + unmarshalled.instance_variable_get(:@hash_ivar).should == 'hash ivar' + unmarshalled[:key].instance_variable_get(:@string_ivar).should == 'string ivar' + end + + it "preserves compare_by_identity behaviour" do + h = { a: 1 } + h.compare_by_identity + unmarshalled = Marshal.load(Marshal.dump(h)) + unmarshalled.should.compare_by_identity? + + h = { a: 1 } + unmarshalled = Marshal.load(Marshal.dump(h)) + unmarshalled.should_not.compare_by_identity? + end + + it "preserves compare_by_identity behaviour for a Hash subclass" do + h = UserHash.new({ a: 1 }) + h.compare_by_identity + unmarshalled = Marshal.load(Marshal.dump(h)) + unmarshalled.should.compare_by_identity? + + h = UserHash.new({ a: 1 }) + unmarshalled = Marshal.load(Marshal.dump(h)) + unmarshalled.should_not.compare_by_identity? + end + + it "allocates an instance of the proper class when Hash subclass with compare_by_identity behaviour" do + h = UserHash.new({ a: 1 }) + h.compare_by_identity + + unmarshalled = Marshal.load(Marshal.dump(h)) + unmarshalled.should.kind_of?(UserHash) + end + end + + describe "for a Symbol" do + it "loads a Symbol" do + sym = Marshal.load("\004\b:\vsymbol") + sym.should == :symbol + sym.encoding.should == Encoding::US_ASCII + end + + it "loads a big Symbol" do + sym = ('big' * 100).to_sym + Marshal.load("\004\b:\002,\001#{'big' * 100}").should == sym + end + + it "loads an encoded Symbol" do + s = "\u2192" + + sym = Marshal.load("\x04\bI:\b\xE2\x86\x92\x06:\x06ET") + sym.should == s.encode("utf-8").to_sym + sym.encoding.should == Encoding::UTF_8 + + sym = Marshal.load("\x04\bI:\t\xFE\xFF!\x92\x06:\rencoding\"\vUTF-16") + sym.should == s.encode("utf-16").to_sym + sym.encoding.should == Encoding::UTF_16 + + sym = Marshal.load("\x04\bI:\a\x92!\x06:\rencoding\"\rUTF-16LE") + sym.should == s.encode("utf-16le").to_sym + sym.encoding.should == Encoding::UTF_16LE + + sym = Marshal.load("\x04\bI:\a!\x92\x06:\rencoding\"\rUTF-16BE") + sym.should == s.encode("utf-16be").to_sym + sym.encoding.should == Encoding::UTF_16BE + + sym = Marshal.load("\x04\bI:\a\xA2\xAA\x06:\rencoding\"\vEUC-JP") + sym.should == s.encode("euc-jp").to_sym + sym.encoding.should == Encoding::EUC_JP + + sym = Marshal.load("\x04\bI:\a\x81\xA8\x06:\rencoding\"\x10Windows-31J") + sym.should == s.encode("sjis").to_sym + sym.encoding.should == Encoding::SJIS + end + + it "loads a binary encoded Symbol" do + s = "\u2192".dup.force_encoding("binary").to_sym + sym = Marshal.load("\x04\b:\b\xE2\x86\x92") + sym.should == s + sym.encoding.should == Encoding::BINARY + end + + it "loads multiple Symbols sharing the same encoding" do + # Note that the encoding is a link for the second Symbol + symbol1 = "I:\t\xE2\x82\xACa\x06:\x06ET" + symbol2 = "I:\t\xE2\x82\xACb\x06;\x06T" + dump = "\x04\b[\a#{symbol1}#{symbol2}" + value = Marshal.load(dump) + value.map(&:encoding).should == [Encoding::UTF_8, Encoding::UTF_8] + expected = [ + "€a".dup.force_encoding(Encoding::UTF_8).to_sym, + "€b".dup.force_encoding(Encoding::UTF_8).to_sym + ] + value.should == expected + + value = Marshal.load("\x04\b[\b#{symbol1}#{symbol2};\x00") + value.map(&:encoding).should == [Encoding::UTF_8, Encoding::UTF_8, Encoding::UTF_8] + value.should == [*expected, expected[0]] + end + + it "raises ArgumentError when end of byte sequence reached before symbol characters end" do + Marshal.dump(:hello).should == "\x04\b:\nhello" + + -> { + Marshal.load("\x04\b:\nhel") + }.should.raise(ArgumentError, "marshal data too short") + end + end + + describe "for a String" do + it "loads a string having ivar with ref to self" do + obj = +'hi' + obj.instance_variable_set(:@self, obj) + Marshal.load("\004\bI\"\ahi\006:\n@self@\000").should == obj + end + + it "loads a string through StringIO stream" do + require 'stringio' + obj = "This is a string which should be unmarshalled through StringIO stream!" + Marshal.load(StringIO.new(Marshal.dump(obj))).should == obj + end + + it "sets binmode if it is loading through StringIO stream" do + io = StringIO.new("\004\b:\vsymbol") + def io.binmode; raise "binmode"; end + -> { Marshal.load(io) }.should.raise(RuntimeError, "binmode") + end + + it "loads a string with an ivar" do + str = Marshal.load("\x04\bI\"\x00\x06:\t@fooI\"\bbar\x06:\x06EF") + str.instance_variable_get("@foo").should == "bar" + end + + it "loads a String subclass with custom constructor" do + str = Marshal.load("\x04\bC: UserCustomConstructorString\"\x00") + str.should.instance_of?(UserCustomConstructorString) + end + + it "loads a US-ASCII String" do + str = "abc".dup.force_encoding("us-ascii") + data = "\x04\bI\"\babc\x06:\x06EF" + result = Marshal.load(data) + result.should == str + result.encoding.should.equal?(Encoding::US_ASCII) + end + + it "loads a UTF-8 String" do + str = "\x6d\xc3\xb6\x68\x72\x65".dup.force_encoding("utf-8") + data = "\x04\bI\"\vm\xC3\xB6hre\x06:\x06ET" + result = Marshal.load(data) + result.should == str + result.encoding.should.equal?(Encoding::UTF_8) + end + + it "loads a String in another encoding" do + str = "\x6d\x00\xf6\x00\x68\x00\x72\x00\x65\x00".dup.force_encoding("utf-16le") + data = "\x04\bI\"\x0Fm\x00\xF6\x00h\x00r\x00e\x00\x06:\rencoding\"\rUTF-16LE" + result = Marshal.load(data) + result.should == str + result.encoding.should.equal?(Encoding::UTF_16LE) + end + + it "loads a String as BINARY if no encoding is specified at the end" do + str = "\xC3\xB8".dup.force_encoding("BINARY") + data = "\x04\b\"\a\xC3\xB8".dup.force_encoding("UTF-8") + result = Marshal.load(data) + result.encoding.should == Encoding::BINARY + result.should == str + end + + it "raises ArgumentError when end of byte sequence reached before string characters end" do + Marshal.dump("hello").should == "\x04\b\"\nhello" + + -> { + Marshal.load("\x04\b\"\nhel") + }.should.raise(ArgumentError, "marshal data too short") + end + end + + describe "for a Struct" do + it "loads a extended_struct having fields with same objects" do + s = 'hi' + obj = Struct.new("Extended", :a, :b).new.extend(Meths) + dump = "\004\be:\nMethsS:\025Struct::Extended\a:\006a0:\006b0" + Marshal.load(dump).should == obj + + obj.a = [:a, s] + obj.b = [:Meths, s] + dump = "\004\be:\nMethsS:\025Struct::Extended\a:\006a[\a;\a\"\ahi:\006b[\a;\000@\a" + Marshal.load(dump).should == obj + Struct.send(:remove_const, :Extended) + end + + it "loads a struct having ivar" do + obj = Struct.new("Thick").new + obj.instance_variable_set(:@foo, 5) + reloaded = Marshal.load("\004\bIS:\022Struct::Thick\000\006:\t@fooi\n") + reloaded.should == obj + reloaded.instance_variable_get(:@foo).should == 5 + Struct.send(:remove_const, :Thick) + end + + it "loads a struct having fields" do + obj = Struct.new("Ure1", :a, :b).new + Marshal.load("\004\bS:\021Struct::Ure1\a:\006a0:\006b0").should == obj + Struct.send(:remove_const, :Ure1) + end + + it "does not call initialize on the unmarshaled struct" do + threadlocal_key = MarshalSpec::StructWithUserInitialize::THREADLOCAL_KEY + + s = MarshalSpec::StructWithUserInitialize.new('foo') + Thread.current[threadlocal_key].should == ['foo'] + s.a.should == 'foo' + + Thread.current[threadlocal_key] = nil + + dumped = Marshal.dump(s) + loaded = Marshal.load(dumped) + + Thread.current[threadlocal_key].should == nil + loaded.a.should == 'foo' + end + end + + describe "for a Data" do + it "loads a Data" do + obj = MarshalSpec::DataSpec::Measure.new(100, 'km') + dumped = "\x04\bS:#MarshalSpec::DataSpec::Measure\a:\vamountii:\tunit\"\akm" + Marshal.dump(obj).should == dumped + + Marshal.load(dumped).should == obj + end + + it "loads an extended Data" do + obj = MarshalSpec::DataSpec::MeasureExtended.new(100, "km") + dumped = "\x04\bS:+MarshalSpec::DataSpec::MeasureExtended\a:\vamountii:\tunit\"\akm" + Marshal.dump(obj).should == dumped + + Marshal.load(dumped).should == obj + end + + it "returns a frozen object" do + obj = MarshalSpec::DataSpec::Measure.new(100, 'km') + dumped = "\x04\bS:#MarshalSpec::DataSpec::Measure\a:\vamountii:\tunit\"\akm" + Marshal.dump(obj).should == dumped + + Marshal.load(dumped).should.frozen? + end + end + + describe "for an Exception" do + it "loads a marshalled exception with no message" do + obj = Exception.new + loaded = Marshal.load("\004\bo:\016Exception\a:\abt0:\tmesg0") + loaded.message.should == obj.message + loaded.backtrace.should == obj.backtrace + loaded = Marshal.load("\x04\bo:\x0EException\a:\tmesg0:\abt0") + loaded.message.should == obj.message + loaded.backtrace.should == obj.backtrace + end + + it "loads a marshalled exception with a message" do + obj = Exception.new("foo") + loaded = Marshal.load("\004\bo:\016Exception\a:\abt0:\tmesg\"\bfoo") + loaded.message.should == obj.message + loaded.backtrace.should == obj.backtrace + loaded = Marshal.load("\x04\bo:\x0EException\a:\tmesgI\"\bfoo\x06:\x06EF:\abt0") + loaded.message.should == obj.message + loaded.backtrace.should == obj.backtrace + end + + it "loads a marshalled exception with a backtrace" do + obj = Exception.new("foo") + obj.set_backtrace(["foo/bar.rb:10"]) + loaded = Marshal.load("\004\bo:\016Exception\a:\abt[\006\"\022foo/bar.rb:10:\tmesg\"\bfoo") + loaded.message.should == obj.message + loaded.backtrace.should == obj.backtrace + loaded = Marshal.load("\x04\bo:\x0EException\a:\tmesgI\"\bfoo\x06:\x06EF:\abt[\x06I\"\x12foo/bar.rb:10\x06;\aF") + loaded.message.should == obj.message + loaded.backtrace.should == obj.backtrace + end + + it "loads an marshalled exception with ivars" do + s = 'hi' + arr = [:so, :so, s, s] + obj = Exception.new("foo") + obj.instance_variable_set :@arr, arr + + loaded = Marshal.load("\x04\bo:\x0EException\b:\tmesg\"\bfoo:\abt0:\t@arr[\t:\aso;\t\"\ahi@\b") + new_arr = loaded.instance_variable_get :@arr + + loaded.message.should == obj.message + new_arr.should == arr + end + end + + describe "for an Object" do + it "loads an object" do + Marshal.load("\004\bo:\vObject\000").should.is_a?(Object) + end + + it "loads an extended Object" do + obj = Object.new.extend(Meths) + + new_obj = Marshal.load("\004\be:\nMethso:\vObject\000") + + new_obj.class.should == obj.class + new_obj_metaclass_ancestors = class << new_obj; ancestors; end + new_obj_metaclass_ancestors[@num_self_class, 2].should == [Meths, Object] + end + + it "loads an object having ivar" do + s = 'hi' + arr = [:so, :so, s, s] + obj = Object.new + obj.instance_variable_set :@str, arr + + new_obj = Marshal.load("\004\bo:\vObject\006:\t@str[\t:\aso;\a\"\ahi@\a") + new_str = new_obj.instance_variable_get :@str + + new_str.should == arr + end + + it "loads an Object with a non-US-ASCII instance variable" do + ivar = "@é".dup.force_encoding(Encoding::UTF_8).to_sym + obj = Marshal.load("\x04\bo:\vObject\x06I:\b@\xC3\xA9\x06:\x06ETi\x06") + obj.instance_variables.should == [ivar] + obj.instance_variables[0].encoding.should == Encoding::UTF_8 + obj.instance_variable_get(ivar).should == 1 + end + + it "raises ArgumentError if the object from an 'o' stream is not dumpable as 'o' type user class" do + -> do + Marshal.load("\x04\bo:\tFile\001\001:\001\005@path\"\x10/etc/passwd") + end.should.raise(ArgumentError) + end + + it "raises ArgumentError when end of byte sequence reached before class name end" do + Marshal.dump(Object.new).should == "\x04\bo:\vObject\x00" + + -> { + Marshal.load("\x04\bo:\vObj") + }.should.raise(ArgumentError, "marshal data too short") + end + end + + describe "for an object responding to #marshal_dump and #marshal_load" do + it "loads a user-marshaled object" do + obj = UserMarshal.new + obj.data = :data + value = [obj, :data] + dump = Marshal.dump(value) + dump.should == "\x04\b[\aU:\x10UserMarshal:\tdata;\x06" + reloaded = Marshal.load(dump) + reloaded.should == value + end + end + + describe "for a user object" do + it "loads a user-marshaled extended object" do + obj = UserMarshal.new.extend(Meths) + + new_obj = Marshal.load("\004\bU:\020UserMarshal\"\nstuff") + + new_obj.should == obj + new_obj_metaclass_ancestors = class << new_obj; ancestors; end + new_obj_metaclass_ancestors[@num_self_class].should == UserMarshal + end + + it "loads a UserObject" do + Marshal.load("\004\bo:\017UserObject\000").should.is_a?(UserObject) + end + + describe "that extends a core type other than Object or BasicObject" do + after :each do + MarshalSpec.reset_swapped_class + end + + it "raises ArgumentError if the resulting class does not extend the same type" do + MarshalSpec.set_swapped_class(Class.new(Hash)) + data = Marshal.dump(MarshalSpec::SwappedClass.new) + + MarshalSpec.set_swapped_class(Class.new(Array)) + -> { Marshal.load(data) }.should.raise(ArgumentError) + + MarshalSpec.set_swapped_class(Class.new) + -> { Marshal.load(data) }.should.raise(ArgumentError) + end + end + end + + describe "for a Regexp" do + ruby_version_is "4.1" do + it "raises FrozenError for an extended Regexp" do + -> { + Marshal.load("\004\be:\nMethse:\016MethsMore/\n[a-z]\000") + }.should.raise(FrozenError) + end + + it "raises FrozenError when regexp has instance variables" do + -> { + Marshal.load("\x04\bI/\nhello\x00\a:\x06EF:\x11@regexp_ivar[\x06i/") + }.should.raise(FrozenError) + end + end + + ruby_version_is ""..."4.1" do + it "loads an extended Regexp" do + obj = /[a-z]/.dup.extend(Meths, MethsMore) + new_obj = Marshal.load("\004\be:\nMethse:\016MethsMore/\n[a-z]\000") + + new_obj.should == obj + new_obj_metaclass_ancestors = class << new_obj; ancestors; end + new_obj_metaclass_ancestors[@num_self_class, 3].should == + [Meths, MethsMore, Regexp] + end + + it "restore the regexp instance variables" do + obj = Regexp.new("hello") + obj.instance_variable_set(:@regexp_ivar, [42]) + + new_obj = Marshal.load("\x04\bI/\nhello\x00\a:\x06EF:\x11@regexp_ivar[\x06i/") + new_obj.instance_variables.should == [:@regexp_ivar] + new_obj.instance_variable_get(:@regexp_ivar).should == [42] + end + end + + it "loads a Regexp subclass instance variables" do + obj = UserRegexp.new('abc') + obj.instance_variable_set(:@noise, 'much') + + new_obj = Marshal.load(Marshal.dump(obj)) + + new_obj.should == obj + new_obj.instance_variable_get(:@noise).should == 'much' + new_obj_metaclass_ancestors = class << new_obj; ancestors; end + new_obj_metaclass_ancestors[@num_self_class, 2].should == + [UserRegexp, Regexp] + end + + it "loads a Regexp subclass instance variables when it is extended with a module" do + obj = UserRegexp.new('').extend(Meths) + obj.instance_variable_set(:@noise, 'much') + + new_obj = Marshal.load("\004\bIe:\nMethsC:\017UserRegexp/\000\000\006:\v@noise\"\tmuch") + + new_obj.should == obj + new_obj.instance_variable_get(:@noise).should == 'much' + new_obj_metaclass_ancestors = class << new_obj; ancestors; end + new_obj_metaclass_ancestors[@num_self_class, 3].should == + [Meths, UserRegexp, Regexp] + end + + it "preserves Regexp encoding" do + source_object = Regexp.new("a".encode("utf-32le")) + regexp = Marshal.load(Marshal.dump(source_object)) + + regexp.encoding.should == Encoding::UTF_32LE + regexp.source.should == "a".encode("utf-32le") + end + + it "raises ArgumentError when end of byte sequence reached before source string end" do + Marshal.dump(/hello world/).should == "\x04\bI/\x10hello world\x00\x06:\x06EF" + + -> { + Marshal.load("\x04\bI/\x10hel") + }.should.raise(ArgumentError, "marshal data too short") + end + end + + describe "for a Float" do + it "loads a Float NaN" do + obj = 0.0 / 0.0 + Marshal.load("\004\bf\bnan").to_s.should == obj.to_s + end + + it "loads a Float 1.3" do + Marshal.load("\004\bf\v1.3\000\314\315").should == 1.3 + end + + it "loads a Float -5.1867345e-22" do + obj = -5.1867345e-22 + Marshal.load("\004\bf\037-5.1867345000000008e-22\000\203_").should be_close(obj, 1e-30) + end + + it "loads a Float 1.1867345e+22" do + obj = 1.1867345e+22 + Marshal.load("\004\bf\0361.1867344999999999e+22\000\344@").should == obj + end + + it "raises ArgumentError when end of byte sequence reached before float string representation end" do + Marshal.dump(1.3).should == "\x04\bf\b1.3" + + -> { + Marshal.load("\004\bf\v1") + }.should.raise(ArgumentError, "marshal data too short") + end + end + + describe "for an Integer" do + it "loads 0" do + Marshal.load("\004\bi\000").should == 0 + Marshal.load("\004\bi\005").should == 0 + end + + it "loads an Integer 8" do + Marshal.load("\004\bi\r" ).should == 8 + end + + it "loads and Integer -8" do + Marshal.load("\004\bi\363" ).should == -8 + end + + it "loads an Integer 1234" do + Marshal.load("\004\bi\002\322\004").should == 1234 + end + + it "loads an Integer -1234" do + Marshal.load("\004\bi\376.\373").should == -1234 + end + + it "loads an Integer 4611686018427387903" do + Marshal.load("\004\bl+\t\377\377\377\377\377\377\377?").should == 4611686018427387903 + end + + it "loads an Integer -4611686018427387903" do + Marshal.load("\004\bl-\t\377\377\377\377\377\377\377?").should == -4611686018427387903 + end + + it "loads an Integer 2361183241434822606847" do + Marshal.load("\004\bl+\n\377\377\377\377\377\377\377\377\177\000").should == 2361183241434822606847 + end + + it "loads an Integer -2361183241434822606847" do + Marshal.load("\004\bl-\n\377\377\377\377\377\377\377\377\177\000").should == -2361183241434822606847 + end + + it "raises ArgumentError if the input is too short" do + ["\004\bi", + "\004\bi\001", + "\004\bi\002", + "\004\bi\002\0", + "\004\bi\003", + "\004\bi\003\0", + "\004\bi\003\0\0", + "\004\bi\004", + "\004\bi\004\0", + "\004\bi\004\0\0", + "\004\bi\004\0\0\0"].each do |invalid| + -> { Marshal.load(invalid) }.should.raise(ArgumentError) + end + end + + if 0.size == 8 # for platforms like x86_64 + it "roundtrips 4611686018427387903 from dump/load correctly" do + Marshal.load(Marshal.dump(4611686018427387903)).should == 4611686018427387903 + end + end + end + + describe "for a Rational" do + it "loads" do + r = Marshal.load(Marshal.dump(Rational(1, 3))) + r.should == Rational(1, 3) + r.should.frozen? + end + end + + describe "for a Complex" do + it "loads" do + c = Marshal.load(Marshal.dump(Complex(4, 3))) + c.should == Complex(4, 3) + c.should.frozen? + end + end + + describe "for a Bignum" do + platform_is c_long_size: 64 do + context "that is Bignum on 32-bit platforms but Fixnum on 64-bit" do + it "dumps a Fixnum" do + val = Marshal.load("\004\bl+\ab:wU") + val.should == 1433877090 + val.class.should == Integer + end + + it "dumps an array containing multiple references to the Bignum as an array of Fixnum" do + arr = Marshal.load("\004\b[\al+\a\223BwU@\006") + arr.should == [1433879187, 1433879187] + arr.each { |v| v.class.should == Integer } + end + end + end + end + + describe "for a Time" do + it "loads" do + Marshal.load(Marshal.dump(Time.at(1))).should == Time.at(1) + end + + it "loads serialized instance variables" do + t = Time.new + t.instance_variable_set(:@foo, 'bar') + + Marshal.load(Marshal.dump(t)).instance_variable_get(:@foo).should == 'bar' + end + + it "loads Time objects stored as links" do + t = Time.new + + t1, t2 = Marshal.load(Marshal.dump([t, t])) + t1.should.equal? t2 + end + + it "keeps the local zone" do + with_timezone 'AST', 3 do + t = Time.local(2012, 1, 1) + Marshal.load(Marshal.dump(t)).zone.should == t.zone + end + end + + it "keeps UTC zone" do + t = Time.now.utc + t2 = Marshal.load(Marshal.dump(t)) + t2.should.utc? + end + + it "keeps the zone" do + t = nil + + with_timezone 'AST', 4 do + t = Time.local(2012, 1, 1) + end + + with_timezone 'EET', -2 do + Marshal.load(Marshal.dump(t)).zone.should == 'AST' + end + end + + it "keeps utc offset" do + t = Time.new(2007,11,1,15,25,0, "+09:00") + t2 = Marshal.load(Marshal.dump(t)) + t2.utc_offset.should == 32400 + end + + it "keeps nanoseconds" do + t = Time.now + Marshal.load(Marshal.dump(t)).nsec.should == t.nsec + end + + it "does not add any additional instance variable" do + t = Time.now + t2 = Marshal.load(Marshal.dump(t)) + t2.instance_variables.should.empty? + end + end + + describe "for nil" do + it "loads" do + Marshal.load("\x04\b0").should == nil + end + end + + describe "for true" do + it "loads" do + Marshal.load("\x04\bT").should == true + end + end + + describe "for false" do + it "loads" do + Marshal.load("\x04\bF").should == false + end + end + + describe "for a Class" do + it "loads" do + Marshal.load("\x04\bc\vString").should == String + end + + it "raises ArgumentError if given the name of a non-Module" do + -> { Marshal.load("\x04\bc\vKernel") }.should.raise(ArgumentError) + end + + it "raises ArgumentError if given a nonexistent class" do + -> { Marshal.load("\x04\bc\vStrung") }.should.raise(ArgumentError) + end + + it "raises ArgumentError when end of byte sequence reached before class name end" do + Marshal.dump(String).should == "\x04\bc\vString" + + -> { + Marshal.load("\x04\bc\vStr") + }.should.raise(ArgumentError, "marshal data too short") + end + end + + describe "for a Module" do + it "loads a module" do + Marshal.load("\x04\bm\vKernel").should == Kernel + end + + it "raises ArgumentError if given the name of a non-Class" do + -> { Marshal.load("\x04\bm\vString") }.should.raise(ArgumentError) + end + + it "loads an old module" do + Marshal.load("\x04\bM\vKernel").should == Kernel + end + + it "raises ArgumentError when end of byte sequence reached before module name end" do + Marshal.dump(Kernel).should == "\x04\bm\vKernel" + + -> { + Marshal.load("\x04\bm\vKer") + }.should.raise(ArgumentError, "marshal data too short") + end + end + + describe "for a wrapped C pointer" do + it "loads" do + class DumpableDir < Dir + def _dump_data + path + end + def _load_data path + initialize(path) + end + end + + data = "\x04\bd:\x10DumpableDirI\"\x06.\x06:\x06ET" + + dir = Marshal.load(data) + begin + dir.path.should == '.' + ensure + dir.close + end + end + + it "raises TypeError when the local class is missing _load_data" do + class UnloadableDumpableDir < Dir + def _dump_data + path + end + # no _load_data + end + + data = "\x04\bd:\x1AUnloadableDumpableDirI\"\x06.\x06:\x06ET" + + -> { Marshal.load(data) }.should.raise(TypeError) + end + + it "raises ArgumentError when the local class is a regular object" do + data = "\004\bd:\020UserDefined\0" + + -> { Marshal.load(data) }.should.raise(ArgumentError) + end + end + + describe "when a class does not exist in the namespace" do + before :each do + NamespaceTest.send(:const_set, :SameName, Class.new) + @data = Marshal.dump(NamespaceTest::SameName.new) + NamespaceTest.send(:remove_const, :SameName) + end + + it "raises an ArgumentError" do + message = "undefined class/module NamespaceTest::SameName" + -> { Marshal.load(@data) }.should.raise(ArgumentError, message) + end + end + + it "raises an ArgumentError with full constant name when the dumped constant is missing" do + NamespaceTest.send(:const_set, :KaBoom, Class.new) + @data = Marshal.dump(NamespaceTest::KaBoom.new) + NamespaceTest.send(:remove_const, :KaBoom) + + -> { Marshal.load(@data) }.should.raise(ArgumentError, /NamespaceTest::KaBoom/) + end end diff --git a/spec/ruby/core/marshal/restore_spec.rb b/spec/ruby/core/marshal/restore_spec.rb index 7e75d7dea6..3135f881d4 100644 --- a/spec/ruby/core/marshal/restore_spec.rb +++ b/spec/ruby/core/marshal/restore_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/load' describe "Marshal.restore" do - it_behaves_like :marshal_load, :restore + it "is an alias of Marshal.load" do + Marshal.method(:restore).should == Marshal.method(:load) + end end diff --git a/spec/ruby/core/marshal/shared/load.rb b/spec/ruby/core/marshal/shared/load.rb deleted file mode 100644 index 02c8e7f0b1..0000000000 --- a/spec/ruby/core/marshal/shared/load.rb +++ /dev/null @@ -1,1291 +0,0 @@ -# encoding: binary -require_relative '../fixtures/marshal_data' - -describe :marshal_load, shared: true do - before :all do - @num_self_class = 1 - end - - it "raises an ArgumentError when the dumped data is truncated" do - obj = {first: 1, second: 2, third: 3} - -> { Marshal.send(@method, Marshal.dump(obj)[0, 5]) }.should.raise(ArgumentError, "marshal data too short") - end - - it "raises an ArgumentError when the argument is empty String" do - -> { Marshal.send(@method, "") }.should.raise(ArgumentError, "marshal data too short") - end - - it "raises an ArgumentError when the dumped class is missing" do - Object.send(:const_set, :KaBoom, Class.new) - kaboom = Marshal.dump(KaBoom.new) - Object.send(:remove_const, :KaBoom) - - -> { Marshal.send(@method, kaboom) }.should.raise(ArgumentError) - end - - describe "when called with freeze: true" do - it "returns frozen strings" do - string = Marshal.send(@method, Marshal.dump("foo"), freeze: true) - string.should == "foo" - string.should.frozen? - - utf8_string = "foo".encode(Encoding::UTF_8) - string = Marshal.send(@method, Marshal.dump(utf8_string), freeze: true) - string.should == utf8_string - string.should.frozen? - end - - it "returns frozen arrays" do - array = Marshal.send(@method, Marshal.dump([1, 2, 3]), freeze: true) - array.should == [1, 2, 3] - array.should.frozen? - end - - it "returns frozen hashes" do - hash = Marshal.send(@method, Marshal.dump({foo: 42}), freeze: true) - hash.should == {foo: 42} - hash.should.frozen? - end - - it "returns frozen regexps" do - regexp = Marshal.send(@method, Marshal.dump(/foo/), freeze: true) - regexp.should == /foo/ - regexp.should.frozen? - end - - it "returns frozen structs" do - struct = Marshal.send(@method, Marshal.dump(MarshalSpec::StructToDump.new(1, 2)), freeze: true) - struct.should == MarshalSpec::StructToDump.new(1, 2) - struct.should.frozen? - end - - it "returns frozen objects" do - source_object = Object.new - - object = Marshal.send(@method, Marshal.dump(source_object), freeze: true) - object.should.frozen? - end - - describe "deep freezing" do - it "returns hashes with frozen keys and values" do - key = Object.new - value = Object.new - source_object = {key => value} - - hash = Marshal.send(@method, Marshal.dump(source_object), freeze: true) - hash.size.should == 1 - hash.keys[0].should.frozen? - hash.values[0].should.frozen? - end - - it "returns arrays with frozen elements" do - object = Object.new - source_object = [object] - - array = Marshal.send(@method, Marshal.dump(source_object), freeze: true) - array.size.should == 1 - array[0].should.frozen? - end - - it "returns structs with frozen members" do - object1 = Object.new - object2 = Object.new - source_object = MarshalSpec::StructToDump.new(object1, object2) - - struct = Marshal.send(@method, Marshal.dump(source_object), freeze: true) - struct.a.should.frozen? - struct.b.should.frozen? - end - - it "returns objects with frozen instance variables" do - source_object = Object.new - instance_variable = Object.new - source_object.instance_variable_set(:@a, instance_variable) - - object = Marshal.send(@method, Marshal.dump(source_object), freeze: true) - object.instance_variable_get(:@a).should != nil - object.instance_variable_get(:@a).should.frozen? - end - - it "deduplicates frozen strings" do - source_object = ["foo" + "bar", "foobar"] - object = Marshal.send(@method, Marshal.dump(source_object), freeze: true) - - object[0].should.equal?(object[1]) - end - end - - it "does not freeze modules" do - object = Marshal.send(@method, Marshal.dump(Kernel), freeze: true) - object.should_not.frozen? - Kernel.should_not.frozen? - end - - it "does not freeze classes" do - object = Marshal.send(@method, Marshal.dump(Object), freeze: true) - object.should_not.frozen? - Object.should_not.frozen? - end - - it "does freeze extended objects" do - object = Marshal.load("\x04\be:\x0FEnumerableo:\vObject\x00", freeze: true) - object.should.frozen? - end - - it "does freeze extended objects with instance variables" do - object = Marshal.load("\x04\be:\x0FEnumerableo:\vObject\x06:\n@ivarT", freeze: true) - object.should.frozen? - end - - it "returns frozen object having #_dump method" do - object = Marshal.send(@method, Marshal.dump(UserDefined.new), freeze: true) - object.should.frozen? - end - - it "returns frozen object responding to #marshal_dump and #marshal_load" do - object = Marshal.send(@method, Marshal.dump(UserMarshal.new), freeze: true) - object.should.frozen? - end - - it "returns frozen object extended by a module" do - object = Object.new - object.extend(MarshalSpec::ModuleToExtendBy) - - object = Marshal.send(@method, Marshal.dump(object), freeze: true) - object.should.frozen? - end - - it "does not call freeze method" do - object = MarshalSpec::ObjectWithFreezeRaisingException.new - object = Marshal.send(@method, Marshal.dump(object), freeze: true) - object.should.frozen? - end - - it "returns frozen object even if object does not respond to freeze method" do - object = MarshalSpec::ObjectWithoutFreeze.new - object = Marshal.send(@method, Marshal.dump(object), freeze: true) - object.should.frozen? - end - - it "returns a frozen object when is an instance of String/Array/Regexp/Hash subclass and has instance variables" do - source_object = UserString.new - source_object.instance_variable_set(:@foo, "bar") - - object = Marshal.send(@method, Marshal.dump(source_object), freeze: true) - object.should.frozen? - end - - describe "when called with a proc" do - it "call the proc with frozen objects" do - arr = [] - s = +'hi' - s.instance_variable_set(:@foo, 5) - st = Struct.new("Brittle", :a).new - st.instance_variable_set(:@clue, 'none') - st.a = 0.0 - h = Hash.new('def') - h['nine'] = 9 - a = [:a, :b, :c] - a.instance_variable_set(:@two, 2) - obj = [s, 10, s, s, st, a] - obj.instance_variable_set(:@zoo, 'ant') - proc = Proc.new { |o| arr << o; o} - - Marshal.send( - @method, - "\x04\bI[\vI\"\ahi\a:\x06EF:\t@fooi\ni\x0F@\x06@\x06IS:\x14Struct::Brittle\x06:\x06af\x060\x06:\n@clueI\"\tnone\x06;\x00FI[\b;\b:\x06b:\x06c\x06:\t@twoi\a\x06:\t@zooI\"\bant\x06;\x00F", - proc, - freeze: true, - ) - - arr.should == [ - false, 5, "hi", 10, "hi", "hi", 0.0, false, "none", st, - :b, :c, 2, a, false, "ant", ["hi", 10, "hi", "hi", st, [:a, :b, :c]], - ] - - arr.each do |v| - v.should.frozen? - end - - Struct.send(:remove_const, :Brittle) - end - - it "does not freeze the object returned by the proc" do - string = Marshal.send(@method, Marshal.dump("foo"), proc { |o| o.upcase }, freeze: true) - string.should == "FOO" - string.should_not.frozen? - end - end - end - - describe "when called with a proc" do - it "call the proc with fully initialized strings" do - utf8_string = "foo".encode(Encoding::UTF_8) - Marshal.send(@method, Marshal.dump(utf8_string), proc { |arg| - if arg.is_a?(String) - arg.should == utf8_string - arg.encoding.should == Encoding::UTF_8 - end - arg - }) - end - - it "no longer mutate the object after it was passed to the proc" do - string = Marshal.load(Marshal.dump("foo"), :freeze.to_proc) - string.should.frozen? - end - - it "call the proc with extended objects" do - objs = [] - obj = Marshal.load("\x04\be:\x0FEnumerableo:\vObject\x00", Proc.new { |o| objs << o; o }) - objs.should == [obj] - end - - it "returns the value of the proc" do - Marshal.send(@method, Marshal.dump([1,2]), proc { [3,4] }).should == [3,4] - end - - it "calls the proc for recursively visited data" do - a = [1] - a << a - ret = [] - Marshal.send(@method, Marshal.dump(a), proc { |arg| ret << arg.inspect; arg }) - ret[0].should == 1.inspect - ret[1].should == a.inspect - ret.size.should == 2 - end - - it "loads an Array with proc" do - arr = [] - s = +'hi' - s.instance_variable_set(:@foo, 5) - st = Struct.new("Brittle", :a).new - st.instance_variable_set(:@clue, 'none') - st.a = 0.0 - h = Hash.new('def') - h['nine'] = 9 - a = [:a, :b, :c] - a.instance_variable_set(:@two, 2) - obj = [s, 10, s, s, st, a] - obj.instance_variable_set(:@zoo, 'ant') - proc = Proc.new { |o| arr << o.dup; o} - - Marshal.send(@method, "\x04\bI[\vI\"\ahi\a:\x06EF:\t@fooi\ni\x0F@\x06@\x06IS:\x14Struct::Brittle\x06:\x06af\x060\x06:\n@clueI\"\tnone\x06;\x00FI[\b;\b:\x06b:\x06c\x06:\t@twoi\a\x06:\t@zooI\"\bant\x06;\x00F", proc) - - arr.should == [ - false, 5, "hi", 10, "hi", "hi", 0.0, false, "none", st, - :b, :c, 2, a, false, "ant", ["hi", 10, "hi", "hi", st, [:a, :b, :c]], - ] - Struct.send(:remove_const, :Brittle) - end - end - - describe "when called with nil for the proc argument" do - it "behaves as if no proc argument was passed" do - a = [1] - a << a - b = Marshal.send(@method, Marshal.dump(a), nil) - b.should == a - end - end - - describe "when called on objects with custom _dump methods" do - it "does not set instance variables of an object with user-defined _dump/_load" do - # this string represents: <#UserPreviouslyDefinedWithInitializedIvar @field2=7 @field1=6> - dump_str = "\004\bu:-UserPreviouslyDefinedWithInitializedIvar\a:\f@field2i\f:\f@field1i\v" - - UserPreviouslyDefinedWithInitializedIvar.should_receive(:_load).and_return(UserPreviouslyDefinedWithInitializedIvar.new) - marshaled_obj = Marshal.send(@method, dump_str) - - marshaled_obj.should.instance_of?(UserPreviouslyDefinedWithInitializedIvar) - marshaled_obj.field1.should == nil - marshaled_obj.field2.should == nil - end - - it "loads the String in non US-ASCII and non UTF-8 encoding" do - source_object = UserDefinedString.new("a".encode("windows-1251")) - object = Marshal.send(@method, Marshal.dump(source_object)) - object.string.should == "a".encode("windows-1251") - end - - it "loads the String in multibyte encoding" do - source_object = UserDefinedString.new("a".encode("utf-32le")) - object = Marshal.send(@method, Marshal.dump(source_object)) - object.string.should == "a".encode("utf-32le") - end - - describe "that returns an immediate value" do - it "loads an array containing an instance of the object, followed by multiple instances of another object" do - str = "string" - - # this string represents: [<#UserDefinedImmediate A>, <#String "string">, <#String "string">] - marshaled_obj = Marshal.send(@method, "\004\b[\bu:\031UserDefinedImmediate\000\"\vstring@\a") - - marshaled_obj.should == [nil, str, str] - end - - it "loads any structure with multiple references to the same object, followed by multiple instances of another object" do - str = "string" - - # this string represents: {a: <#UserDefinedImmediate A>, b: <#UserDefinedImmediate A>, c: <#String "string">, d: <#String "string">} - hash_dump = "\x04\b{\t:\x06aIu:\x19UserDefinedImmediate\x00\x06:\x06ET:\x06b@\x06:\x06cI\"\vstring\x06;\aT:\x06d@\a" - - marshaled_obj = Marshal.send(@method, hash_dump) - marshaled_obj.should == {a: nil, b: nil, c: str, d: str} - - # this string represents: [<#UserDefinedImmediate A>, <#UserDefinedImmediate A>, <#String "string">, <#String "string">] - array_dump = "\x04\b[\tIu:\x19UserDefinedImmediate\x00\x06:\x06ET@\x06I\"\vstring\x06;\x06T@\a" - - marshaled_obj = Marshal.send(@method, array_dump) - marshaled_obj.should == [nil, nil, str, str] - end - - it "loads an array containing references to multiple instances of the object, followed by multiple instances of another object" do - str = "string" - - # this string represents: [<#UserDefinedImmediate A>, <#UserDefinedImmediate B>, <#String "string">, <#String "string">] - array_dump = "\x04\b[\tIu:\x19UserDefinedImmediate\x00\x06:\x06ETIu;\x00\x00\x06;\x06TI\"\vstring\x06;\x06T@\b" - - marshaled_obj = Marshal.send(@method, array_dump) - marshaled_obj.should == [nil, nil, str, str] - end - end - end - - it "loads an array containing objects having _dump method, and with proc" do - arr = [] - myproc = Proc.new { |o| arr << o.dup; o } - o1 = UserDefined.new; - o2 = UserDefinedWithIvar.new - obj = [o1, o2, o1, o2] - - Marshal.send(@method, "\x04\b[\tu:\x10UserDefined\x18\x04\b[\aI\"\nstuff\x06:\x06EF@\x06u:\x18UserDefinedWithIvar>\x04\b[\bI\"\nstuff\a:\x06EF:\t@foo:\x18UserDefinedWithIvarI\"\tmore\x06;\x00F@\a@\x06@\a", myproc) - - arr[0].should == o1 - arr[1].should == o2 - arr[2].should == obj - arr.size.should == 3 - end - - it "loads an array containing objects having marshal_dump method, and with proc" do - arr = [] - proc = Proc.new { |o| arr << o.dup; o } - o1 = UserMarshal.new - o2 = UserMarshalWithIvar.new - - Marshal.send(@method, "\004\b[\tU:\020UserMarshal\"\nstuffU:\030UserMarshalWithIvar[\006\"\fmy data@\006@\b", proc) - - arr[0].should == 'stuff' - arr[1].should == o1 - arr[2].should == 'my data' - arr[3].should == ['my data'] - arr[4].should == o2 - arr[5].should == [o1, o2, o1, o2] - - arr.size.should == 6 - end - - it "assigns classes to nested subclasses of Array correctly" do - arr = ArraySub.new(ArraySub.new) - arr_dump = Marshal.dump(arr) - Marshal.send(@method, arr_dump).class.should == ArraySub - end - - it "loads subclasses of Array with overridden << and push correctly" do - arr = ArraySubPush.new - arr[0] = '1' - arr_dump = Marshal.dump(arr) - Marshal.send(@method, arr_dump).should == arr - end - - it "raises a TypeError with bad Marshal version" do - marshal_data = +'\xff\xff' - marshal_data[0] = (Marshal::MAJOR_VERSION).chr - marshal_data[1] = (Marshal::MINOR_VERSION + 1).chr - - -> { Marshal.send(@method, marshal_data) }.should.raise(TypeError) - - marshal_data = +'\xff\xff' - marshal_data[0] = (Marshal::MAJOR_VERSION - 1).chr - marshal_data[1] = (Marshal::MINOR_VERSION).chr - - -> { Marshal.send(@method, marshal_data) }.should.raise(TypeError) - end - - it "raises EOFError on loading an empty file" do - temp_file = tmp("marshal.rubyspec.tmp.#{Process.pid}") - file = File.new(temp_file, "w+") - begin - -> { Marshal.send(@method, file) }.should.raise(EOFError) - ensure - file.close - rm_r temp_file - end - end - - # Note: Ruby 1.9 should be compatible with older marshal format - MarshalSpec::DATA.each do |description, (object, marshal, attributes)| - it "loads a #{description}" do - Marshal.send(@method, marshal).should == object - end - end - - MarshalSpec::DATA_19.each do |description, (object, marshal, attributes)| - it "loads a #{description}" do - Marshal.send(@method, marshal).should == object - end - end - - describe "for an Array" do - it "loads an array containing the same objects" do - s = 'oh' - b = 'hi' - r = // - d = [b, :no, s, :go] - c = String - f = 1.0 - - o1 = UserMarshalWithIvar.new; o2 = UserMarshal.new - - obj = [:so, 'hello', 100, :so, :so, d, :so, o2, :so, :no, o2, - :go, c, nil, Struct::Pyramid.new, f, :go, :no, s, b, r, - :so, 'huh', o1, true, b, b, 99, r, b, s, :so, f, c, :no, o1, d] - - Marshal.send(@method, "\004\b[*:\aso\"\nhelloii;\000;\000[\t\"\ahi:\ano\"\aoh:\ago;\000U:\020UserMarshal\"\nstuff;\000;\006@\n;\ac\vString0S:\024Struct::Pyramid\000f\0061;\a;\006@\t@\b/\000\000;\000\"\bhuhU:\030UserMarshalWithIvar[\006\"\fmy dataT@\b@\bih@\017@\b@\t;\000@\016@\f;\006@\021@\a").should == - obj - end - - it "loads an array having ivar" do - s = +'well' - s.instance_variable_set(:@foo, 10) - obj = ['5', s, 'hi'].extend(Meths, MethsMore) - obj.instance_variable_set(:@mix, s) - new_obj = Marshal.send(@method, "\004\bI[\b\"\0065I\"\twell\006:\t@fooi\017\"\ahi\006:\t@mix@\a") - new_obj.should == obj - new_obj.instance_variable_get(:@mix).should.equal? new_obj[1] - new_obj[1].instance_variable_get(:@foo).should == 10 - end - - it "loads an extended Array object containing a user-marshaled object" do - obj = [UserMarshal.new, UserMarshal.new].extend(Meths) - dump = "\x04\be:\nMeths[\ao:\x10UserMarshal\x06:\n@dataI\"\nstuff\x06:\x06ETo;\x06\x06;\aI\"\nstuff\x06;\bT" - new_obj = Marshal.send(@method, dump) - - new_obj.should == obj - obj_ancestors = class << obj; ancestors[1..-1]; end - new_obj_ancestors = class << new_obj; ancestors[1..-1]; end - obj_ancestors.should == new_obj_ancestors - end - end - - describe "for a Hash" do - it "loads an extended_user_hash with a parameter to initialize" do - obj = UserHashInitParams.new(:abc).extend(Meths) - - new_obj = Marshal.send(@method, "\004\bIe:\nMethsC:\027UserHashInitParams{\000\006:\a@a:\babc") - - new_obj.should == obj - new_obj_metaclass_ancestors = class << new_obj; ancestors; end - new_obj_metaclass_ancestors[@num_self_class].should == Meths - new_obj_metaclass_ancestors[@num_self_class+1].should == UserHashInitParams - end - - it "loads an extended hash object containing a user-marshaled object" do - obj = {a: UserMarshal.new}.extend(Meths) - - new_obj = Marshal.send(@method, "\004\be:\nMeths{\006:\006aU:\020UserMarshal\"\nstuff") - - new_obj.should == obj - new_obj_metaclass_ancestors = class << new_obj; ancestors; end - new_obj_metaclass_ancestors[@num_self_class].should == Meths - new_obj_metaclass_ancestors[@num_self_class+1].should == Hash - end - - it "preserves hash ivars when hash contains a string having ivar" do - s = +'string' - s.instance_variable_set :@string_ivar, 'string ivar' - h = { key: s } - h.instance_variable_set :@hash_ivar, 'hash ivar' - - unmarshalled = Marshal.send(@method, Marshal.dump(h)) - unmarshalled.instance_variable_get(:@hash_ivar).should == 'hash ivar' - unmarshalled[:key].instance_variable_get(:@string_ivar).should == 'string ivar' - end - - it "preserves compare_by_identity behaviour" do - h = { a: 1 } - h.compare_by_identity - unmarshalled = Marshal.send(@method, Marshal.dump(h)) - unmarshalled.should.compare_by_identity? - - h = { a: 1 } - unmarshalled = Marshal.send(@method, Marshal.dump(h)) - unmarshalled.should_not.compare_by_identity? - end - - it "preserves compare_by_identity behaviour for a Hash subclass" do - h = UserHash.new({ a: 1 }) - h.compare_by_identity - unmarshalled = Marshal.send(@method, Marshal.dump(h)) - unmarshalled.should.compare_by_identity? - - h = UserHash.new({ a: 1 }) - unmarshalled = Marshal.send(@method, Marshal.dump(h)) - unmarshalled.should_not.compare_by_identity? - end - - it "allocates an instance of the proper class when Hash subclass with compare_by_identity behaviour" do - h = UserHash.new({ a: 1 }) - h.compare_by_identity - - unmarshalled = Marshal.send(@method, Marshal.dump(h)) - unmarshalled.should.kind_of?(UserHash) - end - end - - describe "for a Symbol" do - it "loads a Symbol" do - sym = Marshal.send(@method, "\004\b:\vsymbol") - sym.should == :symbol - sym.encoding.should == Encoding::US_ASCII - end - - it "loads a big Symbol" do - sym = ('big' * 100).to_sym - Marshal.send(@method, "\004\b:\002,\001#{'big' * 100}").should == sym - end - - it "loads an encoded Symbol" do - s = "\u2192" - - sym = Marshal.send(@method, "\x04\bI:\b\xE2\x86\x92\x06:\x06ET") - sym.should == s.encode("utf-8").to_sym - sym.encoding.should == Encoding::UTF_8 - - sym = Marshal.send(@method, "\x04\bI:\t\xFE\xFF!\x92\x06:\rencoding\"\vUTF-16") - sym.should == s.encode("utf-16").to_sym - sym.encoding.should == Encoding::UTF_16 - - sym = Marshal.send(@method, "\x04\bI:\a\x92!\x06:\rencoding\"\rUTF-16LE") - sym.should == s.encode("utf-16le").to_sym - sym.encoding.should == Encoding::UTF_16LE - - sym = Marshal.send(@method, "\x04\bI:\a!\x92\x06:\rencoding\"\rUTF-16BE") - sym.should == s.encode("utf-16be").to_sym - sym.encoding.should == Encoding::UTF_16BE - - sym = Marshal.send(@method, "\x04\bI:\a\xA2\xAA\x06:\rencoding\"\vEUC-JP") - sym.should == s.encode("euc-jp").to_sym - sym.encoding.should == Encoding::EUC_JP - - sym = Marshal.send(@method, "\x04\bI:\a\x81\xA8\x06:\rencoding\"\x10Windows-31J") - sym.should == s.encode("sjis").to_sym - sym.encoding.should == Encoding::SJIS - end - - it "loads a binary encoded Symbol" do - s = "\u2192".dup.force_encoding("binary").to_sym - sym = Marshal.send(@method, "\x04\b:\b\xE2\x86\x92") - sym.should == s - sym.encoding.should == Encoding::BINARY - end - - it "loads multiple Symbols sharing the same encoding" do - # Note that the encoding is a link for the second Symbol - symbol1 = "I:\t\xE2\x82\xACa\x06:\x06ET" - symbol2 = "I:\t\xE2\x82\xACb\x06;\x06T" - dump = "\x04\b[\a#{symbol1}#{symbol2}" - value = Marshal.send(@method, dump) - value.map(&:encoding).should == [Encoding::UTF_8, Encoding::UTF_8] - expected = [ - "€a".dup.force_encoding(Encoding::UTF_8).to_sym, - "€b".dup.force_encoding(Encoding::UTF_8).to_sym - ] - value.should == expected - - value = Marshal.send(@method, "\x04\b[\b#{symbol1}#{symbol2};\x00") - value.map(&:encoding).should == [Encoding::UTF_8, Encoding::UTF_8, Encoding::UTF_8] - value.should == [*expected, expected[0]] - end - - it "raises ArgumentError when end of byte sequence reached before symbol characters end" do - Marshal.dump(:hello).should == "\x04\b:\nhello" - - -> { - Marshal.send(@method, "\x04\b:\nhel") - }.should.raise(ArgumentError, "marshal data too short") - end - end - - describe "for a String" do - it "loads a string having ivar with ref to self" do - obj = +'hi' - obj.instance_variable_set(:@self, obj) - Marshal.send(@method, "\004\bI\"\ahi\006:\n@self@\000").should == obj - end - - it "loads a string through StringIO stream" do - require 'stringio' - obj = "This is a string which should be unmarshalled through StringIO stream!" - Marshal.send(@method, StringIO.new(Marshal.dump(obj))).should == obj - end - - it "sets binmode if it is loading through StringIO stream" do - io = StringIO.new("\004\b:\vsymbol") - def io.binmode; raise "binmode"; end - -> { Marshal.load(io) }.should.raise(RuntimeError, "binmode") - end - - it "loads a string with an ivar" do - str = Marshal.send(@method, "\x04\bI\"\x00\x06:\t@fooI\"\bbar\x06:\x06EF") - str.instance_variable_get("@foo").should == "bar" - end - - it "loads a String subclass with custom constructor" do - str = Marshal.send(@method, "\x04\bC: UserCustomConstructorString\"\x00") - str.should.instance_of?(UserCustomConstructorString) - end - - it "loads a US-ASCII String" do - str = "abc".dup.force_encoding("us-ascii") - data = "\x04\bI\"\babc\x06:\x06EF" - result = Marshal.send(@method, data) - result.should == str - result.encoding.should.equal?(Encoding::US_ASCII) - end - - it "loads a UTF-8 String" do - str = "\x6d\xc3\xb6\x68\x72\x65".dup.force_encoding("utf-8") - data = "\x04\bI\"\vm\xC3\xB6hre\x06:\x06ET" - result = Marshal.send(@method, data) - result.should == str - result.encoding.should.equal?(Encoding::UTF_8) - end - - it "loads a String in another encoding" do - str = "\x6d\x00\xf6\x00\x68\x00\x72\x00\x65\x00".dup.force_encoding("utf-16le") - data = "\x04\bI\"\x0Fm\x00\xF6\x00h\x00r\x00e\x00\x06:\rencoding\"\rUTF-16LE" - result = Marshal.send(@method, data) - result.should == str - result.encoding.should.equal?(Encoding::UTF_16LE) - end - - it "loads a String as BINARY if no encoding is specified at the end" do - str = "\xC3\xB8".dup.force_encoding("BINARY") - data = "\x04\b\"\a\xC3\xB8".dup.force_encoding("UTF-8") - result = Marshal.send(@method, data) - result.encoding.should == Encoding::BINARY - result.should == str - end - - it "raises ArgumentError when end of byte sequence reached before string characters end" do - Marshal.dump("hello").should == "\x04\b\"\nhello" - - -> { - Marshal.send(@method, "\x04\b\"\nhel") - }.should.raise(ArgumentError, "marshal data too short") - end - end - - describe "for a Struct" do - it "loads a extended_struct having fields with same objects" do - s = 'hi' - obj = Struct.new("Extended", :a, :b).new.extend(Meths) - dump = "\004\be:\nMethsS:\025Struct::Extended\a:\006a0:\006b0" - Marshal.send(@method, dump).should == obj - - obj.a = [:a, s] - obj.b = [:Meths, s] - dump = "\004\be:\nMethsS:\025Struct::Extended\a:\006a[\a;\a\"\ahi:\006b[\a;\000@\a" - Marshal.send(@method, dump).should == obj - Struct.send(:remove_const, :Extended) - end - - it "loads a struct having ivar" do - obj = Struct.new("Thick").new - obj.instance_variable_set(:@foo, 5) - reloaded = Marshal.send(@method, "\004\bIS:\022Struct::Thick\000\006:\t@fooi\n") - reloaded.should == obj - reloaded.instance_variable_get(:@foo).should == 5 - Struct.send(:remove_const, :Thick) - end - - it "loads a struct having fields" do - obj = Struct.new("Ure1", :a, :b).new - Marshal.send(@method, "\004\bS:\021Struct::Ure1\a:\006a0:\006b0").should == obj - Struct.send(:remove_const, :Ure1) - end - - it "does not call initialize on the unmarshaled struct" do - threadlocal_key = MarshalSpec::StructWithUserInitialize::THREADLOCAL_KEY - - s = MarshalSpec::StructWithUserInitialize.new('foo') - Thread.current[threadlocal_key].should == ['foo'] - s.a.should == 'foo' - - Thread.current[threadlocal_key] = nil - - dumped = Marshal.dump(s) - loaded = Marshal.send(@method, dumped) - - Thread.current[threadlocal_key].should == nil - loaded.a.should == 'foo' - end - end - - describe "for a Data" do - it "loads a Data" do - obj = MarshalSpec::DataSpec::Measure.new(100, 'km') - dumped = "\x04\bS:#MarshalSpec::DataSpec::Measure\a:\vamountii:\tunit\"\akm" - Marshal.dump(obj).should == dumped - - Marshal.send(@method, dumped).should == obj - end - - it "loads an extended Data" do - obj = MarshalSpec::DataSpec::MeasureExtended.new(100, "km") - dumped = "\x04\bS:+MarshalSpec::DataSpec::MeasureExtended\a:\vamountii:\tunit\"\akm" - Marshal.dump(obj).should == dumped - - Marshal.send(@method, dumped).should == obj - end - - it "returns a frozen object" do - obj = MarshalSpec::DataSpec::Measure.new(100, 'km') - dumped = "\x04\bS:#MarshalSpec::DataSpec::Measure\a:\vamountii:\tunit\"\akm" - Marshal.dump(obj).should == dumped - - Marshal.send(@method, dumped).should.frozen? - end - end - - describe "for an Exception" do - it "loads a marshalled exception with no message" do - obj = Exception.new - loaded = Marshal.send(@method, "\004\bo:\016Exception\a:\abt0:\tmesg0") - loaded.message.should == obj.message - loaded.backtrace.should == obj.backtrace - loaded = Marshal.send(@method, "\x04\bo:\x0EException\a:\tmesg0:\abt0") - loaded.message.should == obj.message - loaded.backtrace.should == obj.backtrace - end - - it "loads a marshalled exception with a message" do - obj = Exception.new("foo") - loaded = Marshal.send(@method, "\004\bo:\016Exception\a:\abt0:\tmesg\"\bfoo") - loaded.message.should == obj.message - loaded.backtrace.should == obj.backtrace - loaded = Marshal.send(@method, "\x04\bo:\x0EException\a:\tmesgI\"\bfoo\x06:\x06EF:\abt0") - loaded.message.should == obj.message - loaded.backtrace.should == obj.backtrace - end - - it "loads a marshalled exception with a backtrace" do - obj = Exception.new("foo") - obj.set_backtrace(["foo/bar.rb:10"]) - loaded = Marshal.send(@method, "\004\bo:\016Exception\a:\abt[\006\"\022foo/bar.rb:10:\tmesg\"\bfoo") - loaded.message.should == obj.message - loaded.backtrace.should == obj.backtrace - loaded = Marshal.send(@method, "\x04\bo:\x0EException\a:\tmesgI\"\bfoo\x06:\x06EF:\abt[\x06I\"\x12foo/bar.rb:10\x06;\aF") - loaded.message.should == obj.message - loaded.backtrace.should == obj.backtrace - end - - it "loads an marshalled exception with ivars" do - s = 'hi' - arr = [:so, :so, s, s] - obj = Exception.new("foo") - obj.instance_variable_set :@arr, arr - - loaded = Marshal.send(@method, "\x04\bo:\x0EException\b:\tmesg\"\bfoo:\abt0:\t@arr[\t:\aso;\t\"\ahi@\b") - new_arr = loaded.instance_variable_get :@arr - - loaded.message.should == obj.message - new_arr.should == arr - end - end - - describe "for an Object" do - it "loads an object" do - Marshal.send(@method, "\004\bo:\vObject\000").should.is_a?(Object) - end - - it "loads an extended Object" do - obj = Object.new.extend(Meths) - - new_obj = Marshal.send(@method, "\004\be:\nMethso:\vObject\000") - - new_obj.class.should == obj.class - new_obj_metaclass_ancestors = class << new_obj; ancestors; end - new_obj_metaclass_ancestors[@num_self_class, 2].should == [Meths, Object] - end - - it "loads an object having ivar" do - s = 'hi' - arr = [:so, :so, s, s] - obj = Object.new - obj.instance_variable_set :@str, arr - - new_obj = Marshal.send(@method, "\004\bo:\vObject\006:\t@str[\t:\aso;\a\"\ahi@\a") - new_str = new_obj.instance_variable_get :@str - - new_str.should == arr - end - - it "loads an Object with a non-US-ASCII instance variable" do - ivar = "@é".dup.force_encoding(Encoding::UTF_8).to_sym - obj = Marshal.send(@method, "\x04\bo:\vObject\x06I:\b@\xC3\xA9\x06:\x06ETi\x06") - obj.instance_variables.should == [ivar] - obj.instance_variables[0].encoding.should == Encoding::UTF_8 - obj.instance_variable_get(ivar).should == 1 - end - - it "raises ArgumentError if the object from an 'o' stream is not dumpable as 'o' type user class" do - -> do - Marshal.send(@method, "\x04\bo:\tFile\001\001:\001\005@path\"\x10/etc/passwd") - end.should.raise(ArgumentError) - end - - it "raises ArgumentError when end of byte sequence reached before class name end" do - Marshal.dump(Object.new).should == "\x04\bo:\vObject\x00" - - -> { - Marshal.send(@method, "\x04\bo:\vObj") - }.should.raise(ArgumentError, "marshal data too short") - end - end - - describe "for an object responding to #marshal_dump and #marshal_load" do - it "loads a user-marshaled object" do - obj = UserMarshal.new - obj.data = :data - value = [obj, :data] - dump = Marshal.dump(value) - dump.should == "\x04\b[\aU:\x10UserMarshal:\tdata;\x06" - reloaded = Marshal.load(dump) - reloaded.should == value - end - end - - describe "for a user object" do - it "loads a user-marshaled extended object" do - obj = UserMarshal.new.extend(Meths) - - new_obj = Marshal.send(@method, "\004\bU:\020UserMarshal\"\nstuff") - - new_obj.should == obj - new_obj_metaclass_ancestors = class << new_obj; ancestors; end - new_obj_metaclass_ancestors[@num_self_class].should == UserMarshal - end - - it "loads a UserObject" do - Marshal.send(@method, "\004\bo:\017UserObject\000").should.is_a?(UserObject) - end - - describe "that extends a core type other than Object or BasicObject" do - after :each do - MarshalSpec.reset_swapped_class - end - - it "raises ArgumentError if the resulting class does not extend the same type" do - MarshalSpec.set_swapped_class(Class.new(Hash)) - data = Marshal.dump(MarshalSpec::SwappedClass.new) - - MarshalSpec.set_swapped_class(Class.new(Array)) - -> { Marshal.send(@method, data) }.should.raise(ArgumentError) - - MarshalSpec.set_swapped_class(Class.new) - -> { Marshal.send(@method, data) }.should.raise(ArgumentError) - end - end - end - - describe "for a Regexp" do - ruby_version_is "4.1" do - it "raises FrozenError for an extended Regexp" do - -> { - Marshal.send(@method, "\004\be:\nMethse:\016MethsMore/\n[a-z]\000") - }.should.raise(FrozenError) - end - - it "raises FrozenError when regexp has instance variables" do - -> { - Marshal.send(@method, "\x04\bI/\nhello\x00\a:\x06EF:\x11@regexp_ivar[\x06i/") - }.should.raise(FrozenError) - end - end - - ruby_version_is ""..."4.1" do - it "loads an extended Regexp" do - obj = /[a-z]/.dup.extend(Meths, MethsMore) - new_obj = Marshal.send(@method, "\004\be:\nMethse:\016MethsMore/\n[a-z]\000") - - new_obj.should == obj - new_obj_metaclass_ancestors = class << new_obj; ancestors; end - new_obj_metaclass_ancestors[@num_self_class, 3].should == - [Meths, MethsMore, Regexp] - end - - it "restore the regexp instance variables" do - obj = Regexp.new("hello") - obj.instance_variable_set(:@regexp_ivar, [42]) - - new_obj = Marshal.send(@method, "\x04\bI/\nhello\x00\a:\x06EF:\x11@regexp_ivar[\x06i/") - new_obj.instance_variables.should == [:@regexp_ivar] - new_obj.instance_variable_get(:@regexp_ivar).should == [42] - end - end - - it "loads a Regexp subclass instance variables" do - obj = UserRegexp.new('abc') - obj.instance_variable_set(:@noise, 'much') - - new_obj = Marshal.send(@method, Marshal.dump(obj)) - - new_obj.should == obj - new_obj.instance_variable_get(:@noise).should == 'much' - new_obj_metaclass_ancestors = class << new_obj; ancestors; end - new_obj_metaclass_ancestors[@num_self_class, 2].should == - [UserRegexp, Regexp] - end - - it "loads a Regexp subclass instance variables when it is extended with a module" do - obj = UserRegexp.new('').extend(Meths) - obj.instance_variable_set(:@noise, 'much') - - new_obj = Marshal.send(@method, "\004\bIe:\nMethsC:\017UserRegexp/\000\000\006:\v@noise\"\tmuch") - - new_obj.should == obj - new_obj.instance_variable_get(:@noise).should == 'much' - new_obj_metaclass_ancestors = class << new_obj; ancestors; end - new_obj_metaclass_ancestors[@num_self_class, 3].should == - [Meths, UserRegexp, Regexp] - end - - it "preserves Regexp encoding" do - source_object = Regexp.new("a".encode("utf-32le")) - regexp = Marshal.send(@method, Marshal.dump(source_object)) - - regexp.encoding.should == Encoding::UTF_32LE - regexp.source.should == "a".encode("utf-32le") - end - - it "raises ArgumentError when end of byte sequence reached before source string end" do - Marshal.dump(/hello world/).should == "\x04\bI/\x10hello world\x00\x06:\x06EF" - - -> { - Marshal.send(@method, "\x04\bI/\x10hel") - }.should.raise(ArgumentError, "marshal data too short") - end - end - - describe "for a Float" do - it "loads a Float NaN" do - obj = 0.0 / 0.0 - Marshal.send(@method, "\004\bf\bnan").to_s.should == obj.to_s - end - - it "loads a Float 1.3" do - Marshal.send(@method, "\004\bf\v1.3\000\314\315").should == 1.3 - end - - it "loads a Float -5.1867345e-22" do - obj = -5.1867345e-22 - Marshal.send(@method, "\004\bf\037-5.1867345000000008e-22\000\203_").should be_close(obj, 1e-30) - end - - it "loads a Float 1.1867345e+22" do - obj = 1.1867345e+22 - Marshal.send(@method, "\004\bf\0361.1867344999999999e+22\000\344@").should == obj - end - - it "raises ArgumentError when end of byte sequence reached before float string representation end" do - Marshal.dump(1.3).should == "\x04\bf\b1.3" - - -> { - Marshal.send(@method, "\004\bf\v1") - }.should.raise(ArgumentError, "marshal data too short") - end - end - - describe "for an Integer" do - it "loads 0" do - Marshal.send(@method, "\004\bi\000").should == 0 - Marshal.send(@method, "\004\bi\005").should == 0 - end - - it "loads an Integer 8" do - Marshal.send(@method, "\004\bi\r" ).should == 8 - end - - it "loads and Integer -8" do - Marshal.send(@method, "\004\bi\363" ).should == -8 - end - - it "loads an Integer 1234" do - Marshal.send(@method, "\004\bi\002\322\004").should == 1234 - end - - it "loads an Integer -1234" do - Marshal.send(@method, "\004\bi\376.\373").should == -1234 - end - - it "loads an Integer 4611686018427387903" do - Marshal.send(@method, "\004\bl+\t\377\377\377\377\377\377\377?").should == 4611686018427387903 - end - - it "loads an Integer -4611686018427387903" do - Marshal.send(@method, "\004\bl-\t\377\377\377\377\377\377\377?").should == -4611686018427387903 - end - - it "loads an Integer 2361183241434822606847" do - Marshal.send(@method, "\004\bl+\n\377\377\377\377\377\377\377\377\177\000").should == 2361183241434822606847 - end - - it "loads an Integer -2361183241434822606847" do - Marshal.send(@method, "\004\bl-\n\377\377\377\377\377\377\377\377\177\000").should == -2361183241434822606847 - end - - it "raises ArgumentError if the input is too short" do - ["\004\bi", - "\004\bi\001", - "\004\bi\002", - "\004\bi\002\0", - "\004\bi\003", - "\004\bi\003\0", - "\004\bi\003\0\0", - "\004\bi\004", - "\004\bi\004\0", - "\004\bi\004\0\0", - "\004\bi\004\0\0\0"].each do |invalid| - -> { Marshal.send(@method, invalid) }.should.raise(ArgumentError) - end - end - - if 0.size == 8 # for platforms like x86_64 - it "roundtrips 4611686018427387903 from dump/load correctly" do - Marshal.send(@method, Marshal.dump(4611686018427387903)).should == 4611686018427387903 - end - end - end - - describe "for a Rational" do - it "loads" do - r = Marshal.send(@method, Marshal.dump(Rational(1, 3))) - r.should == Rational(1, 3) - r.should.frozen? - end - end - - describe "for a Complex" do - it "loads" do - c = Marshal.send(@method, Marshal.dump(Complex(4, 3))) - c.should == Complex(4, 3) - c.should.frozen? - end - end - - describe "for a Bignum" do - platform_is c_long_size: 64 do - context "that is Bignum on 32-bit platforms but Fixnum on 64-bit" do - it "dumps a Fixnum" do - val = Marshal.send(@method, "\004\bl+\ab:wU") - val.should == 1433877090 - val.class.should == Integer - end - - it "dumps an array containing multiple references to the Bignum as an array of Fixnum" do - arr = Marshal.send(@method, "\004\b[\al+\a\223BwU@\006") - arr.should == [1433879187, 1433879187] - arr.each { |v| v.class.should == Integer } - end - end - end - end - - describe "for a Time" do - it "loads" do - Marshal.send(@method, Marshal.dump(Time.at(1))).should == Time.at(1) - end - - it "loads serialized instance variables" do - t = Time.new - t.instance_variable_set(:@foo, 'bar') - - Marshal.send(@method, Marshal.dump(t)).instance_variable_get(:@foo).should == 'bar' - end - - it "loads Time objects stored as links" do - t = Time.new - - t1, t2 = Marshal.send(@method, Marshal.dump([t, t])) - t1.should.equal? t2 - end - - it "keeps the local zone" do - with_timezone 'AST', 3 do - t = Time.local(2012, 1, 1) - Marshal.send(@method, Marshal.dump(t)).zone.should == t.zone - end - end - - it "keeps UTC zone" do - t = Time.now.utc - t2 = Marshal.send(@method, Marshal.dump(t)) - t2.should.utc? - end - - it "keeps the zone" do - t = nil - - with_timezone 'AST', 4 do - t = Time.local(2012, 1, 1) - end - - with_timezone 'EET', -2 do - Marshal.send(@method, Marshal.dump(t)).zone.should == 'AST' - end - end - - it "keeps utc offset" do - t = Time.new(2007,11,1,15,25,0, "+09:00") - t2 = Marshal.send(@method, Marshal.dump(t)) - t2.utc_offset.should == 32400 - end - - it "keeps nanoseconds" do - t = Time.now - Marshal.send(@method, Marshal.dump(t)).nsec.should == t.nsec - end - - it "does not add any additional instance variable" do - t = Time.now - t2 = Marshal.send(@method, Marshal.dump(t)) - t2.instance_variables.should.empty? - end - end - - describe "for nil" do - it "loads" do - Marshal.send(@method, "\x04\b0").should == nil - end - end - - describe "for true" do - it "loads" do - Marshal.send(@method, "\x04\bT").should == true - end - end - - describe "for false" do - it "loads" do - Marshal.send(@method, "\x04\bF").should == false - end - end - - describe "for a Class" do - it "loads" do - Marshal.send(@method, "\x04\bc\vString").should == String - end - - it "raises ArgumentError if given the name of a non-Module" do - -> { Marshal.send(@method, "\x04\bc\vKernel") }.should.raise(ArgumentError) - end - - it "raises ArgumentError if given a nonexistent class" do - -> { Marshal.send(@method, "\x04\bc\vStrung") }.should.raise(ArgumentError) - end - - it "raises ArgumentError when end of byte sequence reached before class name end" do - Marshal.dump(String).should == "\x04\bc\vString" - - -> { - Marshal.send(@method, "\x04\bc\vStr") - }.should.raise(ArgumentError, "marshal data too short") - end - end - - describe "for a Module" do - it "loads a module" do - Marshal.send(@method, "\x04\bm\vKernel").should == Kernel - end - - it "raises ArgumentError if given the name of a non-Class" do - -> { Marshal.send(@method, "\x04\bm\vString") }.should.raise(ArgumentError) - end - - it "loads an old module" do - Marshal.send(@method, "\x04\bM\vKernel").should == Kernel - end - - it "raises ArgumentError when end of byte sequence reached before module name end" do - Marshal.dump(Kernel).should == "\x04\bm\vKernel" - - -> { - Marshal.send(@method, "\x04\bm\vKer") - }.should.raise(ArgumentError, "marshal data too short") - end - end - - describe "for a wrapped C pointer" do - it "loads" do - class DumpableDir < Dir - def _dump_data - path - end - def _load_data path - initialize(path) - end - end - - data = "\x04\bd:\x10DumpableDirI\"\x06.\x06:\x06ET" - - dir = Marshal.send(@method, data) - begin - dir.path.should == '.' - ensure - dir.close - end - end - - it "raises TypeError when the local class is missing _load_data" do - class UnloadableDumpableDir < Dir - def _dump_data - path - end - # no _load_data - end - - data = "\x04\bd:\x1AUnloadableDumpableDirI\"\x06.\x06:\x06ET" - - -> { Marshal.send(@method, data) }.should.raise(TypeError) - end - - it "raises ArgumentError when the local class is a regular object" do - data = "\004\bd:\020UserDefined\0" - - -> { Marshal.send(@method, data) }.should.raise(ArgumentError) - end - end - - describe "when a class does not exist in the namespace" do - before :each do - NamespaceTest.send(:const_set, :SameName, Class.new) - @data = Marshal.dump(NamespaceTest::SameName.new) - NamespaceTest.send(:remove_const, :SameName) - end - - it "raises an ArgumentError" do - message = "undefined class/module NamespaceTest::SameName" - -> { Marshal.send(@method, @data) }.should.raise(ArgumentError, message) - end - end - - it "raises an ArgumentError with full constant name when the dumped constant is missing" do - NamespaceTest.send(:const_set, :KaBoom, Class.new) - @data = Marshal.dump(NamespaceTest::KaBoom.new) - NamespaceTest.send(:remove_const, :KaBoom) - - -> { Marshal.send(@method, @data) }.should.raise(ArgumentError, /NamespaceTest::KaBoom/) - end -end diff --git a/spec/ruby/core/matchdata/captures_spec.rb b/spec/ruby/core/matchdata/captures_spec.rb index f829a25481..fdbc1c4346 100644 --- a/spec/ruby/core/matchdata/captures_spec.rb +++ b/spec/ruby/core/matchdata/captures_spec.rb @@ -1,6 +1,13 @@ require_relative '../../spec_helper' -require_relative 'shared/captures' +require_relative 'fixtures/classes' describe "MatchData#captures" do - it_behaves_like :matchdata_captures, :captures + it "returns an array of the match captures" do + /(.)(.)(\d+)(\d)/.match("THX1138.").captures.should == ["H","X","113","8"] + end + + it "returns instances of String when given a String subclass" do + str = MatchDataSpecs::MyString.new("THX1138: The Movie") + /(.)(.)(\d+)(\d)/.match(str).captures.each { |c| c.should.instance_of?(String) } + end end diff --git a/spec/ruby/core/matchdata/deconstruct_spec.rb b/spec/ruby/core/matchdata/deconstruct_spec.rb index c55095665d..13ebd1848f 100644 --- a/spec/ruby/core/matchdata/deconstruct_spec.rb +++ b/spec/ruby/core/matchdata/deconstruct_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/captures' describe "MatchData#deconstruct" do - it_behaves_like :matchdata_captures, :deconstruct + it "is an alias of MatchData#captures" do + MatchData.instance_method(:deconstruct).should == MatchData.instance_method(:captures) + end end diff --git a/spec/ruby/core/matchdata/eql_spec.rb b/spec/ruby/core/matchdata/eql_spec.rb index 1d9666ebe1..937c4424aa 100644 --- a/spec/ruby/core/matchdata/eql_spec.rb +++ b/spec/ruby/core/matchdata/eql_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/eql' describe "MatchData#eql?" do - it_behaves_like :matchdata_eql, :eql? + it "is an alias of MatchData#==" do + MatchData.instance_method(:eql?).should == MatchData.instance_method(:==) + end end diff --git a/spec/ruby/core/matchdata/equal_value_spec.rb b/spec/ruby/core/matchdata/equal_value_spec.rb index a58f1277e4..74d3a5adcd 100644 --- a/spec/ruby/core/matchdata/equal_value_spec.rb +++ b/spec/ruby/core/matchdata/equal_value_spec.rb @@ -1,6 +1,26 @@ require_relative '../../spec_helper' -require_relative 'shared/eql' describe "MatchData#==" do - it_behaves_like :matchdata_eql, :== + it "returns true if both operands have equal target strings, patterns, and match positions" do + a = 'haystack'.match(/hay/) + b = 'haystack'.match(/hay/) + a.==(b).should == true + end + + it "returns false if the operands have different target strings" do + a = 'hay'.match(/hay/) + b = 'haystack'.match(/hay/) + a.==(b).should == false + end + + it "returns false if the operands have different patterns" do + a = 'haystack'.match(/h.y/) + b = 'haystack'.match(/hay/) + a.==(b).should == false + end + + it "returns false if the argument is not a MatchData object" do + a = 'haystack'.match(/hay/) + a.==(Object.new).should == false + end end diff --git a/spec/ruby/core/matchdata/length_spec.rb b/spec/ruby/core/matchdata/length_spec.rb index 39df36df4b..72d4d80cec 100644 --- a/spec/ruby/core/matchdata/length_spec.rb +++ b/spec/ruby/core/matchdata/length_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/length' describe "MatchData#length" do - it_behaves_like :matchdata_length, :length + it "is an alias of MatchData#size" do + MatchData.instance_method(:length).should == MatchData.instance_method(:size) + end end diff --git a/spec/ruby/core/matchdata/shared/captures.rb b/spec/ruby/core/matchdata/shared/captures.rb deleted file mode 100644 index de5870f543..0000000000 --- a/spec/ruby/core/matchdata/shared/captures.rb +++ /dev/null @@ -1,13 +0,0 @@ -require_relative '../../../spec_helper' -require_relative '../fixtures/classes' - -describe :matchdata_captures, shared: true do - it "returns an array of the match captures" do - /(.)(.)(\d+)(\d)/.match("THX1138.").send(@method).should == ["H","X","113","8"] - end - - it "returns instances of String when given a String subclass" do - str = MatchDataSpecs::MyString.new("THX1138: The Movie") - /(.)(.)(\d+)(\d)/.match(str).send(@method).each { |c| c.should.instance_of?(String) } - end -end diff --git a/spec/ruby/core/matchdata/shared/eql.rb b/spec/ruby/core/matchdata/shared/eql.rb deleted file mode 100644 index e4bb8797b7..0000000000 --- a/spec/ruby/core/matchdata/shared/eql.rb +++ /dev/null @@ -1,26 +0,0 @@ -require_relative '../../../spec_helper' - -describe :matchdata_eql, shared: true do - it "returns true if both operands have equal target strings, patterns, and match positions" do - a = 'haystack'.match(/hay/) - b = 'haystack'.match(/hay/) - a.send(@method, b).should == true - end - - it "returns false if the operands have different target strings" do - a = 'hay'.match(/hay/) - b = 'haystack'.match(/hay/) - a.send(@method, b).should == false - end - - it "returns false if the operands have different patterns" do - a = 'haystack'.match(/h.y/) - b = 'haystack'.match(/hay/) - a.send(@method, b).should == false - end - - it "returns false if the argument is not a MatchData object" do - a = 'haystack'.match(/hay/) - a.send(@method, Object.new).should == false - end -end diff --git a/spec/ruby/core/matchdata/shared/length.rb b/spec/ruby/core/matchdata/shared/length.rb deleted file mode 100644 index 6312a7ed4c..0000000000 --- a/spec/ruby/core/matchdata/shared/length.rb +++ /dev/null @@ -1,5 +0,0 @@ -describe :matchdata_length, shared: true do - it "length should return the number of elements in the match array" do - /(.)(.)(\d+)(\d)/.match("THX1138.").send(@method).should == 5 - end -end diff --git a/spec/ruby/core/matchdata/size_spec.rb b/spec/ruby/core/matchdata/size_spec.rb index b4965db3b8..f93ded72cb 100644 --- a/spec/ruby/core/matchdata/size_spec.rb +++ b/spec/ruby/core/matchdata/size_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/length' describe "MatchData#size" do - it_behaves_like :matchdata_length, :size + it "should return the number of elements in the match array" do + /(.)(.)(\d+)(\d)/.match("THX1138.").size.should == 5 + end end diff --git a/spec/ruby/core/method/call_spec.rb b/spec/ruby/core/method/call_spec.rb index 6d997325fa..cb11545e91 100644 --- a/spec/ruby/core/method/call_spec.rb +++ b/spec/ruby/core/method/call_spec.rb @@ -1,7 +1,54 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/call' describe "Method#call" do - it_behaves_like :method_call, :call + it "invokes the method with the specified arguments, returning the method's return value" do + m = 12.method("+") + m.call(3).should == 15 + m.call(20).should == 32 + + m = MethodSpecs::Methods.new.method(:attr=) + m.call(42).should == 42 + end + + it "raises an ArgumentError when given incorrect number of arguments" do + -> { + MethodSpecs::Methods.new.method(:two_req).call(1, 2, 3) + }.should.raise(ArgumentError) + -> { + MethodSpecs::Methods.new.method(:two_req).call(1) + }.should.raise(ArgumentError) + end + + describe "for a Method generated by respond_to_missing?" do + it "invokes method_missing with the specified arguments and returns the result" do + @m = MethodSpecs::Methods.new + meth = @m.method(:handled_via_method_missing) + meth.call(:argument).should == [:argument] + end + + it "invokes method_missing with the method name and the specified arguments" do + @m = MethodSpecs::Methods.new + meth = @m.method(:handled_via_method_missing) + + @m.should_receive(:method_missing).with(:handled_via_method_missing, :argument) + meth.call(:argument) + end + + it "invokes method_missing dynamically" do + @m = MethodSpecs::Methods.new + meth = @m.method(:handled_via_method_missing) + + def @m.method_missing(*); :changed; end + meth.call(:argument).should == :changed + end + + it "does not call the original method name even if it now exists" do + @m = MethodSpecs::Methods.new + meth = @m.method(:handled_via_method_missing) + + def @m.handled_via_method_missing(*); :not_called; end + meth.call(:argument).should == [:argument] + end + end end diff --git a/spec/ruby/core/method/case_compare_spec.rb b/spec/ruby/core/method/case_compare_spec.rb index a78953e8ad..771fea1ce5 100644 --- a/spec/ruby/core/method/case_compare_spec.rb +++ b/spec/ruby/core/method/case_compare_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/call' describe "Method#===" do - it_behaves_like :method_call, :=== + it "is an alias of Method#call" do + Method.instance_method(:===).should == Method.instance_method(:call) + end end diff --git a/spec/ruby/core/method/element_reference_spec.rb b/spec/ruby/core/method/element_reference_spec.rb index aa6c54d1cb..65c13cf32b 100644 --- a/spec/ruby/core/method/element_reference_spec.rb +++ b/spec/ruby/core/method/element_reference_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/call' describe "Method#[]" do - it_behaves_like :method_call, :[] + it "is an alias of Method#call" do + Method.instance_method(:[]).should == Method.instance_method(:call) + end end diff --git a/spec/ruby/core/method/eql_spec.rb b/spec/ruby/core/method/eql_spec.rb index b97c9e4db0..81fd086bd5 100644 --- a/spec/ruby/core/method/eql_spec.rb +++ b/spec/ruby/core/method/eql_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/eql' describe "Method#eql?" do - it_behaves_like :method_equal, :eql? + it "is an alias of Method#==" do + Method.instance_method(:eql?).should == Method.instance_method(:==) + end end diff --git a/spec/ruby/core/method/equal_value_spec.rb b/spec/ruby/core/method/equal_value_spec.rb index 0431d0c5f6..ca9ef9f108 100644 --- a/spec/ruby/core/method/equal_value_spec.rb +++ b/spec/ruby/core/method/equal_value_spec.rb @@ -1,6 +1,94 @@ require_relative '../../spec_helper' -require_relative 'shared/eql' +require_relative 'fixtures/classes' describe "Method#==" do - it_behaves_like :method_equal, :== + before :each do + @m = MethodSpecs::Methods.new + @m_foo = @m.method(:foo) + @m2 = MethodSpecs::Methods.new + @a = MethodSpecs::A.new + end + + it "returns true if methods are the same" do + m2 = @m.method(:foo) + + (@m_foo == @m_foo).should == true + (@m_foo == m2).should == true + end + + it "returns true on aliased methods" do + m_bar = @m.method(:bar) + + (m_bar == @m_foo).should == true + end + + it "returns true if the two core methods are aliases" do + s = "hello" + a = s.method(:size) + b = s.method(:length) + (a == b).should == true + end + + it "returns false on a method which is neither aliased nor the same method" do + m2 = @m.method(:zero) + + (@m_foo == m2).should == false + end + + it "returns false for a method which is not bound to the same object" do + m2_foo = @m2.method(:foo) + a_baz = @a.method(:baz) + + (@m_foo == m2_foo).should == false + (@m_foo == a_baz).should == false + end + + it "returns false if the two methods are bound to the same object but were defined independently" do + m2 = @m.method(:same_as_foo) + (@m_foo == m2).should == false + end + + it "returns true if a method was defined using the other one" do + MethodSpecs::Methods.send :define_method, :defined_foo, MethodSpecs::Methods.instance_method(:foo) + m2 = @m.method(:defined_foo) + (@m_foo == m2).should == true + end + + it "returns false if comparing a method defined via define_method and def" do + defn = @m.method(:zero) + defined = @m.method(:zero_defined_method) + + (defn == defined).should == false + (defined == defn).should == false + end + + describe 'missing methods' do + it "returns true for the same method missing" do + miss1 = @m.method(:handled_via_method_missing) + miss1bis = @m.method(:handled_via_method_missing) + miss2 = @m.method(:also_handled) + + (miss1 == miss1bis).should == true + (miss1 == miss2).should == false + end + + it 'calls respond_to_missing? with true to include private methods' do + @m.should_receive(:respond_to_missing?).with(:some_missing_method, true).and_return(true) + @m.method(:some_missing_method) + end + end + + it "returns false if the two methods are bound to different objects, have the same names, and identical bodies" do + a = MethodSpecs::Eql.instance_method(:same_body) + b = MethodSpecs::Eql2.instance_method(:same_body) + (a == b).should == false + end + + it "returns false if the argument is not a Method object" do + (String.instance_method(:size) == 7).should == false + end + + it "returns false if the argument is an unbound version of self" do + (method(:load) == method(:load).unbind).should == false + end end diff --git a/spec/ruby/core/method/inspect_spec.rb b/spec/ruby/core/method/inspect_spec.rb index 97ff2d8c11..5eb8850ff3 100644 --- a/spec/ruby/core/method/inspect_spec.rb +++ b/spec/ruby/core/method/inspect_spec.rb @@ -1,8 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/to_s' -require_relative 'shared/aliased_inspect' describe "Method#inspect" do - it_behaves_like :method_to_s, :inspect - it_behaves_like :method_to_s_aliased, :inspect, -> meth { meth } + it "is an alias of Method#to_s" do + Method.instance_method(:inspect).should == Method.instance_method(:to_s) + end end diff --git a/spec/ruby/core/method/shared/call.rb b/spec/ruby/core/method/shared/call.rb deleted file mode 100644 index 41ee2b06cb..0000000000 --- a/spec/ruby/core/method/shared/call.rb +++ /dev/null @@ -1,51 +0,0 @@ -describe :method_call, shared: true do - it "invokes the method with the specified arguments, returning the method's return value" do - m = 12.method("+") - m.send(@method, 3).should == 15 - m.send(@method, 20).should == 32 - - m = MethodSpecs::Methods.new.method(:attr=) - m.send(@method, 42).should == 42 - end - - it "raises an ArgumentError when given incorrect number of arguments" do - -> { - MethodSpecs::Methods.new.method(:two_req).send(@method, 1, 2, 3) - }.should.raise(ArgumentError) - -> { - MethodSpecs::Methods.new.method(:two_req).send(@method, 1) - }.should.raise(ArgumentError) - end - - describe "for a Method generated by respond_to_missing?" do - it "invokes method_missing with the specified arguments and returns the result" do - @m = MethodSpecs::Methods.new - meth = @m.method(:handled_via_method_missing) - meth.send(@method, :argument).should == [:argument] - end - - it "invokes method_missing with the method name and the specified arguments" do - @m = MethodSpecs::Methods.new - meth = @m.method(:handled_via_method_missing) - - @m.should_receive(:method_missing).with(:handled_via_method_missing, :argument) - meth.send(@method, :argument) - end - - it "invokes method_missing dynamically" do - @m = MethodSpecs::Methods.new - meth = @m.method(:handled_via_method_missing) - - def @m.method_missing(*); :changed; end - meth.send(@method, :argument).should == :changed - end - - it "does not call the original method name even if it now exists" do - @m = MethodSpecs::Methods.new - meth = @m.method(:handled_via_method_missing) - - def @m.handled_via_method_missing(*); :not_called; end - meth.send(@method, :argument).should == [:argument] - end - end -end diff --git a/spec/ruby/core/method/shared/eql.rb b/spec/ruby/core/method/shared/eql.rb deleted file mode 100644 index 3c340202b7..0000000000 --- a/spec/ruby/core/method/shared/eql.rb +++ /dev/null @@ -1,94 +0,0 @@ -require_relative '../../../spec_helper' -require_relative '../fixtures/classes' - -describe :method_equal, shared: true do - before :each do - @m = MethodSpecs::Methods.new - @m_foo = @m.method(:foo) - @m2 = MethodSpecs::Methods.new - @a = MethodSpecs::A.new - end - - it "returns true if methods are the same" do - m2 = @m.method(:foo) - - @m_foo.send(@method, @m_foo).should == true - @m_foo.send(@method, m2).should == true - end - - it "returns true on aliased methods" do - m_bar = @m.method(:bar) - - m_bar.send(@method, @m_foo).should == true - end - - it "returns true if the two core methods are aliases" do - s = "hello" - a = s.method(:size) - b = s.method(:length) - a.send(@method, b).should == true - end - - it "returns false on a method which is neither aliased nor the same method" do - m2 = @m.method(:zero) - - @m_foo.send(@method, m2).should == false - end - - it "returns false for a method which is not bound to the same object" do - m2_foo = @m2.method(:foo) - a_baz = @a.method(:baz) - - @m_foo.send(@method, m2_foo).should == false - @m_foo.send(@method, a_baz).should == false - end - - it "returns false if the two methods are bound to the same object but were defined independently" do - m2 = @m.method(:same_as_foo) - @m_foo.send(@method, m2).should == false - end - - it "returns true if a method was defined using the other one" do - MethodSpecs::Methods.send :define_method, :defined_foo, MethodSpecs::Methods.instance_method(:foo) - m2 = @m.method(:defined_foo) - @m_foo.send(@method, m2).should == true - end - - it "returns false if comparing a method defined via define_method and def" do - defn = @m.method(:zero) - defined = @m.method(:zero_defined_method) - - defn.send(@method, defined).should == false - defined.send(@method, defn).should == false - end - - describe 'missing methods' do - it "returns true for the same method missing" do - miss1 = @m.method(:handled_via_method_missing) - miss1bis = @m.method(:handled_via_method_missing) - miss2 = @m.method(:also_handled) - - miss1.send(@method, miss1bis).should == true - miss1.send(@method, miss2).should == false - end - - it 'calls respond_to_missing? with true to include private methods' do - @m.should_receive(:respond_to_missing?).with(:some_missing_method, true).and_return(true) - @m.method(:some_missing_method) - end - end - - it "returns false if the two methods are bound to different objects, have the same names, and identical bodies" do - a = MethodSpecs::Eql.instance_method(:same_body) - b = MethodSpecs::Eql2.instance_method(:same_body) - a.send(@method, b).should == false - end - - it "returns false if the argument is not a Method object" do - String.instance_method(:size).send(@method, 7).should == false - end - - it "returns false if the argument is an unbound version of self" do - method(:load).send(@method, method(:load).unbind).should == false - end -end diff --git a/spec/ruby/core/module/class_eval_spec.rb b/spec/ruby/core/module/class_eval_spec.rb index c6665d5aff..0c190ceaff 100644 --- a/spec/ruby/core/module/class_eval_spec.rb +++ b/spec/ruby/core/module/class_eval_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/class_eval' describe "Module#class_eval" do - it_behaves_like :module_class_eval, :class_eval + it "is an alias of Module#module_eval" do + Module.instance_method(:class_eval).should == Module.instance_method(:module_eval) + end end diff --git a/spec/ruby/core/module/class_exec_spec.rb b/spec/ruby/core/module/class_exec_spec.rb index 4acd0169ad..d47a6ba982 100644 --- a/spec/ruby/core/module/class_exec_spec.rb +++ b/spec/ruby/core/module/class_exec_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/class_exec' describe "Module#class_exec" do - it_behaves_like :module_class_exec, :class_exec + it "is an alias of Module#module_exec" do + Module.instance_method(:class_exec).should == Module.instance_method(:module_exec) + end end diff --git a/spec/ruby/core/module/inspect_spec.rb b/spec/ruby/core/module/inspect_spec.rb new file mode 100644 index 0000000000..68c8494c96 --- /dev/null +++ b/spec/ruby/core/module/inspect_spec.rb @@ -0,0 +1,7 @@ +require_relative '../../spec_helper' + +describe "Module#inspect" do + it "is an alias of Module#to_s" do + Module.instance_method(:inspect).should == Module.instance_method(:to_s) + end +end diff --git a/spec/ruby/core/module/module_eval_spec.rb b/spec/ruby/core/module/module_eval_spec.rb index e9e9fda28d..bcd51ca19d 100644 --- a/spec/ruby/core/module/module_eval_spec.rb +++ b/spec/ruby/core/module/module_eval_spec.rb @@ -1,7 +1,175 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/class_eval' describe "Module#module_eval" do - it_behaves_like :module_class_eval, :module_eval + # TODO: This should probably be replaced with a "should behave like" that uses + # the many scoping/binding specs from kernel/eval_spec, since most of those + # behaviors are the same for instance_eval. See also module_eval/class_eval. + + it "evaluates a given string in the context of self" do + ModuleSpecs.module_eval("self").should == ModuleSpecs + ModuleSpecs.module_eval("1 + 1").should == 2 + end + + it "does not add defined methods to other classes" do + FalseClass.module_eval do + def foo + 'foo' + end + end + -> {42.foo}.should.raise(NoMethodError) + end + + it "resolves constants in the caller scope" do + ModuleSpecs::ClassEvalTest.get_constant_from_scope.should == ModuleSpecs::Lookup + end + + it "resolves constants in the caller scope ignoring send" do + ModuleSpecs::ClassEvalTest.get_constant_from_scope_with_send(:module_eval).should == ModuleSpecs::Lookup + end + + it "resolves constants in the receiver's scope" do + ModuleSpecs.module_eval("Lookup").should == ModuleSpecs::Lookup + ModuleSpecs.module_eval("Lookup::LOOKIE").should == ModuleSpecs::Lookup::LOOKIE + end + + it "defines constants in the receiver's scope" do + ModuleSpecs.module_eval("module NewEvaluatedModule;end") + ModuleSpecs.const_defined?(:NewEvaluatedModule, false).should == true + end + + it "evaluates a given block in the context of self" do + ModuleSpecs.module_eval { self }.should == ModuleSpecs + ModuleSpecs.module_eval { 1 + 1 }.should == 2 + end + + it "passes the module as the first argument of the block" do + given = nil + ModuleSpecs.module_eval do |block_parameter| + given = block_parameter + end + given.should.equal? ModuleSpecs + end + + it "uses the optional filename and lineno parameters for error messages" do + ModuleSpecs.module_eval("[__FILE__, __LINE__]", "test", 102).should == ["test", 102] + end + + it "uses the caller location as default filename" do + ModuleSpecs.module_eval("[__FILE__, __LINE__]").should == ["(eval at #{__FILE__}:#{__LINE__})", 1] + end + + it "converts a non-string filename to a string using to_str" do + (file = mock(__FILE__)).should_receive(:to_str).and_return(__FILE__) + ModuleSpecs.module_eval("1+1", file) + + (file = mock(__FILE__)).should_receive(:to_str).and_return(__FILE__) + ModuleSpecs.module_eval("1+1", file, 15) + end + + it "raises a TypeError when the given filename can't be converted to string using to_str" do + (file = mock('123')).should_receive(:to_str).and_return(123) + -> { ModuleSpecs.module_eval("1+1", file) }.should raise_consistent_error(TypeError, /can't convert MockObject into String/) + end + + it "converts non string eval-string to string using to_str" do + (o = mock('1 + 1')).should_receive(:to_str).and_return("1 + 1") + ModuleSpecs.module_eval(o).should == 2 + + (o = mock('1 + 1')).should_receive(:to_str).and_return("1 + 1") + ModuleSpecs.module_eval(o, "file.rb").should == 2 + + (o = mock('1 + 1')).should_receive(:to_str).and_return("1 + 1") + ModuleSpecs.module_eval(o, "file.rb", 15).should == 2 + end + + it "raises a TypeError when the given eval-string can't be converted to string using to_str" do + o = mock('x') + -> { ModuleSpecs.module_eval(o) }.should.raise(TypeError, "no implicit conversion of MockObject into String") + + (o = mock('123')).should_receive(:to_str).and_return(123) + -> { ModuleSpecs.module_eval(o) }.should raise_consistent_error(TypeError, /can't convert MockObject into String/) + end + + it "raises an ArgumentError when no arguments and no block are given" do + -> { ModuleSpecs.module_eval }.should.raise(ArgumentError, "wrong number of arguments (given 0, expected 1..3)") + end + + it "raises an ArgumentError when more than 3 arguments are given" do + -> { + ModuleSpecs.module_eval("1 + 1", "some file", 0, "bogus") + }.should.raise(ArgumentError, "wrong number of arguments (given 4, expected 1..3)") + end + + it "raises an ArgumentError when a block and normal arguments are given" do + -> { + ModuleSpecs.module_eval("1 + 1") { 1 + 1 } + }.should.raise(ArgumentError, "wrong number of arguments (given 1, expected 0)") + end + + # This case was found because Rubinius was caching the compiled + # version of the string and not duping the methods within the + # eval, causing the method addition to change the static scope + # of the shared CompiledCode. + it "adds methods respecting the lexical constant scope" do + code = "def self.attribute; C; end" + + a = Class.new do + self::C = "A" + end + + b = Class.new do + self::C = "B" + end + + a.module_eval(code) + b.module_eval(code) + + a.attribute.should == "A" + b.attribute.should == "B" + end + + it "activates refinements from the eval scope" do + refinery = Module.new do + refine ModuleSpecs::NamedClass do + def foo + "bar" + end + end + end + + mid = :module_eval + result = nil + + Class.new do + using refinery + + result = send(mid, "ModuleSpecs::NamedClass.new.foo") + end + + result.should == "bar" + end + + it "activates refinements from the eval scope with block" do + refinery = Module.new do + refine ModuleSpecs::NamedClass do + def foo + "bar" + end + end + end + + mid = :module_eval + result = nil + + Class.new do + using refinery + + result = send(mid) do + ModuleSpecs::NamedClass.new.foo + end + end + + result.should == "bar" + end end diff --git a/spec/ruby/core/module/module_exec_spec.rb b/spec/ruby/core/module/module_exec_spec.rb index 47cdf7ef52..6b36e8a02f 100644 --- a/spec/ruby/core/module/module_exec_spec.rb +++ b/spec/ruby/core/module/module_exec_spec.rb @@ -1,7 +1,38 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/class_exec' describe "Module#module_exec" do - it_behaves_like :module_class_exec, :module_exec + it "does not add defined methods to other classes" do + FalseClass.module_exec do + def foo + 'foo' + end + end + -> {42.foo}.should.raise(NoMethodError) + end + + it "defines method in the receiver's scope" do + ModuleSpecs::Subclass.module_exec { def foo; end } + ModuleSpecs::Subclass.new.respond_to?(:foo).should == true + end + + it "evaluates a given block in the context of self" do + ModuleSpecs::Subclass.module_exec { self }.should == ModuleSpecs::Subclass + ModuleSpecs::Subclass.new.module_exec { 1 + 1 }.should == 2 + end + + it "raises a LocalJumpError when no block is given" do + -> { ModuleSpecs::Subclass.module_exec }.should.raise(LocalJumpError) + end + + it "passes arguments to the block" do + a = ModuleSpecs::Subclass + a.module_exec(1) { |b| b }.should.equal?(1) + end + + describe "with optional argument" do + it "does not destructure a single array argument" do + ModuleSpecs::Subclass.module_exec([1, 2, 3]) { |a = 99| a }.should == [1, 2, 3] + end + end end diff --git a/spec/ruby/core/module/shared/class_eval.rb b/spec/ruby/core/module/shared/class_eval.rb deleted file mode 100644 index ee2860449a..0000000000 --- a/spec/ruby/core/module/shared/class_eval.rb +++ /dev/null @@ -1,172 +0,0 @@ -describe :module_class_eval, shared: true do - # TODO: This should probably be replaced with a "should behave like" that uses - # the many scoping/binding specs from kernel/eval_spec, since most of those - # behaviors are the same for instance_eval. See also module_eval/class_eval. - - it "evaluates a given string in the context of self" do - ModuleSpecs.send(@method, "self").should == ModuleSpecs - ModuleSpecs.send(@method, "1 + 1").should == 2 - end - - it "does not add defined methods to other classes" do - FalseClass.send(@method) do - def foo - 'foo' - end - end - -> {42.foo}.should.raise(NoMethodError) - end - - it "resolves constants in the caller scope" do - ModuleSpecs::ClassEvalTest.get_constant_from_scope.should == ModuleSpecs::Lookup - end - - it "resolves constants in the caller scope ignoring send" do - ModuleSpecs::ClassEvalTest.get_constant_from_scope_with_send(@method).should == ModuleSpecs::Lookup - end - - it "resolves constants in the receiver's scope" do - ModuleSpecs.send(@method, "Lookup").should == ModuleSpecs::Lookup - ModuleSpecs.send(@method, "Lookup::LOOKIE").should == ModuleSpecs::Lookup::LOOKIE - end - - it "defines constants in the receiver's scope" do - ModuleSpecs.send(@method, "module NewEvaluatedModule;end") - ModuleSpecs.const_defined?(:NewEvaluatedModule, false).should == true - end - - it "evaluates a given block in the context of self" do - ModuleSpecs.send(@method) { self }.should == ModuleSpecs - ModuleSpecs.send(@method) { 1 + 1 }.should == 2 - end - - it "passes the module as the first argument of the block" do - given = nil - ModuleSpecs.send(@method) do |block_parameter| - given = block_parameter - end - given.should.equal? ModuleSpecs - end - - it "uses the optional filename and lineno parameters for error messages" do - ModuleSpecs.send(@method, "[__FILE__, __LINE__]", "test", 102).should == ["test", 102] - end - - it "uses the caller location as default filename" do - ModuleSpecs.send(@method, "[__FILE__, __LINE__]").should == ["(eval at #{__FILE__}:#{__LINE__})", 1] - end - - it "converts a non-string filename to a string using to_str" do - (file = mock(__FILE__)).should_receive(:to_str).and_return(__FILE__) - ModuleSpecs.send(@method, "1+1", file) - - (file = mock(__FILE__)).should_receive(:to_str).and_return(__FILE__) - ModuleSpecs.send(@method, "1+1", file, 15) - end - - it "raises a TypeError when the given filename can't be converted to string using to_str" do - (file = mock('123')).should_receive(:to_str).and_return(123) - -> { ModuleSpecs.send(@method, "1+1", file) }.should raise_consistent_error(TypeError, /can't convert MockObject into String/) - end - - it "converts non string eval-string to string using to_str" do - (o = mock('1 + 1')).should_receive(:to_str).and_return("1 + 1") - ModuleSpecs.send(@method, o).should == 2 - - (o = mock('1 + 1')).should_receive(:to_str).and_return("1 + 1") - ModuleSpecs.send(@method, o, "file.rb").should == 2 - - (o = mock('1 + 1')).should_receive(:to_str).and_return("1 + 1") - ModuleSpecs.send(@method, o, "file.rb", 15).should == 2 - end - - it "raises a TypeError when the given eval-string can't be converted to string using to_str" do - o = mock('x') - -> { ModuleSpecs.send(@method, o) }.should.raise(TypeError, "no implicit conversion of MockObject into String") - - (o = mock('123')).should_receive(:to_str).and_return(123) - -> { ModuleSpecs.send(@method, o) }.should raise_consistent_error(TypeError, /can't convert MockObject into String/) - end - - it "raises an ArgumentError when no arguments and no block are given" do - -> { ModuleSpecs.send(@method) }.should.raise(ArgumentError, "wrong number of arguments (given 0, expected 1..3)") - end - - it "raises an ArgumentError when more than 3 arguments are given" do - -> { - ModuleSpecs.send(@method, "1 + 1", "some file", 0, "bogus") - }.should.raise(ArgumentError, "wrong number of arguments (given 4, expected 1..3)") - end - - it "raises an ArgumentError when a block and normal arguments are given" do - -> { - ModuleSpecs.send(@method, "1 + 1") { 1 + 1 } - }.should.raise(ArgumentError, "wrong number of arguments (given 1, expected 0)") - end - - # This case was found because Rubinius was caching the compiled - # version of the string and not duping the methods within the - # eval, causing the method addition to change the static scope - # of the shared CompiledCode. - it "adds methods respecting the lexical constant scope" do - code = "def self.attribute; C; end" - - a = Class.new do - self::C = "A" - end - - b = Class.new do - self::C = "B" - end - - a.send @method, code - b.send @method, code - - a.attribute.should == "A" - b.attribute.should == "B" - end - - it "activates refinements from the eval scope" do - refinery = Module.new do - refine ModuleSpecs::NamedClass do - def foo - "bar" - end - end - end - - mid = @method - result = nil - - Class.new do - using refinery - - result = send(mid, "ModuleSpecs::NamedClass.new.foo") - end - - result.should == "bar" - end - - it "activates refinements from the eval scope with block" do - refinery = Module.new do - refine ModuleSpecs::NamedClass do - def foo - "bar" - end - end - end - - mid = @method - result = nil - - Class.new do - using refinery - - result = send(mid) do - ModuleSpecs::NamedClass.new.foo - end - end - - result.should == "bar" - end -end diff --git a/spec/ruby/core/module/shared/class_exec.rb b/spec/ruby/core/module/shared/class_exec.rb deleted file mode 100644 index e51af1966d..0000000000 --- a/spec/ruby/core/module/shared/class_exec.rb +++ /dev/null @@ -1,35 +0,0 @@ -describe :module_class_exec, shared: true do - it "does not add defined methods to other classes" do - FalseClass.send(@method) do - def foo - 'foo' - end - end - -> {42.foo}.should.raise(NoMethodError) - end - - it "defines method in the receiver's scope" do - ModuleSpecs::Subclass.send(@method) { def foo; end } - ModuleSpecs::Subclass.new.respond_to?(:foo).should == true - end - - it "evaluates a given block in the context of self" do - ModuleSpecs::Subclass.send(@method) { self }.should == ModuleSpecs::Subclass - ModuleSpecs::Subclass.new.send(@method) { 1 + 1 }.should == 2 - end - - it "raises a LocalJumpError when no block is given" do - -> { ModuleSpecs::Subclass.send(@method) }.should.raise(LocalJumpError) - end - - it "passes arguments to the block" do - a = ModuleSpecs::Subclass - a.send(@method, 1) { |b| b }.should.equal?(1) - end - - describe "with optional argument" do - it "does not destructure a single array argument" do - ModuleSpecs::Subclass.send(@method, [1, 2, 3]) { |a = 99| a }.should == [1, 2, 3] - end - end -end diff --git a/spec/ruby/core/nil/xor_spec.rb b/spec/ruby/core/nil/xor_spec.rb index b45da9d443..31ce33e971 100644 --- a/spec/ruby/core/nil/xor_spec.rb +++ b/spec/ruby/core/nil/xor_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' describe "NilClass#^" do - it "returns false if other is nil or false, otherwise true" do - (nil ^ nil).should == false - (nil ^ true).should == true - (nil ^ false).should == false - (nil ^ "").should == true - (nil ^ mock('x')).should == true + it "is an alias of NilClass#|" do + nil.method(:^).should == nil.method(:|) end end diff --git a/spec/ruby/core/numeric/abs_spec.rb b/spec/ruby/core/numeric/abs_spec.rb index 8bec50e337..4b16e06c97 100644 --- a/spec/ruby/core/numeric/abs_spec.rb +++ b/spec/ruby/core/numeric/abs_spec.rb @@ -1,6 +1,19 @@ require_relative '../../spec_helper' -require_relative 'shared/abs' +require_relative 'fixtures/classes' describe "Numeric#abs" do - it_behaves_like :numeric_abs, :abs + before :each do + @obj = NumericSpecs::Subclass.new + end + + it "returns self when self is greater than 0" do + @obj.should_receive(:<).with(0).and_return(false) + @obj.abs.should == @obj + end + + it "returns self\#@- when self is less than 0" do + @obj.should_receive(:<).with(0).and_return(true) + @obj.should_receive(:-@).and_return(:absolute_value) + @obj.abs.should == :absolute_value + end end diff --git a/spec/ruby/core/numeric/angle_spec.rb b/spec/ruby/core/numeric/angle_spec.rb index bb38165777..25d2834a52 100644 --- a/spec/ruby/core/numeric/angle_spec.rb +++ b/spec/ruby/core/numeric/angle_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/arg' describe "Numeric#angle" do - it_behaves_like :numeric_arg, :angle + it "is an alias of Numeric#arg" do + Numeric.instance_method(:angle).should == Numeric.instance_method(:arg) + end end diff --git a/spec/ruby/core/numeric/arg_spec.rb b/spec/ruby/core/numeric/arg_spec.rb index ba3b57c687..4fd059d7fc 100644 --- a/spec/ruby/core/numeric/arg_spec.rb +++ b/spec/ruby/core/numeric/arg_spec.rb @@ -1,6 +1,38 @@ require_relative '../../spec_helper' -require_relative 'shared/arg' describe "Numeric#arg" do - it_behaves_like :numeric_arg, :arg + before :each do + @numbers = [ + 20, + Rational(3, 4), + bignum_value, + infinity_value + ] + end + + it "returns 0 if positive" do + @numbers.each do |number| + number.arg.should == 0 + end + end + + it "returns Pi if negative" do + @numbers.each do |number| + (0-number).arg.should == Math::PI + end + end + + describe "with a Numeric subclass" do + it "returns 0 if self#<(0) returns false" do + numeric = mock_numeric('positive') + numeric.should_receive(:<).with(0).and_return(false) + numeric.arg.should == 0 + end + + it "returns Pi if self#<(0) returns true" do + numeric = mock_numeric('positive') + numeric.should_receive(:<).with(0).and_return(true) + numeric.arg.should == Math::PI + end + end end diff --git a/spec/ruby/core/numeric/conj_spec.rb b/spec/ruby/core/numeric/conj_spec.rb index 7d4777ca60..f376a0d4b1 100644 --- a/spec/ruby/core/numeric/conj_spec.rb +++ b/spec/ruby/core/numeric/conj_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/conj' describe "Numeric#conj" do - it_behaves_like :numeric_conj, :conj + it "is an alias of Numeric#conjugate" do + Numeric.instance_method(:conj).should == Numeric.instance_method(:conjugate) + end end diff --git a/spec/ruby/core/numeric/conjugate_spec.rb b/spec/ruby/core/numeric/conjugate_spec.rb index 99854766e7..ea4731991d 100644 --- a/spec/ruby/core/numeric/conjugate_spec.rb +++ b/spec/ruby/core/numeric/conjugate_spec.rb @@ -1,6 +1,20 @@ require_relative '../../spec_helper' -require_relative 'shared/conj' describe "Numeric#conjugate" do - it_behaves_like :numeric_conj, :conjugate + before :each do + @numbers = [ + 20, # Integer + 398.72, # Float + Rational(3, 4), # Rational + bignum_value, + infinity_value, + nan_value + ] + end + + it "returns self" do + @numbers.each do |number| + number.conjugate.should.equal?(number) + end + end end diff --git a/spec/ruby/core/numeric/imag_spec.rb b/spec/ruby/core/numeric/imag_spec.rb index b9e343cee9..761d6b0dbe 100644 --- a/spec/ruby/core/numeric/imag_spec.rb +++ b/spec/ruby/core/numeric/imag_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/imag' describe "Numeric#imag" do - it_behaves_like :numeric_imag, :imag + it "is an alias of Numeric#imaginary" do + Numeric.instance_method(:imag).should == Numeric.instance_method(:imaginary) + end end diff --git a/spec/ruby/core/numeric/imaginary_spec.rb b/spec/ruby/core/numeric/imaginary_spec.rb index ec708cb505..7b5d94cc75 100644 --- a/spec/ruby/core/numeric/imaginary_spec.rb +++ b/spec/ruby/core/numeric/imaginary_spec.rb @@ -1,6 +1,26 @@ require_relative '../../spec_helper' -require_relative 'shared/imag' describe "Numeric#imaginary" do - it_behaves_like :numeric_imag, :imaginary + before :each do + @numbers = [ + 20, # Integer + 398.72, # Float + Rational(3, 4), # Rational + bignum_value, # Bignum + infinity_value, + nan_value + ].map{|n| [n,-n]}.flatten + end + + it "returns 0" do + @numbers.each do |number| + number.imaginary.should == 0 + end + end + + it "raises an ArgumentError if given any arguments" do + @numbers.each do |number| + -> { number.imaginary(number) }.should.raise(ArgumentError) + end + end end diff --git a/spec/ruby/core/numeric/magnitude_spec.rb b/spec/ruby/core/numeric/magnitude_spec.rb index 1371dff21f..ea4dbd166f 100644 --- a/spec/ruby/core/numeric/magnitude_spec.rb +++ b/spec/ruby/core/numeric/magnitude_spec.rb @@ -1,6 +1,7 @@ require_relative "../../spec_helper" -require_relative 'shared/abs' describe "Numeric#magnitude" do - it_behaves_like :numeric_abs, :magnitude + it "is an alias of Numeric#abs" do + Numeric.instance_method(:magnitude).should == Numeric.instance_method(:abs) + end end diff --git a/spec/ruby/core/numeric/modulo_spec.rb b/spec/ruby/core/numeric/modulo_spec.rb index e3dc7e56f3..0baf96dc18 100644 --- a/spec/ruby/core/numeric/modulo_spec.rb +++ b/spec/ruby/core/numeric/modulo_spec.rb @@ -1,7 +1,12 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -describe :numeric_modulo_19, shared: true do +describe "Numeric#modulo" do + it "is an alias of Numeric#%" do + Numeric.instance_method(:modulo).should == Numeric.instance_method(:%) + end +end + +describe "Numeric#%" do it "returns self - other * self.div(other)" do s = mock_numeric('self') o = mock_numeric('other') @@ -11,14 +16,6 @@ describe :numeric_modulo_19, shared: true do s.should_receive(:div).with(o).and_return(n3) o.should_receive(:*).with(n3).and_return(n4) s.should_receive(:-).with(n4).and_return(n5) - s.send(@method, o).should == n5 + (s % o).should == n5 end end - -describe "Numeric#modulo" do - it_behaves_like :numeric_modulo_19, :modulo -end - -describe "Numeric#%" do - it_behaves_like :numeric_modulo_19, :% -end diff --git a/spec/ruby/core/numeric/phase_spec.rb b/spec/ruby/core/numeric/phase_spec.rb index bc1995303f..3abe8f2e02 100644 --- a/spec/ruby/core/numeric/phase_spec.rb +++ b/spec/ruby/core/numeric/phase_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/arg' describe "Numeric#phase" do - it_behaves_like :numeric_arg, :phase + it "is an alias of Numeric#arg" do + Numeric.instance_method(:phase).should == Numeric.instance_method(:arg) + end end diff --git a/spec/ruby/core/numeric/rect_spec.rb b/spec/ruby/core/numeric/rect_spec.rb index 79a144c5a4..65cdcc5229 100644 --- a/spec/ruby/core/numeric/rect_spec.rb +++ b/spec/ruby/core/numeric/rect_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/rect' describe "Numeric#rect" do - it_behaves_like :numeric_rect, :rect + it "is an alias of Numeric#rectangular" do + Numeric.instance_method(:rect).should == Numeric.instance_method(:rectangular) + end end diff --git a/spec/ruby/core/numeric/rectangular_spec.rb b/spec/ruby/core/numeric/rectangular_spec.rb index 2c68985a16..81afccc12d 100644 --- a/spec/ruby/core/numeric/rectangular_spec.rb +++ b/spec/ruby/core/numeric/rectangular_spec.rb @@ -1,6 +1,48 @@ require_relative '../../spec_helper' -require_relative 'shared/rect' describe "Numeric#rectangular" do - it_behaves_like :numeric_rect, :rectangular + before :each do + @numbers = [ + 20, # Integer + 398.72, # Float + Rational(3, 4), # Rational + 99999999**99, # Bignum + infinity_value, + nan_value + ] + end + + it "returns an Array" do + @numbers.each do |number| + number.rectangular.should.instance_of?(Array) + end + end + + it "returns a two-element Array" do + @numbers.each do |number| + number.rectangular.size.should == 2 + end + end + + it "returns self as the first element" do + @numbers.each do |number| + if Float === number and number.nan? + number.rectangular.first.nan?.should == true + else + number.rectangular.first.should == number + end + end + end + + it "returns 0 as the last element" do + @numbers.each do |number| + number.rectangular.last.should == 0 + end + end + + it "raises an ArgumentError if given any arguments" do + @numbers.each do |number| + -> { number.rectangular(number) }.should.raise(ArgumentError) + end + end end diff --git a/spec/ruby/core/numeric/shared/abs.rb b/spec/ruby/core/numeric/shared/abs.rb deleted file mode 100644 index c3dadccfd6..0000000000 --- a/spec/ruby/core/numeric/shared/abs.rb +++ /dev/null @@ -1,19 +0,0 @@ -require_relative '../../../spec_helper' -require_relative '../fixtures/classes' - -describe :numeric_abs, shared: true do - before :each do - @obj = NumericSpecs::Subclass.new - end - - it "returns self when self is greater than 0" do - @obj.should_receive(:<).with(0).and_return(false) - @obj.send(@method).should == @obj - end - - it "returns self\#@- when self is less than 0" do - @obj.should_receive(:<).with(0).and_return(true) - @obj.should_receive(:-@).and_return(:absolute_value) - @obj.send(@method).should == :absolute_value - end -end diff --git a/spec/ruby/core/numeric/shared/arg.rb b/spec/ruby/core/numeric/shared/arg.rb deleted file mode 100644 index c8e7ad8333..0000000000 --- a/spec/ruby/core/numeric/shared/arg.rb +++ /dev/null @@ -1,38 +0,0 @@ -require_relative '../../../spec_helper' - -describe :numeric_arg, shared: true do - before :each do - @numbers = [ - 20, - Rational(3, 4), - bignum_value, - infinity_value - ] - end - - it "returns 0 if positive" do - @numbers.each do |number| - number.send(@method).should == 0 - end - end - - it "returns Pi if negative" do - @numbers.each do |number| - (0-number).send(@method).should == Math::PI - end - end - - describe "with a Numeric subclass" do - it "returns 0 if self#<(0) returns false" do - numeric = mock_numeric('positive') - numeric.should_receive(:<).with(0).and_return(false) - numeric.send(@method).should == 0 - end - - it "returns Pi if self#<(0) returns true" do - numeric = mock_numeric('positive') - numeric.should_receive(:<).with(0).and_return(true) - numeric.send(@method).should == Math::PI - end - end -end diff --git a/spec/ruby/core/numeric/shared/conj.rb b/spec/ruby/core/numeric/shared/conj.rb deleted file mode 100644 index 1a661fbbe8..0000000000 --- a/spec/ruby/core/numeric/shared/conj.rb +++ /dev/null @@ -1,20 +0,0 @@ -require_relative '../../../spec_helper' - -describe :numeric_conj, shared: true do - before :each do - @numbers = [ - 20, # Integer - 398.72, # Float - Rational(3, 4), # Rational - bignum_value, - infinity_value, - nan_value - ] - end - - it "returns self" do - @numbers.each do |number| - number.send(@method).should.equal?(number) - end - end -end diff --git a/spec/ruby/core/numeric/shared/imag.rb b/spec/ruby/core/numeric/shared/imag.rb deleted file mode 100644 index 605a23d8c6..0000000000 --- a/spec/ruby/core/numeric/shared/imag.rb +++ /dev/null @@ -1,26 +0,0 @@ -require_relative '../../../spec_helper' - -describe :numeric_imag, shared: true do - before :each do - @numbers = [ - 20, # Integer - 398.72, # Float - Rational(3, 4), # Rational - bignum_value, # Bignum - infinity_value, - nan_value - ].map{|n| [n,-n]}.flatten - end - - it "returns 0" do - @numbers.each do |number| - number.send(@method).should == 0 - end - end - - it "raises an ArgumentError if given any arguments" do - @numbers.each do |number| - -> { number.send(@method, number) }.should.raise(ArgumentError) - end - end -end diff --git a/spec/ruby/core/numeric/shared/rect.rb b/spec/ruby/core/numeric/shared/rect.rb deleted file mode 100644 index 32d03e45d2..0000000000 --- a/spec/ruby/core/numeric/shared/rect.rb +++ /dev/null @@ -1,48 +0,0 @@ -require_relative '../../../spec_helper' - -describe :numeric_rect, shared: true do - before :each do - @numbers = [ - 20, # Integer - 398.72, # Float - Rational(3, 4), # Rational - 99999999**99, # Bignum - infinity_value, - nan_value - ] - end - - it "returns an Array" do - @numbers.each do |number| - number.send(@method).should.instance_of?(Array) - end - end - - it "returns a two-element Array" do - @numbers.each do |number| - number.send(@method).size.should == 2 - end - end - - it "returns self as the first element" do - @numbers.each do |number| - if Float === number and number.nan? - number.send(@method).first.nan?.should == true - else - number.send(@method).first.should == number - end - end - end - - it "returns 0 as the last element" do - @numbers.each do |number| - number.send(@method).last.should == 0 - end - end - - it "raises an ArgumentError if given any arguments" do - @numbers.each do |number| - -> { number.send(@method, number) }.should.raise(ArgumentError) - end - end -end diff --git a/spec/ruby/core/objectspace/weakmap/each_pair_spec.rb b/spec/ruby/core/objectspace/weakmap/each_pair_spec.rb index ea29edbd2f..272669ad0a 100644 --- a/spec/ruby/core/objectspace/weakmap/each_pair_spec.rb +++ b/spec/ruby/core/objectspace/weakmap/each_pair_spec.rb @@ -1,11 +1,8 @@ require_relative '../../../spec_helper' -require_relative 'shared/members' -require_relative 'shared/each' describe "ObjectSpace::WeakMap#each_pair" do - it_behaves_like :weakmap_members, -> map { a = []; map.each_pair{ |k,v| a << "#{k}#{v}" }; a }, %w[Ax By] -end - -describe "ObjectSpace::WeakMap#each_key" do - it_behaves_like :weakmap_each, :each_pair + it "is an alias of ObjectSpace::WeakMap#each" do + ObjectSpace::WeakMap.instance_method(:each_pair).should == + ObjectSpace::WeakMap.instance_method(:each) + end end diff --git a/spec/ruby/core/objectspace/weakmap/each_spec.rb b/spec/ruby/core/objectspace/weakmap/each_spec.rb index 46fcb66a6f..8493a36158 100644 --- a/spec/ruby/core/objectspace/weakmap/each_spec.rb +++ b/spec/ruby/core/objectspace/weakmap/each_spec.rb @@ -6,6 +6,6 @@ describe "ObjectSpace::WeakMap#each" do it_behaves_like :weakmap_members, -> map { a = []; map.each{ |k,v| a << "#{k}#{v}" }; a }, %w[Ax By] end -describe "ObjectSpace::WeakMap#each_key" do +describe "ObjectSpace::WeakMap#each" do it_behaves_like :weakmap_each, :each end diff --git a/spec/ruby/core/objectspace/weakmap/each_value_spec.rb b/spec/ruby/core/objectspace/weakmap/each_value_spec.rb index 65a1a7f6fe..89f2f6ae98 100644 --- a/spec/ruby/core/objectspace/weakmap/each_value_spec.rb +++ b/spec/ruby/core/objectspace/weakmap/each_value_spec.rb @@ -6,6 +6,6 @@ describe "ObjectSpace::WeakMap#each_value" do it_behaves_like :weakmap_members, -> map { a = []; map.each_value{ |k| a << k }; a }, %w[x y] end -describe "ObjectSpace::WeakMap#each_key" do +describe "ObjectSpace::WeakMap#each_value" do it_behaves_like :weakmap_each, :each_value end diff --git a/spec/ruby/core/objectspace/weakmap/include_spec.rb b/spec/ruby/core/objectspace/weakmap/include_spec.rb index 54ca6b3030..1affaef907 100644 --- a/spec/ruby/core/objectspace/weakmap/include_spec.rb +++ b/spec/ruby/core/objectspace/weakmap/include_spec.rb @@ -1,6 +1,32 @@ require_relative '../../../spec_helper' -require_relative 'shared/include' describe "ObjectSpace::WeakMap#include?" do - it_behaves_like :weakmap_include?, :include? + it "recognizes keys in use" do + map = ObjectSpace::WeakMap.new + key1, key2 = %w[a b].map(&:upcase) + ref1, ref2 = %w[x y] + + map[key1] = ref1 + map.include?(key1).should == true + map[key1] = ref1 + map.include?(key1).should == true + map[key2] = ref2 + map.include?(key2).should == true + end + + it "matches using identity semantics" do + map = ObjectSpace::WeakMap.new + key1, key2 = %w[a a].map(&:upcase) + ref = "x" + map[key1] = ref + map.include?(key2).should == false + end + + it "reports true if the pair exists and the value is nil" do + map = ObjectSpace::WeakMap.new + key = Object.new + map[key] = nil + map.size.should == 1 + map.include?(key).should == true + end end diff --git a/spec/ruby/core/objectspace/weakmap/key_spec.rb b/spec/ruby/core/objectspace/weakmap/key_spec.rb index 999685ff95..5d38f1fa5f 100644 --- a/spec/ruby/core/objectspace/weakmap/key_spec.rb +++ b/spec/ruby/core/objectspace/weakmap/key_spec.rb @@ -1,6 +1,8 @@ require_relative '../../../spec_helper' -require_relative 'shared/include' describe "ObjectSpace::WeakMap#key?" do - it_behaves_like :weakmap_include?, :key? + it "is an alias of ObjectSpace::WeakMap#include?" do + ObjectSpace::WeakMap.instance_method(:key?).should == + ObjectSpace::WeakMap.instance_method(:include?) + end end diff --git a/spec/ruby/core/objectspace/weakmap/length_spec.rb b/spec/ruby/core/objectspace/weakmap/length_spec.rb index 3a935648b1..8ad47aa9d6 100644 --- a/spec/ruby/core/objectspace/weakmap/length_spec.rb +++ b/spec/ruby/core/objectspace/weakmap/length_spec.rb @@ -1,6 +1,8 @@ require_relative '../../../spec_helper' -require_relative 'shared/size' describe "ObjectSpace::WeakMap#length" do - it_behaves_like :weakmap_size, :length + it "is an alias of ObjectSpace::WeakMap#size" do + ObjectSpace::WeakMap.instance_method(:length).should == + ObjectSpace::WeakMap.instance_method(:size) + end end diff --git a/spec/ruby/core/objectspace/weakmap/member_spec.rb b/spec/ruby/core/objectspace/weakmap/member_spec.rb index cefb190ce7..eaf9a76285 100644 --- a/spec/ruby/core/objectspace/weakmap/member_spec.rb +++ b/spec/ruby/core/objectspace/weakmap/member_spec.rb @@ -1,6 +1,8 @@ require_relative '../../../spec_helper' -require_relative 'shared/include' describe "ObjectSpace::WeakMap#member?" do - it_behaves_like :weakmap_include?, :member? + it "is an alias of ObjectSpace::WeakMap#include?" do + ObjectSpace::WeakMap.instance_method(:member?).should == + ObjectSpace::WeakMap.instance_method(:include?) + end end diff --git a/spec/ruby/core/objectspace/weakmap/shared/include.rb b/spec/ruby/core/objectspace/weakmap/shared/include.rb deleted file mode 100644 index 1770eeac8b..0000000000 --- a/spec/ruby/core/objectspace/weakmap/shared/include.rb +++ /dev/null @@ -1,30 +0,0 @@ -describe :weakmap_include?, shared: true do - it "recognizes keys in use" do - map = ObjectSpace::WeakMap.new - key1, key2 = %w[a b].map(&:upcase) - ref1, ref2 = %w[x y] - - map[key1] = ref1 - map.send(@method, key1).should == true - map[key1] = ref1 - map.send(@method, key1).should == true - map[key2] = ref2 - map.send(@method, key2).should == true - end - - it "matches using identity semantics" do - map = ObjectSpace::WeakMap.new - key1, key2 = %w[a a].map(&:upcase) - ref = "x" - map[key1] = ref - map.send(@method, key2).should == false - end - - it "reports true if the pair exists and the value is nil" do - map = ObjectSpace::WeakMap.new - key = Object.new - map[key] = nil - map.size.should == 1 - map.send(@method, key).should == true - end -end diff --git a/spec/ruby/core/objectspace/weakmap/shared/size.rb b/spec/ruby/core/objectspace/weakmap/shared/size.rb deleted file mode 100644 index 1064f99d1b..0000000000 --- a/spec/ruby/core/objectspace/weakmap/shared/size.rb +++ /dev/null @@ -1,14 +0,0 @@ -describe :weakmap_size, shared: true do - it "is correct" do - map = ObjectSpace::WeakMap.new - key1, key2 = %w[a b].map(&:upcase) - ref1, ref2 = %w[x y] - map.send(@method).should == 0 - map[key1] = ref1 - map.send(@method).should == 1 - map[key1] = ref1 - map.send(@method).should == 1 - map[key2] = ref2 - map.send(@method).should == 2 - end -end diff --git a/spec/ruby/core/objectspace/weakmap/size_spec.rb b/spec/ruby/core/objectspace/weakmap/size_spec.rb index 1446abaa24..d301750c62 100644 --- a/spec/ruby/core/objectspace/weakmap/size_spec.rb +++ b/spec/ruby/core/objectspace/weakmap/size_spec.rb @@ -1,6 +1,16 @@ require_relative '../../../spec_helper' -require_relative 'shared/size' describe "ObjectSpace::WeakMap#size" do - it_behaves_like :weakmap_size, :size + it "is correct" do + map = ObjectSpace::WeakMap.new + key1, key2 = %w[a b].map(&:upcase) + ref1, ref2 = %w[x y] + map.size.should == 0 + map[key1] = ref1 + map.size.should == 1 + map[key1] = ref1 + map.size.should == 1 + map[key2] = ref2 + map.size.should == 2 + end end diff --git a/spec/ruby/core/proc/call_spec.rb b/spec/ruby/core/proc/call_spec.rb index 6ec2fc8682..8b65be97c9 100644 --- a/spec/ruby/core/proc/call_spec.rb +++ b/spec/ruby/core/proc/call_spec.rb @@ -1,16 +1,138 @@ require_relative '../../spec_helper' -require_relative 'shared/call' -require_relative 'shared/call_arguments' +require_relative 'fixtures/common' +require_relative 'fixtures/proc_call' +require_relative 'fixtures/proc_call_frozen' describe "Proc#call" do - it_behaves_like :proc_call, :call - it_behaves_like :proc_call_block_args, :call -end + it "invokes self" do + Proc.new { "test!" }.call.should == "test!" + -> { "test!" }.call.should == "test!" + proc { "test!" }.call.should == "test!" + end -describe "Proc#call on a Proc created with Proc.new" do - it_behaves_like :proc_call_on_proc_new, :call -end + it "sets self's parameters to the given values" do + Proc.new { |a, b| a + b }.call(1, 2).should == 3 + Proc.new { |*args| args }.call(1, 2, 3, 4).should == [1, 2, 3, 4] + Proc.new { |_, *args| args }.call(1, 2, 3).should == [2, 3] + + -> a, b { a + b }.call(1, 2).should == 3 + -> *args { args }.call(1, 2, 3, 4).should == [1, 2, 3, 4] + -> _, *args { args }.call(1, 2, 3).should == [2, 3] + + proc { |a, b| a + b }.call(1, 2).should == 3 + proc { |*args| args }.call(1, 2, 3, 4).should == [1, 2, 3, 4] + proc { |_, *args| args }.call(1, 2, 3).should == [2, 3] + end + + it "can receive block arguments" do + Proc.new {|&b| b.call}.call {1 + 1}.should == 2 + -> &b { b.call}.call {1 + 1}.should == 2 + proc {|&b| b.call}.call {1 + 1}.should == 2 + end + + it "yields to the block given at declaration and not to the block argument" do + proc_creator = Object.new + def proc_creator.create + Proc.new do |&b| + yield + end + end + a_proc = proc_creator.create { 7 } + a_proc.call { 3 }.should == 7 + end + + it "can call its block argument declared with a block argument" do + proc_creator = Object.new + def proc_creator.create(method_name) + Proc.new do |&b| + yield + b.send(method_name) + end + end + a_proc = proc_creator.create(:call) { 7 } + a_proc.call { 3 }.should == 10 + end + + describe "on a Proc created with frozen_string_literal: true/false" do + it "doesn't duplicate frozen strings" do + ProcCallSpecs.call.frozen?.should == false + ProcCallSpecs.call_freeze.frozen?.should == true + ProcCallFrozenSpecs.call.frozen?.should == true + ProcCallFrozenSpecs.call_freeze.frozen?.should == true + end + end + + context "on a Proc created with Proc.new" do + it "replaces missing arguments with nil" do + Proc.new { |a, b| [a, b] }.call.should == [nil, nil] + Proc.new { |a, b| [a, b] }.call(1).should == [1, nil] + end + + it "silently ignores extra arguments" do + Proc.new { |a, b| a + b }.call(1, 2, 5).should == 3 + end + + it "auto-explodes a single Array argument" do + p = Proc.new { |a, b| [a, b] } + p.call(1, 2).should == [1, 2] + p.call([1, 2]).should == [1, 2] + p.call([1, 2, 3]).should == [1, 2] + p.call([1, 2, 3], 4).should == [[1, 2, 3], 4] + end + end + + context "on a Proc created with Kernel#lambda or Kernel#proc" do + it "ignores excess arguments when self is a proc" do + a = proc {|x| x}.call(1, 2) + a.should == 1 + + a = proc {|x| x}.call(1, 2, 3) + a.should == 1 + + a = proc {|x:| x}.call(2, x: 1) + a.should == 1 + end + + it "will call #to_ary on argument and return self if return is nil" do + argument = ProcSpecs::ToAryAsNil.new + result = proc { |x, _| x }.call(argument) + result.should == argument + end + + it "substitutes nil for missing arguments when self is a proc" do + proc {|x,y| [x,y]}.call.should == [nil,nil] + + a = proc {|x,y| [x, y]}.call(1) + a.should == [1,nil] + end + + it "raises an ArgumentError on excess arguments when self is a lambda" do + -> { + -> x { x }.call(1, 2) + }.should.raise(ArgumentError) + + -> { + -> x { x }.call(1, 2, 3) + }.should.raise(ArgumentError) + end + + it "raises an ArgumentError on missing arguments when self is a lambda" do + -> { + -> x { x }.call + }.should.raise(ArgumentError) + + -> { + -> x, y { [x,y] }.call(1) + }.should.raise(ArgumentError) + end + + it "treats a single Array argument as a single argument when self is a lambda" do + -> a { a }.call([1, 2]).should == [1, 2] + -> a, b { [a, b] }.call([1, 2], 3).should == [[1,2], 3] + end -describe "Proc#call on a Proc created with Kernel#lambda or Kernel#proc" do - it_behaves_like :proc_call_on_proc_or_lambda, :call + it "treats a single Array argument as a single argument when self is a proc" do + proc { |a| a }.call([1, 2]).should == [1, 2] + proc { |a, b| [a, b] }.call([1, 2], 3).should == [[1,2], 3] + end + end end diff --git a/spec/ruby/core/proc/case_compare_spec.rb b/spec/ruby/core/proc/case_compare_spec.rb index f11513cdb9..421afb24f0 100644 --- a/spec/ruby/core/proc/case_compare_spec.rb +++ b/spec/ruby/core/proc/case_compare_spec.rb @@ -1,16 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/call' -require_relative 'shared/call_arguments' describe "Proc#===" do - it_behaves_like :proc_call, :=== - it_behaves_like :proc_call_block_args, :=== -end - -describe "Proc#=== on a Proc created with Proc.new" do - it_behaves_like :proc_call_on_proc_new, :=== -end - -describe "Proc#=== on a Proc created with Kernel#lambda or Kernel#proc" do - it_behaves_like :proc_call_on_proc_or_lambda, :=== + it "is an alias of Proc#call" do + Proc.instance_method(:===).should == Proc.instance_method(:call) + end end diff --git a/spec/ruby/core/proc/element_reference_spec.rb b/spec/ruby/core/proc/element_reference_spec.rb index ea3a915a11..ac14292464 100644 --- a/spec/ruby/core/proc/element_reference_spec.rb +++ b/spec/ruby/core/proc/element_reference_spec.rb @@ -1,27 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/call' -require_relative 'shared/call_arguments' -require_relative 'fixtures/proc_aref' -require_relative 'fixtures/proc_aref_frozen' describe "Proc#[]" do - it_behaves_like :proc_call, :[] - it_behaves_like :proc_call_block_args, :[] -end - -describe "Proc#call on a Proc created with Proc.new" do - it_behaves_like :proc_call_on_proc_new, :call -end - -describe "Proc#call on a Proc created with Kernel#lambda or Kernel#proc" do - it_behaves_like :proc_call_on_proc_or_lambda, :call -end - -describe "Proc#[] with frozen_string_literal: true/false" do - it "doesn't duplicate frozen strings" do - ProcArefSpecs.aref.frozen?.should == false - ProcArefSpecs.aref_freeze.frozen?.should == true - ProcArefFrozenSpecs.aref.frozen?.should == true - ProcArefFrozenSpecs.aref_freeze.frozen?.should == true + it "is an alias of Proc#call" do + Proc.instance_method(:[]).should == Proc.instance_method(:call) end end diff --git a/spec/ruby/core/proc/eql_spec.rb b/spec/ruby/core/proc/eql_spec.rb index ad8f6749fc..1a5fb42a0e 100644 --- a/spec/ruby/core/proc/eql_spec.rb +++ b/spec/ruby/core/proc/eql_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/equal' describe "Proc#eql?" do - it_behaves_like :proc_equal, :eql? + it "is an alias of Proc#==" do + Proc.instance_method(:eql?).should == Proc.instance_method(:==) + end end diff --git a/spec/ruby/core/proc/equal_value_spec.rb b/spec/ruby/core/proc/equal_value_spec.rb index ec7f274732..92e462152e 100644 --- a/spec/ruby/core/proc/equal_value_spec.rb +++ b/spec/ruby/core/proc/equal_value_spec.rb @@ -1,6 +1,83 @@ require_relative '../../spec_helper' -require_relative 'shared/equal' +require_relative 'fixtures/common' describe "Proc#==" do - it_behaves_like :proc_equal, :== + it "is a public method" do + Proc.public_instance_methods(false).should.include?(:==) + end + + it "returns true if self and other are the same object" do + p = proc { :foo } + (p == p).should == true + + p = Proc.new { :foo } + (p == p).should == true + + p = -> { :foo } + (p == p).should == true + end + + it "returns true if other is a dup of the original" do + p = proc { :foo } + (p == p.dup).should == true + + p = Proc.new { :foo } + (p == p.dup).should == true + + p = -> { :foo } + (p == p.dup).should == true + end + + # identical here means the same method invocation. + it "returns false when bodies are the same but capture env is not identical" do + a = ProcSpecs.proc_for_1 + b = ProcSpecs.proc_for_1 + + (a == b).should == false + end + + it "returns false if procs are distinct but have the same body and environment" do + p = proc { :foo } + p2 = proc { :foo } + (p == p2).should == false + end + + it "returns false if lambdas are distinct but have same body and environment" do + x = -> { :foo } + x2 = -> { :foo } + (x == x2).should == false + end + + it "returns false if using comparing lambda to proc, even with the same body and env" do + p = -> { :foo } + p2 = proc { :foo } + (p == p2).should == false + + x = proc { :bar } + x2 = -> { :bar } + (x == x2).should == false + end + + it "returns false if other is not a Proc" do + p = proc { :foo } + (p == []).should == false + + p = Proc.new { :foo } + (p == Object.new).should == false + + p = -> { :foo } + (p == :foo).should == false + end + + it "returns false if self and other are both procs but have different bodies" do + p = proc { :bar } + p2 = proc { :foo } + (p == p2).should == false + end + + it "returns false if self and other are both lambdas but have different bodies" do + p = -> { :foo } + p2 = -> { :bar } + (p == p2).should == false + end end diff --git a/spec/ruby/core/proc/fixtures/proc_aref.rb b/spec/ruby/core/proc/fixtures/proc_aref.rb deleted file mode 100644 index 8ee355b14c..0000000000 --- a/spec/ruby/core/proc/fixtures/proc_aref.rb +++ /dev/null @@ -1,10 +0,0 @@ -# frozen_string_literal: false -module ProcArefSpecs - def self.aref - proc {|a| a }["sometext"] - end - - def self.aref_freeze - proc {|a| a }["sometext".freeze] - end -end diff --git a/spec/ruby/core/proc/fixtures/proc_aref_frozen.rb b/spec/ruby/core/proc/fixtures/proc_aref_frozen.rb deleted file mode 100644 index 50a330ba4f..0000000000 --- a/spec/ruby/core/proc/fixtures/proc_aref_frozen.rb +++ /dev/null @@ -1,10 +0,0 @@ -# frozen_string_literal: true -module ProcArefFrozenSpecs - def self.aref - proc {|a| a }["sometext"] - end - - def self.aref_freeze - proc {|a| a }["sometext".freeze] - end -end diff --git a/spec/ruby/core/proc/fixtures/proc_call.rb b/spec/ruby/core/proc/fixtures/proc_call.rb new file mode 100644 index 0000000000..32048f5319 --- /dev/null +++ b/spec/ruby/core/proc/fixtures/proc_call.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: false +module ProcCallSpecs + def self.call + proc {|a| a }.call("sometext") + end + + def self.call_freeze + proc {|a| a }.call("sometext".freeze) + end +end diff --git a/spec/ruby/core/proc/fixtures/proc_call_frozen.rb b/spec/ruby/core/proc/fixtures/proc_call_frozen.rb new file mode 100644 index 0000000000..29ffc3c4c9 --- /dev/null +++ b/spec/ruby/core/proc/fixtures/proc_call_frozen.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true +module ProcCallFrozenSpecs + def self.call + proc {|a| a }.call("sometext") + end + + def self.call_freeze + proc {|a| a }.call("sometext".freeze) + end +end diff --git a/spec/ruby/core/proc/inspect_spec.rb b/spec/ruby/core/proc/inspect_spec.rb index f53d34116f..96995ec410 100644 --- a/spec/ruby/core/proc/inspect_spec.rb +++ b/spec/ruby/core/proc/inspect_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/to_s' describe "Proc#inspect" do - it_behaves_like :proc_to_s, :inspect + it "is an alias of Proc#to_s" do + Proc.instance_method(:inspect).should == Proc.instance_method(:to_s) + end end diff --git a/spec/ruby/core/proc/shared/call.rb b/spec/ruby/core/proc/shared/call.rb deleted file mode 100644 index fae2331b68..0000000000 --- a/spec/ruby/core/proc/shared/call.rb +++ /dev/null @@ -1,99 +0,0 @@ -require_relative '../fixtures/common' - -describe :proc_call, shared: true do - it "invokes self" do - Proc.new { "test!" }.send(@method).should == "test!" - -> { "test!" }.send(@method).should == "test!" - proc { "test!" }.send(@method).should == "test!" - end - - it "sets self's parameters to the given values" do - Proc.new { |a, b| a + b }.send(@method, 1, 2).should == 3 - Proc.new { |*args| args }.send(@method, 1, 2, 3, 4).should == [1, 2, 3, 4] - Proc.new { |_, *args| args }.send(@method, 1, 2, 3).should == [2, 3] - - -> a, b { a + b }.send(@method, 1, 2).should == 3 - -> *args { args }.send(@method, 1, 2, 3, 4).should == [1, 2, 3, 4] - -> _, *args { args }.send(@method, 1, 2, 3).should == [2, 3] - - proc { |a, b| a + b }.send(@method, 1, 2).should == 3 - proc { |*args| args }.send(@method, 1, 2, 3, 4).should == [1, 2, 3, 4] - proc { |_, *args| args }.send(@method, 1, 2, 3).should == [2, 3] - end -end - - -describe :proc_call_on_proc_new, shared: true do - it "replaces missing arguments with nil" do - Proc.new { |a, b| [a, b] }.send(@method).should == [nil, nil] - Proc.new { |a, b| [a, b] }.send(@method, 1).should == [1, nil] - end - - it "silently ignores extra arguments" do - Proc.new { |a, b| a + b }.send(@method, 1, 2, 5).should == 3 - end - - it "auto-explodes a single Array argument" do - p = Proc.new { |a, b| [a, b] } - p.send(@method, 1, 2).should == [1, 2] - p.send(@method, [1, 2]).should == [1, 2] - p.send(@method, [1, 2, 3]).should == [1, 2] - p.send(@method, [1, 2, 3], 4).should == [[1, 2, 3], 4] - end -end - -describe :proc_call_on_proc_or_lambda, shared: true do - it "ignores excess arguments when self is a proc" do - a = proc {|x| x}.send(@method, 1, 2) - a.should == 1 - - a = proc {|x| x}.send(@method, 1, 2, 3) - a.should == 1 - - a = proc {|x:| x}.send(@method, 2, x: 1) - a.should == 1 - end - - it "will call #to_ary on argument and return self if return is nil" do - argument = ProcSpecs::ToAryAsNil.new - result = proc { |x, _| x }.send(@method, argument) - result.should == argument - end - - it "substitutes nil for missing arguments when self is a proc" do - proc {|x,y| [x,y]}.send(@method).should == [nil,nil] - - a = proc {|x,y| [x, y]}.send(@method, 1) - a.should == [1,nil] - end - - it "raises an ArgumentError on excess arguments when self is a lambda" do - -> { - -> x { x }.send(@method, 1, 2) - }.should.raise(ArgumentError) - - -> { - -> x { x }.send(@method, 1, 2, 3) - }.should.raise(ArgumentError) - end - - it "raises an ArgumentError on missing arguments when self is a lambda" do - -> { - -> x { x }.send(@method) - }.should.raise(ArgumentError) - - -> { - -> x, y { [x,y] }.send(@method, 1) - }.should.raise(ArgumentError) - end - - it "treats a single Array argument as a single argument when self is a lambda" do - -> a { a }.send(@method, [1, 2]).should == [1, 2] - -> a, b { [a, b] }.send(@method, [1, 2], 3).should == [[1,2], 3] - end - - it "treats a single Array argument as a single argument when self is a proc" do - proc { |a| a }.send(@method, [1, 2]).should == [1, 2] - proc { |a, b| [a, b] }.send(@method, [1, 2], 3).should == [[1,2], 3] - end -end diff --git a/spec/ruby/core/proc/shared/call_arguments.rb b/spec/ruby/core/proc/shared/call_arguments.rb deleted file mode 100644 index 91ada3439e..0000000000 --- a/spec/ruby/core/proc/shared/call_arguments.rb +++ /dev/null @@ -1,29 +0,0 @@ -describe :proc_call_block_args, shared: true do - it "can receive block arguments" do - Proc.new {|&b| b.send(@method)}.send(@method) {1 + 1}.should == 2 - -> &b { b.send(@method)}.send(@method) {1 + 1}.should == 2 - proc {|&b| b.send(@method)}.send(@method) {1 + 1}.should == 2 - end - - it "yields to the block given at declaration and not to the block argument" do - proc_creator = Object.new - def proc_creator.create - Proc.new do |&b| - yield - end - end - a_proc = proc_creator.create { 7 } - a_proc.send(@method) { 3 }.should == 7 - end - - it "can call its block argument declared with a block argument" do - proc_creator = Object.new - def proc_creator.create(method_name) - Proc.new do |&b| - yield + b.send(method_name) - end - end - a_proc = proc_creator.create(@method) { 7 } - a_proc.call { 3 }.should == 10 - end -end diff --git a/spec/ruby/core/proc/shared/equal.rb b/spec/ruby/core/proc/shared/equal.rb deleted file mode 100644 index 4f6f6c41be..0000000000 --- a/spec/ruby/core/proc/shared/equal.rb +++ /dev/null @@ -1,83 +0,0 @@ -require_relative '../../../spec_helper' -require_relative '../fixtures/common' - -describe :proc_equal, shared: true do - it "is a public method" do - Proc.public_instance_methods(false).should.include?(@method) - end - - it "returns true if self and other are the same object" do - p = proc { :foo } - p.send(@method, p).should == true - - p = Proc.new { :foo } - p.send(@method, p).should == true - - p = -> { :foo } - p.send(@method, p).should == true - end - - it "returns true if other is a dup of the original" do - p = proc { :foo } - p.send(@method, p.dup).should == true - - p = Proc.new { :foo } - p.send(@method, p.dup).should == true - - p = -> { :foo } - p.send(@method, p.dup).should == true - end - - # identical here means the same method invocation. - it "returns false when bodies are the same but capture env is not identical" do - a = ProcSpecs.proc_for_1 - b = ProcSpecs.proc_for_1 - - a.send(@method, b).should == false - end - - it "returns false if procs are distinct but have the same body and environment" do - p = proc { :foo } - p2 = proc { :foo } - p.send(@method, p2).should == false - end - - it "returns false if lambdas are distinct but have same body and environment" do - x = -> { :foo } - x2 = -> { :foo } - x.send(@method, x2).should == false - end - - it "returns false if using comparing lambda to proc, even with the same body and env" do - p = -> { :foo } - p2 = proc { :foo } - p.send(@method, p2).should == false - - x = proc { :bar } - x2 = -> { :bar } - x.send(@method, x2).should == false - end - - it "returns false if other is not a Proc" do - p = proc { :foo } - p.send(@method, []).should == false - - p = Proc.new { :foo } - p.send(@method, Object.new).should == false - - p = -> { :foo } - p.send(@method, :foo).should == false - end - - it "returns false if self and other are both procs but have different bodies" do - p = proc { :bar } - p2 = proc { :foo } - p.send(@method, p2).should == false - end - - it "returns false if self and other are both lambdas but have different bodies" do - p = -> { :foo } - p2 = -> { :bar } - p.send(@method, p2).should == false - end -end diff --git a/spec/ruby/core/proc/shared/to_s.rb b/spec/ruby/core/proc/shared/to_s.rb deleted file mode 100644 index a52688a89f..0000000000 --- a/spec/ruby/core/proc/shared/to_s.rb +++ /dev/null @@ -1,60 +0,0 @@ -describe :proc_to_s, shared: true do - describe "for a proc created with Proc.new" do - it "returns a description including file and line number" do - Proc.new { "hello" }.send(@method).should =~ /^#<Proc:([^ ]*?) #{Regexp.escape __FILE__}:#{__LINE__ }>$/ - end - - it "has a binary encoding" do - Proc.new { "hello" }.send(@method).encoding.should == Encoding::BINARY - end - end - - describe "for a proc created with lambda" do - it "returns a description including '(lambda)' and including file and line number" do - -> { "hello" }.send(@method).should =~ /^#<Proc:([^ ]*?) #{Regexp.escape __FILE__}:#{__LINE__ } \(lambda\)>$/ - end - - it "has a binary encoding" do - -> { "hello" }.send(@method).encoding.should == Encoding::BINARY - end - end - - describe "for a proc created with proc" do - it "returns a description including file and line number" do - proc { "hello" }.send(@method).should =~ /^#<Proc:([^ ]*?) #{Regexp.escape __FILE__}:#{__LINE__ }>$/ - end - - it "has a binary encoding" do - proc { "hello" }.send(@method).encoding.should == Encoding::BINARY - end - end - - describe "for a proc created with UnboundMethod#to_proc" do - it "returns a description including '(lambda)' and optionally including file and line number" do - def hello; end - s = method("hello").to_proc.send(@method) - if s.include? __FILE__ - s.should =~ /^#<Proc:([^ ]*?) #{Regexp.escape __FILE__}:#{__LINE__ - 3} \(lambda\)>$/ - else - s.should =~ /^#<Proc:([^ ]*?) \(lambda\)>$/ - end - end - - it "has a binary encoding" do - def hello; end - method("hello").to_proc.send(@method).encoding.should == Encoding::BINARY - end - end - - describe "for a proc created with Symbol#to_proc" do - it "returns a description including '(&:symbol)'" do - proc = :foobar.to_proc - proc.send(@method).should.include?('(&:foobar)') - end - - it "has a binary encoding" do - proc = :foobar.to_proc - proc.send(@method).encoding.should == Encoding::BINARY - end - end -end diff --git a/spec/ruby/core/proc/to_s_spec.rb b/spec/ruby/core/proc/to_s_spec.rb index 5e9c46b6b8..58a9aa76fb 100644 --- a/spec/ruby/core/proc/to_s_spec.rb +++ b/spec/ruby/core/proc/to_s_spec.rb @@ -1,6 +1,62 @@ require_relative '../../spec_helper' -require_relative 'shared/to_s' describe "Proc#to_s" do - it_behaves_like :proc_to_s, :to_s + describe "for a proc created with Proc.new" do + it "returns a description including file and line number" do + Proc.new { "hello" }.to_s.should =~ /^#<Proc:([^ ]*?) #{Regexp.escape __FILE__}:#{__LINE__ }>$/ + end + + it "has a binary encoding" do + Proc.new { "hello" }.to_s.encoding.should == Encoding::BINARY + end + end + + describe "for a proc created with lambda" do + it "returns a description including '(lambda)' and including file and line number" do + -> { "hello" }.to_s.should =~ /^#<Proc:([^ ]*?) #{Regexp.escape __FILE__}:#{__LINE__ } \(lambda\)>$/ + end + + it "has a binary encoding" do + -> { "hello" }.to_s.encoding.should == Encoding::BINARY + end + end + + describe "for a proc created with proc" do + it "returns a description including file and line number" do + proc { "hello" }.to_s.should =~ /^#<Proc:([^ ]*?) #{Regexp.escape __FILE__}:#{__LINE__ }>$/ + end + + it "has a binary encoding" do + proc { "hello" }.to_s.encoding.should == Encoding::BINARY + end + end + + describe "for a proc created with UnboundMethod#to_proc" do + it "returns a description including '(lambda)' and optionally including file and line number" do + def hello; end + s = method("hello").to_proc.to_s + if s.include? __FILE__ + s.should =~ /^#<Proc:([^ ]*?) #{Regexp.escape __FILE__}:#{__LINE__ - 3} \(lambda\)>$/ + else + s.should =~ /^#<Proc:([^ ]*?) \(lambda\)>$/ + end + end + + it "has a binary encoding" do + def hello; end + method("hello").to_proc.to_s.encoding.should == Encoding::BINARY + end + end + + describe "for a proc created with Symbol#to_proc" do + it "returns a description including '(&:symbol)'" do + proc = :foobar.to_proc + proc.to_s.should.include?('(&:foobar)') + end + + it "has a binary encoding" do + proc = :foobar.to_proc + proc.to_s.encoding.should == Encoding::BINARY + end + end end diff --git a/spec/ruby/core/proc/yield_spec.rb b/spec/ruby/core/proc/yield_spec.rb index 365d5b04bd..e6ee2d5eff 100644 --- a/spec/ruby/core/proc/yield_spec.rb +++ b/spec/ruby/core/proc/yield_spec.rb @@ -1,16 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/call' -require_relative 'shared/call_arguments' describe "Proc#yield" do - it_behaves_like :proc_call, :yield - it_behaves_like :proc_call_block_args, :yield -end - -describe "Proc#yield on a Proc created with Proc.new" do - it_behaves_like :proc_call_on_proc_new, :yield -end - -describe "Proc#yield on a Proc created with Kernel#lambda or Kernel#proc" do - it_behaves_like :proc_call_on_proc_or_lambda, :yield + it "is an alias of Proc#call" do + Proc.instance_method(:yield).should == Proc.instance_method(:call) + end end diff --git a/spec/ruby/core/process/daemon_spec.rb b/spec/ruby/core/process/daemon_spec.rb index 9b7eba1411..7198dfa6ee 100644 --- a/spec/ruby/core/process/daemon_spec.rb +++ b/spec/ruby/core/process/daemon_spec.rb @@ -1,10 +1,11 @@ require_relative '../../spec_helper' require_relative 'fixtures/common' -platform_is_not :windows do - # macOS 15 is not working this examples - return if /darwin/ =~ RUBY_PLATFORM && /15/ =~ `sw_vers -productVersion` - +guard -> { + Process.respond_to?(:fork) and + # macOS 15 is not working for these examples + !(/darwin/ =~ RUBY_PLATFORM && /15/ =~ `sw_vers -productVersion`) +} do describe :process_daemon_keep_stdio_open_false, shared: true do it "redirects stdout to /dev/null" do @daemon.invoke("keep_stdio_open_false_stdout", @object).should == "" @@ -107,8 +108,12 @@ platform_is_not :windows do end end -platform_is :windows do +guard_not -> { Process.respond_to?(:fork) } do describe "Process.daemon" do + it "returns false from #respond_to?" do + Process.respond_to?(:daemon).should == false + end + it "raises a NotImplementedError" do -> { Process.daemon diff --git a/spec/ruby/core/process/detach_spec.rb b/spec/ruby/core/process/detach_spec.rb index 33c674394e..862768a909 100644 --- a/spec/ruby/core/process/detach_spec.rb +++ b/spec/ruby/core/process/detach_spec.rb @@ -1,81 +1,82 @@ require_relative '../../spec_helper' +require_relative 'fixtures/common' describe "Process.detach" do - platform_is_not :windows do - it "returns a thread" do - pid = Process.fork { Process.exit! } - thr = Process.detach(pid) - thr.should.is_a?(Thread) - thr.join - end + ProcessSpecs.use_system_ruby(self) - it "produces the exit Process::Status as the thread value" do - pid = Process.fork { Process.exit! } - thr = Process.detach(pid) - thr.join + it "returns a thread" do + pid = Process.spawn(*ruby_exe, "-e", "exit") + thr = Process.detach(pid) + thr.should.is_a?(Thread) + thr.join + end - status = thr.value - status.should.is_a?(Process::Status) - status.pid.should == pid - end + it "produces the exit Process::Status as the thread value" do + pid = Process.spawn(*ruby_exe, "-e", "exit") + thr = Process.detach(pid) + thr.join + + status = thr.value + status.should.is_a?(Process::Status) + status.pid.should == pid + end - platform_is_not :openbsd do - it "reaps the child process's status automatically" do - pid = Process.fork { Process.exit! } - Process.detach(pid).join - -> { Process.waitpid(pid) }.should.raise(Errno::ECHILD) - end + platform_is_not :openbsd do + it "reaps the child process's status automatically" do + pid = Process.spawn(*ruby_exe, "-e", "exit") + Process.detach(pid).join + -> { Process.waitpid(pid) }.should.raise(Errno::ECHILD) end + end - it "sets the :pid thread-local to the PID" do - pid = Process.fork { Process.exit! } - thr = Process.detach(pid) - thr.join + it "sets the :pid thread-local to the PID" do + pid = Process.spawn(*ruby_exe, "-e", "exit") + thr = Process.detach(pid) + thr.join - thr[:pid].should == pid - end + thr[:pid].should == pid + end - it "provides a #pid method on the returned thread which returns the PID" do - pid = Process.fork { Process.exit! } - thr = Process.detach(pid) - thr.join + it "provides a #pid method on the returned thread which returns the PID" do + pid = Process.spawn(*ruby_exe, "-e", "exit") + thr = Process.detach(pid) + thr.join - thr.pid.should == pid - end + thr.pid.should == pid + end - it "tolerates not existing child process pid" do - # Use a value that is close to the INT_MAX (pid usually is signed int). - # It should (at least) be greater than allowed pid limit value that depends on OS. - pid_not_existing = 2.pow(30) + it "tolerates not existing child process pid" do + # Use a value that is close to the INT_MAX (pid usually is signed int). + # It should (at least) be greater than allowed pid limit value that depends on OS. + pid_not_existing = 2.pow(30) - # Check that there is no a child process with this hardcoded pid. - # Command `kill 0 pid`: - # - returns "1" if a process exists and - # - raises Errno::ESRCH otherwise - -> { Process.kill(0, pid_not_existing) }.should.raise(Errno::ESRCH) + # Check that there is no a child process with this hardcoded pid. + # Command `kill 0 pid`: + # - returns "1" if a process exists and + # - raises Errno::ESRCH otherwise + -> { Process.kill(0, pid_not_existing) }.should.raise(Errno::ESRCH) - thr = Process.detach(pid_not_existing) - thr.join + thr = Process.detach(pid_not_existing) + thr.join - thr.should.is_a?(Thread) - end + thr.should.is_a?(Thread) + end - it "calls #to_int to implicitly convert non-Integer pid to Integer" do - pid = MockObject.new('mock-enumerable') - pid.should_receive(:to_int).and_return(100500) + it "calls #to_int to implicitly convert non-Integer pid to Integer" do + pid = MockObject.new('mock-enumerable') + pid.should_receive(:to_int).and_return(100500) - Process.detach(pid).join - end + Process.detach(pid).join + end - it "raises TypeError when pid argument does not have #to_int method" do - -> { Process.detach(Object.new) }.should.raise(TypeError, "no implicit conversion of Object into Integer") - end + it "raises TypeError when pid argument does not have #to_int method" do + -> { Process.detach(Object.new) }.should.raise(TypeError, "no implicit conversion of Object into Integer") + end - it "raises TypeError when #to_int returns non-Integer value" do - pid = MockObject.new('mock-enumerable') - pid.should_receive(:to_int).and_return(:symbol) + it "raises TypeError when #to_int returns non-Integer value" do + pid = MockObject.new('mock-enumerable') + pid.should_receive(:to_int).and_return(:symbol) - -> { Process.detach(pid) }.should raise_consistent_error(TypeError, "can't convert MockObject into Integer (MockObject#to_int gives Symbol)") - end + -> { Process.detach(pid) }.should raise_consistent_error(TypeError, "can't convert MockObject into Integer (MockObject#to_int gives Symbol)") end end diff --git a/spec/ruby/core/process/setpgid_spec.rb b/spec/ruby/core/process/setpgid_spec.rb index be724e9007..1442d7f99c 100644 --- a/spec/ruby/core/process/setpgid_spec.rb +++ b/spec/ruby/core/process/setpgid_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' describe "Process.setpgid" do - platform_is_not :windows do + guard -> { Process.respond_to?(:fork) } do # Must use fork as setpgid(2) gives EACCESS after execve() it "sets the process group id of the specified process" do rd, wr = IO.pipe diff --git a/spec/ruby/core/process/setpgrp_spec.rb b/spec/ruby/core/process/setpgrp_spec.rb index 800668008d..7c4344f115 100644 --- a/spec/ruby/core/process/setpgrp_spec.rb +++ b/spec/ruby/core/process/setpgrp_spec.rb @@ -2,7 +2,7 @@ require_relative '../../spec_helper' # TODO: put these in the right files. describe "Process.setpgrp and Process.getpgrp" do - platform_is_not :windows do + guard -> { Process.respond_to?(:fork) } do it "sets and gets the process group ID of the calling process" do # there are two synchronization points here: # One for the child to let the parent know that it has finished diff --git a/spec/ruby/core/process/status/wait_spec.rb b/spec/ruby/core/process/status/wait_spec.rb index 18ecc14f6f..8bd7fc6b43 100644 --- a/spec/ruby/core/process/status/wait_spec.rb +++ b/spec/ruby/core/process/status/wait_spec.rb @@ -70,25 +70,27 @@ describe "Process::Status.wait" do end # This spec is probably system-dependent. - it "doesn't block if no child is available when WNOHANG is used" do - read, write = IO.pipe - pid = Process.fork do - read.close - Signal.trap("TERM") { Process.exit! } - write << 1 + guard -> { Process.respond_to?(:fork) } do + it "doesn't block if no child is available when WNOHANG is used" do + read, write = IO.pipe + pid = Process.fork do + read.close + Signal.trap("TERM") { Process.exit! } + write << 1 + write.close + sleep + end + + Process::Status.wait(pid, Process::WNOHANG).should == nil + + # wait for the child to setup its TERM handler write.close - sleep - end - - Process::Status.wait(pid, Process::WNOHANG).should == nil - - # wait for the child to setup its TERM handler - write.close - read.read(1) - read.close + read.read(1) + read.close - Process.kill("TERM", pid) - Process::Status.wait.pid.should == pid + Process.kill("TERM", pid) + Process::Status.wait.pid.should == pid + end end it "always accepts flags=0" do diff --git a/spec/ruby/core/process/wait2_spec.rb b/spec/ruby/core/process/wait2_spec.rb index 5c57dd40fb..1fa6f76151 100644 --- a/spec/ruby/core/process/wait2_spec.rb +++ b/spec/ruby/core/process/wait2_spec.rb @@ -1,6 +1,9 @@ require_relative '../../spec_helper' +require_relative 'fixtures/common' describe "Process.wait2" do + ProcessSpecs.use_system_ruby(self) + before :all do # HACK: this kludge is temporarily necessary because some # misbehaving spec somewhere else does not clear processes @@ -18,15 +21,13 @@ describe "Process.wait2" do end end - platform_is_not :windows do - it "returns the pid and status of child process" do - pidf = Process.fork { Process.exit! 99 } - results = Process.wait2 - results.size.should == 2 - pidw, status = results - pidf.should == pidw - status.exitstatus.should == 99 - end + it "returns the pid and status of child process" do + pidf = Process.spawn(*ruby_exe, "-e", "exit 99") + results = Process.wait2 + results.size.should == 2 + pidw, status = results + pidf.should == pidw + status.exitstatus.should == 99 end it "raises a StandardError if no child processes exist" do diff --git a/spec/ruby/core/process/wait_spec.rb b/spec/ruby/core/process/wait_spec.rb index 0b2e715f65..5a1889487c 100644 --- a/spec/ruby/core/process/wait_spec.rb +++ b/spec/ruby/core/process/wait_spec.rb @@ -17,19 +17,30 @@ describe "Process.wait" do -> { Process.wait }.should.raise(Errno::ECHILD) end - platform_is_not :windows do - it "returns its child pid" do - pid = Process.spawn(ruby_cmd('exit')) - Process.wait.should == pid - end + it "returns its child pid" do + pid = Process.spawn(ruby_cmd('exit')) + Process.wait.should == pid + end - it "sets $? to a Process::Status" do - pid = Process.spawn(ruby_cmd('exit')) - Process.wait - $?.should.is_a?(Process::Status) - $?.pid.should == pid + it "returns nil when the process has not yet completed and WNOHANG is specified" do + cmd = platform_is(:windows) ? "timeout" : "sleep" + pid = spawn("#{cmd} 5") + begin + Process.wait(pid, Process::WNOHANG).should == nil + Process.kill("KILL", pid) + ensure + Process.wait(pid) end + end + + it "sets $? to a Process::Status" do + pid = Process.spawn(ruby_cmd('exit')) + Process.wait + $?.should.is_a?(Process::Status) + $?.pid.should == pid + end + platform_is_not :windows do it "waits for any child process if no pid is given" do pid = Process.spawn(ruby_cmd('exit')) Process.wait.should == pid @@ -59,8 +70,10 @@ describe "Process.wait" do Process.wait(0).should == pid2 Process.wait.should == pid1 end + end - # This spec is probably system-dependent. + # This spec is probably system-dependent. + guard -> { Process.respond_to?(:fork) } do it "doesn't block if no child is available when WNOHANG is used" do read, write = IO.pipe pid = Process.fork do @@ -81,7 +94,9 @@ describe "Process.wait" do Process.kill("TERM", pid) Process.wait.should == pid end + end + platform_is_not :windows do it "always accepts flags=0" do pid = Process.spawn(ruby_cmd('exit')) Process.wait(-1, 0).should == pid diff --git a/spec/ruby/core/process/waitall_spec.rb b/spec/ruby/core/process/waitall_spec.rb index a77873f553..f5fbce71c1 100644 --- a/spec/ruby/core/process/waitall_spec.rb +++ b/spec/ruby/core/process/waitall_spec.rb @@ -1,6 +1,9 @@ require_relative '../../spec_helper' +require_relative 'fixtures/common' describe "Process.waitall" do + ProcessSpecs.use_system_ruby(self) + before :all do begin Process.waitall @@ -17,23 +20,16 @@ describe "Process.waitall" do end platform_is_not :windows do - it "waits for all children" do + it "waits for all children and returns an array of pid/status pairs" do pids = [] - pids << Process.fork { Process.exit! 2 } - pids << Process.fork { Process.exit! 1 } - pids << Process.fork { Process.exit! 0 } - Process.waitall + pids << Process.spawn(ruby_cmd('exit 2')) + pids << Process.spawn(ruby_cmd('exit 1')) + pids << Process.spawn(ruby_cmd('exit 0')) + a = Process.waitall pids.each { |pid| -> { Process.kill(0, pid) }.should.raise(Errno::ESRCH) } - end - it "returns an array of pid/status pairs" do - pids = [] - pids << Process.fork { Process.exit! 2 } - pids << Process.fork { Process.exit! 1 } - pids << Process.fork { Process.exit! 0 } - a = Process.waitall a.should.is_a?(Array) a.size.should == 3 pids.each { |pid| diff --git a/spec/ruby/core/process/waitpid2_spec.rb b/spec/ruby/core/process/waitpid2_spec.rb index 45513af667..70fe0fbeee 100644 --- a/spec/ruby/core/process/waitpid2_spec.rb +++ b/spec/ruby/core/process/waitpid2_spec.rb @@ -1,5 +1,7 @@ require_relative '../../spec_helper' describe "Process.waitpid2" do - it "needs to be reviewed for spec completeness" + it "is an alias of Process.wait2" do + Process.method(:waitpid2).should == Process.method(:wait2) + end end diff --git a/spec/ruby/core/process/waitpid_spec.rb b/spec/ruby/core/process/waitpid_spec.rb index a02147b663..9b2f49e7cf 100644 --- a/spec/ruby/core/process/waitpid_spec.rb +++ b/spec/ruby/core/process/waitpid_spec.rb @@ -1,14 +1,7 @@ require_relative '../../spec_helper' describe "Process.waitpid" do - it "returns nil when the process has not yet completed and WNOHANG is specified" do - cmd = platform_is(:windows) ? "timeout" : "sleep" - pid = spawn("#{cmd} 5") - begin - Process.waitpid(pid, Process::WNOHANG).should == nil - Process.kill("KILL", pid) - ensure - Process.wait(pid) - end + it "is an alias of Process.wait" do + Process.method(:waitpid).should == Process.method(:wait) end end diff --git a/spec/ruby/core/queue/deq_spec.rb b/spec/ruby/core/queue/deq_spec.rb index a2784e6a63..374611366e 100644 --- a/spec/ruby/core/queue/deq_spec.rb +++ b/spec/ruby/core/queue/deq_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/deque' -require_relative '../../shared/types/rb_num2dbl_fails' describe "Queue#deq" do - it_behaves_like :queue_deq, :deq, -> { Queue.new } -end - -describe "Queue operations with timeout" do - it_behaves_like :rb_num2dbl_fails, nil, -> v { q = Queue.new; q.push(1); q.deq(timeout: v) } + it "is an alias of Queue#pop" do + Queue.instance_method(:deq).should == Queue.instance_method(:pop) + end end diff --git a/spec/ruby/core/queue/enq_spec.rb b/spec/ruby/core/queue/enq_spec.rb index c69c496fbc..76ecf0ca5f 100644 --- a/spec/ruby/core/queue/enq_spec.rb +++ b/spec/ruby/core/queue/enq_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/enque' describe "Queue#enq" do - it_behaves_like :queue_enq, :enq, -> { Queue.new } + it "is an alias of Queue#<<" do + Queue.instance_method(:enq).should == Queue.instance_method(:<<) + end end diff --git a/spec/ruby/core/queue/length_spec.rb b/spec/ruby/core/queue/length_spec.rb index 25399b2b76..0566b1d547 100644 --- a/spec/ruby/core/queue/length_spec.rb +++ b/spec/ruby/core/queue/length_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/length' describe "Queue#length" do - it_behaves_like :queue_length, :length, -> { Queue.new } + it "is an alias of Queue#size" do + Queue.instance_method(:length).should == Queue.instance_method(:size) + end end diff --git a/spec/ruby/core/queue/push_spec.rb b/spec/ruby/core/queue/push_spec.rb index e936f9d282..ef622ac89d 100644 --- a/spec/ruby/core/queue/push_spec.rb +++ b/spec/ruby/core/queue/push_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/enque' describe "Queue#push" do - it_behaves_like :queue_enq, :push, -> { Queue.new } + it "is an alias of Queue#<<" do + Queue.instance_method(:push).should == Queue.instance_method(:<<) + end end diff --git a/spec/ruby/core/queue/shift_spec.rb b/spec/ruby/core/queue/shift_spec.rb index c105da74b2..074332359c 100644 --- a/spec/ruby/core/queue/shift_spec.rb +++ b/spec/ruby/core/queue/shift_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/deque' -require_relative '../../shared/types/rb_num2dbl_fails' describe "Queue#shift" do - it_behaves_like :queue_deq, :shift, -> { Queue.new } -end - -describe "Queue operations with timeout" do - it_behaves_like :rb_num2dbl_fails, nil, -> v { q = Queue.new; q.push(1); q.shift(timeout: v) } + it "is an alias of Queue#pop" do + Queue.instance_method(:shift).should == Queue.instance_method(:pop) + end end diff --git a/spec/ruby/core/range/entries_spec.rb b/spec/ruby/core/range/entries_spec.rb new file mode 100644 index 0000000000..29296711dc --- /dev/null +++ b/spec/ruby/core/range/entries_spec.rb @@ -0,0 +1,7 @@ +require_relative '../../spec_helper' + +describe "Range#entries" do + it "is an alias of Range#to_a" do + Range.instance_method(:entries).should == Range.instance_method(:to_a) + end +end diff --git a/spec/ruby/core/range/include_spec.rb b/spec/ruby/core/range/include_spec.rb index 66a049a90d..e5cc0dc234 100644 --- a/spec/ruby/core/range/include_spec.rb +++ b/spec/ruby/core/range/include_spec.rb @@ -1,12 +1,96 @@ # encoding: binary require_relative '../../spec_helper' +require_relative 'fixtures/classes' require_relative 'shared/cover_and_include' -require_relative 'shared/include' -require_relative 'shared/cover' describe "Range#include?" do it_behaves_like :range_cover_and_include, :include? - it_behaves_like :range_include, :include? + + describe "on string elements" do + it "returns true if other is matched by element.succ" do + ('a'..'c').include?('b').should == true + ('a'...'c').include?('b').should == true + end + + it "returns false if other is not matched by element.succ" do + ('a'..'c').include?('bc').should == false + ('a'...'c').include?('bc').should == false + end + end + + describe "with weird succ" do + describe "when included end value" do + before :each do + @range = RangeSpecs::TenfoldSucc.new(1)..RangeSpecs::TenfoldSucc.new(99) + end + + it "returns false if other is less than first element" do + @range.include?(RangeSpecs::TenfoldSucc.new(0)).should == false + end + + it "returns true if other is equal as first element" do + @range.include?(RangeSpecs::TenfoldSucc.new(1)).should == true + end + + it "returns true if other is matched by element.succ" do + @range.include?(RangeSpecs::TenfoldSucc.new(10)).should == true + end + + it "returns false if other is not matched by element.succ" do + @range.include?(RangeSpecs::TenfoldSucc.new(2)).should == false + end + + it "returns false if other is equal as last element but not matched by element.succ" do + @range.include?(RangeSpecs::TenfoldSucc.new(99)).should == false + end + + it "returns false if other is greater than last element but matched by element.succ" do + @range.include?(RangeSpecs::TenfoldSucc.new(100)).should == false + end + end + + describe "when excluded end value" do + before :each do + @range = RangeSpecs::TenfoldSucc.new(1)...RangeSpecs::TenfoldSucc.new(99) + end + + it "returns false if other is less than first element" do + @range.include?(RangeSpecs::TenfoldSucc.new(0)).should == false + end + + it "returns true if other is equal as first element" do + @range.include?(RangeSpecs::TenfoldSucc.new(1)).should == true + end + + it "returns true if other is matched by element.succ" do + @range.include?(RangeSpecs::TenfoldSucc.new(10)).should == true + end + + it "returns false if other is not matched by element.succ" do + @range.include?(RangeSpecs::TenfoldSucc.new(2)).should == false + end + + it "returns false if other is equal as last element but not matched by element.succ" do + @range.include?(RangeSpecs::TenfoldSucc.new(99)).should == false + end + + it "returns false if other is greater than last element but matched by element.succ" do + @range.include?(RangeSpecs::TenfoldSucc.new(100)).should == false + end + end + end + + describe "with Time endpoints" do + it "uses cover? logic" do + now = Time.now + range = (now..(now + 60)) + + range.include?(now).should == true + range.include?(now - 1).should == false + range.include?(now + 60).should == true + range.include?(now + 61).should == false + end + end it "does not include U+9995 in the range U+0999..U+9999" do ("\u{999}".."\u{9999}").include?("\u{9995}").should == false diff --git a/spec/ruby/core/range/member_spec.rb b/spec/ruby/core/range/member_spec.rb index 78299ae9e5..98835e4cf3 100644 --- a/spec/ruby/core/range/member_spec.rb +++ b/spec/ruby/core/range/member_spec.rb @@ -1,10 +1,7 @@ -# encoding: binary require_relative '../../spec_helper' -require_relative 'shared/cover_and_include' -require_relative 'shared/include' -require_relative 'shared/cover' describe "Range#member?" do - it_behaves_like :range_cover_and_include, :member? - it_behaves_like :range_include, :member? + it "is an alias of Range#include?" do + Range.instance_method(:member?).should == Range.instance_method(:include?) + end end diff --git a/spec/ruby/core/range/shared/include.rb b/spec/ruby/core/range/shared/include.rb deleted file mode 100644 index 5f0db48008..0000000000 --- a/spec/ruby/core/range/shared/include.rb +++ /dev/null @@ -1,91 +0,0 @@ -# encoding: binary -require_relative '../../../spec_helper' -require_relative '../fixtures/classes' - -describe :range_include, shared: true do - describe "on string elements" do - it "returns true if other is matched by element.succ" do - ('a'..'c').send(@method, 'b').should == true - ('a'...'c').send(@method, 'b').should == true - end - - it "returns false if other is not matched by element.succ" do - ('a'..'c').send(@method, 'bc').should == false - ('a'...'c').send(@method, 'bc').should == false - end - end - - describe "with weird succ" do - describe "when included end value" do - before :each do - @range = RangeSpecs::TenfoldSucc.new(1)..RangeSpecs::TenfoldSucc.new(99) - end - - it "returns false if other is less than first element" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(0)).should == false - end - - it "returns true if other is equal as first element" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(1)).should == true - end - - it "returns true if other is matched by element.succ" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(10)).should == true - end - - it "returns false if other is not matched by element.succ" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(2)).should == false - end - - it "returns false if other is equal as last element but not matched by element.succ" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(99)).should == false - end - - it "returns false if other is greater than last element but matched by element.succ" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(100)).should == false - end - end - - describe "when excluded end value" do - before :each do - @range = RangeSpecs::TenfoldSucc.new(1)...RangeSpecs::TenfoldSucc.new(99) - end - - it "returns false if other is less than first element" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(0)).should == false - end - - it "returns true if other is equal as first element" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(1)).should == true - end - - it "returns true if other is matched by element.succ" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(10)).should == true - end - - it "returns false if other is not matched by element.succ" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(2)).should == false - end - - it "returns false if other is equal as last element but not matched by element.succ" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(99)).should == false - end - - it "returns false if other is greater than last element but matched by element.succ" do - @range.send(@method, RangeSpecs::TenfoldSucc.new(100)).should == false - end - end - end - - describe "with Time endpoints" do - it "uses cover? logic" do - now = Time.now - range = (now..(now + 60)) - - range.include?(now).should == true - range.include?(now - 1).should == false - range.include?(now + 60).should == true - range.include?(now + 61).should == false - end - end -end diff --git a/spec/ruby/core/rational/abs_spec.rb b/spec/ruby/core/rational/abs_spec.rb index 54099aa14d..6bb4a0fbef 100644 --- a/spec/ruby/core/rational/abs_spec.rb +++ b/spec/ruby/core/rational/abs_spec.rb @@ -1,6 +1,11 @@ require_relative "../../spec_helper" -require_relative 'shared/abs' describe "Rational#abs" do - it_behaves_like :rational_abs, :abs + it "returns self's absolute value" do + Rational(3, 4).abs.should == Rational(3, 4) + Rational(-3, 4).abs.should == Rational(3, 4) + Rational(3, -4).abs.should == Rational(3, 4) + + Rational(bignum_value, -bignum_value).abs.should == Rational(bignum_value, bignum_value) + end end diff --git a/spec/ruby/core/rational/magnitude_spec.rb b/spec/ruby/core/rational/magnitude_spec.rb index f5f667edb1..0df637df7a 100644 --- a/spec/ruby/core/rational/magnitude_spec.rb +++ b/spec/ruby/core/rational/magnitude_spec.rb @@ -1,6 +1,7 @@ require_relative "../../spec_helper" -require_relative 'shared/abs' -describe "Rational#abs" do - it_behaves_like :rational_abs, :magnitude +describe "Rational#magnitude" do + it "is an alias of Rational#abs" do + Rational.instance_method(:magnitude).should == Rational.instance_method(:abs) + end end diff --git a/spec/ruby/core/rational/quo_spec.rb b/spec/ruby/core/rational/quo_spec.rb index 907898ad34..62178f403b 100644 --- a/spec/ruby/core/rational/quo_spec.rb +++ b/spec/ruby/core/rational/quo_spec.rb @@ -1,25 +1,7 @@ require_relative "../../spec_helper" describe "Rational#quo" do - it "calls #coerce on the passed argument with self" do - rational = Rational(3, 4) - obj = mock("Object") - obj.should_receive(:coerce).with(rational).and_return([1, 2]) - - rational.quo(obj) - end - - it "calls #/ on the coerced Rational with the coerced Object" do - rational = Rational(3, 4) - - coerced_rational = mock("Coerced Rational") - coerced_rational.should_receive(:/).and_return(:result) - - coerced_obj = mock("Coerced Object") - - obj = mock("Object") - obj.should_receive(:coerce).and_return([coerced_rational, coerced_obj]) - - rational.quo(obj).should == :result + it "is an alias of Rational#/" do + Rational.instance_method(:quo).should == Rational.instance_method(:/) end end diff --git a/spec/ruby/core/rational/shared/abs.rb b/spec/ruby/core/rational/shared/abs.rb deleted file mode 100644 index 3d64bcc1a0..0000000000 --- a/spec/ruby/core/rational/shared/abs.rb +++ /dev/null @@ -1,11 +0,0 @@ -require_relative '../../../spec_helper' - -describe :rational_abs, shared: true do - it "returns self's absolute value" do - Rational(3, 4).send(@method).should == Rational(3, 4) - Rational(-3, 4).send(@method).should == Rational(3, 4) - Rational(3, -4).send(@method).should == Rational(3, 4) - - Rational(bignum_value, -bignum_value).send(@method).should == Rational(bignum_value, bignum_value) - end -end diff --git a/spec/ruby/core/refinement/refined_class_spec.rb b/spec/ruby/core/refinement/refined_class_spec.rb index b532d9a773..90f8d963d8 100644 --- a/spec/ruby/core/refinement/refined_class_spec.rb +++ b/spec/ruby/core/refinement/refined_class_spec.rb @@ -1,5 +1,4 @@ require_relative "../../spec_helper" -require_relative 'shared/target' describe "Refinement#refined_class" do ruby_version_is ""..."3.4" do diff --git a/spec/ruby/core/refinement/shared/target.rb b/spec/ruby/core/refinement/shared/target.rb deleted file mode 100644 index 79557bea0b..0000000000 --- a/spec/ruby/core/refinement/shared/target.rb +++ /dev/null @@ -1,13 +0,0 @@ -describe :refinement_target, shared: true do - it "returns the class refined by the receiver" do - refinement_int = nil - - Module.new do - refine Integer do - refinement_int = self - end - end - - refinement_int.send(@method).should == Integer - end -end diff --git a/spec/ruby/core/refinement/target_spec.rb b/spec/ruby/core/refinement/target_spec.rb index 8bd816aea6..eaee71e8c6 100644 --- a/spec/ruby/core/refinement/target_spec.rb +++ b/spec/ruby/core/refinement/target_spec.rb @@ -1,6 +1,15 @@ require_relative "../../spec_helper" -require_relative 'shared/target' describe "Refinement#target" do - it_behaves_like :refinement_target, :target + it "returns the class refined by the receiver" do + refinement_int = nil + + Module.new do + refine Integer do + refinement_int = self + end + end + + refinement_int.target.should == Integer + end end diff --git a/spec/ruby/core/regexp/eql_spec.rb b/spec/ruby/core/regexp/eql_spec.rb index bd5ae43eb2..5924333fbd 100644 --- a/spec/ruby/core/regexp/eql_spec.rb +++ b/spec/ruby/core/regexp/eql_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/equal_value' describe "Regexp#eql?" do - it_behaves_like :regexp_eql, :eql? + it "is an alias of Regexp#==" do + Regexp.instance_method(:eql?).should == Regexp.instance_method(:==) + end end diff --git a/spec/ruby/core/regexp/equal_value_spec.rb b/spec/ruby/core/regexp/equal_value_spec.rb index 5455a30598..ad8dc33222 100644 --- a/spec/ruby/core/regexp/equal_value_spec.rb +++ b/spec/ruby/core/regexp/equal_value_spec.rb @@ -1,6 +1,33 @@ require_relative '../../spec_helper' -require_relative 'shared/equal_value' describe "Regexp#==" do - it_behaves_like :regexp_eql, :== + it "is true if self and other have the same pattern" do + (/abc/ == /abc/).should == true + (/abc/ == /abd/).should == false + end + + not_supported_on :opal do + it "is true if self and other have the same character set code" do + (/abc/ == /abc/x).should == false + (/abc/x == /abc/x).should == true + (/abc/u == /abc/n).should == false + (/abc/u == /abc/u).should == true + (/abc/n == /abc/n).should == true + end + end + + it "is true if other has the same #casefold? values" do + (/abc/ == /abc/i).should == false + (/abc/i == /abc/i).should == true + end + + not_supported_on :opal do + it "is true if self does not specify /n option and other does" do + (// == //n).should == true + end + + it "is true if self specifies /n option and other does not" do + (//n == //).should == true + end + end end diff --git a/spec/ruby/core/regexp/escape_spec.rb b/spec/ruby/core/regexp/escape_spec.rb index 6b06ab1cbc..99e5eb71d6 100644 --- a/spec/ruby/core/regexp/escape_spec.rb +++ b/spec/ruby/core/regexp/escape_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/quote' describe "Regexp.escape" do - it_behaves_like :regexp_quote, :escape + it "is an alias of Regexp.quote" do + Regexp.method(:escape).should == Regexp.method(:quote) + end end diff --git a/spec/ruby/core/regexp/quote_spec.rb b/spec/ruby/core/regexp/quote_spec.rb index 370ab13e30..27fa0c0669 100644 --- a/spec/ruby/core/regexp/quote_spec.rb +++ b/spec/ruby/core/regexp/quote_spec.rb @@ -1,6 +1,43 @@ +# encoding: binary + require_relative '../../spec_helper' -require_relative 'shared/quote' describe "Regexp.quote" do - it_behaves_like :regexp_quote, :quote + it "escapes any characters with special meaning in a regular expression" do + Regexp.quote('\*?{}.+^$[]()- ').should == '\\\\\*\?\{\}\.\+\^\$\[\]\(\)\-\\ ' + Regexp.quote("\*?{}.+^$[]()- ").should == '\\*\\?\\{\\}\\.\\+\\^\\$\\[\\]\\(\\)\\-\\ ' + Regexp.quote('\n\r\f\t').should == '\\\\n\\\\r\\\\f\\\\t' + Regexp.quote("\n\r\f\t").should == '\\n\\r\\f\\t' + end + + it "works with symbols" do + Regexp.quote(:symbol).should == 'symbol' + end + + it "works with substrings" do + str = ".+[]()"[1...-1] + Regexp.quote(str).should == '\+\[\]\(' + end + + it "works for broken strings" do + Regexp.quote("a.\x85b.".dup.force_encoding("US-ASCII")).should =="a\\.\x85b\\.".dup.force_encoding("US-ASCII") + Regexp.quote("a.\x80".dup.force_encoding("UTF-8")).should == "a\\.\x80".dup.force_encoding("UTF-8") + end + + it "sets the encoding of the result to US-ASCII if there are only US-ASCII characters present in the input String" do + str = "abc".dup.force_encoding("euc-jp") + Regexp.quote(str).encoding.should == Encoding::US_ASCII + end + + it "sets the encoding of the result to the encoding of the String if any non-US-ASCII characters are present in an input String with valid encoding" do + str = "ありがとう".dup.force_encoding("utf-8") + str.valid_encoding?.should == true + Regexp.quote(str).encoding.should == Encoding::UTF_8 + end + + it "sets the encoding of the result to BINARY if any non-US-ASCII characters are present in an input String with invalid encoding" do + str = "\xff".dup.force_encoding "us-ascii" + str.valid_encoding?.should == false + Regexp.quote("\xff").encoding.should == Encoding::BINARY + end end diff --git a/spec/ruby/core/regexp/shared/equal_value.rb b/spec/ruby/core/regexp/shared/equal_value.rb deleted file mode 100644 index 803988de9e..0000000000 --- a/spec/ruby/core/regexp/shared/equal_value.rb +++ /dev/null @@ -1,31 +0,0 @@ -describe :regexp_eql, shared: true do - it "is true if self and other have the same pattern" do - /abc/.send(@method, /abc/).should == true - /abc/.send(@method, /abd/).should == false - end - - not_supported_on :opal do - it "is true if self and other have the same character set code" do - /abc/.send(@method, /abc/x).should == false - /abc/x.send(@method, /abc/x).should == true - /abc/u.send(@method, /abc/n).should == false - /abc/u.send(@method, /abc/u).should == true - /abc/n.send(@method, /abc/n).should == true - end - end - - it "is true if other has the same #casefold? values" do - /abc/.send(@method, /abc/i).should == false - /abc/i.send(@method, /abc/i).should == true - end - - not_supported_on :opal do - it "is true if self does not specify /n option and other does" do - //.send(@method, //n).should == true - end - - it "is true if self specifies /n option and other does not" do - //n.send(@method, //).should == true - end - end -end diff --git a/spec/ruby/core/regexp/shared/quote.rb b/spec/ruby/core/regexp/shared/quote.rb deleted file mode 100644 index 083f12d78c..0000000000 --- a/spec/ruby/core/regexp/shared/quote.rb +++ /dev/null @@ -1,41 +0,0 @@ -# encoding: binary - -describe :regexp_quote, shared: true do - it "escapes any characters with special meaning in a regular expression" do - Regexp.send(@method, '\*?{}.+^$[]()- ').should == '\\\\\*\?\{\}\.\+\^\$\[\]\(\)\-\\ ' - Regexp.send(@method, "\*?{}.+^$[]()- ").should == '\\*\\?\\{\\}\\.\\+\\^\\$\\[\\]\\(\\)\\-\\ ' - Regexp.send(@method, '\n\r\f\t').should == '\\\\n\\\\r\\\\f\\\\t' - Regexp.send(@method, "\n\r\f\t").should == '\\n\\r\\f\\t' - end - - it "works with symbols" do - Regexp.send(@method, :symbol).should == 'symbol' - end - - it "works with substrings" do - str = ".+[]()"[1...-1] - Regexp.send(@method, str).should == '\+\[\]\(' - end - - it "works for broken strings" do - Regexp.send(@method, "a.\x85b.".dup.force_encoding("US-ASCII")).should =="a\\.\x85b\\.".dup.force_encoding("US-ASCII") - Regexp.send(@method, "a.\x80".dup.force_encoding("UTF-8")).should == "a\\.\x80".dup.force_encoding("UTF-8") - end - - it "sets the encoding of the result to US-ASCII if there are only US-ASCII characters present in the input String" do - str = "abc".dup.force_encoding("euc-jp") - Regexp.send(@method, str).encoding.should == Encoding::US_ASCII - end - - it "sets the encoding of the result to the encoding of the String if any non-US-ASCII characters are present in an input String with valid encoding" do - str = "ありがとう".dup.force_encoding("utf-8") - str.valid_encoding?.should == true - Regexp.send(@method, str).encoding.should == Encoding::UTF_8 - end - - it "sets the encoding of the result to BINARY if any non-US-ASCII characters are present in an input String with invalid encoding" do - str = "\xff".dup.force_encoding "us-ascii" - str.valid_encoding?.should == false - Regexp.send(@method, "\xff").encoding.should == Encoding::BINARY - end -end diff --git a/spec/ruby/core/set/add_spec.rb b/spec/ruby/core/set/add_spec.rb index 1ce03b1eab..1a018b186a 100644 --- a/spec/ruby/core/set/add_spec.rb +++ b/spec/ruby/core/set/add_spec.rb @@ -1,8 +1,18 @@ require_relative '../../spec_helper' -require_relative 'shared/add' describe "Set#add" do - it_behaves_like :set_add, :add + before :each do + @set = Set.new + end + + it "adds the passed Object to self" do + @set.add("dog") + @set.should.include?("dog") + end + + it "returns self" do + @set.add("dog").should.equal?(@set) + end end describe "Set#add?" do diff --git a/spec/ruby/core/set/append_spec.rb b/spec/ruby/core/set/append_spec.rb index 82d34d9130..4f4e2351e2 100644 --- a/spec/ruby/core/set/append_spec.rb +++ b/spec/ruby/core/set/append_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/add' describe "Set#<<" do - it_behaves_like :set_add, :<< + it "is an alias of Set#add" do + Set.instance_method(:<<).should == Set.instance_method(:add) + end end diff --git a/spec/ruby/core/set/case_compare_spec.rb b/spec/ruby/core/set/case_compare_spec.rb index 3781b1b963..6fe749c79b 100644 --- a/spec/ruby/core/set/case_compare_spec.rb +++ b/spec/ruby/core/set/case_compare_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/include' describe "Set#===" do - it_behaves_like :set_include, :=== - - it "is an alias for include?" do - set = Set.new - set.method(:===).should == set.method(:include?) + it "is an alias of Set#include?" do + Set.instance_method(:===).should == Set.instance_method(:include?) end end diff --git a/spec/ruby/core/set/case_equality_spec.rb b/spec/ruby/core/set/case_equality_spec.rb deleted file mode 100644 index 19c1fb6b9c..0000000000 --- a/spec/ruby/core/set/case_equality_spec.rb +++ /dev/null @@ -1,6 +0,0 @@ -require_relative '../../spec_helper' -require_relative 'shared/include' - -describe "Set#===" do - it_behaves_like :set_include, :=== -end diff --git a/spec/ruby/core/set/collect_spec.rb b/spec/ruby/core/set/collect_spec.rb index d186f1a0d9..b78ee493d4 100644 --- a/spec/ruby/core/set/collect_spec.rb +++ b/spec/ruby/core/set/collect_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/collect' describe "Set#collect!" do - it_behaves_like :set_collect_bang, :collect! + it "is an alias of Set#map!" do + Set.instance_method(:collect!).should == Set.instance_method(:map!) + end end diff --git a/spec/ruby/core/set/difference_spec.rb b/spec/ruby/core/set/difference_spec.rb index 149f946592..22d89973a8 100644 --- a/spec/ruby/core/set/difference_spec.rb +++ b/spec/ruby/core/set/difference_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/difference' describe "Set#difference" do - it_behaves_like :set_difference, :difference + it "is an alias of Set#-" do + Set.instance_method(:difference).should == Set.instance_method(:-) + end end diff --git a/spec/ruby/core/set/eql_spec.rb b/spec/ruby/core/set/eql_spec.rb index 6862ed4eda..e7eacf2999 100644 --- a/spec/ruby/core/set/eql_spec.rb +++ b/spec/ruby/core/set/eql_spec.rb @@ -1,14 +1,22 @@ require_relative '../../spec_helper' describe "Set#eql?" do - it "returns true when the passed argument is a Set and contains the same elements" do - Set[].should.eql?(Set[]) - Set[1, 2, 3].should.eql?(Set[1, 2, 3]) - Set[1, 2, 3].should.eql?(Set[3, 2, 1]) - Set["a", :b, ?c].should.eql?(Set[?c, :b, "a"]) + ruby_version_is ""..."4.0" do + it "returns true when the passed argument is a Set and contains the same elements" do + Set[].should.eql?(Set[]) + Set[1, 2, 3].should.eql?(Set[1, 2, 3]) + Set[1, 2, 3].should.eql?(Set[3, 2, 1]) + Set["a", :b, ?c].should.eql?(Set[?c, :b, "a"]) - Set[1, 2, 3].should_not.eql?(Set[1.0, 2, 3]) - Set[1, 2, 3].should_not.eql?(Set[2, 3]) - Set[1, 2, 3].should_not.eql?(Set[]) + Set[1, 2, 3].should_not.eql?(Set[1.0, 2, 3]) + Set[1, 2, 3].should_not.eql?(Set[2, 3]) + Set[1, 2, 3].should_not.eql?(Set[]) + end + end + + ruby_version_is "4.0" do + it "is an alias of Set#==" do + Set.instance_method(:eql?).should == Set.instance_method(:==) + end end end diff --git a/spec/ruby/core/set/filter_spec.rb b/spec/ruby/core/set/filter_spec.rb index 779254ad68..d0c294c27f 100644 --- a/spec/ruby/core/set/filter_spec.rb +++ b/spec/ruby/core/set/filter_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/select' describe "Set#filter!" do - it_behaves_like :set_select_bang, :filter! + it "is an alias of Set#select!" do + Set.instance_method(:filter!).should == Set.instance_method(:select!) + end end diff --git a/spec/ruby/core/set/gt_spec.rb b/spec/ruby/core/set/gt_spec.rb new file mode 100644 index 0000000000..8a7e421e40 --- /dev/null +++ b/spec/ruby/core/set/gt_spec.rb @@ -0,0 +1,7 @@ +require_relative '../../spec_helper' + +describe "Set#>" do + it "is an alias of Set#proper_superset?" do + Set.instance_method(:>).should == Set.instance_method(:proper_superset?) + end +end diff --git a/spec/ruby/core/set/gte_spec.rb b/spec/ruby/core/set/gte_spec.rb new file mode 100644 index 0000000000..e98c3cb1e2 --- /dev/null +++ b/spec/ruby/core/set/gte_spec.rb @@ -0,0 +1,7 @@ +require_relative '../../spec_helper' + +describe "Set#>=" do + it "is an alias of Set#superset?" do + Set.instance_method(:>=).should == Set.instance_method(:superset?) + end +end diff --git a/spec/ruby/core/set/include_spec.rb b/spec/ruby/core/set/include_spec.rb index dd33bbc3bd..92a6ca04e6 100644 --- a/spec/ruby/core/set/include_spec.rb +++ b/spec/ruby/core/set/include_spec.rb @@ -1,6 +1,31 @@ require_relative '../../spec_helper' -require_relative 'shared/include' describe "Set#include?" do - it_behaves_like :set_include, :include? + it "returns true when self contains the passed Object" do + set = Set[:a, :b, :c] + set.include?(:a).should == true + set.include?(:e).should == false + end + + describe "member equality" do + it "is checked using both #hash and #eql?" do + obj = Object.new + obj_another = Object.new + + def obj.hash; 42 end + def obj_another.hash; 42 end + def obj_another.eql?(o) hash == o.hash end + + set = Set["a", "b", "c", obj] + set.include?(obj_another).should == true + end + + it "is not checked using #==" do + obj = Object.new + set = Set["a", "b", "c"] + + obj.should_not_receive(:==) + set.include?(obj) + end + end end diff --git a/spec/ruby/core/set/inspect_spec.rb b/spec/ruby/core/set/inspect_spec.rb index 0dcce83eb6..45aeed280e 100644 --- a/spec/ruby/core/set/inspect_spec.rb +++ b/spec/ruby/core/set/inspect_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/inspect' describe "Set#inspect" do - it_behaves_like :set_inspect, :inspect + it "is an alias of Set#to_s" do + Set.instance_method(:inspect).should == Set.instance_method(:to_s) + end end diff --git a/spec/ruby/core/set/intersection_spec.rb b/spec/ruby/core/set/intersection_spec.rb index 136b886775..c14e1f62ad 100644 --- a/spec/ruby/core/set/intersection_spec.rb +++ b/spec/ruby/core/set/intersection_spec.rb @@ -1,10 +1,23 @@ require_relative '../../spec_helper' -require_relative 'shared/intersection' describe "Set#intersection" do - it_behaves_like :set_intersection, :intersection + it "is an alias of Set#&" do + Set.instance_method(:intersection).should == Set.instance_method(:&) + end end describe "Set#&" do - it_behaves_like :set_intersection, :& + before :each do + @set = Set[:a, :b, :c] + end + + it "returns a new Set containing only elements shared by self and the passed Enumerable" do + (@set & Set[:b, :c, :d, :e]).should == Set[:b, :c] + (@set & [:b, :c, :d]).should == Set[:b, :c] + end + + it "raises an ArgumentError when passed a non-Enumerable" do + -> { @set & 1 }.should.raise(ArgumentError) + -> { @set & Object.new }.should.raise(ArgumentError) + end end diff --git a/spec/ruby/core/set/length_spec.rb b/spec/ruby/core/set/length_spec.rb index 6bb697b4ca..9b0d3622b8 100644 --- a/spec/ruby/core/set/length_spec.rb +++ b/spec/ruby/core/set/length_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/length' describe "Set#length" do - it_behaves_like :set_length, :length + it "is an alias of Set#size" do + Set.instance_method(:length).should == Set.instance_method(:size) + end end diff --git a/spec/ruby/core/set/lt_spec.rb b/spec/ruby/core/set/lt_spec.rb new file mode 100644 index 0000000000..0f5bc9c642 --- /dev/null +++ b/spec/ruby/core/set/lt_spec.rb @@ -0,0 +1,7 @@ +require_relative '../../spec_helper' + +describe "Set#<" do + it "is an alias of Set#proper_subset?" do + Set.instance_method(:<).should == Set.instance_method(:proper_subset?) + end +end diff --git a/spec/ruby/core/set/lte_spec.rb b/spec/ruby/core/set/lte_spec.rb new file mode 100644 index 0000000000..291d582240 --- /dev/null +++ b/spec/ruby/core/set/lte_spec.rb @@ -0,0 +1,7 @@ +require_relative '../../spec_helper' + +describe "Set#<=" do + it "is an alias of Set#subset?" do + Set.instance_method(:<=).should == Set.instance_method(:subset?) + end +end diff --git a/spec/ruby/core/set/map_spec.rb b/spec/ruby/core/set/map_spec.rb index 996191b0a8..fd04a8bde1 100644 --- a/spec/ruby/core/set/map_spec.rb +++ b/spec/ruby/core/set/map_spec.rb @@ -1,6 +1,22 @@ require_relative '../../spec_helper' -require_relative 'shared/collect' describe "Set#map!" do - it_behaves_like :set_collect_bang, :map! + before :each do + @set = Set[1, 2, 3, 4, 5] + end + + it "yields each Object in self" do + res = [] + @set.map! { |x| res << x } + res.sort.should == [1, 2, 3, 4, 5].sort + end + + it "returns self" do + @set.map! { |x| x }.should.equal?(@set) + end + + it "replaces self with the return values of the block" do + @set.map! { |x| x * 2 } + @set.should == Set[2, 4, 6, 8, 10] + end end diff --git a/spec/ruby/core/set/member_spec.rb b/spec/ruby/core/set/member_spec.rb index 5c82e8f826..a36308eec7 100644 --- a/spec/ruby/core/set/member_spec.rb +++ b/spec/ruby/core/set/member_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/include' describe "Set#member?" do - it_behaves_like :set_include, :member? + it "is an alias of Set#include?" do + Set.instance_method(:member?).should == Set.instance_method(:include?) + end end diff --git a/spec/ruby/core/set/minus_spec.rb b/spec/ruby/core/set/minus_spec.rb index 72f98f985e..8574708559 100644 --- a/spec/ruby/core/set/minus_spec.rb +++ b/spec/ruby/core/set/minus_spec.rb @@ -1,6 +1,17 @@ require_relative '../../spec_helper' -require_relative 'shared/difference' describe "Set#-" do - it_behaves_like :set_difference, :- + before :each do + @set = Set[:a, :b, :c] + end + + it "returns a new Set containing self's elements excluding the elements in the passed Enumerable" do + (@set - Set[:a, :b]).should == Set[:c] + (@set - [:b, :c]).should == Set[:a] + end + + it "raises an ArgumentError when passed a non-Enumerable" do + -> { @set - 1 }.should.raise(ArgumentError) + -> { @set - Object.new }.should.raise(ArgumentError) + end end diff --git a/spec/ruby/core/set/plus_spec.rb b/spec/ruby/core/set/plus_spec.rb index 7e44ff0b7e..839f77fc39 100644 --- a/spec/ruby/core/set/plus_spec.rb +++ b/spec/ruby/core/set/plus_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/union' describe "Set#+" do - it_behaves_like :set_union, :+ + it "is an alias of Set#|" do + Set.instance_method(:+).should == Set.instance_method(:|) + end end diff --git a/spec/ruby/core/set/select_spec.rb b/spec/ruby/core/set/select_spec.rb index b458ffacaa..619194605b 100644 --- a/spec/ruby/core/set/select_spec.rb +++ b/spec/ruby/core/set/select_spec.rb @@ -1,6 +1,41 @@ require_relative '../../spec_helper' -require_relative 'shared/select' describe "Set#select!" do - it_behaves_like :set_select_bang, :select! + before :each do + @set = Set["one", "two", "three"] + end + + it "yields every element of self" do + ret = [] + @set.select! { |x| ret << x } + ret.sort.should == ["one", "two", "three"].sort + end + + it "keeps every element from self for which the passed block returns true" do + @set.select! { |x| x.size != 3 } + @set.size.should.eql?(1) + + @set.should_not.include?("one") + @set.should_not.include?("two") + @set.should.include?("three") + end + + it "returns self when self was modified" do + @set.select! { false }.should.equal?(@set) + end + + it "returns nil when self was not modified" do + @set.select! { true }.should == nil + end + + it "returns an Enumerator when passed no block" do + enum = @set.select! + enum.should.instance_of?(Enumerator) + + enum.each { |x| x.size != 3 } + + @set.should_not.include?("one") + @set.should_not.include?("two") + @set.should.include?("three") + end end diff --git a/spec/ruby/core/set/shared/add.rb b/spec/ruby/core/set/shared/add.rb deleted file mode 100644 index 8d6d83434f..0000000000 --- a/spec/ruby/core/set/shared/add.rb +++ /dev/null @@ -1,14 +0,0 @@ -describe :set_add, shared: true do - before :each do - @set = Set.new - end - - it "adds the passed Object to self" do - @set.send(@method, "dog") - @set.should.include?("dog") - end - - it "returns self" do - @set.send(@method, "dog").should.equal?(@set) - end -end diff --git a/spec/ruby/core/set/shared/collect.rb b/spec/ruby/core/set/shared/collect.rb deleted file mode 100644 index ad5c5afa59..0000000000 --- a/spec/ruby/core/set/shared/collect.rb +++ /dev/null @@ -1,20 +0,0 @@ -describe :set_collect_bang, shared: true do - before :each do - @set = Set[1, 2, 3, 4, 5] - end - - it "yields each Object in self" do - res = [] - @set.send(@method) { |x| res << x } - res.sort.should == [1, 2, 3, 4, 5].sort - end - - it "returns self" do - @set.send(@method) { |x| x }.should.equal?(@set) - end - - it "replaces self with the return values of the block" do - @set.send(@method) { |x| x * 2 } - @set.should == Set[2, 4, 6, 8, 10] - end -end diff --git a/spec/ruby/core/set/shared/difference.rb b/spec/ruby/core/set/shared/difference.rb deleted file mode 100644 index 8a17056a82..0000000000 --- a/spec/ruby/core/set/shared/difference.rb +++ /dev/null @@ -1,15 +0,0 @@ -describe :set_difference, shared: true do - before :each do - @set = Set[:a, :b, :c] - end - - it "returns a new Set containing self's elements excluding the elements in the passed Enumerable" do - @set.send(@method, Set[:a, :b]).should == Set[:c] - @set.send(@method, [:b, :c]).should == Set[:a] - end - - it "raises an ArgumentError when passed a non-Enumerable" do - -> { @set.send(@method, 1) }.should.raise(ArgumentError) - -> { @set.send(@method, Object.new) }.should.raise(ArgumentError) - end -end diff --git a/spec/ruby/core/set/shared/include.rb b/spec/ruby/core/set/shared/include.rb deleted file mode 100644 index 82755ccf59..0000000000 --- a/spec/ruby/core/set/shared/include.rb +++ /dev/null @@ -1,29 +0,0 @@ -describe :set_include, shared: true do - it "returns true when self contains the passed Object" do - set = Set[:a, :b, :c] - set.send(@method, :a).should == true - set.send(@method, :e).should == false - end - - describe "member equality" do - it "is checked using both #hash and #eql?" do - obj = Object.new - obj_another = Object.new - - def obj.hash; 42 end - def obj_another.hash; 42 end - def obj_another.eql?(o) hash == o.hash end - - set = Set["a", "b", "c", obj] - set.send(@method, obj_another).should == true - end - - it "is not checked using #==" do - obj = Object.new - set = Set["a", "b", "c"] - - obj.should_not_receive(:==) - set.send(@method, obj) - end - end -end diff --git a/spec/ruby/core/set/shared/inspect.rb b/spec/ruby/core/set/shared/inspect.rb deleted file mode 100644 index 31bd8accfd..0000000000 --- a/spec/ruby/core/set/shared/inspect.rb +++ /dev/null @@ -1,45 +0,0 @@ -describe :set_inspect, shared: true do - it "returns a String representation of self" do - Set[].send(@method).should.is_a?(String) - Set[nil, false, true].send(@method).should.is_a?(String) - Set[1, 2, 3].send(@method).should.is_a?(String) - Set["1", "2", "3"].send(@method).should.is_a?(String) - Set[:a, "b", Set[?c]].send(@method).should.is_a?(String) - end - - ruby_version_is "4.0" do - it "does include the elements of the set" do - Set["1"].send(@method).should == 'Set["1"]' - end - end - - ruby_version_is ""..."4.0" do - it "does include the elements of the set" do - Set["1"].send(@method).should == '#<Set: {"1"}>' - end - end - - it "puts spaces between the elements" do - Set["1", "2"].send(@method).should.include?('", "') - end - - ruby_version_is "4.0" do - it "correctly handles cyclic-references" do - set1 = Set[] - set2 = Set[set1] - set1 << set2 - set1.send(@method).should.is_a?(String) - set1.send(@method).should.include?("Set[...]") - end - end - - ruby_version_is ""..."4.0" do - it "correctly handles cyclic-references" do - set1 = Set[] - set2 = Set[set1] - set1 << set2 - set1.send(@method).should.is_a?(String) - set1.send(@method).should.include?("#<Set: {...}>") - end - end -end diff --git a/spec/ruby/core/set/shared/intersection.rb b/spec/ruby/core/set/shared/intersection.rb deleted file mode 100644 index 978a4924ef..0000000000 --- a/spec/ruby/core/set/shared/intersection.rb +++ /dev/null @@ -1,15 +0,0 @@ -describe :set_intersection, shared: true do - before :each do - @set = Set[:a, :b, :c] - end - - it "returns a new Set containing only elements shared by self and the passed Enumerable" do - @set.send(@method, Set[:b, :c, :d, :e]).should == Set[:b, :c] - @set.send(@method, [:b, :c, :d]).should == Set[:b, :c] - end - - it "raises an ArgumentError when passed a non-Enumerable" do - -> { @set.send(@method, 1) }.should.raise(ArgumentError) - -> { @set.send(@method, Object.new) }.should.raise(ArgumentError) - end -end diff --git a/spec/ruby/core/set/shared/length.rb b/spec/ruby/core/set/shared/length.rb deleted file mode 100644 index a8fcee9f39..0000000000 --- a/spec/ruby/core/set/shared/length.rb +++ /dev/null @@ -1,6 +0,0 @@ -describe :set_length, shared: true do - it "returns the number of elements in the set" do - set = Set[:a, :b, :c] - set.send(@method).should == 3 - end -end diff --git a/spec/ruby/core/set/shared/select.rb b/spec/ruby/core/set/shared/select.rb deleted file mode 100644 index 0d4a53fffd..0000000000 --- a/spec/ruby/core/set/shared/select.rb +++ /dev/null @@ -1,41 +0,0 @@ -require_relative '../../../spec_helper' - -describe :set_select_bang, shared: true do - before :each do - @set = Set["one", "two", "three"] - end - - it "yields every element of self" do - ret = [] - @set.send(@method) { |x| ret << x } - ret.sort.should == ["one", "two", "three"].sort - end - - it "keeps every element from self for which the passed block returns true" do - @set.send(@method) { |x| x.size != 3 } - @set.size.should.eql?(1) - - @set.should_not.include?("one") - @set.should_not.include?("two") - @set.should.include?("three") - end - - it "returns self when self was modified" do - @set.send(@method) { false }.should.equal?(@set) - end - - it "returns nil when self was not modified" do - @set.send(@method) { true }.should == nil - end - - it "returns an Enumerator when passed no block" do - enum = @set.send(@method) - enum.should.instance_of?(Enumerator) - - enum.each { |x| x.size != 3 } - - @set.should_not.include?("one") - @set.should_not.include?("two") - @set.should.include?("three") - end -end diff --git a/spec/ruby/core/set/shared/union.rb b/spec/ruby/core/set/shared/union.rb deleted file mode 100644 index dddf1716e5..0000000000 --- a/spec/ruby/core/set/shared/union.rb +++ /dev/null @@ -1,15 +0,0 @@ -describe :set_union, shared: true do - before :each do - @set = Set[:a, :b, :c] - end - - it "returns a new Set containing all elements of self and the passed Enumerable" do - @set.send(@method, Set[:b, :d, :e]).should == Set[:a, :b, :c, :d, :e] - @set.send(@method, [:b, :e]).should == Set[:a, :b, :c, :e] - end - - it "raises an ArgumentError when passed a non-Enumerable" do - -> { @set.send(@method, 1) }.should.raise(ArgumentError) - -> { @set.send(@method, Object.new) }.should.raise(ArgumentError) - end -end diff --git a/spec/ruby/core/set/size_spec.rb b/spec/ruby/core/set/size_spec.rb index 4ae22c5f0a..c57272a235 100644 --- a/spec/ruby/core/set/size_spec.rb +++ b/spec/ruby/core/set/size_spec.rb @@ -1,6 +1,8 @@ require_relative '../../spec_helper' -require_relative 'shared/length' describe "Set#size" do - it_behaves_like :set_length, :size + it "returns the number of elements in the set" do + set = Set[:a, :b, :c] + set.size.should == 3 + end end diff --git a/spec/ruby/core/set/to_s_spec.rb b/spec/ruby/core/set/to_s_spec.rb index 55b8bfd9b2..7f768bdcbf 100644 --- a/spec/ruby/core/set/to_s_spec.rb +++ b/spec/ruby/core/set/to_s_spec.rb @@ -1,11 +1,47 @@ require_relative "../../spec_helper" -require_relative 'shared/inspect' describe "Set#to_s" do - it_behaves_like :set_inspect, :to_s + it "returns a String representation of self" do + Set[].to_s.should.is_a?(String) + Set[nil, false, true].to_s.should.is_a?(String) + Set[1, 2, 3].to_s.should.is_a?(String) + Set["1", "2", "3"].to_s.should.is_a?(String) + Set[:a, "b", Set[?c]].to_s.should.is_a?(String) + end + + ruby_version_is "4.0" do + it "does include the elements of the set" do + Set["1"].to_s.should == 'Set["1"]' + end + end + + ruby_version_is ""..."4.0" do + it "does include the elements of the set" do + Set["1"].to_s.should == '#<Set: {"1"}>' + end + end + + it "puts spaces between the elements" do + Set["1", "2"].to_s.should.include?('", "') + end + + ruby_version_is "4.0" do + it "correctly handles cyclic-references" do + set1 = Set[] + set2 = Set[set1] + set1 << set2 + set1.to_s.should.is_a?(String) + set1.to_s.should.include?("Set[...]") + end + end - it "is an alias of inspect" do - set = Set.new - set.method(:to_s).should == set.method(:inspect) + ruby_version_is ""..."4.0" do + it "correctly handles cyclic-references" do + set1 = Set[] + set2 = Set[set1] + set1 << set2 + set1.to_s.should.is_a?(String) + set1.to_s.should.include?("#<Set: {...}>") + end end end diff --git a/spec/ruby/core/set/union_spec.rb b/spec/ruby/core/set/union_spec.rb index 3e77022d4b..206535aae2 100644 --- a/spec/ruby/core/set/union_spec.rb +++ b/spec/ruby/core/set/union_spec.rb @@ -1,10 +1,23 @@ require_relative '../../spec_helper' -require_relative 'shared/union' describe "Set#union" do - it_behaves_like :set_union, :union + it "is an alias of Set#|" do + Set.instance_method(:union).should == Set.instance_method(:|) + end end describe "Set#|" do - it_behaves_like :set_union, :| + before :each do + @set = Set[:a, :b, :c] + end + + it "returns a new Set containing all elements of self and the passed Enumerable" do + (@set | Set[:b, :d, :e]).should == Set[:a, :b, :c, :d, :e] + (@set | [:b, :e]).should == Set[:a, :b, :c, :e] + end + + it "raises an ArgumentError when passed a non-Enumerable" do + -> { @set | 1 }.should.raise(ArgumentError) + -> { @set | Object.new }.should.raise(ArgumentError) + end end diff --git a/spec/ruby/core/sizedqueue/deq_spec.rb b/spec/ruby/core/sizedqueue/deq_spec.rb index 2aeb52f8a6..51ff706557 100644 --- a/spec/ruby/core/sizedqueue/deq_spec.rb +++ b/spec/ruby/core/sizedqueue/deq_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/deque' -require_relative '../../shared/types/rb_num2dbl_fails' describe "SizedQueue#deq" do - it_behaves_like :queue_deq, :deq, -> { SizedQueue.new(10) } -end - -describe "SizedQueue operations with timeout" do - it_behaves_like :rb_num2dbl_fails, nil, -> v { q = SizedQueue.new(10); q.push(1); q.deq(timeout: v) } + it "is an alias of SizedQueue#pop" do + SizedQueue.instance_method(:deq).should == SizedQueue.instance_method(:pop) + end end diff --git a/spec/ruby/core/sizedqueue/enq_spec.rb b/spec/ruby/core/sizedqueue/enq_spec.rb index b955909475..94697cd247 100644 --- a/spec/ruby/core/sizedqueue/enq_spec.rb +++ b/spec/ruby/core/sizedqueue/enq_spec.rb @@ -1,16 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/enque' -require_relative '../../shared/sizedqueue/enque' -require_relative '../../shared/types/rb_num2dbl_fails' describe "SizedQueue#enq" do - it_behaves_like :queue_enq, :enq, -> { SizedQueue.new(10) } -end - -describe "SizedQueue#enq" do - it_behaves_like :sizedqueue_enq, :enq, -> n { SizedQueue.new(n) } -end - -describe "SizedQueue operations with timeout" do - it_behaves_like :rb_num2dbl_fails, nil, -> v { q = SizedQueue.new(1); q.enq(1, timeout: v) } + it "is an alias of SizedQueue#<<" do + SizedQueue.instance_method(:enq).should == SizedQueue.instance_method(:<<) + end end diff --git a/spec/ruby/core/sizedqueue/length_spec.rb b/spec/ruby/core/sizedqueue/length_spec.rb index b93e7f8997..b9d16d8932 100644 --- a/spec/ruby/core/sizedqueue/length_spec.rb +++ b/spec/ruby/core/sizedqueue/length_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/length' describe "SizedQueue#length" do - it_behaves_like :queue_length, :length, -> { SizedQueue.new(10) } + it "is an alias of SizedQueue#size" do + SizedQueue.instance_method(:length).should == SizedQueue.instance_method(:size) + end end diff --git a/spec/ruby/core/sizedqueue/push_spec.rb b/spec/ruby/core/sizedqueue/push_spec.rb index 9eaa6beca0..943d0fcfb4 100644 --- a/spec/ruby/core/sizedqueue/push_spec.rb +++ b/spec/ruby/core/sizedqueue/push_spec.rb @@ -1,16 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/enque' -require_relative '../../shared/sizedqueue/enque' -require_relative '../../shared/types/rb_num2dbl_fails' describe "SizedQueue#push" do - it_behaves_like :queue_enq, :push, -> { SizedQueue.new(10) } -end - -describe "SizedQueue#push" do - it_behaves_like :sizedqueue_enq, :push, -> n { SizedQueue.new(n) } -end - -describe "SizedQueue operations with timeout" do - it_behaves_like :rb_num2dbl_fails, nil, -> v { q = SizedQueue.new(1); q.push(1, timeout: v) } + it "is an alias of SizedQueue#<<" do + SizedQueue.instance_method(:push).should == SizedQueue.instance_method(:<<) + end end diff --git a/spec/ruby/core/sizedqueue/shift_spec.rb b/spec/ruby/core/sizedqueue/shift_spec.rb index 52974c1d99..f410f3f80d 100644 --- a/spec/ruby/core/sizedqueue/shift_spec.rb +++ b/spec/ruby/core/sizedqueue/shift_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' -require_relative '../../shared/queue/deque' -require_relative '../../shared/types/rb_num2dbl_fails' describe "SizedQueue#shift" do - it_behaves_like :queue_deq, :shift, -> { SizedQueue.new(10) } -end - -describe "SizedQueue operations with timeout" do - it_behaves_like :rb_num2dbl_fails, nil, -> v { q = SizedQueue.new(10); q.push(1); q.shift(timeout: v) } + it "is an alias of SizedQueue#pop" do + SizedQueue.instance_method(:shift).should == SizedQueue.instance_method(:pop) + end end diff --git a/spec/ruby/core/string/case_compare_spec.rb b/spec/ruby/core/string/case_compare_spec.rb index b83d1adb91..f98ec003be 100644 --- a/spec/ruby/core/string/case_compare_spec.rb +++ b/spec/ruby/core/string/case_compare_spec.rb @@ -1,8 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/eql' -require_relative 'shared/equal_value' describe "String#===" do - it_behaves_like :string_eql_value, :=== - it_behaves_like :string_equal_value, :=== + it "is an alias of String#==" do + String.instance_method(:===).should == String.instance_method(:==) + end end diff --git a/spec/ruby/core/string/codepoints_spec.rb b/spec/ruby/core/string/codepoints_spec.rb index 51bd57d127..4434eb66a5 100644 --- a/spec/ruby/core/string/codepoints_spec.rb +++ b/spec/ruby/core/string/codepoints_spec.rb @@ -1,7 +1,6 @@ # encoding: binary require_relative '../../spec_helper' require_relative 'shared/codepoints' -require_relative 'shared/each_codepoint_without_block' describe "String#codepoints" do it_behaves_like :string_codepoints, :codepoints diff --git a/spec/ruby/core/string/dedup_spec.rb b/spec/ruby/core/string/dedup_spec.rb index 2b31d80708..940f07668e 100644 --- a/spec/ruby/core/string/dedup_spec.rb +++ b/spec/ruby/core/string/dedup_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/dedup' describe 'String#dedup' do - it_behaves_like :string_dedup, :dedup + it "is an alias of String#-@" do + String.instance_method(:dedup).should == String.instance_method(:-@) + end end diff --git a/spec/ruby/core/string/each_codepoint_spec.rb b/spec/ruby/core/string/each_codepoint_spec.rb index c11cb1beae..08d4292371 100644 --- a/spec/ruby/core/string/each_codepoint_spec.rb +++ b/spec/ruby/core/string/each_codepoint_spec.rb @@ -1,8 +1,38 @@ +# encoding: binary require_relative '../../spec_helper' require_relative 'shared/codepoints' -require_relative 'shared/each_codepoint_without_block' describe "String#each_codepoint" do it_behaves_like :string_codepoints, :each_codepoint - it_behaves_like :string_each_codepoint_without_block, :each_codepoint + + describe "when no block is given" do + it "returns an Enumerator" do + "".each_codepoint.should.instance_of?(Enumerator) + end + + it "returns an Enumerator even when self has an invalid encoding" do + s = "\xDF".dup.force_encoding(Encoding::UTF_8) + s.valid_encoding?.should == false + s.each_codepoint.should.instance_of?(Enumerator) + end + + describe "returned Enumerator" do + describe "size" do + it "should return the size of the string" do + str = "hello" + str.each_codepoint.size.should == str.size + str = "ola" + str.each_codepoint.size.should == str.size + str = "\303\207\342\210\202\303\251\306\222g" + str.each_codepoint.size.should == str.size + end + + it "should return the size of the string even when the string has an invalid encoding" do + s = "\xDF".dup.force_encoding(Encoding::UTF_8) + s.valid_encoding?.should == false + s.each_codepoint.size.should == 1 + end + end + end + end end diff --git a/spec/ruby/core/string/equal_value_spec.rb b/spec/ruby/core/string/equal_value_spec.rb index b9c9c372f8..e8b706c524 100644 --- a/spec/ruby/core/string/equal_value_spec.rb +++ b/spec/ruby/core/string/equal_value_spec.rb @@ -1,8 +1,30 @@ require_relative '../../spec_helper' require_relative 'shared/eql' -require_relative 'shared/equal_value' describe "String#==" do it_behaves_like :string_eql_value, :== - it_behaves_like :string_equal_value, :== + + it "returns false if obj does not respond to to_str" do + ('hello' == 5).should == false + not_supported_on :opal do + ('hello' == :hello).should == false + end + ('hello' == mock('x')).should == false + end + + it "returns obj == self if obj responds to to_str" do + obj = Object.new + + # String#== merely checks if #to_str is defined. It does + # not call it. + obj.stub!(:to_str) + + obj.should_receive(:==).and_return(true) + + ('hello' == obj).should == true + end + + it "is not fooled by NUL characters" do + ("abc\0def" == "abc\0xyz").should == false + end end diff --git a/spec/ruby/core/string/intern_spec.rb b/spec/ruby/core/string/intern_spec.rb index cd7dad4359..af85e56dba 100644 --- a/spec/ruby/core/string/intern_spec.rb +++ b/spec/ruby/core/string/intern_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/to_sym' describe "String#intern" do - it_behaves_like :string_to_sym, :intern + it "is an alias of String#to_sym" do + String.instance_method(:intern).should == String.instance_method(:to_sym) + end end diff --git a/spec/ruby/core/string/length_spec.rb b/spec/ruby/core/string/length_spec.rb index 98cee1f03d..a723babdbc 100644 --- a/spec/ruby/core/string/length_spec.rb +++ b/spec/ruby/core/string/length_spec.rb @@ -1,7 +1,56 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/length' describe "String#length" do - it_behaves_like :string_length, :length + it "returns the length of self" do + "".length.should == 0 + "\x00".length.should == 1 + "one".length.should == 3 + "two".length.should == 3 + "three".length.should == 5 + "four".length.should == 4 + end + + it "returns the length of a string in different encodings" do + utf8_str = 'こにちわ' * 100 + utf8_str.length.should == 400 + utf8_str.encode(Encoding::UTF_32BE).length.should == 400 + utf8_str.encode(Encoding::SHIFT_JIS).length.should == 400 + end + + it "returns the length of the new self after encoding is changed" do + str = +'こにちわ' + str.length + + str.force_encoding('BINARY').length.should == 12 + end + + it "returns the correct length after force_encoding(BINARY)" do + utf8 = "あ" + ascii = "a" + concat = utf8 + ascii + + concat.encoding.should == Encoding::UTF_8 + concat.bytesize.should == 4 + + concat.length.should == 2 + concat.force_encoding(Encoding::ASCII_8BIT) + concat.length.should == 4 + end + + it "adds 1 for every invalid byte in UTF-8" do + "\xF4\x90\x80\x80".length.should == 4 + "a\xF4\x90\x80\x80b".length.should == 6 + "é\xF4\x90\x80\x80è".length.should == 6 + end + + it "adds 1 (and not 2) for a incomplete surrogate in UTF-16" do + "\x00\xd8".dup.force_encoding("UTF-16LE").length.should == 1 + "\xd8\x00".dup.force_encoding("UTF-16BE").length.should == 1 + end + + it "adds 1 for a broken sequence in UTF-32" do + "\x04\x03\x02\x01".dup.force_encoding("UTF-32LE").length.should == 1 + "\x01\x02\x03\x04".dup.force_encoding("UTF-32BE").length.should == 1 + end end diff --git a/spec/ruby/core/string/next_spec.rb b/spec/ruby/core/string/next_spec.rb index fcd3e5ef90..2ab121a909 100644 --- a/spec/ruby/core/string/next_spec.rb +++ b/spec/ruby/core/string/next_spec.rb @@ -1,11 +1,13 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/succ' describe "String#next" do - it_behaves_like :string_succ, :next + it "is an alias of String#succ" do + String.instance_method(:next).should == String.instance_method(:succ) + end end describe "String#next!" do - it_behaves_like :string_succ_bang, :"next!" + it "is an alias of String#succ!" do + String.instance_method(:next!).should == String.instance_method(:succ!) + end end diff --git a/spec/ruby/core/string/shared/dedup.rb b/spec/ruby/core/string/shared/dedup.rb deleted file mode 100644 index 59506c2901..0000000000 --- a/spec/ruby/core/string/shared/dedup.rb +++ /dev/null @@ -1,51 +0,0 @@ -# frozen_string_literal: false -describe :string_dedup, shared: true do - it 'returns self if the String is frozen' do - input = 'foo'.freeze - output = input.send(@method) - - output.should.equal?(input) - output.should.frozen? - end - - it 'returns a frozen copy if the String is not frozen' do - input = 'foo' - output = input.send(@method) - - output.should.frozen? - output.should_not.equal?(input) - output.should == 'foo' - end - - it "returns the same object for equal unfrozen strings" do - origin = "this is a string" - dynamic = %w(this is a string).join(' ') - - origin.should_not.equal?(dynamic) - origin.send(@method).should.equal?(dynamic.send(@method)) - end - - it "returns the same object when it's called on the same String literal" do - "unfrozen string".send(@method).should.equal?("unfrozen string".send(@method)) - "unfrozen string".send(@method).should_not.equal?("another unfrozen string".send(@method)) - end - - it "deduplicates frozen strings" do - dynamic = %w(this string is frozen).join(' ').freeze - - dynamic.should_not.equal?("this string is frozen".freeze) - - dynamic.send(@method).should.equal?("this string is frozen".freeze) - dynamic.send(@method).should.equal?("this string is frozen".send(@method).freeze) - end - - it "does not deduplicate a frozen string when it has instance variables" do - dynamic = %w(this string is frozen).join(' ') - dynamic.instance_variable_set(:@a, 1) - dynamic.freeze - - dynamic.send(@method).should_not.equal?("this string is frozen".freeze) - dynamic.send(@method).should_not.equal?("this string is frozen".send(@method).freeze) - dynamic.send(@method).should.equal?(dynamic) - end -end diff --git a/spec/ruby/core/string/shared/each_codepoint_without_block.rb b/spec/ruby/core/string/shared/each_codepoint_without_block.rb deleted file mode 100644 index 60d603954c..0000000000 --- a/spec/ruby/core/string/shared/each_codepoint_without_block.rb +++ /dev/null @@ -1,33 +0,0 @@ -# encoding: binary -describe :string_each_codepoint_without_block, shared: true do - describe "when no block is given" do - it "returns an Enumerator" do - "".send(@method).should.instance_of?(Enumerator) - end - - it "returns an Enumerator even when self has an invalid encoding" do - s = "\xDF".dup.force_encoding(Encoding::UTF_8) - s.valid_encoding?.should == false - s.send(@method).should.instance_of?(Enumerator) - end - - describe "returned Enumerator" do - describe "size" do - it "should return the size of the string" do - str = "hello" - str.send(@method).size.should == str.size - str = "ola" - str.send(@method).size.should == str.size - str = "\303\207\342\210\202\303\251\306\222g" - str.send(@method).size.should == str.size - end - - it "should return the size of the string even when the string has an invalid encoding" do - s = "\xDF".dup.force_encoding(Encoding::UTF_8) - s.valid_encoding?.should == false - s.send(@method).size.should == 1 - end - end - end - end -end diff --git a/spec/ruby/core/string/shared/equal_value.rb b/spec/ruby/core/string/shared/equal_value.rb deleted file mode 100644 index dfc5c7cd29..0000000000 --- a/spec/ruby/core/string/shared/equal_value.rb +++ /dev/null @@ -1,29 +0,0 @@ -require_relative '../../../spec_helper' -require_relative '../fixtures/classes' - -describe :string_equal_value, shared: true do - it "returns false if obj does not respond to to_str" do - 'hello'.send(@method, 5).should == false - not_supported_on :opal do - 'hello'.send(@method, :hello).should == false - end - 'hello'.send(@method, mock('x')).should == false - end - - it "returns obj == self if obj responds to to_str" do - obj = Object.new - - # String#== merely checks if #to_str is defined. It does - # not call it. - obj.stub!(:to_str) - - # Don't use @method for :== in `obj.should_receive(:==)` - obj.should_receive(:==).and_return(true) - - 'hello'.send(@method, obj).should == true - end - - it "is not fooled by NUL characters" do - "abc\0def".send(@method, "abc\0xyz").should == false - end -end diff --git a/spec/ruby/core/string/shared/length.rb b/spec/ruby/core/string/shared/length.rb deleted file mode 100644 index ae572ba755..0000000000 --- a/spec/ruby/core/string/shared/length.rb +++ /dev/null @@ -1,55 +0,0 @@ -# encoding: utf-8 - -describe :string_length, shared: true do - it "returns the length of self" do - "".send(@method).should == 0 - "\x00".send(@method).should == 1 - "one".send(@method).should == 3 - "two".send(@method).should == 3 - "three".send(@method).should == 5 - "four".send(@method).should == 4 - end - - it "returns the length of a string in different encodings" do - utf8_str = 'こにちわ' * 100 - utf8_str.send(@method).should == 400 - utf8_str.encode(Encoding::UTF_32BE).send(@method).should == 400 - utf8_str.encode(Encoding::SHIFT_JIS).send(@method).should == 400 - end - - it "returns the length of the new self after encoding is changed" do - str = +'こにちわ' - str.send(@method) - - str.force_encoding('BINARY').send(@method).should == 12 - end - - it "returns the correct length after force_encoding(BINARY)" do - utf8 = "あ" - ascii = "a" - concat = utf8 + ascii - - concat.encoding.should == Encoding::UTF_8 - concat.bytesize.should == 4 - - concat.send(@method).should == 2 - concat.force_encoding(Encoding::ASCII_8BIT) - concat.send(@method).should == 4 - end - - it "adds 1 for every invalid byte in UTF-8" do - "\xF4\x90\x80\x80".send(@method).should == 4 - "a\xF4\x90\x80\x80b".send(@method).should == 6 - "é\xF4\x90\x80\x80è".send(@method).should == 6 - end - - it "adds 1 (and not 2) for a incomplete surrogate in UTF-16" do - "\x00\xd8".dup.force_encoding("UTF-16LE").send(@method).should == 1 - "\xd8\x00".dup.force_encoding("UTF-16BE").send(@method).should == 1 - end - - it "adds 1 for a broken sequence in UTF-32" do - "\x04\x03\x02\x01".dup.force_encoding("UTF-32LE").send(@method).should == 1 - "\x01\x02\x03\x04".dup.force_encoding("UTF-32BE").send(@method).should == 1 - end -end diff --git a/spec/ruby/core/string/shared/succ.rb b/spec/ruby/core/string/shared/succ.rb deleted file mode 100644 index 8f1d327741..0000000000 --- a/spec/ruby/core/string/shared/succ.rb +++ /dev/null @@ -1,87 +0,0 @@ -# encoding: binary -describe :string_succ, shared: true do - it "returns an empty string for empty strings" do - "".send(@method).should == "" - end - - it "returns the successor by increasing the rightmost alphanumeric (digit => digit, letter => letter with same case)" do - "abcd".send(@method).should == "abce" - "THX1138".send(@method).should == "THX1139" - - "<<koala>>".send(@method).should == "<<koalb>>" - "==A??".send(@method).should == "==B??" - end - - it "increases non-alphanumerics (via ascii rules) if there are no alphanumerics" do - "***".send(@method).should == "**+" - "**`".send(@method).should == "**a" - end - - it "increases the next best alphanumeric (jumping over non-alphanumerics) if there is a carry" do - "dz".send(@method).should == "ea" - "HZ".send(@method).should == "IA" - "49".send(@method).should == "50" - - "izz".send(@method).should == "jaa" - "IZZ".send(@method).should == "JAA" - "699".send(@method).should == "700" - - "6Z99z99Z".send(@method).should == "7A00a00A" - - "1999zzz".send(@method).should == "2000aaa" - "NZ/[]ZZZ9999".send(@method).should == "OA/[]AAA0000" - end - - it "increases the next best character if there is a carry for non-alphanumerics" do - "(\xFF".send(@method).should == ")\x00" - "`\xFF".send(@method).should == "a\x00" - "<\xFF\xFF".send(@method).should == "=\x00\x00" - end - - it "adds an additional character (just left to the last increased one) if there is a carry and no character left to increase" do - "z".send(@method).should == "aa" - "Z".send(@method).should == "AA" - "9".send(@method).should == "10" - - "zz".send(@method).should == "aaa" - "ZZ".send(@method).should == "AAA" - "99".send(@method).should == "100" - - "9Z99z99Z".send(@method).should == "10A00a00A" - - "ZZZ9999".send(@method).should == "AAAA0000" - "/[]9999".send(@method).should == "/[]10000" - "/[]ZZZ9999".send(@method).should == "/[]AAAA0000" - "Z/[]ZZZ9999".send(@method).should == "AA/[]AAA0000" - - # non-alphanumeric cases - "\xFF".send(@method).should == "\x01\x00" - "\xFF\xFF".send(@method).should == "\x01\x00\x00" - end - - it "returns String instances when called on a subclass" do - StringSpecs::MyString.new("").send(@method).should.instance_of?(String) - StringSpecs::MyString.new("a").send(@method).should.instance_of?(String) - StringSpecs::MyString.new("z").send(@method).should.instance_of?(String) - end - - it "returns a String in the same encoding as self" do - "z".encode("US-ASCII").send(@method).encoding.should == Encoding::US_ASCII - end -end - -describe :string_succ_bang, shared: true do - it "is equivalent to succ, but modifies self in place (still returns self)" do - ["", "abcd", "THX1138"].each do |s| - s = +s - r = s.dup.send(@method) - s.send(@method).should.equal?(s) - s.should == r - end - end - - it "raises a FrozenError if self is frozen" do - -> { "".freeze.send(@method) }.should.raise(FrozenError) - -> { "abcd".freeze.send(@method) }.should.raise(FrozenError) - end -end diff --git a/spec/ruby/core/string/shared/to_s.rb b/spec/ruby/core/string/shared/to_s.rb deleted file mode 100644 index 96c59470d6..0000000000 --- a/spec/ruby/core/string/shared/to_s.rb +++ /dev/null @@ -1,13 +0,0 @@ -describe :string_to_s, shared: true do - it "returns self when self.class == String" do - a = "a string" - a.should.equal?(a.send(@method)) - end - - it "returns a new instance of String when called on a subclass" do - a = StringSpecs::MyString.new("a string") - s = a.send(@method) - s.should == "a string" - s.should.instance_of?(String) - end -end diff --git a/spec/ruby/core/string/shared/to_sym.rb b/spec/ruby/core/string/shared/to_sym.rb deleted file mode 100644 index 2a8a2e3182..0000000000 --- a/spec/ruby/core/string/shared/to_sym.rb +++ /dev/null @@ -1,72 +0,0 @@ -describe :string_to_sym, shared: true do - it "returns the symbol corresponding to self" do - "Koala".send(@method).should.equal? :Koala - 'cat'.send(@method).should.equal? :cat - '@cat'.send(@method).should.equal? :@cat - 'cat and dog'.send(@method).should.equal? :"cat and dog" - "abc=".send(@method).should.equal? :abc= - end - - it "does not special case +(binary) and -(binary)" do - "+(binary)".send(@method).should.equal? :"+(binary)" - "-(binary)".send(@method).should.equal? :"-(binary)" - end - - it "does not special case certain operators" do - "!@".send(@method).should.equal? :"!@" - "~@".send(@method).should.equal? :"~@" - "!(unary)".send(@method).should.equal? :"!(unary)" - "~(unary)".send(@method).should.equal? :"~(unary)" - "+(unary)".send(@method).should.equal? :"+(unary)" - "-(unary)".send(@method).should.equal? :"-(unary)" - end - - it "returns a US-ASCII Symbol for a UTF-8 String containing only US-ASCII characters" do - sym = "foobar".send(@method) - sym.encoding.should == Encoding::US_ASCII - sym.should.equal? :"foobar" - end - - it "returns a US-ASCII Symbol for a binary String containing only US-ASCII characters" do - sym = "foobar".b.send(@method) - sym.encoding.should == Encoding::US_ASCII - sym.should.equal? :"foobar" - end - - it "returns a UTF-8 Symbol for a UTF-8 String containing non US-ASCII characters" do - sym = "il était une fois".send(@method) - sym.encoding.should == Encoding::UTF_8 - sym.should.equal? :"il était une #{'fois'}" - end - - it "returns a UTF-16LE Symbol for a UTF-16LE String containing non US-ASCII characters" do - utf16_str = "UtéF16".encode(Encoding::UTF_16LE) - sym = utf16_str.send(@method) - sym.encoding.should == Encoding::UTF_16LE - sym.to_s.should == utf16_str - end - - it "returns a binary Symbol for a binary String containing non US-ASCII characters" do - binary_string = "binarí".b - sym = binary_string.send(@method) - sym.encoding.should == Encoding::BINARY - sym.to_s.should == binary_string - end - - it "ignores existing symbols with different encoding" do - source = "fée" - - iso_symbol = source.dup.force_encoding(Encoding::ISO_8859_1).send(@method) - iso_symbol.encoding.should == Encoding::ISO_8859_1 - binary_symbol = source.dup.force_encoding(Encoding::BINARY).send(@method) - binary_symbol.encoding.should == Encoding::BINARY - end - - it "raises an EncodingError for UTF-8 String containing invalid bytes" do - invalid_utf8 = "\xC3" - invalid_utf8.should_not.valid_encoding? - -> { - invalid_utf8.send(@method) - }.should.raise(EncodingError, 'invalid symbol in encoding UTF-8 :"\xC3"') - end -end diff --git a/spec/ruby/core/string/size_spec.rb b/spec/ruby/core/string/size_spec.rb index 9e1f40c5ae..6fc81480c4 100644 --- a/spec/ruby/core/string/size_spec.rb +++ b/spec/ruby/core/string/size_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/length' describe "String#size" do - it_behaves_like :string_length, :size + it "is an alias of String#length" do + String.instance_method(:size).should == String.instance_method(:length) + end end diff --git a/spec/ruby/core/string/slice_spec.rb b/spec/ruby/core/string/slice_spec.rb index 14e2251b3f..16d7665bbf 100644 --- a/spec/ruby/core/string/slice_spec.rb +++ b/spec/ruby/core/string/slice_spec.rb @@ -1,39 +1,12 @@ -# -*- encoding: utf-8 -*- # frozen_string_literal: false require_relative '../../spec_helper' require_relative 'fixtures/classes' require_relative 'shared/slice' describe "String#slice" do - it_behaves_like :string_slice, :slice -end - -describe "String#slice with index, length" do - it_behaves_like :string_slice_index_length, :slice -end - -describe "String#slice with Range" do - it_behaves_like :string_slice_range, :slice -end - -describe "String#slice with Regexp" do - it_behaves_like :string_slice_regexp, :slice -end - -describe "String#slice with Regexp, index" do - it_behaves_like :string_slice_regexp_index, :slice -end - -describe "String#slice with Regexp, group" do - it_behaves_like :string_slice_regexp_group, :slice -end - -describe "String#slice with String" do - it_behaves_like :string_slice_string, :slice -end - -describe "String#slice with Symbol" do - it_behaves_like :string_slice_symbol, :slice + it "is an alias of String#[]" do + String.instance_method(:slice).should == String.instance_method(:[]) + end end describe "String#slice! with index" do diff --git a/spec/ruby/core/string/succ_spec.rb b/spec/ruby/core/string/succ_spec.rb index 65047e0aa2..87beca8b09 100644 --- a/spec/ruby/core/string/succ_spec.rb +++ b/spec/ruby/core/string/succ_spec.rb @@ -1,11 +1,90 @@ +# encoding: binary require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/succ' describe "String#succ" do - it_behaves_like :string_succ, :succ + it "returns an empty string for empty strings" do + "".succ.should == "" + end + + it "returns the successor by increasing the rightmost alphanumeric (digit => digit, letter => letter with same case)" do + "abcd".succ.should == "abce" + "THX1138".succ.should == "THX1139" + + "<<koala>>".succ.should == "<<koalb>>" + "==A??".succ.should == "==B??" + end + + it "increases non-alphanumerics (via ascii rules) if there are no alphanumerics" do + "***".succ.should == "**+" + "**`".succ.should == "**a" + end + + it "increases the next best alphanumeric (jumping over non-alphanumerics) if there is a carry" do + "dz".succ.should == "ea" + "HZ".succ.should == "IA" + "49".succ.should == "50" + + "izz".succ.should == "jaa" + "IZZ".succ.should == "JAA" + "699".succ.should == "700" + + "6Z99z99Z".succ.should == "7A00a00A" + + "1999zzz".succ.should == "2000aaa" + "NZ/[]ZZZ9999".succ.should == "OA/[]AAA0000" + end + + it "increases the next best character if there is a carry for non-alphanumerics" do + "(\xFF".succ.should == ")\x00" + "`\xFF".succ.should == "a\x00" + "<\xFF\xFF".succ.should == "=\x00\x00" + end + + it "adds an additional character (just left to the last increased one) if there is a carry and no character left to increase" do + "z".succ.should == "aa" + "Z".succ.should == "AA" + "9".succ.should == "10" + + "zz".succ.should == "aaa" + "ZZ".succ.should == "AAA" + "99".succ.should == "100" + + "9Z99z99Z".succ.should == "10A00a00A" + + "ZZZ9999".succ.should == "AAAA0000" + "/[]9999".succ.should == "/[]10000" + "/[]ZZZ9999".succ.should == "/[]AAAA0000" + "Z/[]ZZZ9999".succ.should == "AA/[]AAA0000" + + # non-alphanumeric cases + "\xFF".succ.should == "\x01\x00" + "\xFF\xFF".succ.should == "\x01\x00\x00" + end + + it "returns String instances when called on a subclass" do + StringSpecs::MyString.new("").succ.should.instance_of?(String) + StringSpecs::MyString.new("a").succ.should.instance_of?(String) + StringSpecs::MyString.new("z").succ.should.instance_of?(String) + end + + it "returns a String in the same encoding as self" do + "z".encode("US-ASCII").succ.encoding.should == Encoding::US_ASCII + end end describe "String#succ!" do - it_behaves_like :string_succ_bang, :"succ!" + it "is equivalent to succ, but modifies self in place (still returns self)" do + ["", "abcd", "THX1138"].each do |s| + s = +s + r = s.dup.succ! + s.succ!.should.equal?(s) + s.should == r + end + end + + it "raises a FrozenError if self is frozen" do + -> { "".freeze.succ! }.should.raise(FrozenError) + -> { "abcd".freeze.succ! }.should.raise(FrozenError) + end end diff --git a/spec/ruby/core/string/to_s_spec.rb b/spec/ruby/core/string/to_s_spec.rb index e5872745a8..c48c7f89ac 100644 --- a/spec/ruby/core/string/to_s_spec.rb +++ b/spec/ruby/core/string/to_s_spec.rb @@ -1,7 +1,16 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/to_s' describe "String#to_s" do - it_behaves_like :string_to_s, :to_s + it "returns self when self.class == String" do + a = "a string" + a.should.equal?(a.to_s) + end + + it "returns a new instance of String when called on a subclass" do + a = StringSpecs::MyString.new("a string") + s = a.to_s + s.should == "a string" + s.should.instance_of?(String) + end end diff --git a/spec/ruby/core/string/to_str_spec.rb b/spec/ruby/core/string/to_str_spec.rb index e24262a7ae..8253b3d8a3 100644 --- a/spec/ruby/core/string/to_str_spec.rb +++ b/spec/ruby/core/string/to_str_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/to_s' describe "String#to_str" do - it_behaves_like :string_to_s, :to_str + it "is an alias of String#to_s" do + String.instance_method(:to_str).should == String.instance_method(:to_s) + end end diff --git a/spec/ruby/core/string/to_sym_spec.rb b/spec/ruby/core/string/to_sym_spec.rb index f9135211ce..f0ffe58674 100644 --- a/spec/ruby/core/string/to_sym_spec.rb +++ b/spec/ruby/core/string/to_sym_spec.rb @@ -1,7 +1,74 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/to_sym' describe "String#to_sym" do - it_behaves_like :string_to_sym, :to_sym + it "returns the symbol corresponding to self" do + "Koala".to_sym.should.equal? :Koala + 'cat'.to_sym.should.equal? :cat + '@cat'.to_sym.should.equal? :@cat + 'cat and dog'.to_sym.should.equal? :"cat and dog" + "abc=".to_sym.should.equal? :abc= + end + + it "does not special case +(binary) and -(binary)" do + "+(binary)".to_sym.should.equal? :"+(binary)" + "-(binary)".to_sym.should.equal? :"-(binary)" + end + + it "does not special case certain operators" do + "!@".to_sym.should.equal? :"!@" + "~@".to_sym.should.equal? :"~@" + "!(unary)".to_sym.should.equal? :"!(unary)" + "~(unary)".to_sym.should.equal? :"~(unary)" + "+(unary)".to_sym.should.equal? :"+(unary)" + "-(unary)".to_sym.should.equal? :"-(unary)" + end + + it "returns a US-ASCII Symbol for a UTF-8 String containing only US-ASCII characters" do + sym = "foobar".to_sym + sym.encoding.should == Encoding::US_ASCII + sym.should.equal? :"foobar" + end + + it "returns a US-ASCII Symbol for a binary String containing only US-ASCII characters" do + sym = "foobar".b.to_sym + sym.encoding.should == Encoding::US_ASCII + sym.should.equal? :"foobar" + end + + it "returns a UTF-8 Symbol for a UTF-8 String containing non US-ASCII characters" do + sym = "il était une fois".to_sym + sym.encoding.should == Encoding::UTF_8 + sym.should.equal? :"il était une fois" + end + + it "returns a UTF-16LE Symbol for a UTF-16LE String containing non US-ASCII characters" do + utf16_str = "UtéF16".encode(Encoding::UTF_16LE) + sym = utf16_str.to_sym + sym.encoding.should == Encoding::UTF_16LE + sym.to_s.should == utf16_str + end + + it "returns a binary Symbol for a binary String containing non US-ASCII characters" do + binary_string = "binarí".b + sym = binary_string.to_sym + sym.encoding.should == Encoding::BINARY + sym.to_s.should == binary_string + end + + it "ignores existing symbols with different encoding" do + source = "fée" + + iso_symbol = source.dup.force_encoding(Encoding::ISO_8859_1).to_sym + iso_symbol.encoding.should == Encoding::ISO_8859_1 + binary_symbol = source.dup.force_encoding(Encoding::BINARY).to_sym + binary_symbol.encoding.should == Encoding::BINARY + end + + it "raises an EncodingError for UTF-8 String containing invalid bytes" do + invalid_utf8 = "\xC3" + invalid_utf8.should_not.valid_encoding? + -> { + invalid_utf8.to_sym + }.should.raise(EncodingError, 'invalid symbol in encoding UTF-8 :"\xC3"') + end end diff --git a/spec/ruby/core/string/uminus_spec.rb b/spec/ruby/core/string/uminus_spec.rb index 46d88f6704..43abf71d50 100644 --- a/spec/ruby/core/string/uminus_spec.rb +++ b/spec/ruby/core/string/uminus_spec.rb @@ -1,6 +1,53 @@ +# frozen_string_literal: false require_relative '../../spec_helper' -require_relative 'shared/dedup' describe 'String#-@' do - it_behaves_like :string_dedup, :-@ + it 'returns self if the String is frozen' do + input = 'foo'.freeze + output = -input + + output.should.equal?(input) + output.should.frozen? + end + + it 'returns a frozen copy if the String is not frozen' do + input = 'foo' + output = -input + + output.should.frozen? + output.should_not.equal?(input) + output.should == 'foo' + end + + it "returns the same object for equal unfrozen strings" do + origin = "this is a string" + dynamic = %w(this is a string).join(' ') + + origin.should_not.equal?(dynamic) + (-origin).should.equal?(-dynamic) + end + + it "returns the same object when it's called on the same String literal" do + (-"unfrozen string").should.equal?(-"unfrozen string") + (-"unfrozen string").should_not.equal?(-"another unfrozen string") + end + + it "deduplicates frozen strings" do + dynamic = %w(this string is frozen).join(' ').freeze + + dynamic.should_not.equal?("this string is frozen".freeze) + + (-dynamic).should.equal?("this string is frozen".freeze) + (-dynamic).should.equal?((-"this string is frozen").freeze) + end + + it "does not deduplicate a frozen string when it has instance variables" do + dynamic = %w(this string is frozen).join(' ') + dynamic.instance_variable_set(:@a, 1) + dynamic.freeze + + (-dynamic).should_not.equal?("this string is frozen".freeze) + (-dynamic).should_not.equal?((-"this string is frozen").freeze) + (-dynamic).should.equal?(-dynamic) + end end diff --git a/spec/ruby/core/struct/deconstruct_spec.rb b/spec/ruby/core/struct/deconstruct_spec.rb index 32d4f6bac4..aad82ac2ba 100644 --- a/spec/ruby/core/struct/deconstruct_spec.rb +++ b/spec/ruby/core/struct/deconstruct_spec.rb @@ -1,10 +1,7 @@ require_relative '../../spec_helper' describe "Struct#deconstruct" do - it "returns an array of attribute values" do - struct = Struct.new(:x, :y) - s = struct.new(1, 2) - - s.deconstruct.should == [1, 2] + it "is an alias of Struct#to_a" do + Struct.instance_method(:deconstruct).should == Struct.instance_method(:to_a) end end diff --git a/spec/ruby/core/struct/filter_spec.rb b/spec/ruby/core/struct/filter_spec.rb index 0ccd8ad6b2..5d11f47e6b 100644 --- a/spec/ruby/core/struct/filter_spec.rb +++ b/spec/ruby/core/struct/filter_spec.rb @@ -1,10 +1,8 @@ require_relative '../../spec_helper' -require_relative 'shared/select' -require_relative 'shared/accessor' -require_relative '../enumerable/shared/enumeratorized' +require_relative 'fixtures/classes' describe "Struct#filter" do - it_behaves_like :struct_select, :filter - it_behaves_like :struct_accessor, :filter - it_behaves_like :enumeratorized_with_origin_size, :filter, Struct.new(:foo).new + it "is an alias of Struct#select" do + StructClasses::Car.instance_method(:filter).should == StructClasses::Car.instance_method(:select) + end end diff --git a/spec/ruby/core/struct/inspect_spec.rb b/spec/ruby/core/struct/inspect_spec.rb index 657b06abc1..13fd0bef41 100644 --- a/spec/ruby/core/struct/inspect_spec.rb +++ b/spec/ruby/core/struct/inspect_spec.rb @@ -1,7 +1,8 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/inspect' describe "Struct#inspect" do - it_behaves_like :struct_inspect, :inspect + it "is an alias of Struct#to_s" do + StructClasses::Car.instance_method(:inspect).should == StructClasses::Car.instance_method(:to_s) + end end diff --git a/spec/ruby/core/struct/length_spec.rb b/spec/ruby/core/struct/length_spec.rb index 1143676122..8d48f4118d 100644 --- a/spec/ruby/core/struct/length_spec.rb +++ b/spec/ruby/core/struct/length_spec.rb @@ -1,12 +1,8 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/accessor' describe "Struct#length" do - it "returns the number of attributes" do - StructClasses::Car.new('Cadillac', 'DeVille').length.should == 3 - StructClasses::Car.new.length.should == 3 + it "is an alias of Struct#size" do + StructClasses::Car.instance_method(:length).should == StructClasses::Car.instance_method(:size) end - - it_behaves_like :struct_accessor, :length end diff --git a/spec/ruby/core/struct/select_spec.rb b/spec/ruby/core/struct/select_spec.rb index ee846ec45f..5f26a177eb 100644 --- a/spec/ruby/core/struct/select_spec.rb +++ b/spec/ruby/core/struct/select_spec.rb @@ -1,10 +1,31 @@ require_relative '../../spec_helper' -require_relative 'shared/select' +require_relative 'fixtures/classes' require_relative 'shared/accessor' require_relative '../enumerable/shared/enumeratorized' describe "Struct#select" do - it_behaves_like :struct_select, :select it_behaves_like :struct_accessor, :select it_behaves_like :enumeratorized_with_origin_size, :select, Struct.new(:foo).new + + it "raises an ArgumentError if given any non-block arguments" do + struct = StructClasses::Car.new + -> { struct.select(1) { } }.should.raise(ArgumentError) + end + + it "returns a new array of elements for which block is true" do + struct = StructClasses::Car.new("Toyota", "Tercel", "2000") + struct.select { |i| i == "2000" }.should == [ "2000" ] + end + + it "returns an instance of Array" do + struct = StructClasses::Car.new("Ford", "Escort", "1995") + struct.select { true }.should.instance_of?(Array) + end + + describe "without block" do + it "returns an instance of Enumerator" do + struct = Struct.new(:foo).new + struct.select.should.instance_of?(Enumerator) + end + end end diff --git a/spec/ruby/core/struct/shared/inspect.rb b/spec/ruby/core/struct/shared/inspect.rb deleted file mode 100644 index 1a0fb6a6b2..0000000000 --- a/spec/ruby/core/struct/shared/inspect.rb +++ /dev/null @@ -1,40 +0,0 @@ -describe :struct_inspect, shared: true do - it "returns a string representation showing members and values" do - car = StructClasses::Car.new('Ford', 'Ranger') - car.send(@method).should == '#<struct StructClasses::Car make="Ford", model="Ranger", year=nil>' - end - - it "returns a string representation without the class name for anonymous structs" do - Struct.new(:a).new("").send(@method).should == '#<struct a="">' - end - - it "returns a string representation without the class name for structs nested in anonymous classes" do - c = Class.new - c.class_eval <<~DOC - class Foo < Struct.new(:a); end - DOC - - c::Foo.new("").send(@method).should == '#<struct a="">' - end - - it "returns a string representation without the class name for structs nested in anonymous modules" do - m = Module.new - m.module_eval <<~DOC - class Foo < Struct.new(:a); end - DOC - - m::Foo.new("").send(@method).should == '#<struct a="">' - end - - it "does not call #name method" do - struct = StructClasses::StructWithOverriddenName.new("") - struct.send(@method).should == '#<struct StructClasses::StructWithOverriddenName a="">' - end - - it "does not call #name method when struct is anonymous" do - struct = Struct.new(:a) - def struct.name; "A"; end - - struct.new("").send(@method).should == '#<struct a="">' - end -end diff --git a/spec/ruby/core/struct/shared/select.rb b/spec/ruby/core/struct/shared/select.rb deleted file mode 100644 index dfa1a809fe..0000000000 --- a/spec/ruby/core/struct/shared/select.rb +++ /dev/null @@ -1,26 +0,0 @@ -require_relative '../../../spec_helper' -require_relative '../fixtures/classes' - -describe :struct_select, shared: true do - it "raises an ArgumentError if given any non-block arguments" do - struct = StructClasses::Car.new - -> { struct.send(@method, 1) { } }.should.raise(ArgumentError) - end - - it "returns a new array of elements for which block is true" do - struct = StructClasses::Car.new("Toyota", "Tercel", "2000") - struct.send(@method) { |i| i == "2000" }.should == [ "2000" ] - end - - it "returns an instance of Array" do - struct = StructClasses::Car.new("Ford", "Escort", "1995") - struct.send(@method) { true }.should.instance_of?(Array) - end - - describe "without block" do - it "returns an instance of Enumerator" do - struct = Struct.new(:foo).new - struct.send(@method).should.instance_of?(Enumerator) - end - end -end diff --git a/spec/ruby/core/struct/size_spec.rb b/spec/ruby/core/struct/size_spec.rb index 09f260cf20..5f07320bb9 100644 --- a/spec/ruby/core/struct/size_spec.rb +++ b/spec/ruby/core/struct/size_spec.rb @@ -3,8 +3,9 @@ require_relative 'fixtures/classes' require_relative 'shared/accessor' describe "Struct#size" do - it "is a synonym for length" do - StructClasses::Car.new.size.should == StructClasses::Car.new.length + it "returns the number of attributes" do + StructClasses::Car.new('Cadillac', 'DeVille').length.should == 3 + StructClasses::Car.new.length.should == 3 end it_behaves_like :struct_accessor, :size diff --git a/spec/ruby/core/struct/to_s_spec.rb b/spec/ruby/core/struct/to_s_spec.rb index 94c672d3d5..9648b8af9b 100644 --- a/spec/ruby/core/struct/to_s_spec.rb +++ b/spec/ruby/core/struct/to_s_spec.rb @@ -1,12 +1,43 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/inspect' describe "Struct#to_s" do - it "is a synonym for inspect" do + it "returns a string representation showing members and values" do car = StructClasses::Car.new('Ford', 'Ranger') - car.inspect.should == car.to_s + car.to_s.should == '#<struct StructClasses::Car make="Ford", model="Ranger", year=nil>' end - it_behaves_like :struct_inspect, :to_s + it "returns a string representation without the class name for anonymous structs" do + Struct.new(:a).new("").to_s.should == '#<struct a="">' + end + + it "returns a string representation without the class name for structs nested in anonymous classes" do + c = Class.new + c.class_eval <<~DOC + class Foo < Struct.new(:a); end + DOC + + c::Foo.new("").to_s.should == '#<struct a="">' + end + + it "returns a string representation without the class name for structs nested in anonymous modules" do + m = Module.new + m.module_eval <<~DOC + class Foo < Struct.new(:a); end + DOC + + m::Foo.new("").to_s.should == '#<struct a="">' + end + + it "does not call #name method" do + struct = StructClasses::StructWithOverriddenName.new("") + struct.to_s.should == '#<struct StructClasses::StructWithOverriddenName a="">' + end + + it "does not call #name method when struct is anonymous" do + struct = Struct.new(:a) + def struct.name; "A"; end + + struct.new("").to_s.should == '#<struct a="">' + end end diff --git a/spec/ruby/core/struct/values_spec.rb b/spec/ruby/core/struct/values_spec.rb index b2d11725b9..16583253d7 100644 --- a/spec/ruby/core/struct/values_spec.rb +++ b/spec/ruby/core/struct/values_spec.rb @@ -2,10 +2,7 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' describe "Struct#values" do - it "is a synonym for to_a" do - car = StructClasses::Car.new('Nissan', 'Maxima') - car.values.should == car.to_a - - StructClasses::Car.new.values.should == StructClasses::Car.new.to_a + it "is an alias of Struct#to_a" do + StructClasses::Car.instance_method(:values).should == StructClasses::Car.instance_method(:to_a) end end diff --git a/spec/ruby/core/symbol/case_compare_spec.rb b/spec/ruby/core/symbol/case_compare_spec.rb index 0c6bc1eda5..a296132c04 100644 --- a/spec/ruby/core/symbol/case_compare_spec.rb +++ b/spec/ruby/core/symbol/case_compare_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' describe "Symbol#===" do - it "returns true when the argument is a Symbol" do - (Symbol === :ruby).should == true - end - - it "returns false when the argument is a String" do - (Symbol === 'ruby').should == false + it "is an alias of Symbol#==" do + Symbol.instance_method(:===).should == Symbol.instance_method(:==) end end diff --git a/spec/ruby/core/symbol/element_reference_spec.rb b/spec/ruby/core/symbol/element_reference_spec.rb index df6bc15ddb..360a661891 100644 --- a/spec/ruby/core/symbol/element_reference_spec.rb +++ b/spec/ruby/core/symbol/element_reference_spec.rb @@ -1,6 +1,263 @@ require_relative '../../spec_helper' -require_relative 'shared/slice' +require_relative 'fixtures/classes' describe "Symbol#[]" do - it_behaves_like :symbol_slice, :[] + describe "with an Integer index" do + it "returns the character code of the element at the index" do + :symbol[1].should == ?y + end + + it "returns nil if the index starts from the end and is greater than the length" do + :symbol[-10].should == nil + end + + it "returns nil if the index is greater than the length" do + :symbol[42].should == nil + end + end + + describe "with an Integer index and length" do + describe "and a positive index and length" do + it "returns a slice" do + :symbol[1, 3].should == "ymb" + end + + it "returns a blank slice if the length is 0" do + :symbol[0, 0].should == "" + :symbol[1, 0].should == "" + end + + it "returns a slice of all remaining characters if the given length is greater than the actual length" do + :symbol[1, 100].should == "ymbol" + end + + it "returns nil if the index is greater than the length" do + :symbol[10, 1].should == nil + end + end + + describe "and a positive index and negative length" do + it "returns nil" do + :symbol[0, -1].should == nil + :symbol[1, -1].should == nil + end + end + + describe "and a negative index and positive length" do + it "returns a slice starting from the end upto the length" do + :symbol[-3, 2].should == "bo" + end + + it "returns a blank slice if the length is 0" do + :symbol[-1, 0].should == "" + end + + it "returns a slice of all remaining characters if the given length is larger than the actual length" do + :symbol[-4, 100].should == "mbol" + end + + it "returns nil if the index is past the start" do + :symbol[-10, 1].should == nil + end + end + + describe "and a negative index and negative length" do + it "returns nil" do + :symbol[-1, -1].should == nil + end + end + + describe "and a Float length" do + it "converts the length to an Integer" do + :symbol[2, 2.5].should == "mb" + end + end + + describe "and a nil length" do + it "raises a TypeError" do + -> { :symbol[1, nil] }.should.raise(TypeError) + end + end + + describe "and a length that cannot be converted into an Integer" do + it "raises a TypeError when given an Array" do + -> { :symbol[1, Array.new] }.should.raise(TypeError) + end + + it "raises a TypeError when given an Hash" do + -> { :symbol[1, Hash.new] }.should.raise(TypeError) + end + + it "raises a TypeError when given an Object" do + -> { :symbol[1, Object.new] }.should.raise(TypeError) + end + end + end + + describe "with a Float index" do + it "converts the index to an Integer" do + :symbol[1.5].should == ?y + end + end + + describe "with a nil index" do + it "raises a TypeError" do + -> { :symbol[nil] }.should.raise(TypeError) + end + end + + describe "with an index that cannot be converted into an Integer" do + it "raises a TypeError when given an Array" do + -> { :symbol[Array.new] }.should.raise(TypeError) + end + + it "raises a TypeError when given an Hash" do + -> { :symbol[Hash.new] }.should.raise(TypeError) + end + + it "raises a TypeError when given an Object" do + -> { :symbol[Object.new] }.should.raise(TypeError) + end + end + + describe "with a Range slice" do + describe "that is within bounds" do + it "returns a slice if both range values begin at the start and are within bounds" do + :symbol[1..4].should == "ymbo" + end + + it "returns a slice if the first range value begins at the start and the last begins at the end" do + :symbol[1..-1].should == "ymbol" + end + + it "returns a slice if the first range value begins at the end and the last begins at the end" do + :symbol[-4..-1].should == "mbol" + end + end + + describe "that is out of bounds" do + it "returns nil if the first range value begins past the end" do + :symbol[10..12].should == nil + end + + it "returns a blank string if the first range value is within bounds and the last range value is not" do + :symbol[-2..-10].should == "" + :symbol[2..-10].should == "" + end + + it "returns nil if the first range value starts from the end and is within bounds and the last value starts from the end and is greater than the length" do + :symbol[-10..-12].should == nil + end + + it "returns nil if the first range value starts from the end and is out of bounds and the last value starts from the end and is less than the length" do + :symbol[-10..-2].should == nil + end + end + + describe "with Float values" do + it "converts the first value to an Integer" do + :symbol[0.5..2].should == "sym" + end + + it "converts the last value to an Integer" do + :symbol[0..2.5].should == "sym" + end + end + end + + describe "with a Range subclass slice" do + it "returns a slice" do + range = SymbolSpecs::MyRange.new(1, 4) + :symbol[range].should == "ymbo" + end + end + + describe "with a Regex slice" do + describe "without a capture index" do + it "returns a string of the match" do + :symbol[/[^bol]+/].should == "sym" + end + + it "returns nil if the expression does not match" do + :symbol[/0-9/].should == nil + end + + it "sets $~ to the MatchData if there is a match" do + :symbol[/[^bol]+/] + $~[0].should == "sym" + end + + it "does not set $~ if there if there is not a match" do + :symbol[/[0-9]+/] + $~.should == nil + end + end + + describe "with a capture index" do + it "returns a string of the complete match if the capture index is 0" do + :symbol[/(sy)(mb)(ol)/, 0].should == "symbol" + end + + it "returns a string for the matched capture at the given index" do + :symbol[/(sy)(mb)(ol)/, 1].should == "sy" + :symbol[/(sy)(mb)(ol)/, -1].should == "ol" + end + + it "returns nil if there is no capture for the index" do + :symbol[/(sy)(mb)(ol)/, 4].should == nil + :symbol[/(sy)(mb)(ol)/, -4].should == nil + end + + it "converts the index to an Integer" do + :symbol[/(sy)(mb)(ol)/, 1.5].should == "sy" + end + + describe "and an index that cannot be converted to an Integer" do + it "raises a TypeError when given an Hash" do + -> { :symbol[/(sy)(mb)(ol)/, Hash.new] }.should.raise(TypeError) + end + + it "raises a TypeError when given an Array" do + -> { :symbol[/(sy)(mb)(ol)/, Array.new] }.should.raise(TypeError) + end + + it "raises a TypeError when given an Object" do + -> { :symbol[/(sy)(mb)(ol)/, Object.new] }.should.raise(TypeError) + end + end + + it "raises a TypeError if the index is nil" do + -> { :symbol[/(sy)(mb)(ol)/, nil] }.should.raise(TypeError) + end + + it "sets $~ to the MatchData if there is a match" do + :symbol[/(sy)(mb)(ol)/, 0] + $~[0].should == "symbol" + $~[1].should == "sy" + $~[2].should == "mb" + $~[3].should == "ol" + end + + it "does not set $~ to the MatchData if there is not a match" do + :symbol[/0-9/, 0] + $~.should == nil + end + end + end + + describe "with a String slice" do + it "does not set $~" do + $~ = nil + :symbol["sym"] + $~.should == nil + end + + it "returns a string if there is match" do + :symbol["ymb"].should == "ymb" + end + + it "returns nil if there is not a match" do + :symbol["foo"].should == nil + end + end end diff --git a/spec/ruby/core/symbol/id2name_spec.rb b/spec/ruby/core/symbol/id2name_spec.rb index 2caa89fc37..abcbff65f4 100644 --- a/spec/ruby/core/symbol/id2name_spec.rb +++ b/spec/ruby/core/symbol/id2name_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/id2name' describe "Symbol#id2name" do - it_behaves_like :symbol_id2name, :id2name + it "is an alias of Symbol#to_s" do + Symbol.instance_method(:id2name).should == Symbol.instance_method(:to_s) + end end diff --git a/spec/ruby/core/symbol/intern_spec.rb b/spec/ruby/core/symbol/intern_spec.rb index 9d0914c7fb..746d313d40 100644 --- a/spec/ruby/core/symbol/intern_spec.rb +++ b/spec/ruby/core/symbol/intern_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' describe "Symbol#intern" do - it "returns self" do - :foo.intern.should == :foo - end - - it "returns a Symbol" do - :foo.intern.should.is_a?(Symbol) + it "is an alias of Symbol#to_sym" do + Symbol.instance_method(:intern).should == Symbol.instance_method(:to_sym) end end diff --git a/spec/ruby/core/symbol/length_spec.rb b/spec/ruby/core/symbol/length_spec.rb index 27bee575ef..29dd4ad46b 100644 --- a/spec/ruby/core/symbol/length_spec.rb +++ b/spec/ruby/core/symbol/length_spec.rb @@ -1,6 +1,23 @@ require_relative '../../spec_helper' -require_relative 'shared/length' describe "Symbol#length" do - it_behaves_like :symbol_length, :length + it "returns 0 for empty name" do + :''.length.should == 0 + end + + it "returns 1 for name formed by a NUL character" do + :"\x00".length.should == 1 + end + + it "returns 3 for name formed by 3 ASCII characters" do + :one.length.should == 3 + end + + it "returns 4 for name formed by 4 ASCII characters" do + :four.length.should == 4 + end + + it "returns 4 for name formed by 1 multibyte and 3 ASCII characters" do + :"\xC3\x9Cber".length.should == 4 + end end diff --git a/spec/ruby/core/symbol/next_spec.rb b/spec/ruby/core/symbol/next_spec.rb index 97fe913739..e80bbaa508 100644 --- a/spec/ruby/core/symbol/next_spec.rb +++ b/spec/ruby/core/symbol/next_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/succ' describe "Symbol#next" do - it_behaves_like :symbol_succ, :next + it "is an alias of Symbol#succ" do + Symbol.instance_method(:next).should == Symbol.instance_method(:succ) + end end diff --git a/spec/ruby/core/symbol/shared/id2name.rb b/spec/ruby/core/symbol/shared/id2name.rb deleted file mode 100644 index 00a9c7d7dc..0000000000 --- a/spec/ruby/core/symbol/shared/id2name.rb +++ /dev/null @@ -1,30 +0,0 @@ -describe :symbol_id2name, shared: true do - it "returns the string corresponding to self" do - :rubinius.send(@method).should == "rubinius" - :squash.send(@method).should == "squash" - :[].send(@method).should == "[]" - :@ruby.send(@method).should == "@ruby" - :@@ruby.send(@method).should == "@@ruby" - end - - it "returns a String in the same encoding as self" do - string = "ruby".encode("US-ASCII") - symbol = string.to_sym - - symbol.send(@method).encoding.should == Encoding::US_ASCII - end - - ruby_version_is "3.4" do - it "warns about mutating returned string" do - -> { :bad!.send(@method).upcase! }.should complain(/warning: string returned by :bad!.to_s will be frozen in the future/) - end - - it "does not warn about mutation when Warning[:deprecated] is false" do - deprecated = Warning[:deprecated] - Warning[:deprecated] = false - -> { :bad!.send(@method).upcase! }.should_not complain - ensure - Warning[:deprecated] = deprecated - end - end -end diff --git a/spec/ruby/core/symbol/shared/length.rb b/spec/ruby/core/symbol/shared/length.rb deleted file mode 100644 index 692e8c57e3..0000000000 --- a/spec/ruby/core/symbol/shared/length.rb +++ /dev/null @@ -1,23 +0,0 @@ -# -*- encoding: utf-8 -*- - -describe :symbol_length, shared: true do - it "returns 0 for empty name" do - :''.send(@method).should == 0 - end - - it "returns 1 for name formed by a NUL character" do - :"\x00".send(@method).should == 1 - end - - it "returns 3 for name formed by 3 ASCII characters" do - :one.send(@method).should == 3 - end - - it "returns 4 for name formed by 4 ASCII characters" do - :four.send(@method).should == 4 - end - - it "returns 4 for name formed by 1 multibyte and 3 ASCII characters" do - :"\xC3\x9Cber".send(@method).should == 4 - end -end diff --git a/spec/ruby/core/symbol/shared/slice.rb b/spec/ruby/core/symbol/shared/slice.rb deleted file mode 100644 index 4e3a35240c..0000000000 --- a/spec/ruby/core/symbol/shared/slice.rb +++ /dev/null @@ -1,262 +0,0 @@ -require_relative '../fixtures/classes' - -describe :symbol_slice, shared: true do - describe "with an Integer index" do - it "returns the character code of the element at the index" do - :symbol.send(@method, 1).should == ?y - end - - it "returns nil if the index starts from the end and is greater than the length" do - :symbol.send(@method, -10).should == nil - end - - it "returns nil if the index is greater than the length" do - :symbol.send(@method, 42).should == nil - end - end - - describe "with an Integer index and length" do - describe "and a positive index and length" do - it "returns a slice" do - :symbol.send(@method, 1,3).should == "ymb" - end - - it "returns a blank slice if the length is 0" do - :symbol.send(@method, 0,0).should == "" - :symbol.send(@method, 1,0).should == "" - end - - it "returns a slice of all remaining characters if the given length is greater than the actual length" do - :symbol.send(@method, 1,100).should == "ymbol" - end - - it "returns nil if the index is greater than the length" do - :symbol.send(@method, 10,1).should == nil - end - end - - describe "and a positive index and negative length" do - it "returns nil" do - :symbol.send(@method, 0,-1).should == nil - :symbol.send(@method, 1,-1).should == nil - end - end - - describe "and a negative index and positive length" do - it "returns a slice starting from the end upto the length" do - :symbol.send(@method, -3,2).should == "bo" - end - - it "returns a blank slice if the length is 0" do - :symbol.send(@method, -1,0).should == "" - end - - it "returns a slice of all remaining characters if the given length is larger than the actual length" do - :symbol.send(@method, -4,100).should == "mbol" - end - - it "returns nil if the index is past the start" do - :symbol.send(@method, -10,1).should == nil - end - end - - describe "and a negative index and negative length" do - it "returns nil" do - :symbol.send(@method, -1,-1).should == nil - end - end - - describe "and a Float length" do - it "converts the length to an Integer" do - :symbol.send(@method, 2,2.5).should == "mb" - end - end - - describe "and a nil length" do - it "raises a TypeError" do - -> { :symbol.send(@method, 1,nil) }.should.raise(TypeError) - end - end - - describe "and a length that cannot be converted into an Integer" do - it "raises a TypeError when given an Array" do - -> { :symbol.send(@method, 1,Array.new) }.should.raise(TypeError) - end - - it "raises a TypeError when given an Hash" do - -> { :symbol.send(@method, 1,Hash.new) }.should.raise(TypeError) - end - - it "raises a TypeError when given an Object" do - -> { :symbol.send(@method, 1,Object.new) }.should.raise(TypeError) - end - end - end - - describe "with a Float index" do - it "converts the index to an Integer" do - :symbol.send(@method, 1.5).should == ?y - end - end - - describe "with a nil index" do - it "raises a TypeError" do - -> { :symbol.send(@method, nil) }.should.raise(TypeError) - end - end - - describe "with an index that cannot be converted into an Integer" do - it "raises a TypeError when given an Array" do - -> { :symbol.send(@method, Array.new) }.should.raise(TypeError) - end - - it "raises a TypeError when given an Hash" do - -> { :symbol.send(@method, Hash.new) }.should.raise(TypeError) - end - - it "raises a TypeError when given an Object" do - -> { :symbol.send(@method, Object.new) }.should.raise(TypeError) - end - end - - describe "with a Range slice" do - describe "that is within bounds" do - it "returns a slice if both range values begin at the start and are within bounds" do - :symbol.send(@method, 1..4).should == "ymbo" - end - - it "returns a slice if the first range value begins at the start and the last begins at the end" do - :symbol.send(@method, 1..-1).should == "ymbol" - end - - it "returns a slice if the first range value begins at the end and the last begins at the end" do - :symbol.send(@method, -4..-1).should == "mbol" - end - end - - describe "that is out of bounds" do - it "returns nil if the first range value begins past the end" do - :symbol.send(@method, 10..12).should == nil - end - - it "returns a blank string if the first range value is within bounds and the last range value is not" do - :symbol.send(@method, -2..-10).should == "" - :symbol.send(@method, 2..-10).should == "" - end - - it "returns nil if the first range value starts from the end and is within bounds and the last value starts from the end and is greater than the length" do - :symbol.send(@method, -10..-12).should == nil - end - - it "returns nil if the first range value starts from the end and is out of bounds and the last value starts from the end and is less than the length" do - :symbol.send(@method, -10..-2).should == nil - end - end - - describe "with Float values" do - it "converts the first value to an Integer" do - :symbol.send(@method, 0.5..2).should == "sym" - end - - it "converts the last value to an Integer" do - :symbol.send(@method, 0..2.5).should == "sym" - end - end - end - - describe "with a Range subclass slice" do - it "returns a slice" do - range = SymbolSpecs::MyRange.new(1, 4) - :symbol.send(@method, range).should == "ymbo" - end - end - - describe "with a Regex slice" do - describe "without a capture index" do - it "returns a string of the match" do - :symbol.send(@method, /[^bol]+/).should == "sym" - end - - it "returns nil if the expression does not match" do - :symbol.send(@method, /0-9/).should == nil - end - - it "sets $~ to the MatchData if there is a match" do - :symbol.send(@method, /[^bol]+/) - $~[0].should == "sym" - end - - it "does not set $~ if there if there is not a match" do - :symbol.send(@method, /[0-9]+/) - $~.should == nil - end - end - - describe "with a capture index" do - it "returns a string of the complete match if the capture index is 0" do - :symbol.send(@method, /(sy)(mb)(ol)/, 0).should == "symbol" - end - - it "returns a string for the matched capture at the given index" do - :symbol.send(@method, /(sy)(mb)(ol)/, 1).should == "sy" - :symbol.send(@method, /(sy)(mb)(ol)/, -1).should == "ol" - end - - it "returns nil if there is no capture for the index" do - :symbol.send(@method, /(sy)(mb)(ol)/, 4).should == nil - :symbol.send(@method, /(sy)(mb)(ol)/, -4).should == nil - end - - it "converts the index to an Integer" do - :symbol.send(@method, /(sy)(mb)(ol)/, 1.5).should == "sy" - end - - describe "and an index that cannot be converted to an Integer" do - it "raises a TypeError when given an Hash" do - -> { :symbol.send(@method, /(sy)(mb)(ol)/, Hash.new) }.should.raise(TypeError) - end - - it "raises a TypeError when given an Array" do - -> { :symbol.send(@method, /(sy)(mb)(ol)/, Array.new) }.should.raise(TypeError) - end - - it "raises a TypeError when given an Object" do - -> { :symbol.send(@method, /(sy)(mb)(ol)/, Object.new) }.should.raise(TypeError) - end - end - - it "raises a TypeError if the index is nil" do - -> { :symbol.send(@method, /(sy)(mb)(ol)/, nil) }.should.raise(TypeError) - end - - it "sets $~ to the MatchData if there is a match" do - :symbol.send(@method, /(sy)(mb)(ol)/, 0) - $~[0].should == "symbol" - $~[1].should == "sy" - $~[2].should == "mb" - $~[3].should == "ol" - end - - it "does not set $~ to the MatchData if there is not a match" do - :symbol.send(@method, /0-9/, 0) - $~.should == nil - end - end - end - - describe "with a String slice" do - it "does not set $~" do - $~ = nil - :symbol.send(@method, "sym") - $~.should == nil - end - - it "returns a string if there is match" do - :symbol.send(@method, "ymb").should == "ymb" - end - - it "returns nil if there is not a match" do - :symbol.send(@method, "foo").should == nil - end - end -end diff --git a/spec/ruby/core/symbol/shared/succ.rb b/spec/ruby/core/symbol/shared/succ.rb deleted file mode 100644 index dde298207e..0000000000 --- a/spec/ruby/core/symbol/shared/succ.rb +++ /dev/null @@ -1,18 +0,0 @@ -require_relative '../../../spec_helper' - -describe :symbol_succ, shared: true do - it "returns a successor" do - :abcd.send(@method).should == :abce - :THX1138.send(@method).should == :THX1139 - end - - it "propagates a 'carry'" do - :"1999zzz".send(@method).should == :"2000aaa" - :ZZZ9999.send(@method).should == :AAAA0000 - end - - it "increments non-alphanumeric characters when no alphanumeric characters are present" do - :"<<koala>>".send(@method).should == :"<<koalb>>" - :"***".send(@method).should == :"**+" - end -end diff --git a/spec/ruby/core/symbol/size_spec.rb b/spec/ruby/core/symbol/size_spec.rb index 5e2aa8d4d2..b5d375b3aa 100644 --- a/spec/ruby/core/symbol/size_spec.rb +++ b/spec/ruby/core/symbol/size_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/length' describe "Symbol#size" do - it_behaves_like :symbol_length, :size + it "is an alias of Symbol#length" do + Symbol.instance_method(:size).should == Symbol.instance_method(:length) + end end diff --git a/spec/ruby/core/symbol/slice_spec.rb b/spec/ruby/core/symbol/slice_spec.rb index d2421c474c..050a2cf38c 100644 --- a/spec/ruby/core/symbol/slice_spec.rb +++ b/spec/ruby/core/symbol/slice_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/slice' describe "Symbol#slice" do - it_behaves_like :symbol_slice, :slice + it "is an alias of Symbol#[]" do + Symbol.instance_method(:slice).should == Symbol.instance_method(:[]) + end end diff --git a/spec/ruby/core/symbol/succ_spec.rb b/spec/ruby/core/symbol/succ_spec.rb index 694bfff862..893164a2a6 100644 --- a/spec/ruby/core/symbol/succ_spec.rb +++ b/spec/ruby/core/symbol/succ_spec.rb @@ -1,6 +1,18 @@ require_relative '../../spec_helper' -require_relative 'shared/succ' describe "Symbol#succ" do - it_behaves_like :symbol_succ, :succ + it "returns a successor" do + :abcd.succ.should == :abce + :THX1138.succ.should == :THX1139 + end + + it "propagates a 'carry'" do + :"1999zzz".succ.should == :"2000aaa" + :ZZZ9999.succ.should == :AAAA0000 + end + + it "increments non-alphanumeric characters when no alphanumeric characters are present" do + :"<<koala>>".succ.should == :"<<koalb>>" + :"***".succ.should == :"**+" + end end diff --git a/spec/ruby/core/symbol/to_s_spec.rb b/spec/ruby/core/symbol/to_s_spec.rb index cd963faa28..2cb57c4cbc 100644 --- a/spec/ruby/core/symbol/to_s_spec.rb +++ b/spec/ruby/core/symbol/to_s_spec.rb @@ -1,6 +1,32 @@ require_relative '../../spec_helper' -require_relative 'shared/id2name' describe "Symbol#to_s" do - it_behaves_like :symbol_id2name, :to_s + it "returns the string corresponding to self" do + :rubinius.to_s.should == "rubinius" + :squash.to_s.should == "squash" + :[].to_s.should == "[]" + :@ruby.to_s.should == "@ruby" + :@@ruby.to_s.should == "@@ruby" + end + + it "returns a String in the same encoding as self" do + string = "ruby".encode("US-ASCII") + symbol = string.to_sym + + symbol.to_s.encoding.should == Encoding::US_ASCII + end + + ruby_version_is "3.4" do + it "warns about mutating returned string" do + -> { :bad!.to_s.upcase! }.should complain(/warning: string returned by :bad!.to_s will be frozen in the future/) + end + + it "does not warn about mutation when Warning[:deprecated] is false" do + deprecated = Warning[:deprecated] + Warning[:deprecated] = false + -> { :bad!.to_s.upcase! }.should_not complain + ensure + Warning[:deprecated] = deprecated + end + end end diff --git a/spec/ruby/core/symbol/to_sym_spec.rb b/spec/ruby/core/symbol/to_sym_spec.rb index e75f3d48a8..062daa3fc7 100644 --- a/spec/ruby/core/symbol/to_sym_spec.rb +++ b/spec/ruby/core/symbol/to_sym_spec.rb @@ -3,7 +3,7 @@ require_relative '../../spec_helper' describe "Symbol#to_sym" do it "returns self" do [:rubinius, :squash, :[], :@ruby, :@@ruby].each do |sym| - sym.to_sym.should == sym + sym.to_sym.should.equal?(sym) end end end diff --git a/spec/ruby/core/thread/exit_spec.rb b/spec/ruby/core/thread/exit_spec.rb index b2e923c680..dbcd889898 100644 --- a/spec/ruby/core/thread/exit_spec.rb +++ b/spec/ruby/core/thread/exit_spec.rb @@ -1,6 +1,11 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/exit' + +describe "Thread#exit" do + it "is an alias of Thread#kill" do + Thread.instance_method(:exit).should == Thread.instance_method(:kill) + end +end describe "Thread#exit!" do it "needs to be reviewed for spec completeness" diff --git a/spec/ruby/core/thread/fork_spec.rb b/spec/ruby/core/thread/fork_spec.rb index a2f4181298..60d574a185 100644 --- a/spec/ruby/core/thread/fork_spec.rb +++ b/spec/ruby/core/thread/fork_spec.rb @@ -1,9 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/start' describe "Thread.fork" do - describe "Thread.start" do - it_behaves_like :thread_start, :fork + it "is an alias of Thread.start" do + Thread.method(:fork).should == Thread.method(:start) end end diff --git a/spec/ruby/core/thread/inspect_spec.rb b/spec/ruby/core/thread/inspect_spec.rb index bd6e0c31fc..fee401830a 100644 --- a/spec/ruby/core/thread/inspect_spec.rb +++ b/spec/ruby/core/thread/inspect_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/to_s' describe "Thread#inspect" do - it_behaves_like :thread_to_s, :inspect + it "is an alias of Thread#to_s" do + Thread.instance_method(:inspect).should == Thread.instance_method(:to_s) + end end diff --git a/spec/ruby/core/thread/kill_spec.rb b/spec/ruby/core/thread/kill_spec.rb index f9f1f46744..907cc5c4d8 100644 --- a/spec/ruby/core/thread/kill_spec.rb +++ b/spec/ruby/core/thread/kill_spec.rb @@ -1,12 +1,221 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/exit' # This spec randomly kills mspec worker like: https://ci.appveyor.com/project/ruby/ruby/builds/19473223/job/f69derxnlo09xhuj # TODO: Investigate the cause or at least print helpful logs, and remove this `platform_is_not` guard. platform_is_not :mingw do describe "Thread#kill" do - it_behaves_like :thread_exit, :kill + before :each do + ScratchPad.clear + end + + it "kills sleeping thread" do + sleeping_thread = Thread.new do + sleep + ScratchPad.record :after_sleep + end + Thread.pass while sleeping_thread.status and sleeping_thread.status != "sleep" + sleeping_thread.kill + sleeping_thread.join + ScratchPad.recorded.should == nil + end + + it "kills current thread" do + thread = Thread.new do + Thread.current.kill + ScratchPad.record :after_sleep + end + thread.join + ScratchPad.recorded.should == nil + end + + it "runs ensure clause" do + thread = ThreadSpecs.dying_thread_ensures(:kill) { ScratchPad.record :in_ensure_clause } + thread.join + ScratchPad.recorded.should == :in_ensure_clause + end + + it "runs nested ensure clauses" do + ScratchPad.record [] + @outer = Thread.new do + begin + @inner = Thread.new do + begin + sleep + ensure + ScratchPad << :inner_ensure_clause + end + end + sleep + ensure + ScratchPad << :outer_ensure_clause + @inner.kill + @inner.join + end + end + Thread.pass while @outer.status and @outer.status != "sleep" + Thread.pass until @inner + Thread.pass while @inner.status and @inner.status != "sleep" + @outer.kill + @outer.join + ScratchPad.recorded.should.include?(:inner_ensure_clause) + ScratchPad.recorded.should.include?(:outer_ensure_clause) + end + + it "does not set $!" do + thread = ThreadSpecs.dying_thread_ensures(:kill) { ScratchPad.record $! } + thread.join + ScratchPad.recorded.should == nil + end + + it "does not reset $!" do + ScratchPad.record [] + + exc = RuntimeError.new("foo") + thread = Thread.new do + begin + raise exc + ensure + ScratchPad << $! + begin + Thread.current.kill + ensure + ScratchPad << $! + end + end + end + thread.join + ScratchPad.recorded.should == [exc, exc] + end + + it "cannot be rescued" do + thread = Thread.new do + begin + Thread.current.kill + rescue Exception + ScratchPad.record :in_rescue + end + ScratchPad.record :end_of_thread_block + end + + thread.join + ScratchPad.recorded.should == nil + end + + it "kills the entire thread when a fiber is active" do + t = Thread.new do + Fiber.new do + sleep + end.resume + ScratchPad.record :fiber_resumed + end + Thread.pass while t.status and t.status != "sleep" + t.kill + t.join + ScratchPad.recorded.should == nil + end + + it "kills other fibers of that thread without running their ensure clauses" do + t = Thread.new do + f = Fiber.new do + ScratchPad.record :fiber_resumed + begin + Fiber.yield + ensure + ScratchPad.record :fiber_ensure + end + end + f.resume + sleep + end + Thread.pass until t.stop? + t.kill + t.join + ScratchPad.recorded.should == :fiber_resumed + end + + # This spec is a mess. It fails randomly, it hangs on MRI, it needs to be removed + quarantine! do + it "killing dying running does nothing" do + in_ensure_clause = false + exit_loop = true + t = ThreadSpecs.dying_thread_ensures do + in_ensure_clause = true + loop { if exit_loop then break end } + ScratchPad.record :after_stop + end + + Thread.pass until in_ensure_clause == true + 10.times { t.kill; Thread.pass } + exit_loop = true + t.join + ScratchPad.recorded.should == :after_stop + end + end + + quarantine! do + + it "propagates inner exception to Thread.join if there is an outer ensure clause" do + thread = ThreadSpecs.dying_thread_with_outer_ensure(:kill) { } + -> { thread.join }.should.raise(RuntimeError, "In dying thread") + end + + it "runs all outer ensure clauses even if inner ensure clause raises exception" do + ThreadSpecs.join_dying_thread_with_outer_ensure(:kill) { ScratchPad.record :in_outer_ensure_clause } + ScratchPad.recorded.should == :in_outer_ensure_clause + end + + it "sets $! in outer ensure clause if inner ensure clause raises exception" do + ThreadSpecs.join_dying_thread_with_outer_ensure(:kill) { ScratchPad.record $! } + ScratchPad.recorded.to_s.should == "In dying thread" + end + end + + it "can be rescued by outer rescue clause when inner ensure clause raises exception" do + thread = Thread.new do + begin + begin + Thread.current.kill + ensure + raise "In dying thread" + end + rescue Exception + ScratchPad.record $! + end + :end_of_thread_block + end + + thread.value.should == :end_of_thread_block + ScratchPad.recorded.to_s.should == "In dying thread" + end + + it "is deferred if ensure clause does Thread.stop" do + ThreadSpecs.wakeup_dying_sleeping_thread(:kill) { Thread.stop; ScratchPad.record :after_sleep } + ScratchPad.recorded.should == :after_sleep + end + + # Hangs on 1.8.6.114 OS X, possibly also on Linux + quarantine! do + it "is deferred if ensure clause sleeps" do + ThreadSpecs.wakeup_dying_sleeping_thread(:kill) { sleep; ScratchPad.record :after_sleep } + ScratchPad.recorded.should == :after_sleep + end + end + + # This case occurred in JRuby where native threads are used to provide + # the same behavior as MRI green threads. Key to this issue was the fact + # that the thread which called #exit in its block was also being explicitly + # sent #join from outside the thread. The 100.times provides a certain + # probability that the deadlock will occur. It was sufficient to reliably + # reproduce the deadlock in JRuby. + it "does not deadlock when called from within the thread while being joined from without" do + 100.times do + t = Thread.new { Thread.stop; Thread.current.kill } + Thread.pass while t.status and t.status != "sleep" + t.wakeup.should == t + t.join.should == t + end + end end describe "Thread.kill" do diff --git a/spec/ruby/core/thread/shared/exit.rb b/spec/ruby/core/thread/shared/exit.rb deleted file mode 100644 index a294c3a4d6..0000000000 --- a/spec/ruby/core/thread/shared/exit.rb +++ /dev/null @@ -1,219 +0,0 @@ -describe :thread_exit, shared: true do - before :each do - ScratchPad.clear - end - - # This spec randomly kills mspec worker like: https://ci.appveyor.com/project/ruby/ruby/builds/19390874/job/wv1bsm8skd4e1pxl - # TODO: Investigate the cause or at least print helpful logs, and remove this `platform_is_not` guard. - platform_is_not :mingw do - - it "kills sleeping thread" do - sleeping_thread = Thread.new do - sleep - ScratchPad.record :after_sleep - end - Thread.pass while sleeping_thread.status and sleeping_thread.status != "sleep" - sleeping_thread.send(@method) - sleeping_thread.join - ScratchPad.recorded.should == nil - end - - it "kills current thread" do - thread = Thread.new do - Thread.current.send(@method) - ScratchPad.record :after_sleep - end - thread.join - ScratchPad.recorded.should == nil - end - - it "runs ensure clause" do - thread = ThreadSpecs.dying_thread_ensures(@method) { ScratchPad.record :in_ensure_clause } - thread.join - ScratchPad.recorded.should == :in_ensure_clause - end - - it "runs nested ensure clauses" do - ScratchPad.record [] - @outer = Thread.new do - begin - @inner = Thread.new do - begin - sleep - ensure - ScratchPad << :inner_ensure_clause - end - end - sleep - ensure - ScratchPad << :outer_ensure_clause - @inner.send(@method) - @inner.join - end - end - Thread.pass while @outer.status and @outer.status != "sleep" - Thread.pass until @inner - Thread.pass while @inner.status and @inner.status != "sleep" - @outer.send(@method) - @outer.join - ScratchPad.recorded.should.include?(:inner_ensure_clause) - ScratchPad.recorded.should.include?(:outer_ensure_clause) - end - - it "does not set $!" do - thread = ThreadSpecs.dying_thread_ensures(@method) { ScratchPad.record $! } - thread.join - ScratchPad.recorded.should == nil - end - - it "does not reset $!" do - ScratchPad.record [] - - exc = RuntimeError.new("foo") - thread = Thread.new do - begin - raise exc - ensure - ScratchPad << $! - begin - Thread.current.send(@method) - ensure - ScratchPad << $! - end - end - end - thread.join - ScratchPad.recorded.should == [exc, exc] - end - - it "cannot be rescued" do - thread = Thread.new do - begin - Thread.current.send(@method) - rescue Exception - ScratchPad.record :in_rescue - end - ScratchPad.record :end_of_thread_block - end - - thread.join - ScratchPad.recorded.should == nil - end - - it "kills the entire thread when a fiber is active" do - t = Thread.new do - Fiber.new do - sleep - end.resume - ScratchPad.record :fiber_resumed - end - Thread.pass while t.status and t.status != "sleep" - t.send(@method) - t.join - ScratchPad.recorded.should == nil - end - - it "kills other fibers of that thread without running their ensure clauses" do - t = Thread.new do - f = Fiber.new do - ScratchPad.record :fiber_resumed - begin - Fiber.yield - ensure - ScratchPad.record :fiber_ensure - end - end - f.resume - sleep - end - Thread.pass until t.stop? - t.send(@method) - t.join - ScratchPad.recorded.should == :fiber_resumed - end - - # This spec is a mess. It fails randomly, it hangs on MRI, it needs to be removed - quarantine! do - it "killing dying running does nothing" do - in_ensure_clause = false - exit_loop = true - t = ThreadSpecs.dying_thread_ensures do - in_ensure_clause = true - loop { if exit_loop then break end } - ScratchPad.record :after_stop - end - - Thread.pass until in_ensure_clause == true - 10.times { t.send(@method); Thread.pass } - exit_loop = true - t.join - ScratchPad.recorded.should == :after_stop - end - end - - quarantine! do - - it "propagates inner exception to Thread.join if there is an outer ensure clause" do - thread = ThreadSpecs.dying_thread_with_outer_ensure(@method) { } - -> { thread.join }.should.raise(RuntimeError, "In dying thread") - end - - it "runs all outer ensure clauses even if inner ensure clause raises exception" do - ThreadSpecs.join_dying_thread_with_outer_ensure(@method) { ScratchPad.record :in_outer_ensure_clause } - ScratchPad.recorded.should == :in_outer_ensure_clause - end - - it "sets $! in outer ensure clause if inner ensure clause raises exception" do - ThreadSpecs.join_dying_thread_with_outer_ensure(@method) { ScratchPad.record $! } - ScratchPad.recorded.to_s.should == "In dying thread" - end - end - - it "can be rescued by outer rescue clause when inner ensure clause raises exception" do - thread = Thread.new do - begin - begin - Thread.current.send(@method) - ensure - raise "In dying thread" - end - rescue Exception - ScratchPad.record $! - end - :end_of_thread_block - end - - thread.value.should == :end_of_thread_block - ScratchPad.recorded.to_s.should == "In dying thread" - end - - it "is deferred if ensure clause does Thread.stop" do - ThreadSpecs.wakeup_dying_sleeping_thread(@method) { Thread.stop; ScratchPad.record :after_sleep } - ScratchPad.recorded.should == :after_sleep - end - - # Hangs on 1.8.6.114 OS X, possibly also on Linux - quarantine! do - it "is deferred if ensure clause sleeps" do - ThreadSpecs.wakeup_dying_sleeping_thread(@method) { sleep; ScratchPad.record :after_sleep } - ScratchPad.recorded.should == :after_sleep - end - end - - # This case occurred in JRuby where native threads are used to provide - # the same behavior as MRI green threads. Key to this issue was the fact - # that the thread which called #exit in its block was also being explicitly - # sent #join from outside the thread. The 100.times provides a certain - # probability that the deadlock will occur. It was sufficient to reliably - # reproduce the deadlock in JRuby. - it "does not deadlock when called from within the thread while being joined from without" do - 100.times do - t = Thread.new { Thread.stop; Thread.current.send(@method) } - Thread.pass while t.status and t.status != "sleep" - t.wakeup.should == t - t.join.should == t - end - end - - end # platform_is_not :mingw -end diff --git a/spec/ruby/core/thread/shared/start.rb b/spec/ruby/core/thread/shared/start.rb deleted file mode 100644 index c5d62ab098..0000000000 --- a/spec/ruby/core/thread/shared/start.rb +++ /dev/null @@ -1,41 +0,0 @@ -describe :thread_start, shared: true do - before :each do - ScratchPad.clear - end - - it "raises an ArgumentError if not passed a block" do - -> { - Thread.send(@method) - }.should.raise(ArgumentError) - end - - it "spawns a new Thread running the block" do - run = false - t = Thread.send(@method) { run = true } - t.should.is_a?(Thread) - t.join - - run.should == true - end - - it "respects Thread subclasses" do - c = Class.new(Thread) - t = c.send(@method) { } - t.should.is_a?(c) - - t.join - end - - it "does not call #initialize" do - c = Class.new(Thread) do - def initialize - ScratchPad.record :bad - end - end - - t = c.send(@method) { } - t.join - - ScratchPad.recorded.should == nil - end -end diff --git a/spec/ruby/core/thread/shared/to_s.rb b/spec/ruby/core/thread/shared/to_s.rb deleted file mode 100644 index 27e53ba4b8..0000000000 --- a/spec/ruby/core/thread/shared/to_s.rb +++ /dev/null @@ -1,53 +0,0 @@ -require_relative '../fixtures/classes' - -describe :thread_to_s, shared: true do - it "returns a description including file and line number" do - thread, line = Thread.new { "hello" }, __LINE__ - thread.join - thread.send(@method).should =~ /^#<Thread:([^ ]*?) #{Regexp.escape __FILE__}:#{line} \w+>$/ - end - - it "has a binary encoding" do - ThreadSpecs.status_of_current_thread.send(@method).encoding.should == Encoding::BINARY - end - - it "can check it's own status" do - ThreadSpecs.status_of_current_thread.send(@method).should.include?('run') - end - - it "describes a running thread" do - ThreadSpecs.status_of_running_thread.send(@method).should.include?('run') - end - - it "describes a sleeping thread" do - ThreadSpecs.status_of_sleeping_thread.send(@method).should.include?('sleep') - end - - it "describes a blocked thread" do - ThreadSpecs.status_of_blocked_thread.send(@method).should.include?('sleep') - end - - it "describes a completed thread" do - ThreadSpecs.status_of_completed_thread.send(@method).should.include?('dead') - end - - it "describes a killed thread" do - ThreadSpecs.status_of_killed_thread.send(@method).should.include?('dead') - end - - it "describes a thread with an uncaught exception" do - ThreadSpecs.status_of_thread_with_uncaught_exception.send(@method).should.include?('dead') - end - - it "describes a dying sleeping thread" do - ThreadSpecs.status_of_dying_sleeping_thread.send(@method).should.include?('sleep') - end - - it "reports aborting on a killed thread" do - ThreadSpecs.status_of_dying_running_thread.send(@method).should.include?('aborting') - end - - it "reports aborting on a killed thread after sleep" do - ThreadSpecs.status_of_dying_thread_after_sleep.send(@method).should.include?('aborting') - end -end diff --git a/spec/ruby/core/thread/start_spec.rb b/spec/ruby/core/thread/start_spec.rb index 3dd040f98b..a2ee52180b 100644 --- a/spec/ruby/core/thread/start_spec.rb +++ b/spec/ruby/core/thread/start_spec.rb @@ -1,9 +1,43 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/start' describe "Thread.start" do - describe "Thread.start" do - it_behaves_like :thread_start, :start + before :each do + ScratchPad.clear + end + + it "raises an ArgumentError if not passed a block" do + -> { + Thread.start + }.should.raise(ArgumentError) + end + + it "spawns a new Thread running the block" do + run = false + t = Thread.start { run = true } + t.should.is_a?(Thread) + t.join + + run.should == true + end + + it "respects Thread subclasses" do + c = Class.new(Thread) + t = c.start { } + t.should.is_a?(c) + + t.join + end + + it "does not call #initialize" do + c = Class.new(Thread) do + def initialize + ScratchPad.record :bad + end + end + + t = c.start { } + t.join + + ScratchPad.recorded.should == nil end end diff --git a/spec/ruby/core/thread/terminate_spec.rb b/spec/ruby/core/thread/terminate_spec.rb index cf6cab472b..68c431a0c0 100644 --- a/spec/ruby/core/thread/terminate_spec.rb +++ b/spec/ruby/core/thread/terminate_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/exit' describe "Thread#terminate" do - it_behaves_like :thread_exit, :terminate + it "is an alias of Thread#kill" do + Thread.instance_method(:terminate).should == Thread.instance_method(:kill) + end end diff --git a/spec/ruby/core/thread/to_s_spec.rb b/spec/ruby/core/thread/to_s_spec.rb index cb182a017f..2aef426de8 100644 --- a/spec/ruby/core/thread/to_s_spec.rb +++ b/spec/ruby/core/thread/to_s_spec.rb @@ -1,6 +1,54 @@ require_relative '../../spec_helper' -require_relative 'shared/to_s' +require_relative 'fixtures/classes' describe "Thread#to_s" do - it_behaves_like :thread_to_s, :to_s + it "returns a description including file and line number" do + thread, line = Thread.new { "hello" }, __LINE__ + thread.join + thread.to_s.should =~ /^#<Thread:([^ ]*?) #{Regexp.escape __FILE__}:#{line} \w+>$/ + end + + it "has a binary encoding" do + ThreadSpecs.status_of_current_thread.to_s.encoding.should == Encoding::BINARY + end + + it "can check it's own status" do + ThreadSpecs.status_of_current_thread.to_s.should.include?('run') + end + + it "describes a running thread" do + ThreadSpecs.status_of_running_thread.to_s.should.include?('run') + end + + it "describes a sleeping thread" do + ThreadSpecs.status_of_sleeping_thread.to_s.should.include?('sleep') + end + + it "describes a blocked thread" do + ThreadSpecs.status_of_blocked_thread.to_s.should.include?('sleep') + end + + it "describes a completed thread" do + ThreadSpecs.status_of_completed_thread.to_s.should.include?('dead') + end + + it "describes a killed thread" do + ThreadSpecs.status_of_killed_thread.to_s.should.include?('dead') + end + + it "describes a thread with an uncaught exception" do + ThreadSpecs.status_of_thread_with_uncaught_exception.to_s.should.include?('dead') + end + + it "describes a dying sleeping thread" do + ThreadSpecs.status_of_dying_sleeping_thread.to_s.should.include?('sleep') + end + + it "reports aborting on a killed thread" do + ThreadSpecs.status_of_dying_running_thread.to_s.should.include?('aborting') + end + + it "reports aborting on a killed thread after sleep" do + ThreadSpecs.status_of_dying_thread_after_sleep.to_s.should.include?('aborting') + end end diff --git a/spec/ruby/core/time/asctime_spec.rb b/spec/ruby/core/time/asctime_spec.rb index a41ee531e4..17e155787a 100644 --- a/spec/ruby/core/time/asctime_spec.rb +++ b/spec/ruby/core/time/asctime_spec.rb @@ -1,6 +1,8 @@ require_relative '../../spec_helper' -require_relative 'shared/asctime' describe "Time#asctime" do - it_behaves_like :time_asctime, :asctime + it "returns a canonical string representation of time" do + t = Time.now + t.asctime.should == t.strftime("%a %b %e %H:%M:%S %Y") + end end diff --git a/spec/ruby/core/time/ctime_spec.rb b/spec/ruby/core/time/ctime_spec.rb index 57e7cfd9ce..b609b03974 100644 --- a/spec/ruby/core/time/ctime_spec.rb +++ b/spec/ruby/core/time/ctime_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/asctime' describe "Time#ctime" do - it_behaves_like :time_asctime, :ctime + it "is an alias of Time#asctime" do + Time.instance_method(:ctime).should == Time.instance_method(:asctime) + end end diff --git a/spec/ruby/core/time/day_spec.rb b/spec/ruby/core/time/day_spec.rb index 895bcd7a86..3dec17644c 100644 --- a/spec/ruby/core/time/day_spec.rb +++ b/spec/ruby/core/time/day_spec.rb @@ -1,6 +1,17 @@ require_relative '../../spec_helper' -require_relative 'shared/day' describe "Time#day" do - it_behaves_like :time_day, :day + it "returns the day of the month (1..n) for a local Time" do + with_timezone("CET", 1) do + Time.local(1970, 1, 1).day.should == 1 + end + end + + it "returns the day of the month for a UTC Time" do + Time.utc(1970, 1, 1).day.should == 1 + end + + it "returns the day of the month for a Time with a fixed offset" do + Time.new(2012, 1, 1, 0, 0, 0, -3600).day.should == 1 + end end diff --git a/spec/ruby/core/time/dst_spec.rb b/spec/ruby/core/time/dst_spec.rb index 436240aae5..42daf86875 100644 --- a/spec/ruby/core/time/dst_spec.rb +++ b/spec/ruby/core/time/dst_spec.rb @@ -1,6 +1,10 @@ require_relative '../../spec_helper' -require_relative 'shared/isdst' describe "Time#dst?" do - it_behaves_like :time_isdst, :dst? + it "returns whether time is during daylight saving time" do + with_timezone("America/Los_Angeles") do + Time.local(2007, 9, 9, 0, 0, 0).dst?.should == true + Time.local(2007, 1, 9, 0, 0, 0).dst?.should == false + end + end end diff --git a/spec/ruby/core/time/getgm_spec.rb b/spec/ruby/core/time/getgm_spec.rb index b5d45b1d9f..7698156c8c 100644 --- a/spec/ruby/core/time/getgm_spec.rb +++ b/spec/ruby/core/time/getgm_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/getgm' describe "Time#getgm" do - it_behaves_like :time_getgm, :getgm + it "is an alias of Time#getutc" do + Time.instance_method(:getgm).should == Time.instance_method(:getutc) + end end diff --git a/spec/ruby/core/time/getutc_spec.rb b/spec/ruby/core/time/getutc_spec.rb index 0cd9c17b00..1d49059a71 100644 --- a/spec/ruby/core/time/getutc_spec.rb +++ b/spec/ruby/core/time/getutc_spec.rb @@ -1,6 +1,11 @@ require_relative '../../spec_helper' -require_relative 'shared/getgm' describe "Time#getutc" do - it_behaves_like :time_getgm, :getutc + it "returns a new time which is the utc representation of time" do + # Testing with America/Regina here because it doesn't have DST. + with_timezone("CST", -6) do + t = Time.local(2007, 1, 9, 6, 0, 0) + t.getutc.should == Time.gm(2007, 1, 9, 12, 0, 0) + end + end end diff --git a/spec/ruby/core/time/gm_spec.rb b/spec/ruby/core/time/gm_spec.rb index 26dffbcedc..fbabede6ba 100644 --- a/spec/ruby/core/time/gm_spec.rb +++ b/spec/ruby/core/time/gm_spec.rb @@ -1,10 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/gm' -require_relative 'shared/time_params' describe "Time.gm" do - it_behaves_like :time_gm, :gm - it_behaves_like :time_params, :gm - it_behaves_like :time_params_10_arg, :gm - it_behaves_like :time_params_microseconds, :gm + it "is an alias of Time.utc" do + Time.method(:gm).should == Time.method(:utc) + end end diff --git a/spec/ruby/core/time/gmt_offset_spec.rb b/spec/ruby/core/time/gmt_offset_spec.rb index df417e6e4e..1769981753 100644 --- a/spec/ruby/core/time/gmt_offset_spec.rb +++ b/spec/ruby/core/time/gmt_offset_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/gmt_offset' describe "Time#gmt_offset" do - it_behaves_like :time_gmt_offset, :gmt_offset + it "is an alias of Time#utc_offset" do + Time.instance_method(:gmt_offset).should == Time.instance_method(:utc_offset) + end end diff --git a/spec/ruby/core/time/gmt_spec.rb b/spec/ruby/core/time/gmt_spec.rb index 840f59e0e8..38e98cc43c 100644 --- a/spec/ruby/core/time/gmt_spec.rb +++ b/spec/ruby/core/time/gmt_spec.rb @@ -1,8 +1,7 @@ require_relative '../../spec_helper' describe "Time#gmt?" do - it "returns true if time represents a time in UTC (GMT)" do - Time.now.should_not.gmt? - Time.now.gmtime.should.gmt? + it "is an alias of Time#utc?" do + Time.instance_method(:gmt?).should == Time.instance_method(:utc?) end end diff --git a/spec/ruby/core/time/gmtime_spec.rb b/spec/ruby/core/time/gmtime_spec.rb index d965cd541d..e7e1d4ffb2 100644 --- a/spec/ruby/core/time/gmtime_spec.rb +++ b/spec/ruby/core/time/gmtime_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/gmtime' describe "Time#gmtime" do - it_behaves_like :time_gmtime, :gmtime + it "is an alias of Time#utc" do + Time.instance_method(:gmtime).should == Time.instance_method(:utc) + end end diff --git a/spec/ruby/core/time/gmtoff_spec.rb b/spec/ruby/core/time/gmtoff_spec.rb index fa28520e9e..c7d801a681 100644 --- a/spec/ruby/core/time/gmtoff_spec.rb +++ b/spec/ruby/core/time/gmtoff_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/gmt_offset' describe "Time#gmtoff" do - it_behaves_like :time_gmt_offset, :gmtoff + it "is an alias of Time#utc_offset" do + Time.instance_method(:gmtoff).should == Time.instance_method(:utc_offset) + end end diff --git a/spec/ruby/core/time/isdst_spec.rb b/spec/ruby/core/time/isdst_spec.rb index 173230ca07..759953cca7 100644 --- a/spec/ruby/core/time/isdst_spec.rb +++ b/spec/ruby/core/time/isdst_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/isdst' describe "Time#isdst" do - it_behaves_like :time_isdst, :isdst + it "is an alias of Time#dst?" do + Time.instance_method(:isdst).should == Time.instance_method(:dst?) + end end diff --git a/spec/ruby/core/time/iso8601_spec.rb b/spec/ruby/core/time/iso8601_spec.rb index ad60c3bb32..a6efc57b28 100644 --- a/spec/ruby/core/time/iso8601_spec.rb +++ b/spec/ruby/core/time/iso8601_spec.rb @@ -1,6 +1,33 @@ require_relative '../../spec_helper' -require_relative 'shared/xmlschema' describe "Time#iso8601" do - it_behaves_like :time_xmlschema, :iso8601 + ruby_version_is "3.4" do + it "generates ISO-8601 strings in Z for UTC times" do + t = Time.utc(1985, 4, 12, 23, 20, 50, 521245) + t.iso8601.should == "1985-04-12T23:20:50Z" + t.iso8601(2).should == "1985-04-12T23:20:50.52Z" + t.iso8601(9).should == "1985-04-12T23:20:50.521245000Z" + end + + it "generates ISO-8601 string with timezone offset for non-UTC times" do + t = Time.new(1985, 4, 12, 23, 20, 50, "+02:00") + t.iso8601.should == "1985-04-12T23:20:50+02:00" + t.iso8601(2).should == "1985-04-12T23:20:50.00+02:00" + end + + it "year is always at least 4 digits" do + t = Time.utc(12, 4, 12) + t.iso8601.should == "0012-04-12T00:00:00Z" + end + + it "year can be more than 4 digits" do + t = Time.utc(40_000, 4, 12) + t.iso8601.should == "40000-04-12T00:00:00Z" + end + + it "year can be negative" do + t = Time.utc(-2000, 4, 12) + t.iso8601.should == "-2000-04-12T00:00:00Z" + end + end end diff --git a/spec/ruby/core/time/mday_spec.rb b/spec/ruby/core/time/mday_spec.rb index 3c21939890..78021785f9 100644 --- a/spec/ruby/core/time/mday_spec.rb +++ b/spec/ruby/core/time/mday_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/day' describe "Time#mday" do - it_behaves_like :time_day, :mday + it "is an alias of Time#day" do + Time.instance_method(:mday).should == Time.instance_method(:day) + end end diff --git a/spec/ruby/core/time/mktime_spec.rb b/spec/ruby/core/time/mktime_spec.rb index 78a6a6e772..83bf12293a 100644 --- a/spec/ruby/core/time/mktime_spec.rb +++ b/spec/ruby/core/time/mktime_spec.rb @@ -1,11 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/local' -require_relative 'shared/time_params' describe "Time.mktime" do - it_behaves_like :time_local, :mktime - it_behaves_like :time_local_10_arg, :mktime - it_behaves_like :time_params, :mktime - it_behaves_like :time_params_10_arg, :mktime - it_behaves_like :time_params_microseconds, :mktime + it "is an alias of Time.local" do + Time.method(:mktime).should == Time.method(:local) + end end diff --git a/spec/ruby/core/time/mon_spec.rb b/spec/ruby/core/time/mon_spec.rb index f41b39648b..d57549dadd 100644 --- a/spec/ruby/core/time/mon_spec.rb +++ b/spec/ruby/core/time/mon_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/month' describe "Time#mon" do - it_behaves_like :time_month, :mon + it "is an alias of Time#month" do + Time.instance_method(:mon).should == Time.instance_method(:month) + end end diff --git a/spec/ruby/core/time/month_spec.rb b/spec/ruby/core/time/month_spec.rb index 81e20384ab..eae0e85acd 100644 --- a/spec/ruby/core/time/month_spec.rb +++ b/spec/ruby/core/time/month_spec.rb @@ -1,6 +1,17 @@ require_relative '../../spec_helper' -require_relative 'shared/month' describe "Time#month" do - it_behaves_like :time_month, :month + it "returns the month of the year for a local Time" do + with_timezone("CET", 1) do + Time.local(1970, 1).month.should == 1 + end + end + + it "returns the month of the year for a UTC Time" do + Time.utc(1970, 1).month.should == 1 + end + + it "returns the four digit year for a Time with a fixed offset" do + Time.new(2012, 1, 1, 0, 0, 0, -3600).month.should == 1 + end end diff --git a/spec/ruby/core/time/shared/asctime.rb b/spec/ruby/core/time/shared/asctime.rb deleted file mode 100644 index d096666863..0000000000 --- a/spec/ruby/core/time/shared/asctime.rb +++ /dev/null @@ -1,6 +0,0 @@ -describe :time_asctime, shared: true do - it "returns a canonical string representation of time" do - t = Time.now - t.send(@method).should == t.strftime("%a %b %e %H:%M:%S %Y") - end -end diff --git a/spec/ruby/core/time/shared/day.rb b/spec/ruby/core/time/shared/day.rb deleted file mode 100644 index 472dc959c1..0000000000 --- a/spec/ruby/core/time/shared/day.rb +++ /dev/null @@ -1,15 +0,0 @@ -describe :time_day, shared: true do - it "returns the day of the month (1..n) for a local Time" do - with_timezone("CET", 1) do - Time.local(1970, 1, 1).send(@method).should == 1 - end - end - - it "returns the day of the month for a UTC Time" do - Time.utc(1970, 1, 1).send(@method).should == 1 - end - - it "returns the day of the month for a Time with a fixed offset" do - Time.new(2012, 1, 1, 0, 0, 0, -3600).send(@method).should == 1 - end -end diff --git a/spec/ruby/core/time/shared/getgm.rb b/spec/ruby/core/time/shared/getgm.rb deleted file mode 100644 index 3576365772..0000000000 --- a/spec/ruby/core/time/shared/getgm.rb +++ /dev/null @@ -1,9 +0,0 @@ -describe :time_getgm, shared: true do - it "returns a new time which is the utc representation of time" do - # Testing with America/Regina here because it doesn't have DST. - with_timezone("CST", -6) do - t = Time.local(2007, 1, 9, 6, 0, 0) - t.send(@method).should == Time.gm(2007, 1, 9, 12, 0, 0) - end - end -end diff --git a/spec/ruby/core/time/shared/gm.rb b/spec/ruby/core/time/shared/gm.rb deleted file mode 100644 index 0ee602c837..0000000000 --- a/spec/ruby/core/time/shared/gm.rb +++ /dev/null @@ -1,70 +0,0 @@ -describe :time_gm, shared: true do - it "creates a time based on given values, interpreted as UTC (GMT)" do - Time.send(@method, 2000,"jan",1,20,15,1).inspect.should == "2000-01-01 20:15:01 UTC" - end - - it "creates a time based on given C-style gmtime arguments, interpreted as UTC (GMT)" do - time = Time.send(@method, 1, 15, 20, 1, 1, 2000, :ignored, :ignored, :ignored, :ignored) - time.inspect.should == "2000-01-01 20:15:01 UTC" - end - - it "interprets pre-Gregorian reform dates using Gregorian proleptic calendar" do - Time.send(@method, 1582, 10, 4, 12).to_i.should == -12220200000 # 2299150j - end - - it "interprets Julian-Gregorian gap dates using Gregorian proleptic calendar" do - Time.send(@method, 1582, 10, 14, 12).to_i.should == -12219336000 # 2299160j - end - - it "interprets post-Gregorian reform dates using Gregorian calendar" do - Time.send(@method, 1582, 10, 15, 12).to_i.should == -12219249600 # 2299161j - end - - it "handles fractional usec close to rounding limit" do - time = Time.send(@method, 2000, 1, 1, 12, 30, 0, 9999r/10000) - - time.usec.should == 0 - time.nsec.should == 999 - end - - guard -> { - with_timezone 'right/UTC' do - (Time.gm(1972, 6, 30, 23, 59, 59) + 1).sec == 60 - end - } do - it "handles real leap seconds in zone 'right/UTC'" do - with_timezone 'right/UTC' do - time = Time.send(@method, 1972, 6, 30, 23, 59, 60) - - time.sec.should == 60 - time.min.should == 59 - time.hour.should == 23 - time.day.should == 30 - time.month.should == 6 - end - end - end - - it "handles bad leap seconds by carrying values forward" do - with_timezone 'UTC' do - time = Time.send(@method, 2017, 7, 5, 23, 59, 60) - time.sec.should == 0 - time.min.should == 0 - time.hour.should == 0 - time.day.should == 6 - time.month.should == 7 - end - end - - it "handles a value of 60 for seconds by carrying values forward in zone 'UTC'" do - with_timezone 'UTC' do - time = Time.send(@method, 1972, 6, 30, 23, 59, 60) - - time.sec.should == 0 - time.min.should == 0 - time.hour.should == 0 - time.day.should == 1 - time.month.should == 7 - end - end -end diff --git a/spec/ruby/core/time/shared/gmt_offset.rb b/spec/ruby/core/time/shared/gmt_offset.rb deleted file mode 100644 index 839566c249..0000000000 --- a/spec/ruby/core/time/shared/gmt_offset.rb +++ /dev/null @@ -1,59 +0,0 @@ -describe :time_gmt_offset, shared: true do - it "returns the offset in seconds between the timezone of time and UTC" do - with_timezone("AST", 3) do - Time.new.send(@method).should == 10800 - end - end - - it "returns 0 when the date is UTC" do - with_timezone("AST", 3) do - Time.new.utc.send(@method).should == 0 - end - end - - platform_is_not :windows do - it "returns the correct offset for US Eastern time zone around daylight savings time change" do - # "2010-03-14 01:59:59 -0500" + 1 ==> "2010-03-14 03:00:00 -0400" - with_timezone("EST5EDT") do - t = Time.local(2010,3,14,1,59,59) - t.send(@method).should == -5*60*60 - (t + 1).send(@method).should == -4*60*60 - end - end - - it "returns the correct offset for Hawaii around daylight savings time change" do - # "2010-03-14 01:59:59 -1000" + 1 ==> "2010-03-14 02:00:00 -1000" - with_timezone("Pacific/Honolulu") do - t = Time.local(2010,3,14,1,59,59) - t.send(@method).should == -10*60*60 - (t + 1).send(@method).should == -10*60*60 - end - end - - it "returns the correct offset for New Zealand around daylight savings time change" do - # "2010-04-04 02:59:59 +1300" + 1 ==> "2010-04-04 02:00:00 +1200" - with_timezone("Pacific/Auckland") do - t = Time.local(2010,4,4,1,59,59) + (60 * 60) - t.send(@method).should == 13*60*60 - (t + 1).send(@method).should == 12*60*60 - end - end - end - - it "returns offset as Rational" do - Time.new(2010,4,4,1,59,59,7245).send(@method).should == 7245 - Time.new(2010,4,4,1,59,59,7245.5).send(@method).should == Rational(14491,2) - end - - context 'given positive offset' do - it 'returns a positive offset' do - Time.new(2013,3,17,nil,nil,nil,"+03:00").send(@method).should == 10800 - end - end - - context 'given negative offset' do - it 'returns a negative offset' do - Time.new(2013,3,17,nil,nil,nil,"-03:00").send(@method).should == -10800 - end - end -end diff --git a/spec/ruby/core/time/shared/gmtime.rb b/spec/ruby/core/time/shared/gmtime.rb deleted file mode 100644 index aa76b436cc..0000000000 --- a/spec/ruby/core/time/shared/gmtime.rb +++ /dev/null @@ -1,40 +0,0 @@ -describe :time_gmtime, shared: true do - it "converts self to UTC, modifying the receiver" do - # Testing with America/Regina here because it doesn't have DST. - with_timezone("CST", -6) do - t = Time.local(2007, 1, 9, 6, 0, 0) - t.send(@method) - # Time#== compensates for time zones, so check all parts separately - t.year.should == 2007 - t.month.should == 1 - t.mday.should == 9 - t.hour.should == 12 - t.min.should == 0 - t.sec.should == 0 - t.zone.should == "UTC" - end - end - - it "returns self" do - with_timezone("CST", -6) do - t = Time.local(2007, 1, 9, 12, 0, 0) - t.send(@method).should.equal?(t) - end - end - - describe "on a frozen time" do - it "does not raise an error if already in UTC" do - time = Time.gm(2007, 1, 9, 12, 0, 0) - time.freeze - time.send(@method).should.equal?(time) - end - - it "raises a FrozenError if the time is not UTC" do - with_timezone("CST", -6) do - time = Time.now - time.freeze - -> { time.send(@method) }.should.raise(FrozenError) - end - end - end -end diff --git a/spec/ruby/core/time/shared/isdst.rb b/spec/ruby/core/time/shared/isdst.rb deleted file mode 100644 index bc6d139230..0000000000 --- a/spec/ruby/core/time/shared/isdst.rb +++ /dev/null @@ -1,8 +0,0 @@ -describe :time_isdst, shared: true do - it "dst? returns whether time is during daylight saving time" do - with_timezone("America/Los_Angeles") do - Time.local(2007, 9, 9, 0, 0, 0).send(@method).should == true - Time.local(2007, 1, 9, 0, 0, 0).send(@method).should == false - end - end -end diff --git a/spec/ruby/core/time/shared/month.rb b/spec/ruby/core/time/shared/month.rb deleted file mode 100644 index 31ca679557..0000000000 --- a/spec/ruby/core/time/shared/month.rb +++ /dev/null @@ -1,15 +0,0 @@ -describe :time_month, shared: true do - it "returns the month of the year for a local Time" do - with_timezone("CET", 1) do - Time.local(1970, 1).send(@method).should == 1 - end - end - - it "returns the month of the year for a UTC Time" do - Time.utc(1970, 1).send(@method).should == 1 - end - - it "returns the four digit year for a Time with a fixed offset" do - Time.new(2012, 1, 1, 0, 0, 0, -3600).send(@method).should == 1 - end -end diff --git a/spec/ruby/core/time/shared/to_i.rb b/spec/ruby/core/time/shared/to_i.rb deleted file mode 100644 index 06c966b708..0000000000 --- a/spec/ruby/core/time/shared/to_i.rb +++ /dev/null @@ -1,16 +0,0 @@ -describe :time_to_i, shared: true do - it "returns the value of time as an integer number of seconds since epoch" do - Time.at(0).send(@method).should == 0 - end - - it "doesn't return an actual number of seconds in time" do - Time.at(65.5).send(@method).should == 65 - end - - it "rounds fractional seconds toward zero" do - t = Time.utc(1960, 1, 1, 0, 0, 0, 999_999) - - t.to_f.to_i.should == -315619199 - t.to_i.should == -315619200 - end -end diff --git a/spec/ruby/core/time/shared/xmlschema.rb b/spec/ruby/core/time/shared/xmlschema.rb deleted file mode 100644 index d68c18df36..0000000000 --- a/spec/ruby/core/time/shared/xmlschema.rb +++ /dev/null @@ -1,31 +0,0 @@ -describe :time_xmlschema, shared: true do - ruby_version_is "3.4" do - it "generates ISO-8601 strings in Z for UTC times" do - t = Time.utc(1985, 4, 12, 23, 20, 50, 521245) - t.send(@method).should == "1985-04-12T23:20:50Z" - t.send(@method, 2).should == "1985-04-12T23:20:50.52Z" - t.send(@method, 9).should == "1985-04-12T23:20:50.521245000Z" - end - - it "generates ISO-8601 string with timeone offset for non-UTC times" do - t = Time.new(1985, 4, 12, 23, 20, 50, "+02:00") - t.send(@method).should == "1985-04-12T23:20:50+02:00" - t.send(@method, 2).should == "1985-04-12T23:20:50.00+02:00" - end - - it "year is always at least 4 digits" do - t = Time.utc(12, 4, 12) - t.send(@method).should == "0012-04-12T00:00:00Z" - end - - it "year can be more than 4 digits" do - t = Time.utc(40_000, 4, 12) - t.send(@method).should == "40000-04-12T00:00:00Z" - end - - it "year can be negative" do - t = Time.utc(-2000, 4, 12) - t.send(@method).should == "-2000-04-12T00:00:00Z" - end - end -end diff --git a/spec/ruby/core/time/to_i_spec.rb b/spec/ruby/core/time/to_i_spec.rb index 54929d1e18..00c4215d31 100644 --- a/spec/ruby/core/time/to_i_spec.rb +++ b/spec/ruby/core/time/to_i_spec.rb @@ -1,6 +1,18 @@ require_relative '../../spec_helper' -require_relative 'shared/to_i' describe "Time#to_i" do - it_behaves_like :time_to_i, :to_i + it "returns the value of time as an integer number of seconds since epoch" do + Time.at(0).to_i.should == 0 + end + + it "doesn't return an actual number of seconds in time" do + Time.at(65.5).to_i.should == 65 + end + + it "rounds fractional seconds toward zero" do + t = Time.utc(1960, 1, 1, 0, 0, 0, 999_999) + + t.to_f.to_i.should == -315619199 + t.to_i.should == -315619200 + end end diff --git a/spec/ruby/core/time/tv_nsec_spec.rb b/spec/ruby/core/time/tv_nsec_spec.rb index feb7998b16..802138bf3a 100644 --- a/spec/ruby/core/time/tv_nsec_spec.rb +++ b/spec/ruby/core/time/tv_nsec_spec.rb @@ -1,5 +1,7 @@ require_relative '../../spec_helper' describe "Time#tv_nsec" do - it "needs to be reviewed for spec completeness" + it "is an alias of Time#nsec" do + Time.instance_method(:tv_nsec).should == Time.instance_method(:nsec) + end end diff --git a/spec/ruby/core/time/tv_sec_spec.rb b/spec/ruby/core/time/tv_sec_spec.rb index f83e1fbfdd..21bdb53ee6 100644 --- a/spec/ruby/core/time/tv_sec_spec.rb +++ b/spec/ruby/core/time/tv_sec_spec.rb @@ -1,6 +1,7 @@ require_relative '../../spec_helper' -require_relative 'shared/to_i' describe "Time#tv_sec" do - it_behaves_like :time_to_i, :tv_sec + it "is an alias of Time#to_i" do + Time.instance_method(:tv_sec).should == Time.instance_method(:to_i) + end end diff --git a/spec/ruby/core/time/tv_usec_spec.rb b/spec/ruby/core/time/tv_usec_spec.rb index f0de4f4a9c..e922ee5625 100644 --- a/spec/ruby/core/time/tv_usec_spec.rb +++ b/spec/ruby/core/time/tv_usec_spec.rb @@ -1,5 +1,7 @@ require_relative '../../spec_helper' describe "Time#tv_usec" do - it "needs to be reviewed for spec completeness" + it "is an alias of Time#usec" do + Time.instance_method(:tv_usec).should == Time.instance_method(:usec) + end end diff --git a/spec/ruby/core/time/utc_offset_spec.rb b/spec/ruby/core/time/utc_offset_spec.rb index 17c031b8c6..8d2fff2012 100644 --- a/spec/ruby/core/time/utc_offset_spec.rb +++ b/spec/ruby/core/time/utc_offset_spec.rb @@ -1,6 +1,61 @@ require_relative '../../spec_helper' -require_relative 'shared/gmt_offset' describe "Time#utc_offset" do - it_behaves_like :time_gmt_offset, :utc_offset + it "returns the offset in seconds between the timezone of time and UTC" do + with_timezone("AST", 3) do + Time.new.utc_offset.should == 10800 + end + end + + it "returns 0 when the date is UTC" do + with_timezone("AST", 3) do + Time.new.utc.utc_offset.should == 0 + end + end + + platform_is_not :windows do + it "returns the correct offset for US Eastern time zone around daylight savings time change" do + # "2010-03-14 01:59:59 -0500" + 1 ==> "2010-03-14 03:00:00 -0400" + with_timezone("EST5EDT") do + t = Time.local(2010,3,14,1,59,59) + t.utc_offset.should == -5*60*60 + (t + 1).utc_offset.should == -4*60*60 + end + end + + it "returns the correct offset for Hawaii around daylight savings time change" do + # "2010-03-14 01:59:59 -1000" + 1 ==> "2010-03-14 02:00:00 -1000" + with_timezone("Pacific/Honolulu") do + t = Time.local(2010,3,14,1,59,59) + t.utc_offset.should == -10*60*60 + (t + 1).utc_offset.should == -10*60*60 + end + end + + it "returns the correct offset for New Zealand around daylight savings time change" do + # "2010-04-04 02:59:59 +1300" + 1 ==> "2010-04-04 02:00:00 +1200" + with_timezone("Pacific/Auckland") do + t = Time.local(2010,4,4,1,59,59) + (60 * 60) + t.utc_offset.should == 13*60*60 + (t + 1).utc_offset.should == 12*60*60 + end + end + end + + it "returns offset as Rational" do + Time.new(2010,4,4,1,59,59,7245).utc_offset.should == 7245 + Time.new(2010,4,4,1,59,59,7245.5).utc_offset.should == Rational(14491,2) + end + + context 'given positive offset' do + it 'returns a positive offset' do + Time.new(2013,3,17,nil,nil,nil,"+03:00").utc_offset.should == 10800 + end + end + + context 'given negative offset' do + it 'returns a negative offset' do + Time.new(2013,3,17,nil,nil,nil,"-03:00").utc_offset.should == -10800 + end + end end diff --git a/spec/ruby/core/time/utc_spec.rb b/spec/ruby/core/time/utc_spec.rb index ab3c0df657..35c1daa9e5 100644 --- a/spec/ruby/core/time/utc_spec.rb +++ b/spec/ruby/core/time/utc_spec.rb @@ -1,6 +1,4 @@ require_relative '../../spec_helper' -require_relative 'shared/gm' -require_relative 'shared/gmtime' require_relative 'shared/time_params' describe "Time#utc?" do @@ -11,7 +9,7 @@ describe "Time#utc?" do it "treats time as UTC what was created in different ways" do Time.now.utc.utc?.should == true - Time.now.gmtime.utc?.should == true + Time.now.utc.utc?.should == true Time.now.getgm.utc?.should == true Time.now.getutc.utc?.should == true Time.utc(2022).utc?.should == true @@ -55,12 +53,117 @@ describe "Time#utc?" do end describe "Time.utc" do - it_behaves_like :time_gm, :utc it_behaves_like :time_params, :utc it_behaves_like :time_params_10_arg, :utc it_behaves_like :time_params_microseconds, :utc + + it "creates a time based on given values, interpreted as UTC (GMT)" do + Time.utc(2000,"jan",1,20,15,1).inspect.should == "2000-01-01 20:15:01 UTC" + end + + it "creates a time based on given C-style gmtime arguments, interpreted as UTC (GMT)" do + time = Time.utc(1, 15, 20, 1, 1, 2000, :ignored, :ignored, :ignored, :ignored) + time.inspect.should == "2000-01-01 20:15:01 UTC" + end + + it "interprets pre-Gregorian reform dates using Gregorian proleptic calendar" do + Time.utc(1582, 10, 4, 12).to_i.should == -12220200000 # 2299150j + end + + it "interprets Julian-Gregorian gap dates using Gregorian proleptic calendar" do + Time.utc(1582, 10, 14, 12).to_i.should == -12219336000 # 2299160j + end + + it "interprets post-Gregorian reform dates using Gregorian calendar" do + Time.utc(1582, 10, 15, 12).to_i.should == -12219249600 # 2299161j + end + + it "handles fractional usec close to rounding limit" do + time = Time.utc(2000, 1, 1, 12, 30, 0, 9999r/10000) + + time.usec.should == 0 + time.nsec.should == 999 + end + + guard -> { + with_timezone 'right/UTC' do + (Time.utc(1972, 6, 30, 23, 59, 59) + 1).sec == 60 + end + } do + it "handles real leap seconds in zone 'right/UTC'" do + with_timezone 'right/UTC' do + time = Time.utc(1972, 6, 30, 23, 59, 60) + + time.sec.should == 60 + time.min.should == 59 + time.hour.should == 23 + time.day.should == 30 + time.month.should == 6 + end + end + end + + it "handles bad leap seconds by carrying values forward" do + with_timezone 'UTC' do + time = Time.utc(2017, 7, 5, 23, 59, 60) + time.sec.should == 0 + time.min.should == 0 + time.hour.should == 0 + time.day.should == 6 + time.month.should == 7 + end + end + + it "handles a value of 60 for seconds by carrying values forward in zone 'UTC'" do + with_timezone 'UTC' do + time = Time.utc(1972, 6, 30, 23, 59, 60) + + time.sec.should == 0 + time.min.should == 0 + time.hour.should == 0 + time.day.should == 1 + time.month.should == 7 + end + end end describe "Time#utc" do - it_behaves_like :time_gmtime, :utc + it "converts self to UTC, modifying the receiver" do + # Testing with America/Regina here because it doesn't have DST. + with_timezone("CST", -6) do + t = Time.local(2007, 1, 9, 6, 0, 0) + t.utc + # Time#== compensates for time zones, so check all parts separately + t.year.should == 2007 + t.month.should == 1 + t.mday.should == 9 + t.hour.should == 12 + t.min.should == 0 + t.sec.should == 0 + t.zone.should == "UTC" + end + end + + it "returns self" do + with_timezone("CST", -6) do + t = Time.local(2007, 1, 9, 12, 0, 0) + t.utc.should.equal?(t) + end + end + + describe "on a frozen time" do + it "does not raise an error if already in UTC" do + time = Time.gm(2007, 1, 9, 12, 0, 0) + time.freeze + time.utc.should.equal?(time) + end + + it "raises a FrozenError if the time is not UTC" do + with_timezone("CST", -6) do + time = Time.now + time.freeze + -> { time.utc }.should.raise(FrozenError) + end + end + end end diff --git a/spec/ruby/core/time/xmlschema_spec.rb b/spec/ruby/core/time/xmlschema_spec.rb index bdf1dc7923..6a26861a45 100644 --- a/spec/ruby/core/time/xmlschema_spec.rb +++ b/spec/ruby/core/time/xmlschema_spec.rb @@ -1,6 +1,9 @@ require_relative '../../spec_helper' -require_relative 'shared/xmlschema' describe "Time#xmlschema" do - it_behaves_like :time_xmlschema, :xmlschema + ruby_version_is "3.4" do + it "is an alias of Time#iso8601" do + Time.instance_method(:xmlschema).should == Time.instance_method(:iso8601) + end + end end diff --git a/spec/ruby/core/true/inspect_spec.rb b/spec/ruby/core/true/inspect_spec.rb index 09d1914856..b9f5390b5c 100644 --- a/spec/ruby/core/true/inspect_spec.rb +++ b/spec/ruby/core/true/inspect_spec.rb @@ -1,7 +1,7 @@ require_relative '../../spec_helper' describe "TrueClass#inspect" do - it "returns the string 'true'" do - true.inspect.should == "true" + it "is an alias of TrueClass#to_s" do + true.method(:inspect).should == true.method(:to_s) end end diff --git a/spec/ruby/core/unboundmethod/eql_spec.rb b/spec/ruby/core/unboundmethod/eql_spec.rb index cf2c6b5aae..3b299d047a 100644 --- a/spec/ruby/core/unboundmethod/eql_spec.rb +++ b/spec/ruby/core/unboundmethod/eql_spec.rb @@ -1,5 +1,7 @@ require_relative '../../spec_helper' describe "UnboundMethod#eql?" do - it "needs to be reviewed for spec completeness" + it "is an alias of UnboundMethod#==" do + UnboundMethod.instance_method(:eql?).should == UnboundMethod.instance_method(:==) + end end diff --git a/spec/ruby/core/unboundmethod/inspect_spec.rb b/spec/ruby/core/unboundmethod/inspect_spec.rb index 3abed94f7f..b0fcfd00ea 100644 --- a/spec/ruby/core/unboundmethod/inspect_spec.rb +++ b/spec/ruby/core/unboundmethod/inspect_spec.rb @@ -1,9 +1,7 @@ require_relative '../../spec_helper' -require_relative 'fixtures/classes' -require_relative 'shared/to_s' -require_relative '../method/shared/aliased_inspect' describe "UnboundMethod#inspect" do - it_behaves_like :unboundmethod_to_s, :inspect - it_behaves_like :method_to_s_aliased, :inspect, -> meth { meth.unbind } + it "is an alias of UnboundMethod#to_s" do + UnboundMethod.instance_method(:inspect).should == UnboundMethod.instance_method(:to_s) + end end diff --git a/spec/ruby/core/unboundmethod/shared/to_s.rb b/spec/ruby/core/unboundmethod/shared/to_s.rb deleted file mode 100644 index 848c1eba2e..0000000000 --- a/spec/ruby/core/unboundmethod/shared/to_s.rb +++ /dev/null @@ -1,33 +0,0 @@ -require_relative '../../../spec_helper' -require_relative '../fixtures/classes' - -describe :unboundmethod_to_s, shared: true do - before :each do - @from_module = UnboundMethodSpecs::Methods.instance_method(:from_mod) - @from_method = UnboundMethodSpecs::Methods.new.method(:from_mod).unbind - end - - it "returns a String" do - @from_module.send(@method).should.is_a?(String) - @from_method.send(@method).should.is_a?(String) - end - - it "the String reflects that this is an UnboundMethod object" do - @from_module.send(@method).should =~ /\bUnboundMethod\b/ - @from_method.send(@method).should =~ /\bUnboundMethod\b/ - end - - it "the String shows the method name, Module defined in and Module extracted from" do - @from_module.send(@method).should =~ /\bfrom_mod\b/ - @from_module.send(@method).should =~ /\bUnboundMethodSpecs::Mod\b/ - end - - it "returns a String including all details" do - @from_module.send(@method).should.start_with? "#<UnboundMethod: UnboundMethodSpecs::Mod#from_mod" - @from_method.send(@method).should.start_with? "#<UnboundMethod: UnboundMethodSpecs::Mod#from_mod" - end - - it "does not show the defining module if it is the same as the origin" do - UnboundMethodSpecs::A.instance_method(:baz).send(@method).should.start_with? "#<UnboundMethod: UnboundMethodSpecs::A#baz" - end -end diff --git a/spec/ruby/core/unboundmethod/to_s_spec.rb b/spec/ruby/core/unboundmethod/to_s_spec.rb index 615d88675b..b90f315c3a 100644 --- a/spec/ruby/core/unboundmethod/to_s_spec.rb +++ b/spec/ruby/core/unboundmethod/to_s_spec.rb @@ -1,9 +1,36 @@ require_relative '../../spec_helper' require_relative 'fixtures/classes' -require_relative 'shared/to_s' require_relative '../method/shared/aliased_inspect' describe "UnboundMethod#to_s" do - it_behaves_like :unboundmethod_to_s, :to_s it_behaves_like :method_to_s_aliased, :to_s, -> meth { meth.unbind } + + before :each do + @from_module = UnboundMethodSpecs::Methods.instance_method(:from_mod) + @from_method = UnboundMethodSpecs::Methods.new.method(:from_mod).unbind + end + + it "returns a String" do + @from_module.to_s.should.is_a?(String) + @from_method.to_s.should.is_a?(String) + end + + it "the String reflects that this is an UnboundMethod object" do + @from_module.to_s.should =~ /\bUnboundMethod\b/ + @from_method.to_s.should =~ /\bUnboundMethod\b/ + end + + it "the String shows the method name, Module defined in and Module extracted from" do + @from_module.to_s.should =~ /\bfrom_mod\b/ + @from_module.to_s.should =~ /\bUnboundMethodSpecs::Mod\b/ + end + + it "returns a String including all details" do + @from_module.to_s.should.start_with? "#<UnboundMethod: UnboundMethodSpecs::Mod#from_mod" + @from_method.to_s.should.start_with? "#<UnboundMethod: UnboundMethodSpecs::Mod#from_mod" + end + + it "does not show the defining module if it is the same as the origin" do + UnboundMethodSpecs::A.instance_method(:baz).to_s.should.start_with? "#<UnboundMethod: UnboundMethodSpecs::A#baz" + end end |
