PageRenderTime 57ms CodeModel.GetById 13ms RepoModel.GetById 1ms 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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file