Ensure test suite is compatible with --frozen-string-literal

As preparation for https://bugs.ruby-lang.org/issues/20205
making sure the test suite is compatible with frozen string
literals is making things easier.
This commit is contained in:
Jean Boussier 2024-03-13 12:50:11 +01:00 committed by Jean Boussier
parent 4e03d56e21
commit 09d8c99cdc
30 changed files with 159 additions and 147 deletions

View File

@ -879,7 +879,7 @@ $x.sort!{|a,b| b-a} # reverse sort
test_ok($x == [7,5,3,2,1]) test_ok($x == [7,5,3,2,1])
# split test # split test
$x = "The Book of Mormon" $x = +"The Book of Mormon"
test_ok($x.split(//).reverse!.join == $x.reverse) test_ok($x.split(//).reverse!.join == $x.reverse)
test_ok($x.reverse == $x.reverse!) test_ok($x.reverse == $x.reverse!)
test_ok("1 byte string".split(//).reverse.join(":") == "g:n:i:r:t:s: :e:t:y:b: :1") test_ok("1 byte string".split(//).reverse.join(":") == "g:n:i:r:t:s: :e:t:y:b: :1")
@ -1643,7 +1643,7 @@ test_ok(/^(?:ab+)+/ =~ "ababb" && $& == "ababb")
test_ok(/(\s+\d+){2}/ =~ " 1 2" && $& == " 1 2") test_ok(/(\s+\d+){2}/ =~ " 1 2" && $& == " 1 2")
test_ok(/(?:\s+\d+){2}/ =~ " 1 2" && $& == " 1 2") test_ok(/(?:\s+\d+){2}/ =~ " 1 2" && $& == " 1 2")
$x = <<END; $x = +<<END;
ABCD ABCD
ABCD ABCD
END END
@ -1682,12 +1682,12 @@ test_ok(?a == ?a)
test_ok(?\C-a == "\1") test_ok(?\C-a == "\1")
test_ok(?\M-a == "\341") test_ok(?\M-a == "\341")
test_ok(?\M-\C-a == "\201") test_ok(?\M-\C-a == "\201")
test_ok("a".upcase![0] == ?A) test_ok("a".dup.upcase![0] == ?A)
test_ok("A".downcase![0] == ?a) test_ok("A".dup.downcase![0] == ?a)
test_ok("abc".tr!("a-z", "A-Z") == "ABC") test_ok("abc".dup.tr!("a-z", "A-Z") == "ABC")
test_ok("aabbcccc".tr_s!("a-z", "A-Z") == "ABC") test_ok("aabbcccc".dup.tr_s!("a-z", "A-Z") == "ABC")
test_ok("abcc".squeeze!("a-z") == "abc") test_ok("abcc".dup.squeeze!("a-z") == "abc")
test_ok("abcd".delete!("bc") == "ad") test_ok("abcd".dup.delete!("bc") == "ad")
$x = "abcdef" $x = "abcdef"
$y = [ ?a, ?b, ?c, ?d, ?e, ?f ] $y = [ ?a, ?b, ?c, ?d, ?e, ?f ]
@ -1700,7 +1700,7 @@ $x.each_byte {|i|
} }
test_ok(!$bad) test_ok(!$bad)
s = "a string" s = +"a string"
s[0..s.size]="another string" s[0..s.size]="another string"
test_ok(s == "another string") test_ok(s == "another string")

View File

@ -548,10 +548,10 @@ class Assertion < Struct.new(:src, :path, :lineno, :proc)
end end
end end
def make_srcfile(frozen_string_literal: nil) def make_srcfile(frozen_string_literal: true)
filename = "bootstraptest.#{self.path}_#{self.lineno}_#{self.id}.rb" filename = "bootstraptest.#{self.path}_#{self.lineno}_#{self.id}.rb"
File.open(filename, 'w') {|f| File.open(filename, 'w') {|f|
f.puts "#frozen_string_literal:true" if frozen_string_literal f.puts "#frozen_string_literal:#{frozen_string_literal}" unless frozen_string_literal.nil?
if $stress if $stress
f.puts "GC.stress = true" if $stress f.puts "GC.stress = true" if $stress
else else
@ -572,9 +572,9 @@ def add_assertion src, pr
Assertion.new(src, path, lineno, pr) Assertion.new(src, path, lineno, pr)
end end
def assert_equal(expected, testsrc, message = '', opt = '', **argh) def assert_equal(expected, testsrc, message = '', opt = '', **kwargs)
add_assertion testsrc, -> as do add_assertion testsrc, -> as do
as.assert_check(message, opt, **argh) {|result| as.assert_check(message, opt, **kwargs) {|result|
if expected == result if expected == result
nil nil
else else
@ -585,9 +585,9 @@ def assert_equal(expected, testsrc, message = '', opt = '', **argh)
end end
end end
def assert_match(expected_pattern, testsrc, message = '') def assert_match(expected_pattern, testsrc, message = '', **argh)
add_assertion testsrc, -> as do add_assertion testsrc, -> as do
as.assert_check(message) {|result| as.assert_check(message, **argh) {|result|
if expected_pattern =~ result if expected_pattern =~ result
nil nil
else else

View File

@ -363,7 +363,7 @@ assert_equal %q{[1, 2, 3, 5, 2, 3, 5, 7, 8]}, %q{$a = []; begin; ; $a << 1
; $a << 8 ; $a << 8
; rescue Exception; $a << 99; end; $a} ; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 6, 3, 5, 7, 8]}, %q{$a = []; begin; ; $a << 1 assert_equal %q{[1, 2, 6, 3, 5, 7, 8]}, %q{$a = []; begin; ; $a << 1
o = "test"; $a << 2 o = "test".dup; $a << 2
def o.test(a); $a << 3 def o.test(a); $a << 3
return a; $a << 4 return a; $a << 4
ensure; $a << 5 ensure; $a << 5

View File

@ -354,7 +354,7 @@ tests = [
[ 'opt_ge', %q{ +0.0.next_float >= 0.0 }, ], [ 'opt_ge', %q{ +0.0.next_float >= 0.0 }, ],
[ 'opt_ge', %q{ ?z >= ?a }, ], [ 'opt_ge', %q{ ?z >= ?a }, ],
[ 'opt_ltlt', %q{ '' << 'true' }, ], [ 'opt_ltlt', %q{ +'' << 'true' }, ],
[ 'opt_ltlt', %q{ ([] << 'true').join }, ], [ 'opt_ltlt', %q{ ([] << 'true').join }, ],
[ 'opt_ltlt', %q{ (1 << 31) == 2147483648 }, ], [ 'opt_ltlt', %q{ (1 << 31) == 2147483648 }, ],
@ -363,7 +363,7 @@ tests = [
[ 'opt_aref', %q{ 'true'[0] == ?t }, ], [ 'opt_aref', %q{ 'true'[0] == ?t }, ],
[ 'opt_aset', %q{ [][0] = true }, ], [ 'opt_aset', %q{ [][0] = true }, ],
[ 'opt_aset', %q{ {}[0] = true }, ], [ 'opt_aset', %q{ {}[0] = true }, ],
[ 'opt_aset', %q{ x = 'frue'; x[0] = 't'; x }, ], [ 'opt_aset', %q{ x = +'frue'; x[0] = 't'; x }, ],
[ 'opt_aset', <<-'},', ], # { [ 'opt_aset', <<-'},', ], # {
# opt_aref / opt_aset mixup situation # opt_aref / opt_aset mixup situation
class X; def x; {}; end; end class X; def x; {}; end; end

View File

@ -292,7 +292,7 @@ assert_equal "true", %q{
end end
end end
end end
s = "foo" s = +"foo"
s.return_eigenclass == class << s; self; end s.return_eigenclass == class << s; self; end
}, '[ruby-core:21379]' }, '[ruby-core:21379]'

View File

@ -628,7 +628,7 @@ assert_equal "allocator undefined for Thread", %q{
} }
# send shareable and unshareable objects # send shareable and unshareable objects
assert_equal "ok", %q{ assert_equal "ok", <<~'RUBY', frozen_string_literal: false
echo_ractor = Ractor.new do echo_ractor = Ractor.new do
loop do loop do
v = Ractor.receive v = Ractor.receive
@ -695,10 +695,10 @@ assert_equal "ok", %q{
else else
results.inspect results.inspect
end end
} RUBY
# frozen Objects are shareable # frozen Objects are shareable
assert_equal [false, true, false].inspect, %q{ assert_equal [false, true, false].inspect, <<~'RUBY', frozen_string_literal: false
class C class C
def initialize freeze def initialize freeze
@a = 1 @a = 1
@ -721,11 +721,11 @@ assert_equal [false, true, false].inspect, %q{
results << check(C.new(true)) # false results << check(C.new(true)) # false
results << check(C.new(true).freeze) # true results << check(C.new(true).freeze) # true
results << check(C.new(false).freeze) # false results << check(C.new(false).freeze) # false
} RUBY
# move example2: String # move example2: String
# touching moved object causes an error # touching moved object causes an error
assert_equal 'hello world', %q{ assert_equal 'hello world', <<~'RUBY', frozen_string_literal: false
# move # move
r = Ractor.new do r = Ractor.new do
obj = Ractor.receive obj = Ractor.receive
@ -743,7 +743,7 @@ assert_equal 'hello world', %q{
else else
raise 'unreachable' raise 'unreachable'
end end
} RUBY
# move example2: Array # move example2: Array
assert_equal '[0, 1]', %q{ assert_equal '[0, 1]', %q{
@ -946,7 +946,7 @@ assert_equal 'ArgumentError', %q{
} }
# ivar in shareable-objects are not allowed to access from non-main Ractor # ivar in shareable-objects are not allowed to access from non-main Ractor
assert_equal "can not get unshareable values from instance variables of classes/modules from non-main Ractors", %q{ assert_equal "can not get unshareable values from instance variables of classes/modules from non-main Ractors", <<~'RUBY', frozen_string_literal: false
class C class C
@iv = 'str' @iv = 'str'
end end
@ -957,13 +957,12 @@ assert_equal "can not get unshareable values from instance variables of classes/
end end
end end
begin begin
r.take r.take
rescue Ractor::RemoteError => e rescue Ractor::RemoteError => e
e.cause.message e.cause.message
end end
} RUBY
# ivar in shareable-objects are not allowed to access from non-main Ractor # ivar in shareable-objects are not allowed to access from non-main Ractor
assert_equal 'can not access instance variables of shareable objects from non-main Ractors', %q{ assert_equal 'can not access instance variables of shareable objects from non-main Ractors', %q{
@ -1150,7 +1149,7 @@ assert_equal 'can not access class variables from non-main Ractors', %q{
} }
# Getting non-shareable objects via constants by other Ractors is not allowed # Getting non-shareable objects via constants by other Ractors is not allowed
assert_equal 'can not access non-shareable objects in constant C::CONST by non-main Ractor.', %q{ assert_equal 'can not access non-shareable objects in constant C::CONST by non-main Ractor.', <<~'RUBY', frozen_string_literal: false
class C class C
CONST = 'str' CONST = 'str'
end end
@ -1162,10 +1161,10 @@ assert_equal 'can not access non-shareable objects in constant C::CONST by non-m
rescue Ractor::RemoteError => e rescue Ractor::RemoteError => e
e.cause.message e.cause.message
end end
} RUBY
# Constant cache should care about non-sharable constants # Constant cache should care about non-sharable constants
assert_equal "can not access non-shareable objects in constant Object::STR by non-main Ractor.", %q{ assert_equal "can not access non-shareable objects in constant Object::STR by non-main Ractor.", <<~'RUBY', frozen_string_literal: false
STR = "hello" STR = "hello"
def str; STR; end def str; STR; end
s = str() # fill const cache s = str() # fill const cache
@ -1174,10 +1173,10 @@ assert_equal "can not access non-shareable objects in constant Object::STR by no
rescue Ractor::RemoteError => e rescue Ractor::RemoteError => e
e.cause.message e.cause.message
end end
} RUBY
# Setting non-shareable objects into constants by other Ractors is not allowed # Setting non-shareable objects into constants by other Ractors is not allowed
assert_equal 'can not set constants with non-shareable objects by non-main Ractors', %q{ assert_equal 'can not set constants with non-shareable objects by non-main Ractors', <<~'RUBY', frozen_string_literal: false
class C class C
end end
r = Ractor.new do r = Ractor.new do
@ -1188,7 +1187,7 @@ assert_equal 'can not set constants with non-shareable objects by non-main Racto
rescue Ractor::RemoteError => e rescue Ractor::RemoteError => e
e.cause.message e.cause.message
end end
} RUBY
# define_method is not allowed # define_method is not allowed
assert_equal "defined with an un-shareable Proc in a different Ractor", %q{ assert_equal "defined with an un-shareable Proc in a different Ractor", %q{
@ -1241,7 +1240,7 @@ assert_equal '0', %q{
} }
# ObjectSpace._id2ref can not handle unshareable objects with Ractors # ObjectSpace._id2ref can not handle unshareable objects with Ractors
assert_equal 'ok', %q{ assert_equal 'ok', <<~'RUBY', frozen_string_literal: false
s = 'hello' s = 'hello'
Ractor.new s.object_id do |id ;s| Ractor.new s.object_id do |id ;s|
@ -1251,10 +1250,10 @@ assert_equal 'ok', %q{
:ok :ok
end end
end.take end.take
} RUBY
# Ractor.make_shareable(obj) # Ractor.make_shareable(obj)
assert_equal 'true', %q{ assert_equal 'true', <<~'RUBY', frozen_string_literal: false
class C class C
def initialize def initialize
@a = 'foo' @a = 'foo'
@ -1325,7 +1324,7 @@ assert_equal 'true', %q{
} }
Ractor.shareable?(a) Ractor.shareable?(a)
} RUBY
# Ractor.make_shareable(obj) doesn't freeze shareable objects # Ractor.make_shareable(obj) doesn't freeze shareable objects
assert_equal 'true', %q{ assert_equal 'true', %q{
@ -1422,14 +1421,14 @@ assert_equal '[false, false, true, true]', %q{
} }
# TracePoint with normal Proc should be Ractor local # TracePoint with normal Proc should be Ractor local
assert_equal '[6, 10]', %q{ assert_equal '[7, 11]', %q{
rs = [] rs = []
TracePoint.new(:line){|tp| rs << tp.lineno if tp.path == __FILE__}.enable do TracePoint.new(:line){|tp| rs << tp.lineno if tp.path == __FILE__}.enable do
Ractor.new{ # line 4 Ractor.new{ # line 5
a = 1 a = 1
b = 2 b = 2
}.take }.take
c = 3 # line 8 c = 3 # line 9
end end
rs rs
} }
@ -1503,7 +1502,7 @@ assert_equal "#{n}#{n}", %Q{
2.times.map{ 2.times.map{
Ractor.new do Ractor.new do
#{n}.times do #{n}.times do
obj = '' obj = +''
obj.instance_variable_set("@a", 1) obj.instance_variable_set("@a", 1)
obj.instance_variable_set("@b", 1) obj.instance_variable_set("@b", 1)
obj.instance_variable_set("@c", 1) obj.instance_variable_set("@c", 1)
@ -1662,7 +1661,7 @@ assert_match /\Atest_ractor\.rb:1:\s+warning:\s+Ractor is experimental/, %q{
Warning[:experimental] = $VERBOSE = true Warning[:experimental] = $VERBOSE = true
STDERR.reopen(STDOUT) STDERR.reopen(STDOUT)
eval("Ractor.new{}.take", nil, "test_ractor.rb", 1) eval("Ractor.new{}.take", nil, "test_ractor.rb", 1)
} }, frozen_string_literal: false
# check moved object # check moved object
assert_equal 'ok', %q{ assert_equal 'ok', %q{

View File

@ -629,7 +629,7 @@ assert_equal '2', %q{
assert_match /invalid multibyte char/, %q{ assert_match /invalid multibyte char/, %q{
$stderr = STDOUT $stderr = STDOUT
eval("\"\xf0".force_encoding("utf-8")) eval("\"\xf0".dup.force_encoding("utf-8"))
}, '[ruby-dev:32429]' }, '[ruby-dev:32429]'
# method ! and != # method ! and !=

View File

@ -185,7 +185,7 @@ assert_equal '[0, :sum, 0, :sum]', %q{
end end
def cstring(iter) def cstring(iter)
string = "" string = "".dup
string.sum(iter.times { def string.sum(_) = :sum }) string.sum(iter.times { def string.sum(_) = :sum })
end end
@ -1250,7 +1250,7 @@ assert_equal "good", %q{
# Test polymorphic getinstancevariable. T_OBJECT -> T_STRING # Test polymorphic getinstancevariable. T_OBJECT -> T_STRING
assert_equal 'ok', %q{ assert_equal 'ok', %q{
@hello = @h1 = @h2 = @h3 = @h4 = 'ok' @hello = @h1 = @h2 = @h3 = @h4 = 'ok'
str = "" str = +""
str.instance_variable_set(:@hello, 'ok') str.instance_variable_set(:@hello, 'ok')
public def get public def get
@ -1395,7 +1395,7 @@ assert_equal '[42, :default]', %q{
} }
# Test default value block for Hash with opt_aref_with # Test default value block for Hash with opt_aref_with
assert_equal "false", %q{ assert_equal "false", <<~RUBY, frozen_string_literal: false
def index_with_string(h) def index_with_string(h)
h["foo"] h["foo"]
end end
@ -1404,7 +1404,7 @@ assert_equal "false", %q{
index_with_string(h) index_with_string(h)
index_with_string(h) index_with_string(h)
} RUBY
# A regression test for making sure cfp->sp is proper when # A regression test for making sure cfp->sp is proper when
# hitting stubs. See :stub-sp-flush: # hitting stubs. See :stub-sp-flush:
@ -1904,7 +1904,7 @@ assert_equal 'foo', %q{
} }
# Test that String unary plus returns the same object ID for an unfrozen string. # Test that String unary plus returns the same object ID for an unfrozen string.
assert_equal 'true', %q{ assert_equal 'true', <<~RUBY, frozen_string_literal: false
def jittable_method def jittable_method
str = "bar" str = "bar"
@ -1914,7 +1914,7 @@ assert_equal 'true', %q{
uplus_str.object_id == old_obj_id uplus_str.object_id == old_obj_id
end end
jittable_method jittable_method
} RUBY
# Test that String unary plus returns a different unfrozen string when given a frozen string # Test that String unary plus returns a different unfrozen string when given a frozen string
assert_equal 'false', %q{ assert_equal 'false', %q{
@ -2048,7 +2048,7 @@ assert_equal '[97, :nil, 97, :nil, :raised]', %q{
# Basic test for String#setbyte # Basic test for String#setbyte
assert_equal 'AoZ', %q{ assert_equal 'AoZ', %q{
s = "foo" s = +"foo"
s.setbyte(0, 65) s.setbyte(0, 65)
s.setbyte(-1, 90) s.setbyte(-1, 90)
s s
@ -2091,7 +2091,7 @@ assert_equal 'String#setbyte', %q{
0 0
end end
def ccall = "a".setbyte(self, 98) def ccall = "a".dup.setbyte(self, 98)
ccall ccall
@caller.first.split("'").last @caller.first.split("'").last
@ -4167,7 +4167,7 @@ assert_equal '2', %q{
assert_equal 'Hello World', %q{ assert_equal 'Hello World', %q{
def bar def bar
args = ["Hello "] args = ["Hello "]
greeting = "World" greeting = +"World"
greeting.insert(0, *args) greeting.insert(0, *args)
greeting greeting
end end

View File

@ -1,3 +1,5 @@
# frozen_string_literal: true
# Simple DSL implementation for Ripper code generation # Simple DSL implementation for Ripper code generation
# #
# input: /*% ripper: stmts_add!(stmts_new!, void_stmt!) %*/ # input: /*% ripper: stmts_add!(stmts_new!, void_stmt!) %*/
@ -33,7 +35,7 @@ class DSL
# struct parser_params *p # struct parser_params *p
p = p = "p" p = p = "p"
@code = "" @code = +""
code = code.gsub(%r[\G#{NOT_REF_PATTERN}\K(\$|\$:|@)#{TAG_PATTERN}?#{NAME_PATTERN}]o, '"\&"') code = code.gsub(%r[\G#{NOT_REF_PATTERN}\K(\$|\$:|@)#{TAG_PATTERN}?#{NAME_PATTERN}]o, '"\&"')
@last_value = eval(code) @last_value = eval(code)
rescue SyntaxError rescue SyntaxError

View File

@ -7955,7 +7955,7 @@ pm_compile_node(rb_iseq_t *iseq, const pm_node_t *node, LINK_ANCHOR *const ret,
const pm_string_node_t *cast = (const pm_string_node_t *) node; const pm_string_node_t *cast = (const pm_string_node_t *) node;
VALUE value = rb_fstring(parse_string_encoded(scope_node, node, &cast->unescaped)); VALUE value = rb_fstring(parse_string_encoded(scope_node, node, &cast->unescaped));
if (PM_NODE_FLAG_P(node, PM_STRING_FLAGS_FROZEN)) { if (PM_NODE_FLAG_P(node, PM_STRING_FLAGS_FROZEN) || ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal) {
PUSH_INSN1(ret, location, putobject, value); PUSH_INSN1(ret, location, putobject, value);
} }
else { else {

View File

@ -11,6 +11,7 @@ class TestTracepointObj < Test::Unit::TestCase
def test_tracks_objspace_events def test_tracks_objspace_events
result = EnvUtil.suppress_warning {eval(<<-EOS, nil, __FILE__, __LINE__+1)} result = EnvUtil.suppress_warning {eval(<<-EOS, nil, __FILE__, __LINE__+1)}
# frozen_string_literal: false
Bug.tracepoint_track_objspace_events { Bug.tracepoint_track_objspace_events {
99 99
'abc' 'abc'

View File

@ -673,7 +673,7 @@ class TestObjSpace < Test::Unit::TestCase
assert_equal("TEST2", entry_hash["value"], "value is wrong") assert_equal("TEST2", entry_hash["value"], "value is wrong")
assert_equal("UTF-8", entry_hash["encoding"], "encoding is wrong") assert_equal("UTF-8", entry_hash["encoding"], "encoding is wrong")
assert_equal("-", entry_hash["file"], "file is wrong") assert_equal("-", entry_hash["file"], "file is wrong")
assert_equal(4, entry_hash["line"], "line is wrong") assert_equal(5, entry_hash["line"], "line is wrong")
assert_equal("dump_my_heap_please", entry_hash["method"], "method is wrong") assert_equal("dump_my_heap_please", entry_hash["method"], "method is wrong")
assert_not_nil(entry_hash["generation"]) assert_not_nil(entry_hash["generation"])
end end
@ -682,6 +682,7 @@ class TestObjSpace < Test::Unit::TestCase
opts = %w[--disable-gem --disable=frozen-string-literal -robjspace] opts = %w[--disable-gem --disable=frozen-string-literal -robjspace]
assert_in_out_err(opts, "#{<<-"begin;"}#{<<-'end;'}") do |output, error| assert_in_out_err(opts, "#{<<-"begin;"}#{<<-'end;'}") do |output, error|
# frozen_string_literal: false
begin; begin;
def dump_my_heap_please def dump_my_heap_please
ObjectSpace.trace_object_allocations_start ObjectSpace.trace_object_allocations_start
@ -698,6 +699,7 @@ class TestObjSpace < Test::Unit::TestCase
assert_in_out_err(%w[-robjspace], "#{<<-"begin;"}#{<<-'end;'}") do |(output), (error)| assert_in_out_err(%w[-robjspace], "#{<<-"begin;"}#{<<-'end;'}") do |(output), (error)|
begin; begin;
# frozen_string_literal: false
def dump_my_heap_please def dump_my_heap_please
ObjectSpace.trace_object_allocations_start ObjectSpace.trace_object_allocations_start
GC.start GC.start
@ -828,6 +830,7 @@ class TestObjSpace < Test::Unit::TestCase
def test_objspace_trace def test_objspace_trace
assert_in_out_err(%w[-robjspace/trace], "#{<<-"begin;"}\n#{<<-'end;'}") do |out, err| assert_in_out_err(%w[-robjspace/trace], "#{<<-"begin;"}\n#{<<-'end;'}") do |out, err|
begin; begin;
# frozen_string_literal: false
a = "foo" a = "foo"
b = "b" + "a" + "r" b = "b" + "a" + "r"
c = 42 c = 42
@ -835,8 +838,8 @@ class TestObjSpace < Test::Unit::TestCase
end; end;
assert_equal ["objspace/trace is enabled"], err assert_equal ["objspace/trace is enabled"], err
assert_equal 3, out.size assert_equal 3, out.size
assert_equal '"foo" @ -:2', out[0] assert_equal '"foo" @ -:3', out[0]
assert_equal '"bar" @ -:3', out[1] assert_equal '"bar" @ -:4', out[1]
assert_equal '42', out[2] assert_equal '42', out[2]
end end
end end

View File

@ -47,7 +47,7 @@ class TestCaseMappingPreliminary < Test::Unit::TestCase
# different properties; careful: roundtrip isn't always guaranteed # different properties; careful: roundtrip isn't always guaranteed
def check_swapcase_properties(expected, start, *flags) def check_swapcase_properties(expected, start, *flags)
assert_equal expected, start.swapcase(*flags) assert_equal expected, start.swapcase(*flags)
temp = start temp = +start
assert_equal expected, temp.swapcase!(*flags) assert_equal expected, temp.swapcase!(*flags)
assert_equal start, start.swapcase(*flags).swapcase(*flags) assert_equal start, start.swapcase(*flags).swapcase(*flags)
assert_equal expected, expected.swapcase(*flags).swapcase(*flags) assert_equal expected, expected.swapcase(*flags).swapcase(*flags)
@ -61,10 +61,10 @@ class TestCaseMappingPreliminary < Test::Unit::TestCase
end end
def test_invalid def test_invalid
assert_raise(ArgumentError, "Should not be possible to upcase invalid string.") { "\xEB".force_encoding('UTF-8').upcase } assert_raise(ArgumentError, "Should not be possible to upcase invalid string.") { "\xEB".dup.force_encoding('UTF-8').upcase }
assert_raise(ArgumentError, "Should not be possible to downcase invalid string.") { "\xEB".force_encoding('UTF-8').downcase } assert_raise(ArgumentError, "Should not be possible to downcase invalid string.") { "\xEB".dup.force_encoding('UTF-8').downcase }
assert_raise(ArgumentError, "Should not be possible to capitalize invalid string.") { "\xEB".force_encoding('UTF-8').capitalize } assert_raise(ArgumentError, "Should not be possible to capitalize invalid string.") { "\xEB".dup.force_encoding('UTF-8').capitalize }
assert_raise(ArgumentError, "Should not be possible to swapcase invalid string.") { "\xEB".force_encoding('UTF-8').swapcase } assert_raise(ArgumentError, "Should not be possible to swapcase invalid string.") { "\xEB".dup.force_encoding('UTF-8').swapcase }
end end
def test_general def test_general

View File

@ -19,7 +19,7 @@ class TestCaseOptions < Test::Unit::TestCase
def assert_raise_both_types(*options) def assert_raise_both_types(*options)
assert_raise_functional_operations 'a', *options assert_raise_functional_operations 'a', *options
assert_raise_bang_operations 'a', *options assert_raise_bang_operations +'a', *options
assert_raise_functional_operations :a, *options assert_raise_functional_operations :a, *options
end end
@ -51,7 +51,7 @@ class TestCaseOptions < Test::Unit::TestCase
def assert_okay_both_types(*options) def assert_okay_both_types(*options)
assert_okay_functional_operations 'a', *options assert_okay_functional_operations 'a', *options
assert_okay_bang_operations 'a', *options assert_okay_bang_operations +'a', *options
assert_okay_functional_operations :a, *options assert_okay_functional_operations :a, *options
end end
@ -69,10 +69,10 @@ class TestCaseOptions < Test::Unit::TestCase
assert_raise(ArgumentError) { 'a'.upcase :fold } assert_raise(ArgumentError) { 'a'.upcase :fold }
assert_raise(ArgumentError) { 'a'.capitalize :fold } assert_raise(ArgumentError) { 'a'.capitalize :fold }
assert_raise(ArgumentError) { 'a'.swapcase :fold } assert_raise(ArgumentError) { 'a'.swapcase :fold }
assert_nothing_raised { 'a'.downcase! :fold } assert_nothing_raised { 'a'.dup.downcase! :fold }
assert_raise(ArgumentError) { 'a'.upcase! :fold } assert_raise(ArgumentError) { 'a'.dup.upcase! :fold }
assert_raise(ArgumentError) { 'a'.capitalize! :fold } assert_raise(ArgumentError) { 'a'.dup.capitalize! :fold }
assert_raise(ArgumentError) { 'a'.swapcase! :fold } assert_raise(ArgumentError) { 'a'.dup.swapcase! :fold }
assert_nothing_raised { :a.downcase :fold } assert_nothing_raised { :a.downcase :fold }
assert_raise(ArgumentError) { :a.upcase :fold } assert_raise(ArgumentError) { :a.upcase :fold }
assert_raise(ArgumentError) { :a.capitalize :fold } assert_raise(ArgumentError) { :a.capitalize :fold }

View File

@ -593,7 +593,7 @@ class TestArgf < Test::Unit::TestCase
def test_read2 def test_read2
ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f| ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f|
{# {#
s = "" s = +""
ARGF.read(8, s) ARGF.read(8, s)
p s p s
}; };
@ -604,7 +604,7 @@ class TestArgf < Test::Unit::TestCase
def test_read2_with_not_empty_buffer def test_read2_with_not_empty_buffer
ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f| ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f|
{# {#
s = "0123456789" s = +"0123456789"
ARGF.read(8, s) ARGF.read(8, s)
p s p s
}; };
@ -617,7 +617,7 @@ class TestArgf < Test::Unit::TestCase
{# {#
nil while ARGF.gets nil while ARGF.gets
p ARGF.read p ARGF.read
p ARGF.read(0, "") p ARGF.read(0, +"")
}; };
assert_equal("nil\n\"\"\n", f.read) assert_equal("nil\n\"\"\n", f.read)
end end
@ -626,13 +626,13 @@ class TestArgf < Test::Unit::TestCase
def test_readpartial def test_readpartial
ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f| ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f|
{# {#
s = "" s = +""
begin begin
loop do loop do
s << ARGF.readpartial(1) s << ARGF.readpartial(1)
t = ""; ARGF.readpartial(1, t); s << t t = +""; ARGF.readpartial(1, t); s << t
# not empty buffer # not empty buffer
u = "abcdef"; ARGF.readpartial(1, u); s << u u = +"abcdef"; ARGF.readpartial(1, u); s << u
end end
rescue EOFError rescue EOFError
puts s puts s
@ -645,11 +645,11 @@ class TestArgf < Test::Unit::TestCase
def test_readpartial2 def test_readpartial2
ruby('-e', "#{<<~"{#"}\n#{<<~'};'}") do |f| ruby('-e', "#{<<~"{#"}\n#{<<~'};'}") do |f|
{# {#
s = "" s = +""
begin begin
loop do loop do
s << ARGF.readpartial(1) s << ARGF.readpartial(1)
t = ""; ARGF.readpartial(1, t); s << t t = +""; ARGF.readpartial(1, t); s << t
end end
rescue EOFError rescue EOFError
$stdout.binmode $stdout.binmode
@ -680,7 +680,7 @@ class TestArgf < Test::Unit::TestCase
def test_getc def test_getc
ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f| ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f|
{# {#
s = "" s = +""
while c = ARGF.getc while c = ARGF.getc
s << c s << c
end end
@ -706,7 +706,7 @@ class TestArgf < Test::Unit::TestCase
def test_readchar def test_readchar
ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f| ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f|
{# {#
s = "" s = +""
begin begin
while c = ARGF.readchar while c = ARGF.readchar
s << c s << c
@ -784,7 +784,7 @@ class TestArgf < Test::Unit::TestCase
def test_each_char def test_each_char
ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f| ruby('-e', "#{<<~"{#"}\n#{<<~'};'}", @t1.path, @t2.path, @t3.path) do |f|
{# {#
s = "" s = +""
ARGF.each_char {|c| s << c } ARGF.each_char {|c| s << c }
puts s puts s
}; };
@ -1073,7 +1073,7 @@ class TestArgf < Test::Unit::TestCase
ruby('-e', "#{<<~"{#"}\n#{<<~'};'}") do |f| ruby('-e', "#{<<~"{#"}\n#{<<~'};'}") do |f|
{# {#
$stdout.sync = true $stdout.sync = true
:wait_readable == ARGF.read_nonblock(1, "", exception: false) or :wait_readable == ARGF.read_nonblock(1, +"", exception: false) or
abort "did not return :wait_readable" abort "did not return :wait_readable"
begin begin
@ -1086,7 +1086,7 @@ class TestArgf < Test::Unit::TestCase
IO.select([ARGF]) == [[ARGF], [], []] or IO.select([ARGF]) == [[ARGF], [], []] or
abort 'did not awaken for readability (before byte)' abort 'did not awaken for readability (before byte)'
buf = '' buf = +''
buf.object_id == ARGF.read_nonblock(1, buf).object_id or buf.object_id == ARGF.read_nonblock(1, buf).object_id or
abort "read destination buffer failed" abort "read destination buffer failed"
print buf print buf

View File

@ -207,7 +207,7 @@ class TestBignum < Test::Unit::TestCase
assert_separately([], "#{<<~"begin;"}\n#{<<~'end;'}") assert_separately([], "#{<<~"begin;"}\n#{<<~'end;'}")
begin; begin;
digits = [["3", 700], ["0", 2700], ["1", 1], ["0", 26599]] digits = [["3", 700], ["0", 2700], ["1", 1], ["0", 26599]]
num = digits.inject("") {|s,(c,n)|s << c*n}.to_i num = digits.inject(+"") {|s,(c,n)|s << c*n}.to_i
assert_equal digits.sum {|c,n|n}, num.to_s.size assert_equal digits.sum {|c,n|n}, num.to_s.size
end; end;
end end

View File

@ -56,7 +56,7 @@ class TestDir_M17N < Test::Unit::TestCase
return if Bug::File::Fs.fsname(Dir.tmpdir) == "apfs" return if Bug::File::Fs.fsname(Dir.tmpdir) == "apfs"
with_tmpdir {|d| with_tmpdir {|d|
assert_separately(%w[-EASCII-8BIT], <<-'EOS', :chdir=>d) assert_separately(%w[-EASCII-8BIT], <<-'EOS', :chdir=>d)
filename = "\xff".force_encoding("ASCII-8BIT") # invalid byte sequence as UTF-8 filename = "\xff".dup.force_encoding("ASCII-8BIT") # invalid byte sequence as UTF-8
File.open(filename, "w") {} File.open(filename, "w") {}
opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM
ents = Dir.entries(".", **(opts||{})) ents = Dir.entries(".", **(opts||{}))
@ -64,7 +64,7 @@ class TestDir_M17N < Test::Unit::TestCase
assert_include(ents, filename) assert_include(ents, filename)
EOS EOS
assert_separately(%w[-EUTF-8], <<-'EOS', :chdir=>d) assert_separately(%w[-EUTF-8], <<-'EOS', :chdir=>d)
filename = "\xff".force_encoding("UTF-8") # invalid byte sequence as UTF-8 filename = "\xff".dup.force_encoding("UTF-8") # invalid byte sequence as UTF-8
File.open(filename, "w") {} File.open(filename, "w") {}
opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM
ents = Dir.entries(".", **(opts||{})) ents = Dir.entries(".", **(opts||{}))
@ -77,7 +77,7 @@ class TestDir_M17N < Test::Unit::TestCase
def test_filename_as_bytes_extutf8 def test_filename_as_bytes_extutf8
with_tmpdir {|d| with_tmpdir {|d|
assert_separately(%w[-EUTF-8], <<-'EOS', :chdir=>d) assert_separately(%w[-EUTF-8], <<-'EOS', :chdir=>d)
filename = "\xc2\xa1".force_encoding("utf-8") filename = "\xc2\xa1".dup.force_encoding("utf-8")
File.open(filename, "w") {} File.open(filename, "w") {}
opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM
ents = Dir.entries(".", **(opts||{})) ents = Dir.entries(".", **(opts||{}))
@ -85,9 +85,9 @@ class TestDir_M17N < Test::Unit::TestCase
EOS EOS
assert_separately(%w[-EUTF-8], <<-'EOS', :chdir=>d) assert_separately(%w[-EUTF-8], <<-'EOS', :chdir=>d)
if /mswin|mingw|darwin/ =~ RUBY_PLATFORM if /mswin|mingw|darwin/ =~ RUBY_PLATFORM
filename = "\x8f\xa2\xc2".force_encoding("euc-jp") filename = "\x8f\xa2\xc2".dup.force_encoding("euc-jp")
else else
filename = "\xc2\xa1".force_encoding("euc-jp") filename = "\xc2\xa1".dup.force_encoding("euc-jp")
end end
assert_nothing_raised(Errno::ENOENT) do assert_nothing_raised(Errno::ENOENT) do
open(filename) {} open(filename) {}
@ -96,8 +96,8 @@ class TestDir_M17N < Test::Unit::TestCase
# no meaning test on windows # no meaning test on windows
unless /mswin|mingw|darwin/ =~ RUBY_PLATFORM unless /mswin|mingw|darwin/ =~ RUBY_PLATFORM
assert_separately(%W[-EUTF-8], <<-'EOS', :chdir=>d) assert_separately(%W[-EUTF-8], <<-'EOS', :chdir=>d)
filename1 = "\xc2\xa1".force_encoding("utf-8") filename1 = "\xc2\xa1".dup.force_encoding("utf-8")
filename2 = "\xc2\xa1".force_encoding("euc-jp") filename2 = "\xc2\xa1".dup.force_encoding("euc-jp")
filename3 = filename1.encode("euc-jp") filename3 = filename1.encode("euc-jp")
filename4 = filename2.encode("utf-8") filename4 = filename2.encode("utf-8")
assert_file.stat(filename1) assert_file.stat(filename1)
@ -121,13 +121,13 @@ class TestDir_M17N < Test::Unit::TestCase
assert_include(ents, filename) assert_include(ents, filename)
EOS EOS
assert_separately(%w[-EUTF-8:EUC-JP], <<-'EOS', :chdir=>d) assert_separately(%w[-EUTF-8:EUC-JP], <<-'EOS', :chdir=>d)
filename = "\xA4\xA2".force_encoding("euc-jp") filename = "\xA4\xA2".dup.force_encoding("euc-jp")
opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM
ents = Dir.entries(".", **(opts||{})) ents = Dir.entries(".", **(opts||{}))
assert_include(ents, filename) assert_include(ents, filename)
EOS EOS
assert_separately(%w[-EUTF-8:EUC-JP], <<-'EOS', :chdir=>d) assert_separately(%w[-EUTF-8:EUC-JP], <<-'EOS', :chdir=>d)
filename = "\xA4\xA2".force_encoding("euc-jp") filename = "\xA4\xA2".dup.force_encoding("euc-jp")
assert_nothing_raised(Errno::ENOENT) do assert_nothing_raised(Errno::ENOENT) do
open(filename) {} open(filename) {}
end end
@ -149,7 +149,7 @@ class TestDir_M17N < Test::Unit::TestCase
EOS EOS
assert_separately(%w[-EUTF-8:EUC-JP], <<-'EOS', :chdir=>d) assert_separately(%w[-EUTF-8:EUC-JP], <<-'EOS', :chdir=>d)
filename1 = "\u2661" # WHITE HEART SUIT which is not representable in EUC-JP filename1 = "\u2661" # WHITE HEART SUIT which is not representable in EUC-JP
filename2 = "\xA4\xA2".force_encoding("euc-jp") # HIRAGANA LETTER A in EUC-JP filename2 = "\xA4\xA2".dup.force_encoding("euc-jp") # HIRAGANA LETTER A in EUC-JP
opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM
ents = Dir.entries(".", **(opts||{})) ents = Dir.entries(".", **(opts||{}))
assert_include(ents, filename1) assert_include(ents, filename1)
@ -158,7 +158,7 @@ class TestDir_M17N < Test::Unit::TestCase
assert_separately(%w[-EUTF-8:EUC-JP], <<-'EOS', :chdir=>d) assert_separately(%w[-EUTF-8:EUC-JP], <<-'EOS', :chdir=>d)
filename1 = "\u2661" # WHITE HEART SUIT which is not representable in EUC-JP filename1 = "\u2661" # WHITE HEART SUIT which is not representable in EUC-JP
filename2 = "\u3042" # HIRAGANA LETTER A which is representable in EUC-JP filename2 = "\u3042" # HIRAGANA LETTER A which is representable in EUC-JP
filename3 = "\xA4\xA2".force_encoding("euc-jp") # HIRAGANA LETTER A in EUC-JP filename3 = "\xA4\xA2".dup.force_encoding("euc-jp") # HIRAGANA LETTER A in EUC-JP
assert_file.stat(filename1) assert_file.stat(filename1)
assert_file.stat(filename2) assert_file.stat(filename2)
assert_file.stat(filename3) assert_file.stat(filename3)
@ -172,7 +172,7 @@ class TestDir_M17N < Test::Unit::TestCase
return if /cygwin/ =~ RUBY_PLATFORM return if /cygwin/ =~ RUBY_PLATFORM
with_tmpdir {|d| with_tmpdir {|d|
assert_separately(%w[-EEUC-JP], <<-'EOS', :chdir=>d) assert_separately(%w[-EEUC-JP], <<-'EOS', :chdir=>d)
filename = "\xA4\xA2".force_encoding("euc-jp") filename = "\xA4\xA2".dup.force_encoding("euc-jp")
File.open(filename, "w") {} File.open(filename, "w") {}
opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM
ents = Dir.entries(".", **(opts||{})) ents = Dir.entries(".", **(opts||{}))
@ -189,7 +189,7 @@ class TestDir_M17N < Test::Unit::TestCase
return if /cygwin/ =~ RUBY_PLATFORM return if /cygwin/ =~ RUBY_PLATFORM
with_tmpdir {|d| with_tmpdir {|d|
assert_separately(%w[-EEUC-JP], <<-'EOS', :chdir=>d) assert_separately(%w[-EEUC-JP], <<-'EOS', :chdir=>d)
filename = "\xA4\xA2".force_encoding("euc-jp") filename = "\xA4\xA2".dup.force_encoding("euc-jp")
File.open(filename, "w") {} File.open(filename, "w") {}
ents = Dir.entries(".") ents = Dir.entries(".")
if /darwin/ =~ RUBY_PLATFORM if /darwin/ =~ RUBY_PLATFORM
@ -200,7 +200,7 @@ class TestDir_M17N < Test::Unit::TestCase
assert_include(ents, filename) assert_include(ents, filename)
EOS EOS
assert_separately(%w[-EASCII-8BIT], <<-'EOS', :chdir=>d) assert_separately(%w[-EASCII-8BIT], <<-'EOS', :chdir=>d)
filename = "\xA4\xA2".force_encoding('ASCII-8BIT') filename = "\xA4\xA2".dup.force_encoding('ASCII-8BIT')
ents = Dir.entries(".") ents = Dir.entries(".")
unless ents.include?(filename) unless ents.include?(filename)
case RUBY_PLATFORM case RUBY_PLATFORM
@ -231,7 +231,7 @@ class TestDir_M17N < Test::Unit::TestCase
return if /cygwin/ =~ RUBY_PLATFORM return if /cygwin/ =~ RUBY_PLATFORM
with_tmpdir {|d| with_tmpdir {|d|
assert_separately(%w[-EEUC-JP], <<-'EOS', :chdir=>d) assert_separately(%w[-EEUC-JP], <<-'EOS', :chdir=>d)
filename = "\xA4\xA2".force_encoding("euc-jp") filename = "\xA4\xA2".dup.force_encoding("euc-jp")
File.open(filename, "w") {} File.open(filename, "w") {}
opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM
ents = Dir.entries(".", **(opts||{})) ents = Dir.entries(".", **(opts||{}))
@ -241,7 +241,7 @@ class TestDir_M17N < Test::Unit::TestCase
assert_include(ents, filename) assert_include(ents, filename)
EOS EOS
assert_separately(%w[-EEUC-JP:UTF-8], <<-'EOS', :chdir=>d) assert_separately(%w[-EEUC-JP:UTF-8], <<-'EOS', :chdir=>d)
filename = "\u3042" filename = "\u3042".dup
opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM opts = {:encoding => Encoding.default_external} if /mswin|mingw/ =~ RUBY_PLATFORM
ents = Dir.entries(".", **(opts||{})) ents = Dir.entries(".", **(opts||{}))
if /darwin/ =~ RUBY_PLATFORM if /darwin/ =~ RUBY_PLATFORM
@ -350,7 +350,7 @@ class TestDir_M17N < Test::Unit::TestCase
end end
def test_glob_escape_multibyte def test_glob_escape_multibyte
name = "\x81\\".force_encoding(Encoding::Shift_JIS) name = "\x81\\".dup.force_encoding(Encoding::Shift_JIS)
with_tmpdir do with_tmpdir do
open(name, "w") {} rescue next open(name, "w") {} rescue next
match, = Dir.glob("#{name}*") match, = Dir.glob("#{name}*")
@ -363,8 +363,8 @@ class TestDir_M17N < Test::Unit::TestCase
with_tmpdir do with_tmpdir do
list = %W"file_one.ext file_two.ext \u{6587 4ef6}1.txt \u{6587 4ef6}2.txt" list = %W"file_one.ext file_two.ext \u{6587 4ef6}1.txt \u{6587 4ef6}2.txt"
list.each {|f| open(f, "w") {}} list.each {|f| open(f, "w") {}}
a = "file_one*".force_encoding Encoding::IBM437 a = "file_one*".dup.force_encoding Encoding::IBM437
b = "file_two*".force_encoding Encoding::EUC_JP b = "file_two*".dup.force_encoding Encoding::EUC_JP
assert_equal([a, b].map(&:encoding), Dir[a, b].map(&:encoding)) assert_equal([a, b].map(&:encoding), Dir[a, b].map(&:encoding))
if Bug::File::Fs.fsname(Dir.pwd) == "apfs" if Bug::File::Fs.fsname(Dir.pwd) == "apfs"
# High Sierra's APFS cannot use filenames with undefined character # High Sierra's APFS cannot use filenames with undefined character
@ -375,7 +375,7 @@ class TestDir_M17N < Test::Unit::TestCase
Dir.mkdir(dir) Dir.mkdir(dir)
list << dir list << dir
bug12081 = '[ruby-core:73868] [Bug #12081]' bug12081 = '[ruby-core:73868] [Bug #12081]'
a = "*".force_encoding("us-ascii") a = "*".dup.force_encoding("us-ascii")
result = Dir[a].map {|n| result = Dir[a].map {|n|
if n.encoding == Encoding::ASCII_8BIT || if n.encoding == Encoding::ASCII_8BIT ||
n.encoding == Encoding::ISO_8859_1 || n.encoding == Encoding::ISO_8859_1 ||

View File

@ -612,8 +612,8 @@ class TestEnv < Test::Unit::TestCase
<<-"end;" <<-"end;"
envvars_to_check = [ envvars_to_check = [
"foo\0bar", "foo\0bar",
"#{'\xa1\xa1'}".force_encoding(Encoding::UTF_16LE), "#{'\xa1\xa1'}".dup.force_encoding(Encoding::UTF_16LE),
"foo".force_encoding(Encoding::ISO_2022_JP), "foo".dup.force_encoding(Encoding::ISO_2022_JP),
] ]
envvars_to_check.each do |#{var_name}| envvars_to_check.each do |#{var_name}|
#{str_for_yielding_exception_class(code_str)} #{str_for_yielding_exception_class(code_str)}

View File

@ -372,7 +372,7 @@ class TestGCCompact < Test::Unit::TestCase
Fiber.new { Fiber.new {
str = "a" * GC::INTERNAL_CONSTANTS[:BASE_SLOT_SIZE] * 4 str = "a" * GC::INTERNAL_CONSTANTS[:BASE_SLOT_SIZE] * 4
$ary = STR_COUNT.times.map { "" << str } $ary = STR_COUNT.times.map { +"" << str }
}.resume }.resume
stats = GC.verify_compaction_references(expand_heap: true, toward: :empty) stats = GC.verify_compaction_references(expand_heap: true, toward: :empty)

View File

@ -1963,14 +1963,14 @@ class TestHashOnly < Test::Unit::TestCase
end end
def test_AREF_fstring_key_default_proc def test_AREF_fstring_key_default_proc
assert_separately([], "#{<<~"begin;"}\n#{<<~'end;'}") assert_separately(['--disable-frozen-string-literal'], "#{<<~"begin;"}\n#{<<~'end;'}")
begin; begin;
h = Hash.new do |h, k| h = Hash.new do |h, k|
k.frozen? k.frozen?
end end
str = "foo" str = "foo"
refute str.frozen? # assumes this file is frozen_string_literal: false refute str.frozen?
refute h[str] refute h[str]
refute h["foo"] refute h["foo"]
end; end;

View File

@ -168,7 +168,7 @@ class TestISeq < Test::Unit::TestCase
end end
def test_disasm_encoding def test_disasm_encoding
src = "\u{3042} = 1; \u{3042}; \u{3043}" src = +"\u{3042} = 1; \u{3042}; \u{3043}"
asm = compile(src).disasm asm = compile(src).disasm
assert_equal(src.encoding, asm.encoding) assert_equal(src.encoding, asm.encoding)
assert_predicate(asm, :valid_encoding?) assert_predicate(asm, :valid_encoding?)

View File

@ -142,6 +142,8 @@ class TestRubyLiteral < Test::Unit::TestCase
end end
def test_frozen_string def test_frozen_string
default = eval("'test'").frozen?
all_assertions do |a| all_assertions do |a|
a.for("false with indicator") do a.for("false with indicator") do
str = eval("# -*- frozen-string-literal: false -*-\n""'foo'") str = eval("# -*- frozen-string-literal: false -*-\n""'foo'")
@ -161,19 +163,19 @@ class TestRubyLiteral < Test::Unit::TestCase
end end
a.for("false with preceding garbage") do a.for("false with preceding garbage") do
str = eval("# x frozen-string-literal: false\n""'foo'") str = eval("# x frozen-string-literal: false\n""'foo'")
assert_not_predicate(str, :frozen?) assert_equal(default, str.frozen?)
end end
a.for("true with preceding garbage") do a.for("true with preceding garbage") do
str = eval("# x frozen-string-literal: true\n""'foo'") str = eval("# x frozen-string-literal: true\n""'foo'")
assert_not_predicate(str, :frozen?) assert_equal(default, str.frozen?)
end end
a.for("false with succeeding garbage") do a.for("false with succeeding garbage") do
str = eval("# frozen-string-literal: false x\n""'foo'") str = eval("# frozen-string-literal: false x\n""'foo'")
assert_not_predicate(str, :frozen?) assert_equal(default, str.frozen?)
end end
a.for("true with succeeding garbage") do a.for("true with succeeding garbage") do
str = eval("# frozen-string-literal: true x\n""'foo'") str = eval("# frozen-string-literal: true x\n""'foo'")
assert_not_predicate(str, :frozen?) assert_equal(default, str.frozen?)
end end
end end
end end

View File

@ -1044,7 +1044,7 @@ class TestRefinement < Test::Unit::TestCase
end end
using Test using Test
def t def t
'Refinements are broken!'.chop! 'Refinements are broken!'.dup.chop!
end end
t t
module Test module Test

View File

@ -1196,13 +1196,16 @@ class TestRubyOptions < Test::Unit::TestCase
end end
def test_frozen_string_literal_debug def test_frozen_string_literal_debug
default_frozen = eval("'test'").frozen?
with_debug_pat = /created at/ with_debug_pat = /created at/
wo_debug_pat = /can\'t modify frozen String: "\w+" \(FrozenError\)\n\z/ wo_debug_pat = /can\'t modify frozen String: "\w+" \(FrozenError\)\n\z/
frozen = [ frozen = [
["--enable-frozen-string-literal", true], ["--enable-frozen-string-literal", true],
["--disable-frozen-string-literal", false], ["--disable-frozen-string-literal", false],
[nil, false],
] ]
frozen << [nil, false] unless default_frozen
debugs = [ debugs = [
["--debug-frozen-string-literal", true], ["--debug-frozen-string-literal", true],
["--debug=frozen-string-literal", true], ["--debug=frozen-string-literal", true],

View File

@ -2265,7 +2265,7 @@ class TestTranscode < Test::Unit::TestCase
result = th.map(&:value) result = th.map(&:value)
end end
end end
expected = "\xa4\xa2".force_encoding(Encoding::EUC_JP) expected = "\xa4\xa2".dup.force_encoding(Encoding::EUC_JP)
assert_equal([expected]*num, result, bug11277) assert_equal([expected]*num, result, bug11277)
end; end;
end end

View File

@ -320,10 +320,10 @@ class TestYJIT < Test::Unit::TestCase
end end
def test_compile_opt_aset def test_compile_opt_aset
assert_compiles('[1,2,3][2] = 4', insns: %i[opt_aset]) assert_compiles('[1,2,3][2] = 4', insns: %i[opt_aset], frozen_string_literal: false)
assert_compiles('{}[:foo] = :bar', insns: %i[opt_aset]) assert_compiles('{}[:foo] = :bar', insns: %i[opt_aset], frozen_string_literal: false)
assert_compiles('[1,2,3][0..-1] = []', insns: %i[opt_aset]) assert_compiles('[1,2,3][0..-1] = []', insns: %i[opt_aset], frozen_string_literal: false)
assert_compiles('"foo"[3] = "d"', insns: %i[opt_aset]) assert_compiles('"foo"[3] = "d"', insns: %i[opt_aset], frozen_string_literal: false)
end end
def test_compile_attr_set def test_compile_attr_set
@ -1471,8 +1471,8 @@ class TestYJIT < Test::Unit::TestCase
end end
h = Hash.new { nil } h = Hash.new { nil }
foo("\x80".b, "\xA1A1".force_encoding("EUC-JP"), h) foo("\x80".b, "\xA1A1".dup.force_encoding("EUC-JP"), h)
foo("\x80".b, "\xA1A1".force_encoding("EUC-JP"), h) foo("\x80".b, "\xA1A1".dup.force_encoding("EUC-JP"), h)
RUBY RUBY
end end
@ -1489,7 +1489,7 @@ class TestYJIT < Test::Unit::TestCase
end end
def test_opt_aref_with def test_opt_aref_with
assert_compiles(<<~RUBY, insns: %i[opt_aref_with], result: "bar") assert_compiles(<<~RUBY, insns: %i[opt_aref_with], result: "bar", frozen_string_literal: false)
h = {"foo" => "bar"} h = {"foo" => "bar"}
h["foo"] h["foo"]
@ -1671,7 +1671,7 @@ class TestYJIT < Test::Unit::TestCase
RUBY RUBY
script = <<~RUBY script = <<~RUBY
#{"# frozen_string_literal: true" if frozen_string_literal} #{"# frozen_string_literal: " + frozen_string_literal.to_s unless frozen_string_literal.nil?}
_test_proc = -> { _test_proc = -> {
#{test_script} #{test_script}
} }

View File

@ -11,7 +11,7 @@ class TestStringIOInRactor < Test::Unit::TestCase
require "stringio" require "stringio"
$VERBOSE = nil $VERBOSE = nil
r = Ractor.new do r = Ractor.new do
io = StringIO.new("") io = StringIO.new(+"")
io.puts "abc" io.puts "abc"
io.truncate(0) io.truncate(0)
io.puts "def" io.puts "def"

View File

@ -1,3 +1,5 @@
# frozen_string_literal: false
require "test/unit" require "test/unit"
require "ripper" require "ripper"
require "envutil" require "envutil"
@ -12,24 +14,24 @@ class TestTRICK2013 < Test::Unit::TestCase
def test_kinaba def test_kinaba
src = File.join(__dir__, "../sample/trick2013/kinaba/entry.rb") src = File.join(__dir__, "../sample/trick2013/kinaba/entry.rb")
expected = [*" ".."~"].join("") # all ASCII printables expected = [*" ".."~"].join("") # all ASCII printables
assert_in_out_err(["-W0", src], "", [expected]) assert_in_out_err(["-W0", "--disable-frozen-string-literal", src], "", [expected])
assert_equal(expected, File.read(src).chomp.chars.sort.join) assert_equal(expected, File.read(src).chomp.chars.sort.join)
end end
def test_mame def test_mame
src = File.join(__dir__, "../sample/trick2013/mame/entry.rb") src = File.join(__dir__, "../sample/trick2013/mame/entry.rb")
ignore_dsp = "def open(_file, _mode); s = ''; def s.flush; self;end; yield s; end;" ignore_dsp = "def open(_file, _mode); s = ''; def s.flush; self;end; yield s; end;"
assert_in_out_err(["-W0"], ignore_dsp + File.read(src), File.read(src).lines(chomp: true), timeout: 60) assert_in_out_err(["-W0", "--disable-frozen-string-literal"], ignore_dsp + File.read(src), File.read(src).lines(chomp: true), timeout: 60)
end end
def test_shinh def test_shinh
src = File.join(__dir__, "../sample/trick2013/shinh/entry.rb") src = File.join(__dir__, "../sample/trick2013/shinh/entry.rb")
assert_in_out_err(["-W0", src], "", []) assert_in_out_err(["-W0", "--disable-frozen-string-literal", src], "", [])
end end
def test_yhara def test_yhara
src = File.join(__dir__, "../sample/trick2013/yhara/entry.rb") src = File.join(__dir__, "../sample/trick2013/yhara/entry.rb")
assert_in_out_err(["-W0", src], "", ["JUST ANOTHER RUBY HACKER"]) assert_in_out_err(["-W0", "--disable-frozen-string-literal", src], "", ["JUST ANOTHER RUBY HACKER"])
end end
end end
@ -45,7 +47,7 @@ class TestTRICK2015 < Test::Unit::TestCase
end end
pi = "3#{ a - b }" pi = "3#{ a - b }"
assert_in_out_err(["-W0", src], "", [pi], timeout: 60) assert_in_out_err(["-W0", "--disable-frozen-string-literal", src], "", [pi], timeout: 60)
assert_equal(pi[0, 242], Ripper.tokenize(File.read(src)).grep(/\S/).map{|t|t.size%10}.join) assert_equal(pi[0, 242], Ripper.tokenize(File.read(src)).grep(/\S/).map{|t|t.size%10}.join)
end end
@ -60,7 +62,7 @@ class TestTRICK2015 < Test::Unit::TestCase
s << n.to_s s << n.to_s
end end
assert_in_out_err(["-W0", src, "27"], "", s) assert_in_out_err(["-W0", "--disable-frozen-string-literal", src, "27"], "", s)
end end
def test_monae def test_monae
@ -78,13 +80,13 @@ class TestTRICK2015 < Test::Unit::TestCase
end end
expected = /\A#{ expected.map {|s| "#{ Regexp.quote(s) }\s*\n" }.join }\z/ expected = /\A#{ expected.map {|s| "#{ Regexp.quote(s) }\s*\n" }.join }\z/
assert_in_out_err(["-W0", src], "", expected) assert_in_out_err(["-W0", "--disable-frozen-string-literal", src], "", expected)
end end
def test_eregon def test_eregon
src = File.join(__dir__, "../sample/trick2015/eregon/entry.rb") src = File.join(__dir__, "../sample/trick2015/eregon/entry.rb")
assert_in_out_err(["-W0", src], "", <<END.lines(chomp: true)) assert_in_out_err(["-W0", "--disable-frozen-string-literal", src], "", <<END.lines(chomp: true))
1 9 4 2 3 8 7 6 5 1 9 4 2 3 8 7 6 5
3 7 2 6 5 1 4 8 9 3 7 2 6 5 1 4 8 9
8 5 6 7 4 9 2 3 1 8 5 6 7 4 9 2 3 1
@ -123,7 +125,7 @@ p cnf 3 5
1 3 0 1 3 0
END END
assert_in_out_err(["-W0", src], inp, ["s SATISFIABLE", "v 1 2 -3"]) assert_in_out_err(["-W0", "--disable-frozen-string-literal", src], inp, ["s SATISFIABLE", "v 1 2 -3"])
end end
end end
@ -131,17 +133,17 @@ class TestTRICK2018 < Test::Unit::TestCase
def test_01_kinaba def test_01_kinaba
src = File.join(__dir__, "../sample/trick2018/01-kinaba/entry.rb") src = File.join(__dir__, "../sample/trick2018/01-kinaba/entry.rb")
assert_in_out_err(["-W0", src], "", []) assert_in_out_err(["-W0", "--disable-frozen-string-literal", src], "", [])
end end
def test_02_mame def test_02_mame
src = File.join(__dir__, "../sample/trick2018/02-mame/entry.rb") src = File.join(__dir__, "../sample/trick2018/02-mame/entry.rb")
ignore_sleep = "def sleep(_); end;" ignore_sleep = "def sleep(_); end;"
assert_in_out_err(["-W0"], ignore_sleep + File.read(src)) do |stdout, _stderr, _status| assert_in_out_err(["-W0", "--disable-frozen-string-literal"], ignore_sleep + File.read(src)) do |stdout, _stderr, _status|
code = stdout.join("\n") + "\n" code = stdout.join("\n") + "\n"
expected = code.lines(chomp: true) expected = code.lines(chomp: true)
assert_in_out_err(["-W0"], ignore_sleep + code, expected) assert_in_out_err(["-W0", "--disable-frozen-string-literal"], ignore_sleep + code, expected)
end end
end end
@ -149,7 +151,7 @@ class TestTRICK2018 < Test::Unit::TestCase
src = File.join(__dir__, "../sample/trick2018/03-tompng/entry.rb") src = File.join(__dir__, "../sample/trick2018/03-tompng/entry.rb")
# only syntax check because it requires chunky_png # only syntax check because it requires chunky_png
assert_in_out_err(["-W0", "-c", src], "", ["Syntax OK"]) assert_in_out_err(["-W0", "--disable-frozen-string-literal", "-c", src], "", ["Syntax OK"])
end end
def test_04_colin def test_04_colin
@ -172,7 +174,7 @@ class TestTRICK2018 < Test::Unit::TestCase
end end
end end
END END
assert_in_out_err(["-W0"], code, <<END.lines(chomp: true), encoding: "UTF-8") assert_in_out_err(["-W0", "--disable-frozen-string-literal"], code, <<END.lines(chomp: true), encoding: "UTF-8")
Math Math
Addition Addition
One plus one equals two. One plus one equals two.
@ -187,7 +189,7 @@ END
src = File.join(__dir__, "../sample/trick2018/05-tompng/entry.rb") src = File.join(__dir__, "../sample/trick2018/05-tompng/entry.rb")
# only syntax check because it generates 3D model data # only syntax check because it generates 3D model data
assert_in_out_err(["-W0", "-c", src], "", ["Syntax OK"]) assert_in_out_err(["-W0", "--disable-frozen-string-literal", "-c", src], "", ["Syntax OK"])
end end
end end
@ -196,21 +198,21 @@ class TestTRICK2022 < Test::Unit::TestCase
src = File.join(__dir__, "../sample/trick2022/01-tompng/entry.rb") src = File.join(__dir__, "../sample/trick2022/01-tompng/entry.rb")
# only syntax check because it requires matrix # only syntax check because it requires matrix
assert_in_out_err(["-W0", "-c", src], "", ["Syntax OK"]) assert_in_out_err(["-W0", "--disable-frozen-string-literal", "-c", src], "", ["Syntax OK"])
end end
def test_02_tompng def test_02_tompng
src = File.join(__dir__, "../sample/trick2022/02-tompng/entry.rb") src = File.join(__dir__, "../sample/trick2022/02-tompng/entry.rb")
# only syntax check because it works as a web server # only syntax check because it works as a web server
assert_in_out_err(["-W0", "-c", src], "", ["Syntax OK"]) assert_in_out_err(["-W0", "--disable-frozen-string-literal", "-c", src], "", ["Syntax OK"])
end end
def test_03_mame def test_03_mame
src = File.join(__dir__, "../sample/trick2022/03-mame/entry.rb") src = File.join(__dir__, "../sample/trick2022/03-mame/entry.rb")
# TODO # TODO
assert_in_out_err(["-W0", "-c", src], "", ["Syntax OK"]) assert_in_out_err(["-W0", "--disable-frozen-string-literal", "-c", src], "", ["Syntax OK"])
end end
end end

View File

@ -100,11 +100,11 @@ def parse_args(argv = ARGV)
unless $install_procs.empty? unless $install_procs.empty?
w = (w = ENV["COLUMNS"] and (w = w.to_i) > 80) ? w - 30 : 50 w = (w = ENV["COLUMNS"] and (w = w.to_i) > 80) ? w - 30 : 50
opt.on("\n""Types for --install and --exclude:") opt.on("\n""Types for --install and --exclude:")
mesg = " " mesg = +" "
$install_procs.each_key do |t| $install_procs.each_key do |t|
if mesg.size + t.size > w if mesg.size + t.size > w
opt.on(mesg) opt.on(mesg)
mesg = " " mesg = +" "
end end
mesg << " " << t.to_s mesg << " " << t.to_s
end end

4
tool/test/webrick/webrick.cgi Normal file → Executable file
View File

@ -15,11 +15,11 @@ class TestApp < WEBrick::CGI
}.join(", ") }.join(", ")
}.join(", ") }.join(", ")
elsif %r{/$} =~ req.request_uri.to_s elsif %r{/$} =~ req.request_uri.to_s
res.body = "" res.body = +""
res.body << req.request_uri.to_s << "\n" res.body << req.request_uri.to_s << "\n"
res.body << req.script_name res.body << req.script_name
elsif !req.cookies.empty? elsif !req.cookies.empty?
res.body = req.cookies.inject(""){|result, cookie| res.body = req.cookies.inject(+""){|result, cookie|
result << "%s=%s\n" % [cookie.name, cookie.value] result << "%s=%s\n" % [cookie.name, cookie.value]
} }
res.cookies << WEBrick::Cookie.new("Customer", "WILE_E_COYOTE") res.cookies << WEBrick::Cookie.new("Customer", "WILE_E_COYOTE")