PageRenderTime 60ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/test/ruby/test_string.rb

http://github.com/ruby/ruby
Ruby | 3202 lines | 3039 code | 153 blank | 10 comment | 9 complexity | 2a32f36d4f03160c3b65c115265ad162 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-3.0
  1. # frozen_string_literal: false
  2. require 'test/unit'
  3. class TestString < Test::Unit::TestCase
  4. ENUMERATOR_WANTARRAY = RUBY_VERSION >= "3.0.0"
  5. WIDE_ENCODINGS = [
  6. Encoding::UTF_16BE, Encoding::UTF_16LE,
  7. Encoding::UTF_32BE, Encoding::UTF_32LE,
  8. ]
  9. def initialize(*args)
  10. @cls = String
  11. @aref_re_nth = true
  12. @aref_re_silent = false
  13. @aref_slicebang_silent = true
  14. super
  15. end
  16. def S(*args, **kw)
  17. @cls.new(*args, **kw)
  18. end
  19. def test_s_new
  20. assert_equal("", S())
  21. assert_equal(Encoding::ASCII_8BIT, S().encoding)
  22. assert_equal("", S(""))
  23. assert_equal(__ENCODING__, S("").encoding)
  24. src = "RUBY"
  25. assert_equal(src, S(src))
  26. assert_equal(__ENCODING__, S(src).encoding)
  27. src.force_encoding("euc-jp")
  28. assert_equal(src, S(src))
  29. assert_equal(Encoding::EUC_JP, S(src).encoding)
  30. assert_equal("", S(encoding: "euc-jp"))
  31. assert_equal(Encoding::EUC_JP, S(encoding: "euc-jp").encoding)
  32. assert_equal("", S("", encoding: "euc-jp"))
  33. assert_equal(Encoding::EUC_JP, S("", encoding: "euc-jp").encoding)
  34. src = "RUBY"
  35. assert_equal(src, S(src, encoding: "euc-jp"))
  36. assert_equal(Encoding::EUC_JP, S(src, encoding: "euc-jp").encoding)
  37. src.force_encoding("euc-jp")
  38. assert_equal(src, S(src, encoding: "utf-8"))
  39. assert_equal(Encoding::UTF_8, S(src, encoding: "utf-8").encoding)
  40. assert_equal("", S(capacity: 1000))
  41. assert_equal(Encoding::ASCII_8BIT, S(capacity: 1000).encoding)
  42. assert_equal("", S(capacity: 1000, encoding: "euc-jp"))
  43. assert_equal(Encoding::EUC_JP, S(capacity: 1000, encoding: "euc-jp").encoding)
  44. assert_equal("", S("", capacity: 1000))
  45. assert_equal(__ENCODING__, S("", capacity: 1000).encoding)
  46. assert_equal("", S("", capacity: 1000, encoding: "euc-jp"))
  47. assert_equal(Encoding::EUC_JP, S("", capacity: 1000, encoding: "euc-jp").encoding)
  48. end
  49. def test_initialize
  50. str = S("").freeze
  51. assert_equal("", str.__send__(:initialize))
  52. assert_raise(FrozenError){ str.__send__(:initialize, 'abc') }
  53. assert_raise(FrozenError){ str.__send__(:initialize, capacity: 1000) }
  54. assert_raise(FrozenError){ str.__send__(:initialize, 'abc', capacity: 1000) }
  55. assert_raise(FrozenError){ str.__send__(:initialize, encoding: 'euc-jp') }
  56. assert_raise(FrozenError){ str.__send__(:initialize, 'abc', encoding: 'euc-jp') }
  57. assert_raise(FrozenError){ str.__send__(:initialize, 'abc', capacity: 1000, encoding: 'euc-jp') }
  58. str = S("")
  59. assert_equal("mystring", str.__send__(:initialize, "mystring"))
  60. str = S("mystring")
  61. assert_equal("mystring", str.__send__(:initialize, str))
  62. str = S("")
  63. assert_equal("mystring", str.__send__(:initialize, "mystring", capacity: 1000))
  64. str = S("mystring")
  65. assert_equal("mystring", str.__send__(:initialize, str, capacity: 1000))
  66. end
  67. def test_initialize_shared
  68. String.new(str = "mystring" * 10).__send__(:initialize, capacity: str.bytesize)
  69. assert_equal("mystring", str[0, 8])
  70. end
  71. def test_initialize_nonstring
  72. assert_raise(TypeError) {
  73. S(1)
  74. }
  75. assert_raise(TypeError) {
  76. S(1, capacity: 1000)
  77. }
  78. end
  79. def test_initialize_memory_leak
  80. assert_no_memory_leak([], <<-PREP, <<-CODE, rss: true)
  81. code = proc {('x'*100000).__send__(:initialize, '')}
  82. 1_000.times(&code)
  83. PREP
  84. 100_000.times(&code)
  85. CODE
  86. end
  87. def test_AREF # '[]'
  88. assert_equal("A", S("AooBar")[0])
  89. assert_equal("B", S("FooBaB")[-1])
  90. assert_equal(nil, S("FooBar")[6])
  91. assert_equal(nil, S("FooBar")[-7])
  92. assert_equal(S("Foo"), S("FooBar")[0,3])
  93. assert_equal(S("Bar"), S("FooBar")[-3,3])
  94. assert_equal(S(""), S("FooBar")[6,2])
  95. assert_equal(nil, S("FooBar")[-7,10])
  96. assert_equal(S("Foo"), S("FooBar")[0..2])
  97. assert_equal(S("Foo"), S("FooBar")[0...3])
  98. assert_equal(S("Bar"), S("FooBar")[-3..-1])
  99. assert_equal(S(""), S("FooBar")[6..2])
  100. assert_equal(nil, S("FooBar")[-10..-7])
  101. assert_equal(S("Foo"), S("FooBar")[/^F../])
  102. assert_equal(S("Bar"), S("FooBar")[/..r$/])
  103. assert_equal(nil, S("FooBar")[/xyzzy/])
  104. assert_equal(nil, S("FooBar")[/plugh/])
  105. assert_equal(S("Foo"), S("FooBar")[S("Foo")])
  106. assert_equal(S("Bar"), S("FooBar")[S("Bar")])
  107. assert_equal(nil, S("FooBar")[S("xyzzy")])
  108. assert_equal(nil, S("FooBar")[S("plugh")])
  109. if @aref_re_nth
  110. assert_equal(S("Foo"), S("FooBar")[/([A-Z]..)([A-Z]..)/, 1])
  111. assert_equal(S("Bar"), S("FooBar")[/([A-Z]..)([A-Z]..)/, 2])
  112. assert_equal(nil, S("FooBar")[/([A-Z]..)([A-Z]..)/, 3])
  113. assert_equal(S("Bar"), S("FooBar")[/([A-Z]..)([A-Z]..)/, -1])
  114. assert_equal(S("Foo"), S("FooBar")[/([A-Z]..)([A-Z]..)/, -2])
  115. assert_equal(nil, S("FooBar")[/([A-Z]..)([A-Z]..)/, -3])
  116. end
  117. o = Object.new
  118. def o.to_int; 2; end
  119. assert_equal("o", "foo"[o])
  120. assert_raise(ArgumentError) { "foo"[] }
  121. end
  122. def test_ASET # '[]='
  123. s = S("FooBar")
  124. s[0] = S('A')
  125. assert_equal(S("AooBar"), s)
  126. s[-1]= S('B')
  127. assert_equal(S("AooBaB"), s)
  128. assert_raise(IndexError) { s[-7] = S("xyz") }
  129. assert_equal(S("AooBaB"), s)
  130. s[0] = S("ABC")
  131. assert_equal(S("ABCooBaB"), s)
  132. s = S("FooBar")
  133. s[0,3] = S("A")
  134. assert_equal(S("ABar"),s)
  135. s[0] = S("Foo")
  136. assert_equal(S("FooBar"), s)
  137. s[-3,3] = S("Foo")
  138. assert_equal(S("FooFoo"), s)
  139. assert_raise(IndexError) { s[7,3] = S("Bar") }
  140. assert_raise(IndexError) { s[-7,3] = S("Bar") }
  141. s = S("FooBar")
  142. s[0..2] = S("A")
  143. assert_equal(S("ABar"), s)
  144. s[1..3] = S("Foo")
  145. assert_equal(S("AFoo"), s)
  146. s[-4..-4] = S("Foo")
  147. assert_equal(S("FooFoo"), s)
  148. assert_raise(RangeError) { s[7..10] = S("Bar") }
  149. assert_raise(RangeError) { s[-7..-10] = S("Bar") }
  150. s = S("FooBar")
  151. s[/^F../]= S("Bar")
  152. assert_equal(S("BarBar"), s)
  153. s[/..r$/] = S("Foo")
  154. assert_equal(S("BarFoo"), s)
  155. if @aref_re_silent
  156. s[/xyzzy/] = S("None")
  157. assert_equal(S("BarFoo"), s)
  158. else
  159. assert_raise(IndexError) { s[/xyzzy/] = S("None") }
  160. end
  161. if @aref_re_nth
  162. s[/([A-Z]..)([A-Z]..)/, 1] = S("Foo")
  163. assert_equal(S("FooFoo"), s)
  164. s[/([A-Z]..)([A-Z]..)/, 2] = S("Bar")
  165. assert_equal(S("FooBar"), s)
  166. assert_raise(IndexError) { s[/([A-Z]..)([A-Z]..)/, 3] = "None" }
  167. s[/([A-Z]..)([A-Z]..)/, -1] = S("Foo")
  168. assert_equal(S("FooFoo"), s)
  169. s[/([A-Z]..)([A-Z]..)/, -2] = S("Bar")
  170. assert_equal(S("BarFoo"), s)
  171. assert_raise(IndexError) { s[/([A-Z]..)([A-Z]..)/, -3] = "None" }
  172. end
  173. s = S("FooBar")
  174. s[S("Foo")] = S("Bar")
  175. assert_equal(S("BarBar"), s)
  176. s = S("a string")
  177. s[0..s.size] = S("another string")
  178. assert_equal(S("another string"), s)
  179. o = Object.new
  180. def o.to_int; 2; end
  181. s = "foo"
  182. s[o] = "bar"
  183. assert_equal("fobar", s)
  184. assert_raise(ArgumentError) { "foo"[1, 2, 3] = "" }
  185. assert_raise(IndexError) {"foo"[RbConfig::LIMITS["LONG_MIN"]] = "l"}
  186. end
  187. def test_CMP # '<=>'
  188. assert_equal(1, S("abcdef") <=> S("abcde"))
  189. assert_equal(0, S("abcdef") <=> S("abcdef"))
  190. assert_equal(-1, S("abcde") <=> S("abcdef"))
  191. assert_equal(-1, S("ABCDEF") <=> S("abcdef"))
  192. assert_nil("foo" <=> Object.new)
  193. o = Object.new
  194. def o.to_str; "bar"; end
  195. assert_equal(1, "foo" <=> o)
  196. class << o;remove_method :to_str;end
  197. def o.<=>(x); nil; end
  198. assert_nil("foo" <=> o)
  199. class << o;remove_method :<=>;end
  200. def o.<=>(x); 1; end
  201. assert_equal(-1, "foo" <=> o)
  202. class << o;remove_method :<=>;end
  203. def o.<=>(x); 2**100; end
  204. assert_equal(-1, "foo" <=> o)
  205. end
  206. def test_EQUAL # '=='
  207. assert_not_equal(:foo, S("foo"))
  208. assert_equal(S("abcdef"), S("abcdef"))
  209. assert_not_equal(S("CAT"), S('cat'))
  210. assert_not_equal(S("CaT"), S('cAt'))
  211. o = Object.new
  212. def o.to_str; end
  213. def o.==(x); false; end
  214. assert_equal(false, "foo" == o)
  215. class << o;remove_method :==;end
  216. def o.==(x); true; end
  217. assert_equal(true, "foo" == o)
  218. end
  219. def test_LSHIFT # '<<'
  220. assert_equal(S("world!"), S("world") << 33)
  221. assert_equal(S("world!"), S("world") << S("!"))
  222. s = "a"
  223. 10.times {|i|
  224. s << s
  225. assert_equal("a" * (2 << i), s)
  226. }
  227. s = ["foo"].pack("p")
  228. l = s.size
  229. s << "bar"
  230. assert_equal(l + 3, s.size)
  231. bug = '[ruby-core:27583]'
  232. assert_raise(RangeError, bug) {S("a".force_encoding(Encoding::UTF_8)) << -3}
  233. assert_raise(RangeError, bug) {S("a".force_encoding(Encoding::UTF_8)) << -2}
  234. assert_raise(RangeError, bug) {S("a".force_encoding(Encoding::UTF_8)) << -1}
  235. assert_raise(RangeError, bug) {S("a".force_encoding(Encoding::UTF_8)) << 0x81308130}
  236. assert_nothing_raised {S("a".force_encoding(Encoding::GB18030)) << 0x81308130}
  237. end
  238. def test_MATCH # '=~'
  239. assert_equal(10, S("FeeFieFoo-Fum") =~ /Fum$/)
  240. assert_equal(nil, S("FeeFieFoo-Fum") =~ /FUM$/)
  241. o = Object.new
  242. def o.=~(x); x + "bar"; end
  243. assert_equal("foobar", S("foo") =~ o)
  244. assert_raise(TypeError) { S("foo") =~ "foo" }
  245. end
  246. def test_MOD # '%'
  247. assert_equal(S("00123"), S("%05d") % 123)
  248. assert_equal(S("123 |00000001"), S("%-5s|%08x") % [123, 1])
  249. x = S("%3s %-4s%%foo %.0s%5d %#x%c%3.1f %b %x %X %#b %#x %#X") %
  250. [S("hi"),
  251. 123,
  252. S("never seen"),
  253. 456,
  254. 0,
  255. ?A,
  256. 3.0999,
  257. 11,
  258. 171,
  259. 171,
  260. 11,
  261. 171,
  262. 171]
  263. assert_equal(S(' hi 123 %foo 456 0A3.1 1011 ab AB 0b1011 0xab 0XAB'), x)
  264. end
  265. def test_MUL # '*'
  266. assert_equal(S("XXX"), S("X") * 3)
  267. assert_equal(S("HOHO"), S("HO") * 2)
  268. end
  269. def test_PLUS # '+'
  270. assert_equal(S("Yodel"), S("Yo") + S("del"))
  271. end
  272. def casetest(a, b, rev=false)
  273. msg = proc {"#{a} should#{' not' if rev} match #{b}"}
  274. case a
  275. when b
  276. assert(!rev, msg)
  277. else
  278. assert(rev, msg)
  279. end
  280. end
  281. def test_VERY_EQUAL # '==='
  282. # assert_equal(true, S("foo") === :foo)
  283. casetest(S("abcdef"), S("abcdef"))
  284. casetest(S("CAT"), S('cat'), true) # Reverse the test - we don't want to
  285. casetest(S("CaT"), S('cAt'), true) # find these in the case.
  286. end
  287. def test_capitalize
  288. assert_equal(S("Hello"), S("hello").capitalize)
  289. assert_equal(S("Hello"), S("hELLO").capitalize)
  290. assert_equal(S("123abc"), S("123ABC").capitalize)
  291. end
  292. def test_capitalize!
  293. a = S("hello"); a.capitalize!
  294. assert_equal(S("Hello"), a)
  295. a = S("hELLO"); a.capitalize!
  296. assert_equal(S("Hello"), a)
  297. a = S("123ABC"); a.capitalize!
  298. assert_equal(S("123abc"), a)
  299. assert_equal(nil, S("123abc").capitalize!)
  300. assert_equal(S("123abc"), S("123ABC").capitalize!)
  301. assert_equal(S("Abc"), S("ABC").capitalize!)
  302. assert_equal(S("Abc"), S("abc").capitalize!)
  303. assert_equal(nil, S("Abc").capitalize!)
  304. a = S("hello")
  305. b = a.dup
  306. assert_equal(S("Hello"), a.capitalize!)
  307. assert_equal(S("hello"), b)
  308. end
  309. Bug2463 = '[ruby-dev:39856]'
  310. def test_center
  311. assert_equal(S("hello"), S("hello").center(4))
  312. assert_equal(S(" hello "), S("hello").center(11))
  313. assert_equal(S("ababaababa"), S("").center(10, "ab"), Bug2463)
  314. assert_equal(S("ababaababab"), S("").center(11, "ab"), Bug2463)
  315. end
  316. def test_chomp
  317. verbose, $VERBOSE = $VERBOSE, nil
  318. assert_equal(S("hello"), S("hello").chomp("\n"))
  319. assert_equal(S("hello"), S("hello\n").chomp("\n"))
  320. save = $/
  321. $/ = "\n"
  322. assert_equal(S("hello"), S("hello").chomp)
  323. assert_equal(S("hello"), S("hello\n").chomp)
  324. $/ = "!"
  325. assert_equal(S("hello"), S("hello").chomp)
  326. assert_equal(S("hello"), S("hello!").chomp)
  327. $/ = save
  328. assert_equal(S("a").hash, S("a\u0101").chomp(S("\u0101")).hash, '[ruby-core:22414]')
  329. s = S("hello")
  330. assert_equal("hel", s.chomp('lo'))
  331. assert_equal("hello", s)
  332. s = S("hello")
  333. assert_equal("hello", s.chomp('he'))
  334. assert_equal("hello", s)
  335. s = S("\u{3053 3093 306b 3061 306f}")
  336. assert_equal("\u{3053 3093 306b}", s.chomp("\u{3061 306f}"))
  337. assert_equal("\u{3053 3093 306b 3061 306f}", s)
  338. s = S("\u{3053 3093 306b 3061 306f}")
  339. assert_equal("\u{3053 3093 306b 3061 306f}", s.chomp('lo'))
  340. assert_equal("\u{3053 3093 306b 3061 306f}", s)
  341. s = S("hello")
  342. assert_equal("hello", s.chomp("\u{3061 306f}"))
  343. assert_equal("hello", s)
  344. # skip if argument is a broken string
  345. s = S("\xe3\x81\x82")
  346. assert_equal("\xe3\x81\x82", s.chomp("\x82"))
  347. assert_equal("\xe3\x81\x82", s)
  348. s = S("\x95\x5c").force_encoding("Shift_JIS")
  349. assert_equal("\x95\x5c".force_encoding("Shift_JIS"), s.chomp("\x5c"))
  350. assert_equal("\x95\x5c".force_encoding("Shift_JIS"), s)
  351. # clear coderange
  352. s = S("hello\u{3053 3093}")
  353. assert_not_predicate(s, :ascii_only?)
  354. assert_predicate(s.chomp("\u{3053 3093}"), :ascii_only?)
  355. # argument should be converted to String
  356. klass = Class.new { def to_str; 'a'; end }
  357. s = S("abba")
  358. assert_equal("abb", s.chomp(klass.new))
  359. assert_equal("abba", s)
  360. # chomp removes any of "\n", "\r\n", "\r" when "\n" is specified
  361. s = "foo\n"
  362. assert_equal("foo", s.chomp("\n"))
  363. s = "foo\r\n"
  364. assert_equal("foo", s.chomp("\n"))
  365. s = "foo\r"
  366. assert_equal("foo", s.chomp("\n"))
  367. ensure
  368. $/ = save
  369. $VERBOSE = verbose
  370. end
  371. def test_chomp!
  372. verbose, $VERBOSE = $VERBOSE, nil
  373. a = S("hello")
  374. a.chomp!(S("\n"))
  375. assert_equal(S("hello"), a)
  376. assert_equal(nil, a.chomp!(S("\n")))
  377. a = S("hello\n")
  378. a.chomp!(S("\n"))
  379. assert_equal(S("hello"), a)
  380. save = $/
  381. $/ = "\n"
  382. a = S("hello")
  383. a.chomp!
  384. assert_equal(S("hello"), a)
  385. a = S("hello\n")
  386. a.chomp!
  387. assert_equal(S("hello"), a)
  388. $/ = "!"
  389. a = S("hello")
  390. a.chomp!
  391. assert_equal(S("hello"), a)
  392. a="hello!"
  393. a.chomp!
  394. assert_equal(S("hello"), a)
  395. $/ = save
  396. a = S("hello\n")
  397. b = a.dup
  398. assert_equal(S("hello"), a.chomp!)
  399. assert_equal(S("hello\n"), b)
  400. s = "foo\r\n"
  401. s.chomp!
  402. assert_equal("foo", s)
  403. s = "foo\r"
  404. s.chomp!
  405. assert_equal("foo", s)
  406. s = "foo\r\n"
  407. s.chomp!("")
  408. assert_equal("foo", s)
  409. s = "foo\r"
  410. s.chomp!("")
  411. assert_equal("foo\r", s)
  412. assert_equal(S("a").hash, S("a\u0101").chomp!(S("\u0101")).hash, '[ruby-core:22414]')
  413. s = S("").freeze
  414. assert_raise_with_message(FrozenError, /frozen/) {s.chomp!}
  415. $VERBOSE = nil # EnvUtil.suppress_warning resets $VERBOSE to the original state
  416. s = S("ax")
  417. o = Struct.new(:s).new(s)
  418. def o.to_str
  419. s.freeze
  420. "x"
  421. end
  422. assert_raise_with_message(FrozenError, /frozen/) {s.chomp!(o)}
  423. $VERBOSE = nil # EnvUtil.suppress_warning resets $VERBOSE to the original state
  424. s = S("hello")
  425. assert_equal("hel", s.chomp!('lo'))
  426. assert_equal("hel", s)
  427. s = S("hello")
  428. assert_equal(nil, s.chomp!('he'))
  429. assert_equal("hello", s)
  430. s = S("\u{3053 3093 306b 3061 306f}")
  431. assert_equal("\u{3053 3093 306b}", s.chomp!("\u{3061 306f}"))
  432. assert_equal("\u{3053 3093 306b}", s)
  433. s = S("\u{3053 3093 306b 3061 306f}")
  434. assert_equal(nil, s.chomp!('lo'))
  435. assert_equal("\u{3053 3093 306b 3061 306f}", s)
  436. s = S("hello")
  437. assert_equal(nil, s.chomp!("\u{3061 306f}"))
  438. assert_equal("hello", s)
  439. # skip if argument is a broken string
  440. s = S("\xe3\x81\x82")
  441. assert_equal(nil, s.chomp!("\x82"))
  442. assert_equal("\xe3\x81\x82", s)
  443. s = S("\x95\x5c").force_encoding("Shift_JIS")
  444. assert_equal(nil, s.chomp!("\x5c"))
  445. assert_equal("\x95\x5c".force_encoding("Shift_JIS"), s)
  446. # clear coderange
  447. s = S("hello\u{3053 3093}")
  448. assert_not_predicate(s, :ascii_only?)
  449. assert_predicate(s.chomp!("\u{3053 3093}"), :ascii_only?)
  450. # argument should be converted to String
  451. klass = Class.new { def to_str; 'a'; end }
  452. s = S("abba")
  453. assert_equal("abb", s.chomp!(klass.new))
  454. assert_equal("abb", s)
  455. # chomp removes any of "\n", "\r\n", "\r" when "\n" is specified
  456. s = "foo\n"
  457. assert_equal("foo", s.chomp!("\n"))
  458. s = "foo\r\n"
  459. assert_equal("foo", s.chomp!("\n"))
  460. s = "foo\r"
  461. assert_equal("foo", s.chomp!("\n"))
  462. ensure
  463. $/ = save
  464. $VERBOSE = verbose
  465. end
  466. def test_chop
  467. assert_equal(S("hell"), S("hello").chop)
  468. assert_equal(S("hello"), S("hello\r\n").chop)
  469. assert_equal(S("hello\n"), S("hello\n\r").chop)
  470. assert_equal(S(""), S("\r\n").chop)
  471. assert_equal(S(""), S("").chop)
  472. assert_equal(S("a").hash, S("a\u00d8").chop.hash)
  473. end
  474. def test_chop!
  475. a = S("hello").chop!
  476. assert_equal(S("hell"), a)
  477. a = S("hello\r\n").chop!
  478. assert_equal(S("hello"), a)
  479. a = S("hello\n\r").chop!
  480. assert_equal(S("hello\n"), a)
  481. a = S("\r\n").chop!
  482. assert_equal(S(""), a)
  483. a = S("").chop!
  484. assert_nil(a)
  485. a = S("a\u00d8")
  486. a.chop!
  487. assert_equal(S("a").hash, a.hash)
  488. a = S("hello\n")
  489. b = a.dup
  490. assert_equal(S("hello"), a.chop!)
  491. assert_equal(S("hello\n"), b)
  492. end
  493. def test_clone
  494. for frozen in [ false, true ]
  495. a = S("Cool")
  496. a.freeze if frozen
  497. b = a.clone
  498. assert_equal(a, b)
  499. assert_not_same(a, b)
  500. assert_equal(a.frozen?, b.frozen?)
  501. end
  502. assert_equal("", File.read(IO::NULL).clone, '[ruby-dev:32819] reported by Kazuhiro NISHIYAMA')
  503. end
  504. def test_concat
  505. assert_equal(S("world!"), S("world").concat(33))
  506. assert_equal(S("world!"), S("world").concat(S('!')))
  507. b = S("sn")
  508. assert_equal(S("snsnsn"), b.concat(b, b))
  509. bug7090 = '[ruby-core:47751]'
  510. result = S("").force_encoding(Encoding::UTF_16LE)
  511. result << 0x0300
  512. expected = S("\u0300".encode(Encoding::UTF_16LE))
  513. assert_equal(expected, result, bug7090)
  514. assert_raise(TypeError) { 'foo' << :foo }
  515. assert_raise(FrozenError) { 'foo'.freeze.concat('bar') }
  516. end
  517. def test_concat_literals
  518. s="." * 50
  519. assert_equal(Encoding::UTF_8, "#{s}x".encoding)
  520. end
  521. def test_count
  522. a = S("hello world")
  523. assert_equal(5, a.count(S("lo")))
  524. assert_equal(2, a.count(S("lo"), S("o")))
  525. assert_equal(4, a.count(S("hello"), S("^l")))
  526. assert_equal(4, a.count(S("ej-m")))
  527. assert_equal(0, S("y").count(S("a\\-z")))
  528. assert_equal(5, "abc\u{3042 3044 3046}".count("^a"))
  529. assert_equal(1, "abc\u{3042 3044 3046}".count("\u3042"))
  530. assert_equal(5, "abc\u{3042 3044 3046}".count("^\u3042"))
  531. assert_equal(2, "abc\u{3042 3044 3046}".count("a-z", "^a"))
  532. assert_equal(0, "abc\u{3042 3044 3046}".count("a", "\u3042"))
  533. assert_equal(0, "abc\u{3042 3044 3046}".count("\u3042", "a"))
  534. assert_equal(0, "abc\u{3042 3044 3046}".count("\u3042", "\u3044"))
  535. assert_equal(4, "abc\u{3042 3044 3046}".count("^a", "^\u3044"))
  536. assert_equal(4, "abc\u{3042 3044 3046}".count("^\u3044", "^a"))
  537. assert_equal(4, "abc\u{3042 3044 3046}".count("^\u3042", "^\u3044"))
  538. assert_raise(ArgumentError) { "foo".count }
  539. end
  540. def crypt_supports_des_crypt?
  541. /openbsd/ !~ RUBY_PLATFORM
  542. end
  543. def test_crypt
  544. if crypt_supports_des_crypt?
  545. pass = "aaGUC/JkO9/Sc"
  546. good_salt = "aa"
  547. bad_salt = "ab"
  548. else
  549. pass = "$2a$04$0WVaz0pV3jzfZ5G5tpmHWuBQGbkjzgtSc3gJbmdy0GAGMa45MFM2."
  550. good_salt = "$2a$04$0WVaz0pV3jzfZ5G5tpmHWu"
  551. bad_salt = "$2a$04$0WVaz0pV3jzfZ5G5tpmHXu"
  552. end
  553. assert_equal(S(pass), S("mypassword").crypt(S(good_salt)))
  554. assert_not_equal(S(pass), S("mypassword").crypt(S(bad_salt)))
  555. assert_raise(ArgumentError) {S("mypassword").crypt(S(""))}
  556. assert_raise(ArgumentError) {S("mypassword").crypt(S("\0a"))}
  557. assert_raise(ArgumentError) {S("mypassword").crypt(S("a\0"))}
  558. assert_raise(ArgumentError) {S("poison\u0000null").crypt(S("aa"))}
  559. WIDE_ENCODINGS.each do |enc|
  560. assert_raise(ArgumentError) {S("mypassword").crypt(S("aa".encode(enc)))}
  561. assert_raise(ArgumentError) {S("mypassword".encode(enc)).crypt(S("aa"))}
  562. end
  563. @cls == String and
  564. assert_no_memory_leak([], "s = ''; salt_proc = proc{#{(crypt_supports_des_crypt? ? '..' : good_salt).inspect}}", "#{<<~"begin;"}\n#{<<~'end;'}")
  565. begin;
  566. 1000.times { s.crypt(-salt_proc.call).clear }
  567. end;
  568. end
  569. def test_delete
  570. assert_equal(S("heo"), S("hello").delete(S("l"), S("lo")))
  571. assert_equal(S("he"), S("hello").delete(S("lo")))
  572. assert_equal(S("hell"), S("hello").delete(S("aeiou"), S("^e")))
  573. assert_equal(S("ho"), S("hello").delete(S("ej-m")))
  574. assert_equal("a".hash, "a\u0101".delete("\u0101").hash, '[ruby-talk:329267]')
  575. assert_equal(true, "a\u0101".delete("\u0101").ascii_only?)
  576. assert_equal(true, "a\u3041".delete("\u3041").ascii_only?)
  577. assert_equal(false, "a\u3041\u3042".delete("\u3041").ascii_only?)
  578. assert_equal("a", "abc\u{3042 3044 3046}".delete("^a"))
  579. assert_equal("bc\u{3042 3044 3046}", "abc\u{3042 3044 3046}".delete("a"))
  580. assert_equal("\u3042", "abc\u{3042 3044 3046}".delete("^\u3042"))
  581. bug6160 = '[ruby-dev:45374]'
  582. assert_equal("", '\\'.delete('\\'), bug6160)
  583. end
  584. def test_delete!
  585. a = S("hello")
  586. a.delete!(S("l"), S("lo"))
  587. assert_equal(S("heo"), a)
  588. a = S("hello")
  589. a.delete!(S("lo"))
  590. assert_equal(S("he"), a)
  591. a = S("hello")
  592. a.delete!(S("aeiou"), S("^e"))
  593. assert_equal(S("hell"), a)
  594. a = S("hello")
  595. a.delete!(S("ej-m"))
  596. assert_equal(S("ho"), a)
  597. a = S("hello")
  598. assert_nil(a.delete!(S("z")))
  599. a = S("hello")
  600. b = a.dup
  601. a.delete!(S("lo"))
  602. assert_equal(S("he"), a)
  603. assert_equal(S("hello"), b)
  604. a = S("hello")
  605. a.delete!(S("^el"))
  606. assert_equal(S("ell"), a)
  607. assert_raise(ArgumentError) { S("foo").delete! }
  608. end
  609. def test_downcase
  610. assert_equal(S("hello"), S("helLO").downcase)
  611. assert_equal(S("hello"), S("hello").downcase)
  612. assert_equal(S("hello"), S("HELLO").downcase)
  613. assert_equal(S("abc hello 123"), S("abc HELLO 123").downcase)
  614. end
  615. def test_downcase!
  616. a = S("helLO")
  617. b = a.dup
  618. assert_equal(S("hello"), a.downcase!)
  619. assert_equal(S("hello"), a)
  620. assert_equal(S("helLO"), b)
  621. a=S("hello")
  622. assert_nil(a.downcase!)
  623. assert_equal(S("hello"), a)
  624. end
  625. def test_dump
  626. a= S("Test") << 1 << 2 << 3 << 9 << 13 << 10
  627. assert_equal(S('"Test\\x01\\x02\\x03\\t\\r\\n"'), a.dump)
  628. b= S("\u{7F}")
  629. assert_equal(S('"\\x7F"'), b.dump)
  630. b= S("\u{AB}")
  631. assert_equal(S('"\\u00AB"'), b.dump)
  632. b= S("\u{ABC}")
  633. assert_equal(S('"\\u0ABC"'), b.dump)
  634. b= S("\uABCD")
  635. assert_equal(S('"\\uABCD"'), b.dump)
  636. b= S("\u{ABCDE}")
  637. assert_equal(S('"\\u{ABCDE}"'), b.dump)
  638. b= S("\u{10ABCD}")
  639. assert_equal(S('"\\u{10ABCD}"'), b.dump)
  640. end
  641. def test_undump
  642. a = S("Test") << 1 << 2 << 3 << 9 << 13 << 10
  643. assert_equal(a, S('"Test\\x01\\x02\\x03\\t\\r\\n"').undump)
  644. assert_equal(S("\\ca"), S('"\\ca"').undump)
  645. assert_equal(S("\u{7F}"), S('"\\x7F"').undump)
  646. assert_equal(S("\u{7F}A"), S('"\\x7FA"').undump)
  647. assert_equal(S("\u{AB}"), S('"\\u00AB"').undump)
  648. assert_equal(S("\u{ABC}"), S('"\\u0ABC"').undump)
  649. assert_equal(S("\uABCD"), S('"\\uABCD"').undump)
  650. assert_equal(S("\uABCD"), S('"\\uABCD"').undump)
  651. assert_equal(S("\u{ABCDE}"), S('"\\u{ABCDE}"').undump)
  652. assert_equal(S("\u{10ABCD}"), S('"\\u{10ABCD}"').undump)
  653. assert_equal(S("\u{ABCDE 10ABCD}"), S('"\\u{ABCDE 10ABCD}"').undump)
  654. assert_equal(S(""), S('"\\u{}"').undump)
  655. assert_equal(S(""), S('"\\u{ }"').undump)
  656. assert_equal(S("\u3042".encode("sjis")), S('"\x82\xA0"'.force_encoding("sjis")).undump)
  657. assert_equal(S("\u8868".encode("sjis")), S("\"\\x95\\\\\"".force_encoding("sjis")).undump)
  658. assert_equal(S("äöü"), S('"\u00E4\u00F6\u00FC"').undump)
  659. assert_equal(S("äöü"), S('"\xC3\xA4\xC3\xB6\xC3\xBC"').undump)
  660. assert_equal(Encoding::UTF_8, S('"\\u3042"').encode(Encoding::EUC_JP).undump.encoding)
  661. assert_equal("abc".encode(Encoding::UTF_16LE),
  662. '"a\x00b\x00c\x00".force_encoding("UTF-16LE")'.undump)
  663. assert_equal('\#', '"\\\\#"'.undump)
  664. assert_equal('\#{', '"\\\\\#{"'.undump)
  665. assert_raise(RuntimeError) { S('\u3042').undump }
  666. assert_raise(RuntimeError) { S('"\x82\xA0\u3042"'.force_encoding("SJIS")).undump }
  667. assert_raise(RuntimeError) { S('"\u3042\x82\xA0"'.force_encoding("SJIS")).undump }
  668. assert_raise(RuntimeError) { S('"".force_encoding()').undump }
  669. assert_raise(RuntimeError) { S('"".force_encoding("').undump }
  670. assert_raise(RuntimeError) { S('"".force_encoding("UNKNOWN")').undump }
  671. assert_raise(RuntimeError) { S('"\u3042".force_encoding("UTF-16LE")').undump }
  672. assert_raise(RuntimeError) { S('"\x00\x00".force_encoding("UTF-16LE")"').undump }
  673. assert_raise(RuntimeError) { S('"\x00\x00".force_encoding("'+("a"*9999999)+'")"').undump }
  674. assert_raise(RuntimeError) { S(%("\u00E4")).undump }
  675. assert_raise(RuntimeError) { S('"').undump }
  676. assert_raise(RuntimeError) { S('"""').undump }
  677. assert_raise(RuntimeError) { S('""""').undump }
  678. assert_raise(RuntimeError) { S('"a').undump }
  679. assert_raise(RuntimeError) { S('"\u"').undump }
  680. assert_raise(RuntimeError) { S('"\u{"').undump }
  681. assert_raise(RuntimeError) { S('"\u304"').undump }
  682. assert_raise(RuntimeError) { S('"\u304Z"').undump }
  683. assert_raise(RuntimeError) { S('"\udfff"').undump }
  684. assert_raise(RuntimeError) { S('"\u{dfff}"').undump }
  685. assert_raise(RuntimeError) { S('"\u{3042"').undump }
  686. assert_raise(RuntimeError) { S('"\u{3042 "').undump }
  687. assert_raise(RuntimeError) { S('"\u{110000}"').undump }
  688. assert_raise(RuntimeError) { S('"\u{1234567}"').undump }
  689. assert_raise(RuntimeError) { S('"\x"').undump }
  690. assert_raise(RuntimeError) { S('"\xA"').undump }
  691. assert_raise(RuntimeError) { S('"\\"').undump }
  692. assert_raise(RuntimeError) { S(%("\0")).undump }
  693. assert_raise_with_message(RuntimeError, /invalid/) {
  694. '"\\u{007F}".xxxxxx'.undump
  695. }
  696. end
  697. def test_dup
  698. for frozen in [ false, true ]
  699. a = S("hello")
  700. a.freeze if frozen
  701. b = a.dup
  702. assert_equal(a, b)
  703. assert_not_same(a, b)
  704. assert_not_predicate(b, :frozen?)
  705. end
  706. end
  707. def test_each
  708. verbose, $VERBOSE = $VERBOSE, nil
  709. save = $/
  710. $/ = "\n"
  711. res=[]
  712. S("hello\nworld").lines.each {|x| res << x}
  713. assert_equal(S("hello\n"), res[0])
  714. assert_equal(S("world"), res[1])
  715. res=[]
  716. S("hello\n\n\nworld").lines(S('')).each {|x| res << x}
  717. assert_equal(S("hello\n\n"), res[0])
  718. assert_equal(S("world"), res[1])
  719. $/ = "!"
  720. res=[]
  721. S("hello!world").lines.each {|x| res << x}
  722. assert_equal(S("hello!"), res[0])
  723. assert_equal(S("world"), res[1])
  724. ensure
  725. $/ = save
  726. $VERBOSE = verbose
  727. end
  728. def test_each_byte
  729. s = S("ABC")
  730. res = []
  731. assert_equal s.object_id, s.each_byte {|x| res << x }.object_id
  732. assert_equal(65, res[0])
  733. assert_equal(66, res[1])
  734. assert_equal(67, res[2])
  735. assert_equal 65, s.each_byte.next
  736. end
  737. def test_bytes
  738. s = S("ABC")
  739. assert_equal [65, 66, 67], s.bytes
  740. if ENUMERATOR_WANTARRAY
  741. assert_warn(/block not used/) {
  742. assert_equal [65, 66, 67], s.bytes {}
  743. }
  744. else
  745. res = []
  746. assert_equal s.object_id, s.bytes {|x| res << x }.object_id
  747. assert_equal(65, res[0])
  748. assert_equal(66, res[1])
  749. assert_equal(67, res[2])
  750. s = S("ABC")
  751. res = []
  752. assert_same s, s.bytes {|x| res << x }
  753. assert_equal [65, 66, 67], res
  754. end
  755. end
  756. def test_each_codepoint
  757. # Single byte optimization
  758. assert_equal 65, S("ABC").each_codepoint.next
  759. s = S("\u3042\u3044\u3046")
  760. res = []
  761. assert_equal s.object_id, s.each_codepoint {|x| res << x }.object_id
  762. assert_equal(0x3042, res[0])
  763. assert_equal(0x3044, res[1])
  764. assert_equal(0x3046, res[2])
  765. assert_equal 0x3042, s.each_codepoint.next
  766. end
  767. def test_codepoints
  768. # Single byte optimization
  769. assert_equal [65, 66, 67], S("ABC").codepoints
  770. s = S("\u3042\u3044\u3046")
  771. assert_equal [0x3042, 0x3044, 0x3046], s.codepoints
  772. if ENUMERATOR_WANTARRAY
  773. assert_warn(/block not used/) {
  774. assert_equal [0x3042, 0x3044, 0x3046], s.codepoints {}
  775. }
  776. else
  777. res = []
  778. assert_equal s.object_id, s.codepoints {|x| res << x }.object_id
  779. assert_equal(0x3042, res[0])
  780. assert_equal(0x3044, res[1])
  781. assert_equal(0x3046, res[2])
  782. s = S("ABC")
  783. res = []
  784. assert_same s, s.codepoints {|x| res << x }
  785. assert_equal [65, 66, 67], res
  786. end
  787. end
  788. def test_each_char
  789. s = S("ABC")
  790. res = []
  791. assert_equal s.object_id, s.each_char {|x| res << x }.object_id
  792. assert_equal("A", res[0])
  793. assert_equal("B", res[1])
  794. assert_equal("C", res[2])
  795. assert_equal "A", S("ABC").each_char.next
  796. end
  797. def test_chars
  798. s = S("ABC")
  799. assert_equal ["A", "B", "C"], s.chars
  800. if ENUMERATOR_WANTARRAY
  801. assert_warn(/block not used/) {
  802. assert_equal ["A", "B", "C"], s.chars {}
  803. }
  804. else
  805. res = []
  806. assert_equal s.object_id, s.chars {|x| res << x }.object_id
  807. assert_equal("A", res[0])
  808. assert_equal("B", res[1])
  809. assert_equal("C", res[2])
  810. end
  811. end
  812. def test_each_grapheme_cluster
  813. [
  814. "\u{0D 0A}",
  815. "\u{20 200d}",
  816. "\u{600 600}",
  817. "\u{600 20}",
  818. "\u{261d 1F3FB}",
  819. "\u{1f600}",
  820. "\u{20 308}",
  821. "\u{1F477 1F3FF 200D 2640 FE0F}",
  822. "\u{1F468 200D 1F393}",
  823. "\u{1F46F 200D 2642 FE0F}",
  824. "\u{1f469 200d 2764 fe0f 200d 1f469}",
  825. ].each do |g|
  826. assert_equal [g], g.each_grapheme_cluster.to_a
  827. assert_equal 1, g.each_grapheme_cluster.size
  828. end
  829. [
  830. ["\u{a 324}", ["\u000A", "\u0324"]],
  831. ["\u{d 324}", ["\u000D", "\u0324"]],
  832. ["abc", ["a", "b", "c"]],
  833. ].each do |str, grapheme_clusters|
  834. assert_equal grapheme_clusters, str.each_grapheme_cluster.to_a
  835. assert_equal grapheme_clusters.size, str.each_grapheme_cluster.size
  836. end
  837. s = ("x"+"\u{10ABCD}"*250000)
  838. assert_empty(s.each_grapheme_cluster {s.clear})
  839. end
  840. def test_grapheme_clusters
  841. [
  842. "\u{20 200d}",
  843. "\u{600 600}",
  844. "\u{600 20}",
  845. "\u{261d 1F3FB}",
  846. "\u{1f600}",
  847. "\u{20 308}",
  848. "\u{1F477 1F3FF 200D 2640 FE0F}",
  849. "\u{1F468 200D 1F393}",
  850. "\u{1F46F 200D 2642 FE0F}",
  851. "\u{1f469 200d 2764 fe0f 200d 1f469}",
  852. ].product([Encoding::UTF_8, *WIDE_ENCODINGS]) do |g, enc|
  853. g = g.encode(enc)
  854. assert_equal [g], g.grapheme_clusters
  855. end
  856. [
  857. "\u{a 324}",
  858. "\u{d 324}",
  859. "abc",
  860. ].product([Encoding::UTF_8, *WIDE_ENCODINGS]) do |g, enc|
  861. g = g.encode(enc)
  862. assert_equal g.chars, g.grapheme_clusters
  863. end
  864. assert_equal ["a", "b", "c"], "abc".b.grapheme_clusters
  865. if ENUMERATOR_WANTARRAY
  866. assert_warn(/block not used/) {
  867. assert_equal ["A", "B", "C"], "ABC".grapheme_clusters {}
  868. }
  869. else
  870. s = "ABC".b
  871. res = []
  872. assert_same s, s.grapheme_clusters {|x| res << x }
  873. assert_equal(3, res.size)
  874. assert_equal("A", res[0])
  875. assert_equal("B", res[1])
  876. assert_equal("C", res[2])
  877. end
  878. end
  879. def test_each_line
  880. verbose, $VERBOSE = $VERBOSE, nil
  881. save = $/
  882. $/ = "\n"
  883. res=[]
  884. S("hello\nworld").each_line {|x| res << x}
  885. assert_equal(S("hello\n"), res[0])
  886. assert_equal(S("world"), res[1])
  887. res=[]
  888. S("hello\n\n\nworld").each_line(S('')) {|x| res << x}
  889. assert_equal(S("hello\n\n"), res[0])
  890. assert_equal(S("world"), res[1])
  891. res=[]
  892. S("hello\r\n\r\nworld").each_line(S('')) {|x| res << x}
  893. assert_equal(S("hello\r\n\r\n"), res[0])
  894. assert_equal(S("world"), res[1])
  895. $/ = "!"
  896. res=[]
  897. S("hello!world").each_line {|x| res << x}
  898. assert_equal(S("hello!"), res[0])
  899. assert_equal(S("world"), res[1])
  900. $/ = "ab"
  901. res=[]
  902. S("a").lines.each {|x| res << x}
  903. assert_equal(1, res.size)
  904. assert_equal(S("a"), res[0])
  905. $/ = save
  906. s = nil
  907. "foo\nbar".each_line(nil) {|s2| s = s2 }
  908. assert_equal("foo\nbar", s)
  909. assert_equal "hello\n", S("hello\nworld").each_line.next
  910. assert_equal "hello\nworld", S("hello\nworld").each_line(nil).next
  911. bug7646 = "[ruby-dev:46827]"
  912. assert_nothing_raised(bug7646) do
  913. "\n\u0100".each_line("\n") {}
  914. end
  915. ensure
  916. $/ = save
  917. $VERBOSE = verbose
  918. end
  919. def test_each_line_chomp
  920. res = []
  921. S("hello\nworld").each_line("\n", chomp: true) {|x| res << x}
  922. assert_equal(S("hello"), res[0])
  923. assert_equal(S("world"), res[1])
  924. res = []
  925. S("hello\n\n\nworld").each_line(S(''), chomp: true) {|x| res << x}
  926. assert_equal(S("hello\n"), res[0])
  927. assert_equal(S("world"), res[1])
  928. res = []
  929. S("hello\r\n\r\nworld").each_line(S(''), chomp: true) {|x| res << x}
  930. assert_equal(S("hello\r\n"), res[0])
  931. assert_equal(S("world"), res[1])
  932. res = []
  933. S("hello!world").each_line(S('!'), chomp: true) {|x| res << x}
  934. assert_equal(S("hello"), res[0])
  935. assert_equal(S("world"), res[1])
  936. res = []
  937. S("a").each_line(S('ab'), chomp: true).each {|x| res << x}
  938. assert_equal(1, res.size)
  939. assert_equal(S("a"), res[0])
  940. s = nil
  941. "foo\nbar".each_line(nil, chomp: true) {|s2| s = s2 }
  942. assert_equal("foo\nbar", s)
  943. assert_equal "hello", S("hello\nworld").each_line(chomp: true).next
  944. assert_equal "hello\nworld", S("hello\nworld").each_line(nil, chomp: true).next
  945. res = []
  946. S("").each_line(chomp: true) {|x| res << x}
  947. assert_equal([], res)
  948. res = []
  949. S("\n").each_line(chomp: true) {|x| res << x}
  950. assert_equal([S("")], res)
  951. res = []
  952. S("\r\n").each_line(chomp: true) {|x| res << x}
  953. assert_equal([S("")], res)
  954. res = []
  955. S("a\n b\n").each_line(" ", chomp: true) {|x| res << x}
  956. assert_equal([S("a\n"), S("b\n")], res)
  957. end
  958. def test_lines
  959. s = S("hello\nworld")
  960. assert_equal ["hello\n", "world"], s.lines
  961. assert_equal ["hello\nworld"], s.lines(nil)
  962. if ENUMERATOR_WANTARRAY
  963. assert_warn(/block not used/) {
  964. assert_equal ["hello\n", "world"], s.lines {}
  965. }
  966. else
  967. res = []
  968. assert_equal s.object_id, s.lines {|x| res << x }.object_id
  969. assert_equal(S("hello\n"), res[0])
  970. assert_equal(S("world"), res[1])
  971. end
  972. end
  973. def test_empty?
  974. assert_empty(S(""))
  975. assert_not_empty(S("not"))
  976. end
  977. def test_end_with?
  978. assert_send([S("hello"), :end_with?, S("llo")])
  979. assert_not_send([S("hello"), :end_with?, S("ll")])
  980. assert_send([S("hello"), :end_with?, S("el"), S("lo")])
  981. bug5536 = '[ruby-core:40623]'
  982. assert_raise(TypeError, bug5536) {S("str").end_with? :not_convertible_to_string}
  983. end
  984. def test_eql?
  985. a = S("hello")
  986. assert_operator(a, :eql?, S("hello"))
  987. assert_operator(a, :eql?, a)
  988. end
  989. def test_gsub
  990. assert_equal(S("h*ll*"), S("hello").gsub(/[aeiou]/, S('*')))
  991. assert_equal(S("h<e>ll<o>"), S("hello").gsub(/([aeiou])/, S('<\1>')))
  992. assert_equal(S("h e l l o "),
  993. S("hello").gsub(/./) { |s| s[0].to_s + S(' ')})
  994. assert_equal(S("HELL-o"),
  995. S("hello").gsub(/(hell)(.)/) { |s| $1.upcase + S('-') + $2 })
  996. assert_equal(S("<>h<>e<>l<>l<>o<>"), S("hello").gsub(S(''), S('<\0>')))
  997. assert_equal("z", "abc".gsub(/./, "a" => "z"), "moved from btest/knownbug")
  998. assert_raise(ArgumentError) { "foo".gsub }
  999. end
  1000. def test_gsub_encoding
  1001. a = S("hello world")
  1002. a.force_encoding Encoding::UTF_8
  1003. b = S("hi")
  1004. b.force_encoding Encoding::US_ASCII
  1005. assert_equal Encoding::UTF_8, a.gsub(/hello/, b).encoding
  1006. c = S("everybody")
  1007. c.force_encoding Encoding::US_ASCII
  1008. assert_equal Encoding::UTF_8, a.gsub(/world/, c).encoding
  1009. assert_equal S("a\u{e9}apos&lt;"), S("a\u{e9}'&lt;").gsub("'", "apos")
  1010. bug9849 = '[ruby-core:62669] [Bug #9849]'
  1011. assert_equal S("\u{3042 3042 3042}!foo!"), S("\u{3042 3042 3042}/foo/").gsub("/", "!"), bug9849
  1012. end
  1013. def test_gsub!
  1014. a = S("hello")
  1015. b = a.dup
  1016. a.gsub!(/[aeiou]/, S('*'))
  1017. assert_equal(S("h*ll*"), a)
  1018. assert_equal(S("hello"), b)
  1019. a = S("hello")
  1020. a.gsub!(/([aeiou])/, S('<\1>'))
  1021. assert_equal(S("h<e>ll<o>"), a)
  1022. a = S("hello")
  1023. a.gsub!(/./) { |s| s[0].to_s + S(' ')}
  1024. assert_equal(S("h e l l o "), a)
  1025. a = S("hello")
  1026. a.gsub!(/(hell)(.)/) { |s| $1.upcase + S('-') + $2 }
  1027. assert_equal(S("HELL-o"), a)
  1028. a = S("hello")
  1029. assert_nil(a.sub!(S('X'), S('Y')))
  1030. end
  1031. def test_sub_hash
  1032. assert_equal('azc', 'abc'.sub(/b/, "b" => "z"))
  1033. assert_equal('ac', 'abc'.sub(/b/, {}))
  1034. assert_equal('a1c', 'abc'.sub(/b/, "b" => 1))
  1035. assert_equal('aBc', 'abc'.sub(/b/, Hash.new {|h, k| k.upcase }))
  1036. assert_equal('a[\&]c', 'abc'.sub(/b/, "b" => '[\&]'))
  1037. assert_equal('aBcabc', 'abcabc'.sub(/b/, Hash.new {|h, k| h[k] = k.upcase }))
  1038. assert_equal('aBcdef', 'abcdef'.sub(/de|b/, "b" => "B", "de" => "DE"))
  1039. end
  1040. def test_gsub_hash
  1041. assert_equal('azc', 'abc'.gsub(/b/, "b" => "z"))
  1042. assert_equal('ac', 'abc'.gsub(/b/, {}))
  1043. assert_equal('a1c', 'abc'.gsub(/b/, "b" => 1))
  1044. assert_equal('aBc', 'abc'.gsub(/b/, Hash.new {|h, k| k.upcase }))
  1045. assert_equal('a[\&]c', 'abc'.gsub(/b/, "b" => '[\&]'))
  1046. assert_equal('aBcaBc', 'abcabc'.gsub(/b/, Hash.new {|h, k| h[k] = k.upcase }))
  1047. assert_equal('aBcDEf', 'abcdef'.gsub(/de|b/, "b" => "B", "de" => "DE"))
  1048. end
  1049. def test_hash
  1050. assert_equal(S("hello").hash, S("hello").hash)
  1051. assert_not_equal(S("hello").hash, S("helLO").hash)
  1052. bug4104 = '[ruby-core:33500]'
  1053. assert_not_equal(S("a").hash, S("a\0").hash, bug4104)
  1054. bug9172 = '[ruby-core:58658] [Bug #9172]'
  1055. assert_not_equal(S("sub-setter").hash, S("discover").hash, bug9172)
  1056. end
  1057. def test_hex
  1058. assert_equal(255, S("0xff").hex)
  1059. assert_equal(-255, S("-0xff").hex)
  1060. assert_equal(255, S("ff").hex)
  1061. assert_equal(-255, S("-ff").hex)
  1062. assert_equal(0, S("-ralph").hex)
  1063. assert_equal(-15, S("-fred").hex)
  1064. assert_equal(15, S("fred").hex)
  1065. end
  1066. def test_include?
  1067. assert_include(S("foobar"), ?f)
  1068. assert_include(S("foobar"), S("foo"))
  1069. assert_not_include(S("foobar"), S("baz"))
  1070. assert_not_include(S("foobar"), ?z)
  1071. end
  1072. def test_index
  1073. assert_equal(0, S("hello").index(?h))
  1074. assert_equal(1, S("hello").index(S("ell")))
  1075. assert_equal(2, S("hello").index(/ll./))
  1076. assert_equal(3, S("hello").index(?l, 3))
  1077. assert_equal(3, S("hello").index(S("l"), 3))
  1078. assert_equal(3, S("hello").index(/l./, 3))
  1079. assert_nil(S("hello").index(?z, 3))
  1080. assert_nil(S("hello").index(S("z"), 3))
  1081. assert_nil(S("hello").index(/z./, 3))
  1082. assert_nil(S("hello").index(?z))
  1083. assert_nil(S("hello").index(S("z")))
  1084. assert_nil(S("hello").index(/z./))
  1085. assert_equal(0, S("").index(S("")))
  1086. assert_equal(0, S("").index(//))
  1087. assert_nil(S("").index(S("hello")))
  1088. assert_nil(S("").index(/hello/))
  1089. assert_equal(0, S("hello").index(S("")))
  1090. assert_equal(0, S("hello").index(//))
  1091. s = S("long") * 1000 << "x"
  1092. assert_nil(s.index(S("y")))
  1093. assert_equal(4 * 1000, s.index(S("x")))
  1094. s << "yx"
  1095. assert_equal(4 * 1000, s.index(S("x")))
  1096. assert_equal(4 * 1000, s.index(S("xyx")))
  1097. o = Object.new
  1098. def o.to_str; "bar"; end
  1099. assert_equal(3, "foobarbarbaz".index(o))
  1100. assert_raise(TypeError) { "foo".index(Object.new) }
  1101. assert_nil("foo".index(//, -100))
  1102. assert_nil($~)
  1103. end
  1104. def test_insert
  1105. assert_equal("Xabcd", S("abcd").insert(0, 'X'))
  1106. assert_equal("abcXd", S("abcd").insert(3, 'X'))
  1107. assert_equal("abcdX", S("abcd").insert(4, 'X'))
  1108. assert_equal("abXcd", S("abcd").insert(-3, 'X'))
  1109. assert_equal("abcdX", S("abcd").insert(-1, 'X'))
  1110. end
  1111. def test_intern
  1112. assert_equal(:koala, S("koala").intern)
  1113. assert_not_equal(:koala, S("Koala").intern)
  1114. end
  1115. def test_length
  1116. assert_equal(0, S("").length)
  1117. assert_equal(4, S("1234").length)
  1118. assert_equal(6, S("1234\r\n").length)
  1119. assert_equal(7, S("\0011234\r\n").length)
  1120. end
  1121. def test_ljust
  1122. assert_equal(S("hello"), S("hello").ljust(4))
  1123. assert_equal(S("hello "), S("hello").ljust(11))
  1124. assert_equal(S("ababababab"), S("").ljust(10, "ab"), Bug2463)
  1125. assert_equal(S("abababababa"), S("").ljust(11, "ab"), Bug2463)
  1126. end
  1127. def test_next
  1128. assert_equal(S("abd"), S("abc").next)
  1129. assert_equal(S("z"), S("y").next)
  1130. assert_equal(S("aaa"), S("zz").next)
  1131. assert_equal(S("124"), S("123").next)
  1132. assert_equal(S("1000"), S("999").next)
  1133. assert_equal(S("2000aaa"), S("1999zzz").next)
  1134. assert_equal(S("AAAAA000"), S("ZZZZ999").next)
  1135. assert_equal(S("*+"), S("**").next)
  1136. assert_equal(S("!"), S(" ").next)
  1137. assert_equal(S(""), S("").next)
  1138. end
  1139. def test_next!
  1140. a = S("abc")
  1141. b = a.dup
  1142. assert_equal(S("abd"), a.next!)
  1143. assert_equal(S("abd"), a)
  1144. assert_equal(S("abc"), b)
  1145. a = S("y")
  1146. assert_equal(S("z"), a.next!)
  1147. assert_equal(S("z"), a)
  1148. a = S("zz")
  1149. assert_equal(S("aaa"), a.next!)
  1150. assert_equal(S("aaa"), a)
  1151. a = S("123")
  1152. assert_equal(S("124"), a.next!)
  1153. assert_equal(S("124"), a)
  1154. a = S("999")
  1155. assert_equal(S("1000"), a.next!)
  1156. assert_equal(S("1000"), a)
  1157. a = S("1999zzz")
  1158. assert_equal(S("2000aaa"), a.next!)
  1159. assert_equal(S("2000aaa"), a)
  1160. a = S("ZZZZ999")
  1161. assert_equal(S("AAAAA000"), a.next!)
  1162. assert_equal(S("AAAAA000"), a)
  1163. a = S("**")
  1164. assert_equal(S("*+"), a.next!)
  1165. assert_equal(S("*+"), a)
  1166. a = S(" ")
  1167. assert_equal(S("!"), a.next!)
  1168. assert_equal(S("!"), a)
  1169. end
  1170. def test_oct
  1171. assert_equal(255, S("0377").oct)
  1172. assert_equal(255, S("377").oct)
  1173. assert_equal(-255, S("-0377").oct)
  1174. assert_equal(-255, S("-377").oct)
  1175. assert_equal(0, S("OO").oct)
  1176. assert_equal(24, S("030OO").oct)
  1177. end
  1178. def test_replace
  1179. a = S("foo")
  1180. assert_equal(S("f"), a.replace(S("f")))
  1181. a = S("foo")
  1182. assert_equal(S("foobar"), a.replace(S("foobar")))
  1183. a = S("foo")
  1184. b = a.replace(S("xyz"))
  1185. assert_equal(S("xyz"), b)
  1186. s = "foo" * 100
  1187. s2 = ("bar" * 100).dup
  1188. s.replace(s2)
  1189. assert_equal(s2, s)
  1190. s2 = ["foo"].pack("p")
  1191. s.replace(s2)
  1192. assert_equal(s2, s)
  1193. fs = "".freeze
  1194. assert_raise(FrozenError) { fs.replace("a") }
  1195. assert_raise(FrozenError) { fs.replace(fs) }
  1196. assert_raise(ArgumentError) { fs.replace() }
  1197. assert_raise(FrozenError) { fs.replace(42) }
  1198. end
  1199. def test_reverse
  1200. assert_equal(S("beta"), S("ateb").reverse)
  1201. assert_equal(S("madamImadam"), S("madamImadam").reverse)
  1202. a=S("beta")
  1203. assert_equal(S("ateb"), a.reverse)
  1204. assert_equal(S("beta"), a)
  1205. end
  1206. def test_reverse!
  1207. a = S("beta")
  1208. b = a.dup
  1209. assert_equal(S("ateb"), a.reverse!)
  1210. assert_equal(S("ateb"), a)
  1211. assert_equal(S("beta"), b)
  1212. assert_equal(S("madamImadam"), S("madamImadam").reverse!)
  1213. a = S("madamImadam")
  1214. assert_equal(S("madamImadam"), a.reverse!) # ??
  1215. assert_equal(S("madamImadam"), a)
  1216. end
  1217. def test_rindex
  1218. assert_equal(3, S("hello").rindex(?l))
  1219. assert_equal(6, S("ell, hello").rindex(S("ell")))
  1220. assert_equal(7, S("ell, hello").rindex(/ll./))
  1221. assert_equal(3, S("hello,lo").rindex(?l, 3))
  1222. assert_equal(3, S("hello,lo").rindex(S("l"), 3))
  1223. assert_equal(3, S("hello,lo").rindex(/l./, 3))
  1224. assert_nil(S("hello").rindex(?z, 3))
  1225. assert_nil(S("hello").rindex(S("z"), 3))
  1226. assert_nil(S("hello").rindex(/z./, 3))
  1227. assert_nil(S("hello").rindex(?z))
  1228. assert_nil(S("hello").rindex(S("z")))
  1229. assert_nil(S("hello").rindex(/z./))
  1230. o = Object.new
  1231. def o.to_str; "bar"; end
  1232. assert_equal(6, "foobarbarbaz".rindex(o))
  1233. assert_raise(TypeError) { "foo".rindex(Object.new) }
  1234. assert_nil("foo".rindex(//, -100))
  1235. assert_nil($~)
  1236. assert_equal(3, "foo".rindex(//))
  1237. assert_equal([3, 3], $~.offset(0))
  1238. end
  1239. def test_rjust
  1240. assert_equal(S("hello"), S("hello").rjust(4))
  1241. assert_equal(S(" hello"), S("hello").rjust(11))
  1242. assert_equal(S("ababababab"), S("").rjust(10, "ab"), Bug2463)
  1243. assert_equal(S("abababababa"), S("").rjust(11, "ab"), Bug2463)
  1244. end
  1245. def test_scan
  1246. a = S("cruel world")
  1247. assert_equal([S("cruel"), S("world")],a.scan(/\w+/))
  1248. assert_equal([S("cru"), S("el "), S("wor")],a.scan(/.../))
  1249. assert_equal([[S("cru")], [S("el ")], [S("wor")]],a.scan(/(...)/))
  1250. res = []
  1251. a.scan(/\w+/) { |w| res << w }
  1252. assert_equal([S("cruel"), S("world") ],res)
  1253. res = []
  1254. a.scan(/.../) { |w| res << w }
  1255. assert_equal([S("cru"), S("el "), S("wor")],res)
  1256. res = []
  1257. a.scan(/(...)/) { |w| res << w }
  1258. assert_equal([[S("cru")], [S("el ")], [S("wor")]],res)
  1259. /h/ =~ a
  1260. a.scan(/x/)
  1261. assert_nil($~)
  1262. /h/ =~ a
  1263. a.scan('x')
  1264. assert_nil($~)
  1265. assert_equal(%w[1 2 3], S("a1 a2 a3").scan(/a\K./))
  1266. end
  1267. def test_size
  1268. assert_equal(0, S("").size)
  1269. assert_equal(4, S("1234").size)
  1270. assert_equal(6, S("1234\r\n").size)
  1271. assert_equal(7, S("\0011234\r\n").size)
  1272. end
  1273. def test_slice
  1274. assert_equal(?A, S("AooBar").slice(0))
  1275. assert_equal(?B, S("FooBaB").slice(-1))
  1276. assert_nil(S("FooBar").slice(6))
  1277. assert_nil(S("FooBar").slice(-7))
  1278. assert_equal(S("Foo"), S("FooBar").slice(0,3))
  1279. assert_equal(S(S("Bar")), S("FooBar").slice(-3,3))
  1280. assert_nil(S("FooBar").slice(7,2)) # Maybe should be six?
  1281. assert_nil(S("FooBar").slice(-7,10))
  1282. assert_equal(S("Foo"), S("FooBar").slice(0..2))
  1283. assert_equal(S("Bar"), S("FooBar").slice(-3..-1))
  1284. assert_equal(S(""), S("FooBar").slice(6..2))
  1285. assert_nil(S("FooBar").slice(-10..-7))
  1286. assert_equal(S("Foo"), S("FooBar").slice(/^F../))
  1287. assert_equal(S("Bar"), S("FooBar").slice(/..r$/))
  1288. assert_nil(S("FooBar").slice(/xyzzy/))
  1289. assert_nil(S("FooBar").slice(/plugh/))
  1290. assert_equal(S("Foo"), S("FooBar").slice(S("Foo")))
  1291. assert_equal(S("Bar"), S("FooBar").slice(S("Bar")))
  1292. assert_nil(S("FooBar").slice(S("xyzzy")))
  1293. assert_nil(S("FooBar").slice(S("plugh")))
  1294. bug9882 = '[ruby-core:62842] [Bug #9882]'
  1295. substr = S("\u{30c6 30b9 30c8 2019}#{bug9882}").slice(4..-1)
  1296. assert_equal(S(bug9882).hash, substr.hash, bug9882)
  1297. assert_predicate(substr, :ascii_only?, bug9882)
  1298. end
  1299. def test_slice!
  1300. a = S("AooBar")
  1301. b = a.dup
  1302. assert_equal(?A, a.slice!(0))
  1303. assert_equal(S("ooBar"), a)
  1304. assert_equal(S("AooBar"), b)
  1305. a = S("FooBar")
  1306. assert_equal(?r,a.slice!(-1))
  1307. assert_equal(S("FooBa"), a)
  1308. a = S("FooBar")
  1309. if @aref_slicebang_silent
  1310. assert_nil( a.slice!(6) )
  1311. else
  1312. assert_raise(IndexError) { a.slice!(6) }
  1313. end
  1314. assert_equal(S("FooBar"), a)
  1315. if @aref_slicebang_silent
  1316. assert_nil( a.slice!(-7) )
  1317. else
  1318. assert_raise(IndexError) { a.slice!(-7) }
  1319. end
  1320. assert_equal(S("FooBar"), a)
  1321. a = S("FooBar")
  1322. assert_equal(S("Foo"), a.slice!(0,3))
  1323. assert_equal(S("Bar"), a)
  1324. a = S("FooBar")
  1325. assert_equal(S("Bar"), a.slice!(-3,3))
  1326. assert_equal(S("Foo"), a)
  1327. a=S("FooBar")
  1328. if @aref_slicebang_silent
  1329. assert_nil(a.slice!(7,2)) # Maybe should be six?
  1330. else
  1331. assert_raise(IndexError) {a.slice!(7,2)} # Maybe should be six?
  1332. end
  1333. assert_equal(S("FooBar"), a)
  1334. if @aref_slicebang_silent
  1335. assert_nil(a.slice!(-7,10))
  1336. else
  1337. assert_raise(IndexError) {a.slice!(-7,10)}
  1338. end
  1339. assert_equal(S("FooBar"), a)
  1340. a=S("FooBar")
  1341. assert_equal(S("Foo"), a.slice!(0..2))
  1342. assert_equal(S("Bar"), a)
  1343. a=S("FooBar")
  1344. assert_equal(S("Bar"), a.slice!(-3..-1))
  1345. assert_equal(S("Foo"), a)
  1346. a=S("FooBar")
  1347. if @aref_slicebang_silent
  1348. assert_equal(S(""), a.slice!(6..2))
  1349. else
  1350. assert_raise(RangeError) {a.slice!(6..2)}
  1351. end
  1352. assert_equal(S("FooBar"), a)
  1353. if @aref_slicebang_silent
  1354. assert_nil(a.slice!(-10..-7))
  1355. else
  1356. assert_raise(RangeError) {a.slice!(-10..-7)}
  1357. end
  1358. assert_equal(S("FooBar"), a)
  1359. a=S("FooBar")
  1360. assert_equal(S("Foo"), a.slice!(/^F../))
  1361. assert_equal(S("Bar"), a)
  1362. a=S("FooBar")
  1363. assert_equal(S("Bar"), a.slice!(/..r$/))
  1364. assert_equal(S("Foo"), a)
  1365. a=S("FooBar")
  1366. if @aref_slicebang_silent
  1367. assert_nil(a.slice!(/xyzzy/))
  1368. else
  1369. assert_raise(IndexError) {a.slice!(/xyzzy/)}
  1370. end
  1371. assert_equal(S("FooBar"), a)
  1372. if @aref_slicebang_silent
  1373. assert_nil(a.slice!(/plugh/))
  1374. else
  1375. assert_raise(IndexError) {a.slice!(/plugh/)}
  1376. end
  1377. assert_equal(S("FooBar"), a)
  1378. a=S("FooBar")
  1379. assert_equal(S("Foo"), a.slice!(S("Foo")))
  1380. assert_equal(S("Bar"), a)
  1381. a=S("FooBar")
  1382. assert_equal(S("Bar"), a.slice!(S("Bar")))
  1383. assert_equal(S("Foo"), a)
  1384. assert_raise(ArgumentError) { "foo".slice! }
  1385. end
  1386. def test_split
  1387. fs, $; = $;, nil
  1388. assert_equal([S("a"), S("b"), S("c")], S(" a b\t c ").split)
  1389. assert_equal([S("a"), S("b"), S("c")], S(" a b\t c ").split(S(" ")))
  1390. assert_equal([S(" a "), S(" b "), S(" c ")], S(" a | b | c ").split(S("|")))
  1391. assert_equal([S("a"), S("b"), S("c")], S("aXXbXXcXX").split(/X./))
  1392. assert_equal([S("a"), S("b"), S("c")], S("abc").split(//))
  1393. assert_equal([S("a|b|c")], S("a|b|c").split(S('|'), 1))
  1394. assert_equal([S("a"), S("b|c")], S("a|b|c").split(S('|'), 2))
  1395. assert_equal([S("a"), S("b"), S("c")], S("a|b|c").split(S('|'), 3))
  1396. assert_equal([S("a"), S("b"), S("c"), S("")], S("a|b|c|").split(S('|'), -1))
  1397. assert_equal([S("a"), S("b"), S("c"), S(""), S("")], S("a|b|c||").split(S('|'), -1))
  1398. assert_equal([S("a"), S(""), S("b"), S("c")], S("a||b|c|").split(S('|')))
  1399. assert_equal([S("a"), S(""), S("b"), S("c"), S("")], S("a||b|c|").split(S('|'), -1))
  1400. assert_equal([], "".split(//, 1))
  1401. ensure
  1402. EnvUtil.suppress_warning {$; = fs}
  1403. end
  1404. def test_split_with_block
  1405. fs, $; = $;, nil
  1406. result = []; S(" a b\t c ").split {|s| result << s}
  1407. assert_equal([S("a"), S("b"), S("c")], result)
  1408. result = []; S(" a b\t c ").split(S(" ")) {|s| result << s}
  1409. assert_equal([S("a"), S("b"), S("c")], result)
  1410. result = []; S(" a | b | c ").split(S("|")) {|s| result << s}
  1411. assert_equal([S(" a "), S(" b "), S(" c ")], result)
  1412. result = []; S("aXXbXXcXX").split(/X./) {|s| result << s}
  1413. assert_equal([S("a"), S("b"), S("c")], result)
  1414. result = []; S("abc").split(//) {|s| result << s}
  1415. assert_equal([S("a"), S("b"), S("c")], result)
  1416. result = []; S("a|b|c").split(S('|'), 1) {|s| result << s}
  1417. assert_equal([S("a|b|c")], result)
  1418. result = []; S("a|b|c").split(S('|'), 2) {|s| result << s}
  1419. assert_equal([S("a"), S("b|c")], result)
  1420. result = []; S("a|b|c").split(S('|'), 3) {|s| result << s}
  1421. assert_equal([S("a"), S("b"), S("c")], result)
  1422. result = []; S("a|b|c|").split(S('|'), -1) {|s| result << s}
  1423. assert_equal([S("a"), S("b"), S("c"), S("")], result)
  1424. result = []; S("a|b|c||").split(S('|'), -1) {|s| result << s}
  1425. assert_equal([S("a"), S("b"), S("c"), S(""), S("")], result)
  1426. result = []; S("a||b|c|").split(S('|')) {|s| result << s}
  1427. assert_equal([S("a"), S(""), S("b"), S("c")], result)
  1428. result = []; S("a||b|c|").split(S('|'), -1) {|s| result << s}
  1429. assert_equal([S("a"), S(""), S("b"), S("c"), S("")], result)
  1430. result = []; "".split(//, 1) {|s| result << s}
  1431. assert_equal([], result)
  1432. result = []; "aaa,bbb,ccc,ddd".split(/,/) {|s| result << s.gsub(/./, "A")}
  1433. assert_equal(["AAA"]*4, result)
  1434. ensure
  1435. EnvUtil.suppress_warning {$; = fs}
  1436. end
  1437. def test_fs
  1438. assert_raise_with_message(TypeError, /\$;/) {
  1439. $; = []
  1440. }
  1441. assert_separately(%W[-W0], "#{<<~"begin;"}\n#{<<~'end;'}")
  1442. bug = '[ruby-core:79582] $; must not be GCed'
  1443. begin;
  1444. $; = " "
  1445. $a = nil
  1446. alias $; $a
  1447. alias $-F $a
  1448. GC.start
  1449. assert_equal([], "".split, bug)
  1450. end;
  1451. begin
  1452. fs = $;
  1453. assert_warn(/`\$;' is deprecated/) {$; = " "}
  1454. ensure
  1455. EnvUtil.suppress_warning {$; = fs}
  1456. end
  1457. end
  1458. def test_split_encoding
  1459. bug6206 = '[ruby-dev:45441]'
  1460. Encoding.list.each do |enc|
  1461. next unless enc.ascii_compatible?
  1462. s = S("a:".force_encoding(enc))
  1463. assert_equal([enc]*2, s.split(":", 2).map(&:encoding), bug6206)
  1464. end
  1465. end
  1466. def test_split_wchar
  1467. bug8642 = '[ruby-core:56036] [Bug #8642]'
  1468. WIDE_ENCODINGS.each do |enc|
  1469. s = S("abc,def".encode(enc))
  1470. assert_equal(["abc", "def"].map {|c| c.encode(enc)},
  1471. s.split(",".encode(enc)),
  1472. "#{bug8642} in #{enc.name}")
  1473. end
  1474. end
  1475. def test_split_invalid_sequence
  1476. bug10886 = '[ruby-core:68229] [Bug #10886]'
  1477. broken = S("\xa1".force_encoding("utf-8"))
  1478. assert_raise(ArgumentError, bug10886) {
  1479. S("a,b").split(broken)
  1480. }
  1481. end
  1482. def test_split_invalid_argument
  1483. assert_raise(TypeError) {
  1484. S("a,b").split(BasicObject.new)
  1485. }
  1486. end
  1487. def test_split_dupped
  1488. s = "abc"
  1489. s.split("b", 1).map(&:upcase!)
  1490. assert_equal("abc", s)
  1491. end
  1492. def test_squeeze
  1493. assert_equal(S("abc"), S("aaabbbbccc").squeeze)
  1494. assert_equal(S("aa bb cc"), S("aa bb cc").squeeze(S(" ")))
  1495. assert_equal(S("BxTyWz"), S("BxxxTyyyWzzzzz").squeeze(S("a-z")))
  1496. end
  1497. def test_squeeze!
  1498. a = S("aaabbbbccc")
  1499. b = a.dup
  1500. assert_equal(S("abc"), a.squeeze!)
  1501. assert_equal(S("abc"), a)
  1502. assert_equal(S("aaabbbbccc"), b)
  1503. a = S("aa bb cc")
  1504. assert_equal(S("aa bb cc"), a.squeeze!(S(" ")))
  1505. assert_equal(S("aa bb cc"), a)
  1506. a = S("BxxxTyyyWzzzzz")
  1507. assert_equal(S("BxTyWz"), a.squeeze!(S("a-z")))
  1508. assert_equal(S("BxTyWz"), a)
  1509. a=S("The quick brown fox")
  1510. assert_nil(a.squeeze!)
  1511. end
  1512. def test_start_with?
  1513. assert_send([S("hello"), :start_with?, S("hel")])
  1514. assert_not_send([S("hello"), :start_with?, S("el")])
  1515. assert_send([S("hello"), :start_with?, S("el"), S("he")])
  1516. bug5536 = '[ruby-core:40623]'
  1517. assert_raise(TypeError, bug5536) {S("str").start_with? :not_convertible_to_string}
  1518. assert_equal(true, "hello".start_with?(/hel/))
  1519. assert_equal("hel", $&)
  1520. assert_equal(false, "hello".start_with?(/el/))
  1521. assert_nil($&)
  1522. end
  1523. def test_strip
  1524. assert_equal(S("x"), S(" x ").strip)
  1525. assert_equal(S("x"), S(" \n\r\t x \t\r\n\n ").strip)
  1526. assert_equal("0b0 ".force_encoding("UTF-16BE"),
  1527. "\x00 0b0 ".force_encoding("UTF-16BE").strip)
  1528. assert_equal("0\x000b0 ".force_encoding("UTF-16BE"),
  1529. "0\x000b0 ".force_encoding("UTF-16BE").strip)
  1530. end
  1531. def test_strip!
  1532. a = S(" x ")
  1533. b = a.dup
  1534. assert_equal(S("x") ,a.strip!)
  1535. assert_equal(S("x") ,a)
  1536. assert_equal(S(" x "), b)
  1537. a = S(" \n\r\t x \t\r\n\n ")
  1538. assert_equal(S("x"), a.strip!)
  1539. assert_equal(S("x"), a)
  1540. a = S("x")
  1541. assert_nil(a.strip!)
  1542. assert_equal(S("x") ,a)
  1543. end
  1544. def test_sub
  1545. assert_equal(S("h*llo"), S("hello").sub(/[aeiou]/, S('*')))
  1546. assert_equal(S("h<e>llo"), S("hello").sub(/([aeiou])/, S('<\1>')))
  1547. assert_equal(S("h ello"), S("hello").sub(/./) {
  1548. |s| s[0].to_s + S(' ')})
  1549. assert_equal(S("HELL-o"), S("hello").sub(/(hell)(.)/) {
  1550. |s| $1.upcase + S('-') + $2
  1551. })
  1552. assert_equal(S("h<e>llo"), S("hello").sub('e', S('<\0>')))
  1553. assert_equal(S("a\\aba"), S("ababa").sub(/b/, '\\'))
  1554. assert_equal(S("ab\\aba"), S("ababa").sub(/(b)/, '\1\\'))
  1555. assert_equal(S("ababa"), S("ababa").sub(/(b)/, '\1'))
  1556. assert_equal(S("ababa"), S("ababa").sub(/(b)/, '\\1'))
  1557. assert_equal(S("a\\1aba"), S("ababa").sub(/(b)/, '\\\1'))
  1558. assert_equal(S("a\\1aba"), S("ababa").sub(/(b)/, '\\\\1'))
  1559. assert_equal(S("a\\baba"), S("ababa").sub(/(b)/, '\\\\\1'))
  1560. assert_equal(S("a--ababababababababab"),
  1561. S("abababababababababab").sub(/(b)/, '-\9-'))
  1562. assert_equal(S("1-b-0"),
  1563. S("1b2b3b4b5b6b7b8b9b0").
  1564. sub(/(b).(b).(b).(b).(b).(b).(b).(b).(b)/, '-\9-'))
  1565. assert_equal(S("1-b-0"),
  1566. S("1b2b3b4b5b6b7b8b9b0").
  1567. sub(/(b).(b).(b).(b).(b).(b).(b).(b).(b)/, '-\\9-'))
  1568. assert_equal(S("1-\\9-0"),
  1569. S("1b2b3b4b5b6b7b8b9b0").
  1570. sub(/(b).(b).(b).(b).(b).(b).(b).(b).(b)/, '-\\\9-'))
  1571. assert_equal(S("k"),
  1572. S("1a2b3c4d5e6f7g8h9iAjBk").
  1573. sub(/.(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.)/, '\+'))
  1574. assert_equal(S("ab\\aba"), S("ababa").sub(/b/, '\&\\'))
  1575. assert_equal(S("ababa"), S("ababa").sub(/b/, '\&'))
  1576. assert_equal(S("ababa"), S("ababa").sub(/b/, '\\&'))
  1577. assert_equal(S("a\\&aba"), S("ababa").sub(/b/, '\\\&'))
  1578. assert_equal(S("a\\&aba"), S("ababa").sub(/b/, '\\\\&'))
  1579. assert_equal(S("a\\baba"), S("ababa").sub(/b/, '\\\\\&'))
  1580. o = Object.new
  1581. def o.to_str; "bar"; end
  1582. assert_equal("fooBARbaz", "foobarbaz".sub(o, "BAR"))
  1583. assert_raise(TypeError) { "foo".sub(Object.new, "") }
  1584. assert_raise(ArgumentError) { "foo".sub }
  1585. assert_raise(IndexError) { "foo"[/(?:(o$)|(x))/, 2] = 'bar' }
  1586. o = Object.new
  1587. def o.to_s; self; end
  1588. assert_match(/^foo#<Object:0x.*>baz$/, "foobarbaz".sub("bar") { o })
  1589. assert_equal(S("Abc"), S("abc").sub("a", "A"))
  1590. m = nil
  1591. assert_equal(S("Abc"), S("abc").sub("a") {m = $~; "A"})
  1592. assert_equal(S("a"), m[0])
  1593. assert_equal(/a/, m.regexp)
  1594. bug = '[ruby-core:78686] [Bug #13042] other than regexp has no name references'
  1595. assert_raise_with_message(IndexError, /oops/, bug) {
  1596. 'hello'.gsub('hello', '\k<oops>')
  1597. }
  1598. end
  1599. def test_sub!
  1600. a = S("hello")
  1601. b = a.dup
  1602. a.sub!(/[aeiou]/, S('*'))
  1603. assert_equal(S("h*llo"), a)
  1604. assert_equal(S("hello"), b)
  1605. a = S("hello")
  1606. a.sub!(/([aeiou])/, S('<\1>'))
  1607. assert_equal(S("h<e>llo"), a)
  1608. a = S("hello")
  1609. a.sub!(/./) { |s| s[0].to_s + S(' ')}
  1610. assert_equal(S("h ello"), a)
  1611. a = S("hello")
  1612. a.sub!(/(hell)(.)/) { |s| $1.upcase + S('-') + $2 }
  1613. assert_equal(S("HELL-o"), a)
  1614. a=S("hello")
  1615. assert_nil(a.sub!(/X/, S('Y')))
  1616. bug16105 = '[Bug #16105] heap-use-after-free'
  1617. a = S("ABCDEFGHIJKLMNOPQRSTUVWXYZ012345678")
  1618. b = a.dup
  1619. c = a.slice(1, 100)
  1620. assert_equal("AABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", b.sub!(c, b), bug16105)
  1621. end
  1622. def test_succ
  1623. assert_equal(S("abd"), S("abc").succ)
  1624. assert_equal(S("z"), S("y").succ)
  1625. assert_equal(S("aaa"), S("zz").succ)
  1626. assert_equal(S("124"), S("123").succ)
  1627. assert_equal(S("1000"), S("999").succ)
  1628. assert_equal(S("2.000"), S("1.999").succ)
  1629. assert_equal(S("No.10"), S("No.9").succ)
  1630. assert_equal(S("2000aaa"), S("1999zzz").succ)
  1631. assert_equal(S("AAAAA000"), S("ZZZZ999").succ)
  1632. assert_equal(S("*+"), S("**").succ)
  1633. assert_equal("abce", "abcd".succ)
  1634. assert_equal("THX1139", "THX1138".succ)
  1635. assert_equal("<\<koalb>>", "<\<koala>>".succ)
  1636. assert_equal("2000aaa", "1999zzz".succ)
  1637. assert_equal("AAAA0000", "ZZZ9999".succ)
  1638. assert_equal("**+", "***".succ)
  1639. assert_equal("!", " ".succ)
  1640. assert_equal("", "".succ)
  1641. bug = '[ruby-core:83062] [Bug #13952]'
  1642. s = "\xff".b
  1643. assert_not_predicate(s, :ascii_only?)
  1644. assert_predicate(s.succ, :ascii_only?, bug)
  1645. end
  1646. def test_succ!
  1647. a = S("abc")
  1648. b = a.dup
  1649. assert_equal(S("abd"), a.succ!)
  1650. assert_equal(S("abd"), a)
  1651. assert_equal(S("abc"), b)
  1652. a = S("y")
  1653. assert_equal(S("z"), a.succ!)
  1654. assert_equal(S("z"), a)
  1655. a = S("zz")
  1656. assert_equal(S("aaa"), a.succ!)
  1657. assert_equal(S("aaa"), a)
  1658. a = S("123")
  1659. assert_equal(S("124"), a.succ!)
  1660. assert_equal(S("124"), a)
  1661. a = S("999")
  1662. assert_equal(S("1000"), a.succ!)
  1663. assert_equal(S("1000"), a)
  1664. a = S("1999zzz")
  1665. assert_equal(S("2000aaa"), a.succ!)
  1666. assert_equal(S("2000aaa"), a)
  1667. a = S("ZZZZ999")
  1668. assert_equal(S("AAAAA000"), a.succ!)
  1669. assert_equal(S("AAAAA000"), a)
  1670. a = S("**")
  1671. assert_equal(S("*+"), a.succ!)
  1672. assert_equal(S("*+"), a)
  1673. a = S("No.9")
  1674. assert_equal(S("No.10"), a.succ!)
  1675. assert_equal(S("No.10"), a)
  1676. a = S(" ")
  1677. assert_equal(S("!"), a.succ!)
  1678. assert_equal(S("!"), a)
  1679. a = S("")
  1680. assert_equal(S(""), a.succ!)
  1681. assert_equal(S(""), a)
  1682. assert_equal("aaaaaaaaaaaa", "zzzzzzzzzzz".succ!)
  1683. assert_equal("aaaaaaaaaaaaaaaaaaaaaaaa", "zzzzzzzzzzzzzzzzzzzzzzz".succ!)
  1684. end
  1685. def test_sum
  1686. n = S("\001\001\001\001\001\001\001\001\001\001\001\001\001\001\001")
  1687. assert_equal(15, n.sum)
  1688. n += S("\001")
  1689. assert_equal(16, n.sum(17))
  1690. n[0] = 2.chr
  1691. assert_not_equal(15, n.sum)
  1692. assert_equal(17, n.sum(0))
  1693. assert_equal(17, n.sum(-1))
  1694. end
  1695. def check_sum(str, bits=16)
  1696. sum = 0
  1697. str.each_byte {|c| sum += c}
  1698. sum = sum & ((1 << bits) - 1) if bits != 0
  1699. assert_equal(sum, str.sum(bits))
  1700. end
  1701. def test_sum_2
  1702. assert_equal(0, "".sum)
  1703. assert_equal(294, "abc".sum)
  1704. check_sum("abc")
  1705. check_sum("\x80")
  1706. -3.upto(70) {|bits|
  1707. check_sum("xyz", bits)
  1708. }
  1709. end
  1710. def test_sum_long
  1711. s8421505 = "\xff" * 8421505
  1712. assert_equal(127, s8421505.sum(31))
  1713. assert_equal(2147483775, s8421505.sum(0))
  1714. s16843010 = ("\xff" * 16843010)
  1715. assert_equal(254, s16843010.sum(32))
  1716. assert_equal(4294967550, s16843010.sum(0))
  1717. end
  1718. def test_swapcase
  1719. assert_equal(S("hi&LOW"), S("HI&low").swapcase)
  1720. end
  1721. def test_swapcase!
  1722. a = S("hi&LOW")
  1723. b = a.dup
  1724. assert_equal(S("HI&low"), a.swapcase!)
  1725. assert_equal(S("HI&low"), a)
  1726. assert_equal(S("hi&LOW"), b)
  1727. a = S("$^#^%$#!!")
  1728. assert_nil(a.swapcase!)
  1729. assert_equal(S("$^#^%$#!!"), a)
  1730. end
  1731. def test_to_f
  1732. assert_equal(344.3, S("344.3").to_f)
  1733. assert_equal(5.9742e24, S("5.9742e24").to_f)
  1734. assert_equal(98.6, S("98.6 degrees").to_f)
  1735. assert_equal(0.0, S("degrees 100.0").to_f)
  1736. assert_equal([ 0.0].pack('G'), [S(" 0.0").to_f].pack('G'))
  1737. assert_equal([-0.0].pack('G'), [S("-0.0").to_f].pack('G'))
  1738. end
  1739. def test_to_i
  1740. assert_equal(1480, S("1480ft/sec").to_i)
  1741. assert_equal(0, S("speed of sound in water @20C = 1480ft/sec)").to_i)
  1742. assert_equal(0, " 0".to_i)
  1743. assert_equal(0, "+0".to_i)
  1744. assert_equal(0, "-0".to_i)
  1745. assert_equal(0, "--0".to_i)
  1746. assert_equal(16, "0x10".to_i(0))
  1747. assert_equal(16, "0X10".to_i(0))
  1748. assert_equal(2, "0b10".to_i(0))
  1749. assert_equal(2, "0B10".to_i(0))
  1750. assert_equal(8, "0o10".to_i(0))
  1751. assert_equal(8, "0O10".to_i(0))
  1752. assert_equal(10, "0d10".to_i(0))
  1753. assert_equal(10, "0D10".to_i(0))
  1754. assert_equal(8, "010".to_i(0))
  1755. assert_raise(ArgumentError) { "010".to_i(-10) }
  1756. 2.upto(36) {|radix|
  1757. assert_equal(radix, "10".to_i(radix))
  1758. assert_equal(radix**2, "100".to_i(radix))
  1759. }
  1760. assert_raise(ArgumentError) { "0".to_i(1) }
  1761. assert_raise(ArgumentError) { "0".to_i(37) }
  1762. assert_equal(0, "z".to_i(10))
  1763. assert_equal(12, "1_2".to_i(10))
  1764. assert_equal(0x40000000, "1073741824".to_i(10))
  1765. assert_equal(0x4000000000000000, "4611686018427387904".to_i(10))
  1766. assert_equal(1, "1__2".to_i(10))
  1767. assert_equal(1, "1_z".to_i(10))
  1768. bug6192 = '[ruby-core:43566]'
  1769. assert_raise(Encoding::CompatibilityError, bug6192) {"0".encode("utf-16be").to_i}
  1770. assert_raise(Encoding::CompatibilityError, bug6192) {"0".encode("utf-16le").to_i}
  1771. assert_raise(Encoding::CompatibilityError, bug6192) {"0".encode("utf-32be").to_i}
  1772. assert_raise(Encoding::CompatibilityError, bug6192) {"0".encode("utf-32le").to_i}
  1773. assert_raise(Encoding::CompatibilityError, bug6192) {"0".encode("iso-2022-jp").to_i}
  1774. end
  1775. def test_to_s
  1776. a = S("me")
  1777. assert_equal("me", a.to_s)
  1778. assert_equal(a.__id__, a.to_s.__id__) if @cls == String
  1779. end
  1780. def test_to_str
  1781. a = S("me")
  1782. assert_equal("me", a.to_s)
  1783. assert_equal(a.__id__, a.to_s.__id__) if @cls == String
  1784. o = Object.new
  1785. def o.to_str
  1786. "at"
  1787. end
  1788. assert_equal("meat", a.concat(o))
  1789. o = Object.new
  1790. def o.to_str
  1791. foo_bar()
  1792. end
  1793. assert_match(/foo_bar/, assert_raise(NoMethodError) {a.concat(o)}.message)
  1794. end
  1795. def test_tr
  1796. assert_equal(S("hippo"), S("hello").tr(S("el"), S("ip")))
  1797. assert_equal(S("*e**o"), S("hello").tr(S("^aeiou"), S("*")))
  1798. assert_equal(S("hal"), S("ibm").tr(S("b-z"), S("a-z")))
  1799. a = "abc".force_encoding(Encoding::US_ASCII)
  1800. assert_equal(Encoding::US_ASCII, a.tr(S("z"), S("\u0101")).encoding, '[ruby-core:22326]')
  1801. assert_equal("a".hash, "a".tr("a", "\u0101").tr("\u0101", "a").hash, '[ruby-core:22328]')
  1802. assert_equal(true, "\u0101".tr("\u0101", "a").ascii_only?)
  1803. assert_equal(true, "\u3041".tr("\u3041", "a").ascii_only?)
  1804. assert_equal(false, "\u3041\u3042".tr("\u3041", "a").ascii_only?)
  1805. bug6156 = '[ruby-core:43335]'
  1806. bug13950 = '[ruby-core:83056] [Bug #13950]'
  1807. str, range, star = %w[b a-z *].map{|s|s.encode("utf-16le")}
  1808. result = str.tr(range, star)
  1809. assert_equal(star, result, bug6156)
  1810. assert_not_predicate(str, :ascii_only?)
  1811. assert_not_predicate(star, :ascii_only?)
  1812. assert_not_predicate(result, :ascii_only?, bug13950)
  1813. end
  1814. def test_tr!
  1815. a = S("hello")
  1816. b = a.dup
  1817. assert_equal(S("hippo"), a.tr!(S("el"), S("ip")))
  1818. assert_equal(S("hippo"), a)
  1819. assert_equal(S("hello"),b)
  1820. a = S("hello")
  1821. assert_equal(S("*e**o"), a.tr!(S("^aeiou"), S("*")))
  1822. assert_equal(S("*e**o"), a)
  1823. a = S("IBM")
  1824. assert_equal(S("HAL"), a.tr!(S("B-Z"), S("A-Z")))
  1825. assert_equal(S("HAL"), a)
  1826. a = S("ibm")
  1827. assert_nil(a.tr!(S("B-Z"), S("A-Z")))
  1828. assert_equal(S("ibm"), a)
  1829. a = "abc".force_encoding(Encoding::US_ASCII)
  1830. assert_nil(a.tr!(S("z"), S("\u0101")), '[ruby-core:22326]')
  1831. assert_equal(Encoding::US_ASCII, a.encoding, '[ruby-core:22326]')
  1832. end
  1833. def test_tr_s
  1834. assert_equal(S("hypo"), S("hello").tr_s(S("el"), S("yp")))
  1835. assert_equal(S("h*o"), S("hello").tr_s(S("el"), S("*")))
  1836. assert_equal("a".hash, "\u0101\u0101".tr_s("\u0101", "a").hash)
  1837. assert_equal(true, "\u3041\u3041".tr("\u3041", "a").ascii_only?)
  1838. end
  1839. def test_tr_s!
  1840. a = S("hello")
  1841. b = a.dup
  1842. assert_equal(S("hypo"), a.tr_s!(S("el"), S("yp")))
  1843. assert_equal(S("hypo"), a)
  1844. assert_equal(S("hello"), b)
  1845. a = S("hello")
  1846. assert_equal(S("h*o"), a.tr_s!(S("el"), S("*")))
  1847. assert_equal(S("h*o"), a)
  1848. end
  1849. def test_unpack
  1850. a = [S("cat"), S("wom"), S("x"), S("yy")]
  1851. assert_equal(a, S("catwomx yy ").unpack(S("A3A3A3A3")))
  1852. assert_equal([S("cat")], S("cat \000\000").unpack(S("A*")))
  1853. assert_equal([S("cwx"), S("wx"), S("x"), S("yy")],
  1854. S("cwx yy ").unpack(S("A3@1A3@2A3A3")))
  1855. assert_equal([S("cat"), S("wom"), S("x\000\000"), S("yy\000")],
  1856. S("catwomx\000\000yy\000").unpack(S("a3a3a3a3")))
  1857. assert_equal([S("cat \000\000")], S("cat \000\000").unpack(S("a*")))
  1858. assert_equal([S("ca")], S("catdog").unpack(S("a2")))
  1859. assert_equal([S("cat\000\000")],
  1860. S("cat\000\000\000\000\000dog").unpack(S("a5")))
  1861. assert_equal([S("01100001")], S("\x61").unpack(S("B8")))
  1862. assert_equal([S("01100001")], S("\x61").unpack(S("B*")))
  1863. assert_equal([S("0110000100110111")], S("\x61\x37").unpack(S("B16")))
  1864. assert_equal([S("01100001"), S("00110111")], S("\x61\x37").unpack(S("B8B8")))
  1865. assert_equal([S("0110")], S("\x60").unpack(S("B4")))
  1866. assert_equal([S("01")], S("\x40").unpack(S("B2")))
  1867. assert_equal([S("01100001")], S("\x86").unpack(S("b8")))
  1868. assert_equal([S("01100001")], S("\x86").unpack(S("b*")))
  1869. assert_equal([S("0110000100110111")], S("\x86\xec").unpack(S("b16")))
  1870. assert_equal([S("01100001"), S("00110111")], S("\x86\xec").unpack(S("b8b8")))
  1871. assert_equal([S("0110")], S("\x06").unpack(S("b4")))
  1872. assert_equal([S("01")], S("\x02").unpack(S("b2")))
  1873. assert_equal([ 65, 66, 67 ], S("ABC").unpack(S("C3")))
  1874. assert_equal([ 255, 66, 67 ], S("\377BC").unpack("C*"))
  1875. assert_equal([ 65, 66, 67 ], S("ABC").unpack("c3"))
  1876. assert_equal([ -1, 66, 67 ], S("\377BC").unpack("c*"))
  1877. assert_equal([S("4142"), S("0a"), S("1")], S("AB\n\x10").unpack(S("H4H2H1")))
  1878. assert_equal([S("1424"), S("a0"), S("2")], S("AB\n\x02").unpack(S("h4h2h1")))
  1879. assert_equal([S("abc\002defcat\001"), S(""), S("")],
  1880. S("abc=02def=\ncat=\n=01=\n").unpack(S("M9M3M4")))
  1881. assert_equal([S("hello\n")], S("aGVsbG8K\n").unpack(S("m")))
  1882. assert_equal([S("hello\nhello\n")], S(",:&5L;&\\*:&5L;&\\*\n").unpack(S("u")))
  1883. assert_equal([0xa9, 0x42, 0x2260], S("\xc2\xa9B\xe2\x89\xa0").unpack(S("U*")))
  1884. =begin
  1885. skipping "Not tested:
  1886. D,d & double-precision float, native format\\
  1887. E & double-precision float, little-endian byte order\\
  1888. e & single-precision float, little-endian byte order\\
  1889. F,f & single-precision float, native format\\
  1890. G & double-precision float, network (big-endian) byte order\\
  1891. g & single-precision float, network (big-endian) byte order\\
  1892. I & unsigned integer\\
  1893. i & integer\\
  1894. L & unsigned long\\
  1895. l & long\\
  1896. m & string encoded in base64 (uuencoded)\\
  1897. N & long, network (big-endian) byte order\\
  1898. n & short, network (big-endian) byte-order\\
  1899. P & pointer to a structure (fixed-length string)\\
  1900. p & pointer to a null-terminated string\\
  1901. S & unsigned short\\
  1902. s & short\\
  1903. V & long, little-endian byte order\\
  1904. v & short, little-endian byte order\\
  1905. X & back up a byte\\
  1906. x & null byte\\
  1907. Z & ASCII string (null padded, count is width)\\
  1908. "
  1909. =end
  1910. end
  1911. def test_upcase
  1912. assert_equal(S("HELLO"), S("hello").upcase)
  1913. assert_equal(S("HELLO"), S("hello").upcase)
  1914. assert_equal(S("HELLO"), S("HELLO").upcase)
  1915. assert_equal(S("ABC HELLO 123"), S("abc HELLO 123").upcase)
  1916. end
  1917. def test_upcase!
  1918. a = S("hello")
  1919. b = a.dup
  1920. assert_equal(S("HELLO"), a.upcase!)
  1921. assert_equal(S("HELLO"), a)
  1922. assert_equal(S("hello"), b)
  1923. a = S("HELLO")
  1924. assert_nil(a.upcase!)
  1925. assert_equal(S("HELLO"), a)
  1926. end
  1927. def test_upto
  1928. a = S("aa")
  1929. start = S("aa")
  1930. count = 0
  1931. assert_equal(S("aa"), a.upto(S("zz")) {|s|
  1932. assert_equal(start, s)
  1933. start.succ!
  1934. count += 1
  1935. })
  1936. assert_equal(676, count)
  1937. end
  1938. def test_upto_numeric
  1939. a = S("00")
  1940. start = S("00")
  1941. count = 0
  1942. assert_equal(S("00"), a.upto(S("23")) {|s|
  1943. assert_equal(start, s, "[ruby-dev:39361]")
  1944. assert_equal(Encoding::US_ASCII, s.encoding)
  1945. start.succ!
  1946. count += 1
  1947. })
  1948. assert_equal(24, count, "[ruby-dev:39361]")
  1949. end
  1950. def test_upto_nonalnum
  1951. first = S("\u3041")
  1952. last = S("\u3093")
  1953. count = 0
  1954. assert_equal(first, first.upto(last) {|s|
  1955. count += 1
  1956. s.replace(last)
  1957. })
  1958. assert_equal(83, count, "[ruby-dev:39626]")
  1959. end
  1960. def test_mod_check
  1961. assert_raise(RuntimeError) {
  1962. s = ""
  1963. s.sub!(/\A/) { s.replace "z" * 2000; "zzz" }
  1964. }
  1965. end
  1966. def test_frozen_check
  1967. assert_raise(FrozenError) {
  1968. s = ""
  1969. s.sub!(/\A/) { s.freeze; "zzz" }
  1970. }
  1971. end
  1972. class S2 < String
  1973. end
  1974. def test_str_new4
  1975. s = (0..54).to_a.join # length = 100
  1976. s2 = S2.new(s[10,90])
  1977. s3 = s2[10,80]
  1978. assert_equal((10..54).to_a.to_a.join, s2)
  1979. assert_equal((15..54).to_a.to_a.join, s3)
  1980. end
  1981. def test_rb_str_new4
  1982. s = "a" * 100
  1983. s2 = s[10,90]
  1984. assert_equal("a" * 90, s2)
  1985. s3 = s2[10,80]
  1986. assert_equal("a" * 80, s3)
  1987. end
  1988. class StringLike
  1989. def initialize(str)
  1990. @str = str
  1991. end
  1992. def to_str
  1993. @str
  1994. end
  1995. end
  1996. def test_rb_str_to_str
  1997. assert_equal("ab", "a" + StringLike.new("b"))
  1998. end
  1999. def test_rb_str_shared_replace
  2000. s = "a" * 100
  2001. s.succ!
  2002. assert_equal("a" * 99 + "b", s)
  2003. s = ""
  2004. s.succ!
  2005. assert_equal("", s)
  2006. end
  2007. def test_times
  2008. assert_raise(ArgumentError) { "a" * (-1) }
  2009. end
  2010. def test_splice!
  2011. l = S("1234\n234\n34\n4\n")
  2012. assert_equal(S("1234\n"), l.slice!(/\A.*\n/), "[ruby-dev:31665]")
  2013. assert_equal(S("234\n"), l.slice!(/\A.*\n/), "[ruby-dev:31665]")
  2014. assert_equal(S("34\n"), l.slice!(/\A.*\n/), "[ruby-dev:31665]")
  2015. assert_equal(S("4\n"), l.slice!(/\A.*\n/), "[ruby-dev:31665]")
  2016. assert_nil(l.slice!(/\A.*\n/), "[ruby-dev:31665]")
  2017. end
  2018. def test_times2
  2019. s1 = ''
  2020. 100.times {|n|
  2021. s2 = "a" * n
  2022. assert_equal(s1, s2)
  2023. s1 << 'a'
  2024. }
  2025. assert_raise(ArgumentError) { "foo" * (-1) }
  2026. end
  2027. def test_respond_to
  2028. o = Object.new
  2029. def o.respond_to?(arg) [:to_str].include?(arg) ? nil : super end
  2030. def o.to_str() "" end
  2031. def o.==(other) "" == other end
  2032. assert_equal(false, "" == o)
  2033. end
  2034. def test_match_method
  2035. assert_equal("bar", "foobarbaz".match(/bar/).to_s)
  2036. o = Regexp.new('foo')
  2037. def o.match(x, y, z); x + y + z; end
  2038. assert_equal("foobarbaz", "foo".match(o, "bar", "baz"))
  2039. x = nil
  2040. "foo".match(o, "bar", "baz") {|y| x = y }
  2041. assert_equal("foobarbaz", x)
  2042. assert_raise(ArgumentError) { "foo".match }
  2043. end
  2044. def test_match_p_regexp
  2045. /backref/ =~ 'backref'
  2046. # must match here, but not in a separate method, e.g., assert_send,
  2047. # to check if $~ is affected or not.
  2048. assert_equal(true, "".match?(//))
  2049. assert_equal(true, :abc.match?(/.../))
  2050. assert_equal(true, 'abc'.match?(/b/))
  2051. assert_equal(true, 'abc'.match?(/b/, 1))
  2052. assert_equal(true, 'abc'.match?(/../, 1))
  2053. assert_equal(true, 'abc'.match?(/../, -2))
  2054. assert_equal(false, 'abc'.match?(/../, -4))
  2055. assert_equal(false, 'abc'.match?(/../, 4))
  2056. assert_equal(true, "\u3042xx".match?(/../, 1))
  2057. assert_equal(false, "\u3042x".match?(/../, 1))
  2058. assert_equal(true, ''.match?(/\z/))
  2059. assert_equal(true, 'abc'.match?(/\z/))
  2060. assert_equal(true, 'Ruby'.match?(/R.../))
  2061. assert_equal(false, 'Ruby'.match?(/R.../, 1))
  2062. assert_equal(false, 'Ruby'.match?(/P.../))
  2063. assert_equal('backref', $&)
  2064. end
  2065. def test_match_p_string
  2066. /backref/ =~ 'backref'
  2067. # must match here, but not in a separate method, e.g., assert_send,
  2068. # to check if $~ is affected or not.
  2069. assert_equal(true, "".match?(''))
  2070. assert_equal(true, :abc.match?('...'))
  2071. assert_equal(true, 'abc'.match?('b'))
  2072. assert_equal(true, 'abc'.match?('b', 1))
  2073. assert_equal(true, 'abc'.match?('..', 1))
  2074. assert_equal(true, 'abc'.match?('..', -2))
  2075. assert_equal(false, 'abc'.match?('..', -4))
  2076. assert_equal(false, 'abc'.match?('..', 4))
  2077. assert_equal(true, "\u3042xx".match?('..', 1))
  2078. assert_equal(false, "\u3042x".match?('..', 1))
  2079. assert_equal(true, ''.match?('\z'))
  2080. assert_equal(true, 'abc'.match?('\z'))
  2081. assert_equal(true, 'Ruby'.match?('R...'))
  2082. assert_equal(false, 'Ruby'.match?('R...', 1))
  2083. assert_equal(false, 'Ruby'.match?('P...'))
  2084. assert_equal('backref', $&)
  2085. end
  2086. def test_clear
  2087. s = "foo" * 100
  2088. s.clear
  2089. assert_equal("", s)
  2090. end
  2091. def test_to_s_2
  2092. c = Class.new(String)
  2093. s = c.new
  2094. s.replace("foo")
  2095. assert_equal("foo", s.to_s)
  2096. assert_instance_of(String, s.to_s)
  2097. end
  2098. def test_inspect_nul
  2099. bug8290 = '[ruby-core:54458]'
  2100. s = "\0" + "12"
  2101. assert_equal '"\u000012"', s.inspect, bug8290
  2102. s = "\0".b + "12"
  2103. assert_equal '"\x0012"', s.inspect, bug8290
  2104. end
  2105. def test_partition
  2106. assert_equal(%w(he l lo), "hello".partition(/l/))
  2107. assert_equal(%w(he l lo), "hello".partition("l"))
  2108. assert_raise(TypeError) { "hello".partition(1) }
  2109. def (hyphen = Object.new).to_str; "-"; end
  2110. assert_equal(%w(foo - bar), "foo-bar".partition(hyphen), '[ruby-core:23540]')
  2111. bug6206 = '[ruby-dev:45441]'
  2112. Encoding.list.each do |enc|
  2113. next unless enc.ascii_compatible?
  2114. s = S("a:".force_encoding(enc))
  2115. assert_equal([enc]*3, s.partition("|").map(&:encoding), bug6206)
  2116. end
  2117. assert_equal(["\u30E6\u30FC\u30B6", "@", "\u30C9\u30E1.\u30A4\u30F3"],
  2118. "\u30E6\u30FC\u30B6@\u30C9\u30E1.\u30A4\u30F3".partition(/[@.]/))
  2119. bug = '[ruby-core:82911]'
  2120. hello = "hello"
  2121. hello.partition("hi").map(&:upcase!)
  2122. assert_equal("hello", hello, bug)
  2123. assert_equal(["", "", "foo"], "foo".partition(/^=*/))
  2124. end
  2125. def test_rpartition
  2126. assert_equal(%w(hel l o), "hello".rpartition(/l/))
  2127. assert_equal(%w(hel l o), "hello".rpartition("l"))
  2128. assert_raise(TypeError) { "hello".rpartition(1) }
  2129. def (hyphen = Object.new).to_str; "-"; end
  2130. assert_equal(%w(foo - bar), "foo-bar".rpartition(hyphen), '[ruby-core:23540]')
  2131. bug6206 = '[ruby-dev:45441]'
  2132. Encoding.list.each do |enc|
  2133. next unless enc.ascii_compatible?
  2134. s = S("a:".force_encoding(enc))
  2135. assert_equal([enc]*3, s.rpartition("|").map(&:encoding), bug6206)
  2136. end
  2137. bug8138 = '[ruby-dev:47183]'
  2138. assert_equal(["\u30E6\u30FC\u30B6@\u30C9\u30E1", ".", "\u30A4\u30F3"],
  2139. "\u30E6\u30FC\u30B6@\u30C9\u30E1.\u30A4\u30F3".rpartition(/[@.]/), bug8138)
  2140. bug = '[ruby-core:82911]'
  2141. hello = "hello"
  2142. hello.rpartition("hi").map(&:upcase!)
  2143. assert_equal("hello", hello, bug)
  2144. end
  2145. def test_setter
  2146. assert_raise(TypeError) { $/ = 1 }
  2147. name = "\u{5206 884c}"
  2148. assert_separately([], <<-"end;") # do
  2149. alias $#{name} $/
  2150. assert_raise_with_message(TypeError, /\\$#{name}/) { $#{name} = 1 }
  2151. end;
  2152. end
  2153. def test_to_id
  2154. c = Class.new
  2155. c.class_eval do
  2156. def initialize
  2157. @foo = :foo
  2158. end
  2159. end
  2160. assert_raise(TypeError) do
  2161. c.class_eval { attr 1 }
  2162. end
  2163. o = Object.new
  2164. def o.to_str; :foo; end
  2165. assert_raise(TypeError) do
  2166. c.class_eval { attr 1 }
  2167. end
  2168. class << o;remove_method :to_str;end
  2169. def o.to_str; "foo"; end
  2170. assert_nothing_raised do
  2171. c.class_eval { attr o }
  2172. end
  2173. assert_equal(:foo, c.new.foo)
  2174. end
  2175. def test_gsub_enumerator
  2176. assert_normal_exit %q{"abc".gsub(/./).next}, "[ruby-dev:34828]"
  2177. end
  2178. def test_clear_nonasciicompat
  2179. assert_equal("", "\u3042".encode("ISO-2022-JP").clear)
  2180. end
  2181. def test_try_convert
  2182. assert_equal(nil, String.try_convert(1))
  2183. assert_equal("foo", String.try_convert("foo"))
  2184. end
  2185. def test_substr_negative_begin
  2186. assert_equal("\u3042", ("\u3042" * 100)[-1])
  2187. end
  2188. =begin
  2189. def test_compare_different_encoding_string
  2190. s1 = "\xff".force_encoding("UTF-8")
  2191. s2 = "\xff".force_encoding("ISO-2022-JP")
  2192. assert_equal([-1, 1], [s1 <=> s2, s2 <=> s1].sort)
  2193. end
  2194. =end
  2195. def test_casecmp
  2196. assert_equal(0, "FoO".casecmp("fOO"))
  2197. assert_equal(1, "FoO".casecmp("BaR"))
  2198. assert_equal(-1, "baR".casecmp("FoO"))
  2199. assert_equal(1, "\u3042B".casecmp("\u3042a"))
  2200. assert_nil("foo".casecmp(:foo))
  2201. assert_nil("foo".casecmp(Object.new))
  2202. o = Object.new
  2203. def o.to_str; "fOO"; end
  2204. assert_equal(0, "FoO".casecmp(o))
  2205. end
  2206. def test_casecmp?
  2207. assert_equal(true, 'FoO'.casecmp?('fOO'))
  2208. assert_equal(false, 'FoO'.casecmp?('BaR'))
  2209. assert_equal(false, 'baR'.casecmp?('FoO'))
  2210. assert_equal(true, 'äöü'.casecmp?('ÄÖÜ'))
  2211. assert_nil("foo".casecmp?(:foo))
  2212. assert_nil("foo".casecmp?(Object.new))
  2213. o = Object.new
  2214. def o.to_str; "fOO"; end
  2215. assert_equal(true, "FoO".casecmp?(o))
  2216. end
  2217. def test_upcase2
  2218. assert_equal("\u3042AB", "\u3042aB".upcase)
  2219. end
  2220. def test_downcase2
  2221. assert_equal("\u3042ab", "\u3042aB".downcase)
  2222. end
  2223. def test_rstrip
  2224. assert_equal(" hello", " hello ".rstrip)
  2225. assert_equal("\u3042", "\u3042 ".rstrip)
  2226. assert_raise(Encoding::CompatibilityError) { "\u3042".encode("ISO-2022-JP").rstrip }
  2227. end
  2228. def test_rstrip_bang
  2229. s1 = S(" hello ")
  2230. assert_equal(" hello", s1.rstrip!)
  2231. assert_equal(" hello", s1)
  2232. s2 = S("\u3042 ")
  2233. assert_equal("\u3042", s2.rstrip!)
  2234. assert_equal("\u3042", s2)
  2235. s3 = S(" \u3042")
  2236. assert_equal(nil, s3.rstrip!)
  2237. assert_equal(" \u3042", s3)
  2238. s4 = S("\u3042")
  2239. assert_equal(nil, s4.rstrip!)
  2240. assert_equal("\u3042", s4)
  2241. assert_raise(Encoding::CompatibilityError) { "\u3042".encode("ISO-2022-JP").rstrip! }
  2242. end
  2243. def test_lstrip
  2244. assert_equal("hello ", " hello ".lstrip)
  2245. assert_equal("\u3042", " \u3042".lstrip)
  2246. end
  2247. def test_lstrip_bang
  2248. s1 = S(" hello ")
  2249. assert_equal("hello ", s1.lstrip!)
  2250. assert_equal("hello ", s1)
  2251. s2 = S("\u3042 ")
  2252. assert_equal(nil, s2.lstrip!)
  2253. assert_equal("\u3042 ", s2)
  2254. s3 = S(" \u3042")
  2255. assert_equal("\u3042", s3.lstrip!)
  2256. assert_equal("\u3042", s3)
  2257. s4 = S("\u3042")
  2258. assert_equal(nil, s4.lstrip!)
  2259. assert_equal("\u3042", s4)
  2260. end
  2261. def test_delete_prefix
  2262. assert_raise(TypeError) { 'hello'.delete_prefix(nil) }
  2263. assert_raise(TypeError) { 'hello'.delete_prefix(1) }
  2264. assert_raise(TypeError) { 'hello'.delete_prefix(/hel/) }
  2265. s = S("hello")
  2266. assert_equal("lo", s.delete_prefix('hel'))
  2267. assert_equal("hello", s)
  2268. s = S("hello")
  2269. assert_equal("hello", s.delete_prefix('lo'))
  2270. assert_equal("hello", s)
  2271. s = S("\u{3053 3093 306b 3061 306f}")
  2272. assert_equal("\u{306b 3061 306f}", s.delete_prefix("\u{3053 3093}"))
  2273. assert_equal("\u{3053 3093 306b 3061 306f}", s)
  2274. s = S("\u{3053 3093 306b 3061 306f}")
  2275. assert_equal("\u{3053 3093 306b 3061 306f}", s.delete_prefix('hel'))
  2276. assert_equal("\u{3053 3093 306b 3061 306f}", s)
  2277. s = S("hello")
  2278. assert_equal("hello", s.delete_prefix("\u{3053 3093}"))
  2279. assert_equal("hello", s)
  2280. # skip if argument is a broken string
  2281. s = S("\xe3\x81\x82")
  2282. assert_equal("\xe3\x81\x82", s.delete_prefix("\xe3"))
  2283. assert_equal("\xe3\x81\x82", s)
  2284. s = S("\x95\x5c").force_encoding("Shift_JIS")
  2285. assert_equal("\x95\x5c".force_encoding("Shift_JIS"), s.delete_prefix("\x95"))
  2286. assert_equal("\x95\x5c".force_encoding("Shift_JIS"), s)
  2287. # clear coderange
  2288. s = S("\u{3053 3093}hello")
  2289. assert_not_predicate(s, :ascii_only?)
  2290. assert_predicate(s.delete_prefix("\u{3053 3093}"), :ascii_only?)
  2291. # argument should be converted to String
  2292. klass = Class.new { def to_str; 'a'; end }
  2293. s = S("abba")
  2294. assert_equal("bba", s.delete_prefix(klass.new))
  2295. assert_equal("abba", s)
  2296. end
  2297. def test_delete_prefix_bang
  2298. assert_raise(TypeError) { 'hello'.delete_prefix!(nil) }
  2299. assert_raise(TypeError) { 'hello'.delete_prefix!(1) }
  2300. assert_raise(TypeError) { 'hello'.delete_prefix!(/hel/) }
  2301. s = S("hello")
  2302. assert_equal("lo", s.delete_prefix!('hel'))
  2303. assert_equal("lo", s)
  2304. s = S("hello")
  2305. assert_equal(nil, s.delete_prefix!('lo'))
  2306. assert_equal("hello", s)
  2307. s = S("\u{3053 3093 306b 3061 306f}")
  2308. assert_equal("\u{306b 3061 306f}", s.delete_prefix!("\u{3053 3093}"))
  2309. assert_equal("\u{306b 3061 306f}", s)
  2310. s = S("\u{3053 3093 306b 3061 306f}")
  2311. assert_equal(nil, s.delete_prefix!('hel'))
  2312. assert_equal("\u{3053 3093 306b 3061 306f}", s)
  2313. s = S("hello")
  2314. assert_equal(nil, s.delete_prefix!("\u{3053 3093}"))
  2315. assert_equal("hello", s)
  2316. # skip if argument is a broken string
  2317. s = S("\xe3\x81\x82")
  2318. assert_equal(nil, s.delete_prefix!("\xe3"))
  2319. assert_equal("\xe3\x81\x82", s)
  2320. # clear coderange
  2321. s = S("\u{3053 3093}hello")
  2322. assert_not_predicate(s, :ascii_only?)
  2323. assert_predicate(s.delete_prefix!("\u{3053 3093}"), :ascii_only?)
  2324. # argument should be converted to String
  2325. klass = Class.new { def to_str; 'a'; end }
  2326. s = S("abba")
  2327. assert_equal("bba", s.delete_prefix!(klass.new))
  2328. assert_equal("bba", s)
  2329. s = S("ax").freeze
  2330. assert_raise_with_message(FrozenError, /frozen/) {s.delete_prefix!("a")}
  2331. s = S("ax")
  2332. o = Struct.new(:s).new(s)
  2333. def o.to_str
  2334. s.freeze
  2335. "a"
  2336. end
  2337. assert_raise_with_message(FrozenError, /frozen/) {s.delete_prefix!(o)}
  2338. end
  2339. def test_delete_suffix
  2340. assert_raise(TypeError) { 'hello'.delete_suffix(nil) }
  2341. assert_raise(TypeError) { 'hello'.delete_suffix(1) }
  2342. assert_raise(TypeError) { 'hello'.delete_suffix(/hel/) }
  2343. s = S("hello")
  2344. assert_equal("hel", s.delete_suffix('lo'))
  2345. assert_equal("hello", s)
  2346. s = S("hello")
  2347. assert_equal("hello", s.delete_suffix('he'))
  2348. assert_equal("hello", s)
  2349. s = S("\u{3053 3093 306b 3061 306f}")
  2350. assert_equal("\u{3053 3093 306b}", s.delete_suffix("\u{3061 306f}"))
  2351. assert_equal("\u{3053 3093 306b 3061 306f}", s)
  2352. s = S("\u{3053 3093 306b 3061 306f}")
  2353. assert_equal("\u{3053 3093 306b 3061 306f}", s.delete_suffix('lo'))
  2354. assert_equal("\u{3053 3093 306b 3061 306f}", s)
  2355. s = S("hello")
  2356. assert_equal("hello", s.delete_suffix("\u{3061 306f}"))
  2357. assert_equal("hello", s)
  2358. # skip if argument is a broken string
  2359. s = S("\xe3\x81\x82")
  2360. assert_equal("\xe3\x81\x82", s.delete_suffix("\x82"))
  2361. assert_equal("\xe3\x81\x82", s)
  2362. # clear coderange
  2363. s = S("hello\u{3053 3093}")
  2364. assert_not_predicate(s, :ascii_only?)
  2365. assert_predicate(s.delete_suffix("\u{3053 3093}"), :ascii_only?)
  2366. # argument should be converted to String
  2367. klass = Class.new { def to_str; 'a'; end }
  2368. s = S("abba")
  2369. assert_equal("abb", s.delete_suffix(klass.new))
  2370. assert_equal("abba", s)
  2371. # chomp removes any of "\n", "\r\n", "\r" when "\n" is specified,
  2372. # but delete_suffix does not
  2373. s = "foo\n"
  2374. assert_equal("foo", s.delete_suffix("\n"))
  2375. s = "foo\r\n"
  2376. assert_equal("foo\r", s.delete_suffix("\n"))
  2377. s = "foo\r"
  2378. assert_equal("foo\r", s.delete_suffix("\n"))
  2379. end
  2380. def test_delete_suffix_bang
  2381. assert_raise(TypeError) { 'hello'.delete_suffix!(nil) }
  2382. assert_raise(TypeError) { 'hello'.delete_suffix!(1) }
  2383. assert_raise(TypeError) { 'hello'.delete_suffix!(/hel/) }
  2384. s = S("hello").freeze
  2385. assert_raise_with_message(FrozenError, /frozen/) {s.delete_suffix!('lo')}
  2386. s = S("ax")
  2387. o = Struct.new(:s).new(s)
  2388. def o.to_str
  2389. s.freeze
  2390. "x"
  2391. end
  2392. assert_raise_with_message(FrozenError, /frozen/) {s.delete_suffix!(o)}
  2393. s = S("hello")
  2394. assert_equal("hel", s.delete_suffix!('lo'))
  2395. assert_equal("hel", s)
  2396. s = S("hello")
  2397. assert_equal(nil, s.delete_suffix!('he'))
  2398. assert_equal("hello", s)
  2399. s = S("\u{3053 3093 306b 3061 306f}")
  2400. assert_equal("\u{3053 3093 306b}", s.delete_suffix!("\u{3061 306f}"))
  2401. assert_equal("\u{3053 3093 306b}", s)
  2402. s = S("\u{3053 3093 306b 3061 306f}")
  2403. assert_equal(nil, s.delete_suffix!('lo'))
  2404. assert_equal("\u{3053 3093 306b 3061 306f}", s)
  2405. s = S("hello")
  2406. assert_equal(nil, s.delete_suffix!("\u{3061 306f}"))
  2407. assert_equal("hello", s)
  2408. # skip if argument is a broken string
  2409. s = S("\xe3\x81\x82")
  2410. assert_equal(nil, s.delete_suffix!("\x82"))
  2411. assert_equal("\xe3\x81\x82", s)
  2412. s = S("\x95\x5c").force_encoding("Shift_JIS")
  2413. assert_equal(nil, s.delete_suffix!("\x5c"))
  2414. assert_equal("\x95\x5c".force_encoding("Shift_JIS"), s)
  2415. # clear coderange
  2416. s = S("hello\u{3053 3093}")
  2417. assert_not_predicate(s, :ascii_only?)
  2418. assert_predicate(s.delete_suffix!("\u{3053 3093}"), :ascii_only?)
  2419. # argument should be converted to String
  2420. klass = Class.new { def to_str; 'a'; end }
  2421. s = S("abba")
  2422. assert_equal("abb", s.delete_suffix!(klass.new))
  2423. assert_equal("abb", s)
  2424. # chomp removes any of "\n", "\r\n", "\r" when "\n" is specified,
  2425. # but delete_suffix does not
  2426. s = "foo\n"
  2427. assert_equal("foo", s.delete_suffix!("\n"))
  2428. s = "foo\r\n"
  2429. assert_equal("foo\r", s.delete_suffix!("\n"))
  2430. s = "foo\r"
  2431. assert_equal(nil, s.delete_suffix!("\n"))
  2432. end
  2433. =begin
  2434. def test_symbol_table_overflow
  2435. assert_in_out_err([], <<-INPUT, [], /symbol table overflow \(symbol [a-z]{8}\) \(RuntimeError\)/)
  2436. ("aaaaaaaa".."zzzzzzzz").each {|s| s.to_sym }
  2437. INPUT
  2438. end
  2439. =end
  2440. def test_nesting_shared
  2441. a = ('a' * 24).encode(Encoding::ASCII).gsub('x', '')
  2442. hash = {}
  2443. hash[a] = true
  2444. assert_equal(('a' * 24), a)
  2445. 4.times { GC.start }
  2446. assert_equal(('a' * 24), a, '[Bug #15792]')
  2447. end
  2448. def test_nesting_shared_b
  2449. a = ('j' * 24).b.b
  2450. eval('', binding, a)
  2451. assert_equal(('j' * 24), a)
  2452. 4.times { GC.start }
  2453. assert_equal(('j' * 24), a, '[Bug #15934]')
  2454. end
  2455. def test_shared_force_encoding
  2456. s = "\u{3066}\u{3059}\u{3068}".gsub(//, '')
  2457. h = {}
  2458. h[s] = nil
  2459. k = h.keys[0]
  2460. assert_equal(s, k, '[ruby-dev:39068]')
  2461. assert_equal(Encoding::UTF_8, k.encoding, '[ruby-dev:39068]')
  2462. s.dup.force_encoding(Encoding::ASCII_8BIT).gsub(//, '')
  2463. k = h.keys[0]
  2464. assert_equal(s, k, '[ruby-dev:39068]')
  2465. assert_equal(Encoding::UTF_8, k.encoding, '[ruby-dev:39068]')
  2466. end
  2467. def test_ascii_incomat_inspect
  2468. bug4081 = '[ruby-core:33283]'
  2469. WIDE_ENCODINGS.each do |e|
  2470. assert_equal('"abc"', "abc".encode(e).inspect)
  2471. assert_equal('"\\u3042\\u3044\\u3046"', "\u3042\u3044\u3046".encode(e).inspect)
  2472. assert_equal('"ab\\"c"', "ab\"c".encode(e).inspect, bug4081)
  2473. end
  2474. begin
  2475. verbose, $VERBOSE = $VERBOSE, nil
  2476. ext = Encoding.default_external
  2477. Encoding.default_external = "us-ascii"
  2478. $VERBOSE = verbose
  2479. i = "abc\"\\".force_encoding("utf-8").inspect
  2480. ensure
  2481. $VERBOSE = nil
  2482. Encoding.default_external = ext
  2483. $VERBOSE = verbose
  2484. end
  2485. assert_equal('"abc\\"\\\\"', i, bug4081)
  2486. end
  2487. def test_dummy_inspect
  2488. assert_equal('"\e\x24\x42\x22\x4C\x22\x68\e\x28\x42"',
  2489. "\u{ffe2}\u{2235}".encode("cp50220").inspect)
  2490. end
  2491. def test_prepend
  2492. assert_equal(S("hello world!"), "!".prepend("hello ", "world"))
  2493. b = S("ue")
  2494. assert_equal(S("ueueue"), b.prepend(b, b))
  2495. foo = Object.new
  2496. def foo.to_str
  2497. "b"
  2498. end
  2499. assert_equal(S("ba"), "a".prepend(foo))
  2500. a = S("world")
  2501. b = S("hello ")
  2502. a.prepend(b)
  2503. assert_equal(S("hello world"), a)
  2504. assert_equal(S("hello "), b)
  2505. end
  2506. def u(str)
  2507. str.force_encoding(Encoding::UTF_8)
  2508. end
  2509. def test_byteslice
  2510. assert_equal("h", "hello".byteslice(0))
  2511. assert_equal(nil, "hello".byteslice(5))
  2512. assert_equal("o", "hello".byteslice(-1))
  2513. assert_equal(nil, "hello".byteslice(-6))
  2514. assert_equal("", "hello".byteslice(0, 0))
  2515. assert_equal("hello", "hello".byteslice(0, 6))
  2516. assert_equal("hello", "hello".byteslice(0, 6))
  2517. assert_equal("", "hello".byteslice(5, 1))
  2518. assert_equal("o", "hello".byteslice(-1, 6))
  2519. assert_equal(nil, "hello".byteslice(-6, 1))
  2520. assert_equal(nil, "hello".byteslice(0, -1))
  2521. assert_equal("h", "hello".byteslice(0..0))
  2522. assert_equal("", "hello".byteslice(5..0))
  2523. assert_equal("o", "hello".byteslice(4..5))
  2524. assert_equal(nil, "hello".byteslice(6..0))
  2525. assert_equal("", "hello".byteslice(-1..0))
  2526. assert_equal("llo", "hello".byteslice(-3..5))
  2527. assert_equal(u("\x81"), "\u3042".byteslice(1))
  2528. assert_equal(u("\x81\x82"), "\u3042".byteslice(1, 2))
  2529. assert_equal(u("\x81\x82"), "\u3042".byteslice(1..2))
  2530. assert_equal(u("\x82")+("\u3042"*9), ("\u3042"*10).byteslice(2, 28))
  2531. bug7954 = '[ruby-dev:47108]'
  2532. assert_equal(false, "\u3042".byteslice(0, 2).valid_encoding?, bug7954)
  2533. assert_equal(false, ("\u3042"*10).byteslice(0, 20).valid_encoding?, bug7954)
  2534. end
  2535. def test_unknown_string_option
  2536. str = nil
  2537. assert_nothing_raised(SyntaxError) do
  2538. eval(%{
  2539. str = begin"hello"end
  2540. })
  2541. end
  2542. assert_equal "hello", str
  2543. end
  2544. def test_eq_tilde_can_be_overridden
  2545. assert_separately([], <<-RUBY)
  2546. class String
  2547. undef =~
  2548. def =~(str)
  2549. "foo"
  2550. end
  2551. end
  2552. assert_equal("foo", "" =~ //)
  2553. RUBY
  2554. end
  2555. class Bug9581 < String
  2556. def =~ re; :foo end
  2557. end
  2558. def test_regexp_match_subclass
  2559. s = Bug9581.new("abc")
  2560. r = /abc/
  2561. assert_equal(:foo, s =~ r)
  2562. assert_equal(:foo, s.send(:=~, r))
  2563. assert_equal(:foo, s.send(:=~, /abc/))
  2564. assert_equal(:foo, s =~ /abc/, "should not use optimized instruction")
  2565. end
  2566. def test_LSHIFT_neary_long_max
  2567. return unless @cls == String
  2568. assert_ruby_status([], <<-'end;', '[ruby-core:61886] [Bug #9709]', timeout: 20)
  2569. begin
  2570. a = "a" * 0x4000_0000
  2571. a << "a" * 0x1_0000
  2572. rescue NoMemoryError
  2573. end
  2574. end;
  2575. end if [0].pack("l!").bytesize < [nil].pack("p").bytesize
  2576. # enable only when string size range is smaller than memory space
  2577. def test_uplus_minus
  2578. str = "foo"
  2579. assert_not_predicate(str, :frozen?)
  2580. assert_not_predicate(+str, :frozen?)
  2581. assert_predicate(-str, :frozen?)
  2582. assert_same(str, +str)
  2583. assert_not_same(str, -str)
  2584. str = "bar".freeze
  2585. assert_predicate(str, :frozen?)
  2586. assert_not_predicate(+str, :frozen?)
  2587. assert_predicate(-str, :frozen?)
  2588. assert_not_same(str, +str)
  2589. assert_same(str, -str)
  2590. bar = %w(b a r).join('')
  2591. assert_same(str, -bar, "uminus deduplicates [Feature #13077]")
  2592. end
  2593. def test_uminus_no_freeze_not_bare
  2594. str = @cls.new("foo")
  2595. assert_instance_of(@cls, -str)
  2596. assert_equal(false, str.frozen?)
  2597. str = @cls.new("foo")
  2598. str.instance_variable_set(:@iv, 1)
  2599. assert_instance_of(@cls, -str)
  2600. assert_equal(false, str.frozen?)
  2601. assert_equal(1, str.instance_variable_get(:@iv))
  2602. str = @cls.new("foo")
  2603. assert_instance_of(@cls, -str)
  2604. assert_equal(false, str.frozen?)
  2605. end
  2606. def test_ord
  2607. assert_equal(97, "a".ord)
  2608. assert_equal(97, "abc".ord)
  2609. assert_equal(0x3042, "\u3042\u3043".ord)
  2610. assert_raise(ArgumentError) { "".ord }
  2611. end
  2612. def test_chr
  2613. assert_equal("a", "abcde".chr)
  2614. assert_equal("a", "a".chr)
  2615. assert_equal("\u3042", "\u3042\u3043".chr)
  2616. assert_equal('', ''.chr)
  2617. end
  2618. def test_substr_code_range
  2619. data = "\xff" + "a"*200
  2620. assert_not_predicate(data, :valid_encoding?)
  2621. assert_predicate(data[100..-1], :valid_encoding?)
  2622. end
  2623. end
  2624. class TestString2 < TestString
  2625. def initialize(*args)
  2626. super
  2627. @cls = S2
  2628. end
  2629. end