PageRenderTime 66ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/projects/jruby-1.7.3/test/rubicon/test_kernel.rb

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Ruby | 2209 lines | 1839 code | 309 blank | 61 comment | 49 complexity | c8d1523485bcb18b3897f58ddedfd606 MD5 | raw file
  1. require 'test/unit'
  2. # FIXME: This has platform-specific bits in it
  3. class TestKernel < Test::Unit::TestCase
  4. def test_EQUAL # '=='
  5. o1 = Object.new
  6. o2 = Object.new
  7. assert(o1 == o1)
  8. assert(o2 == o2)
  9. assert(o1 != o2)
  10. assert(!(o1 == o2))
  11. end
  12. def test_MATCH # '=~'
  13. o1 = Object.new
  14. o2 = Object.new
  15. assert(!(o1 =~ o1))
  16. assert(!(o2 =~ o2))
  17. assert(o1 !~ o2)
  18. assert(!(o1 =~ o2))
  19. end
  20. def test_VERY_EQUAL # '==='
  21. o1 = Object.new
  22. o2 = Object.new
  23. assert(o1 === o1)
  24. assert(o2 === o2)
  25. assert(!(o1 === o2))
  26. end
  27. def test___id__
  28. # naive test - no 2 ids the same
  29. objs = []
  30. ObjectSpace.each_object { |obj| objs << obj.__id__ }
  31. objs.sort!
  32. 0.upto(objs.size-2) {|i| assert(objs[i] != objs[i+1]) }
  33. assert_equal(1.__id__, (3-2).__id__)
  34. assert_instance_of(Fixnum, 1.__id__)
  35. end
  36. class SendTest
  37. def send_test1
  38. "send1"
  39. end
  40. def send_test2(a, b)
  41. a + b
  42. end
  43. end
  44. def test___send__
  45. t = SendTest.new
  46. assert_equal("send1", t.__send__(:send_test1))
  47. assert_equal(99, t.__send__("send_test2", 44, 55))
  48. end
  49. def test_class
  50. assert_instance_of(Class, 1.class)
  51. assert_equal(Fixnum, 1.class)
  52. assert_equal(Class, TestKernel.class)
  53. assert_equal(Class, TestKernel.class.class)
  54. assert_equal(Module, Enumerable.class)
  55. end
  56. class CloneTest
  57. attr_accessor :str
  58. end
  59. def test_clone
  60. s1 = CloneTest.new
  61. s1.str = "hello"
  62. s2 = s1.clone
  63. assert(s1.str == s2.str)
  64. assert(s1.str.__id__ == s2.str.__id__)
  65. assert(s1.__id__ != s2.__id__)
  66. foo = Object.new
  67. def foo.test
  68. "test"
  69. end
  70. bar = foo.clone
  71. def bar.test2
  72. "test2"
  73. end
  74. assert_equal("test2", bar.test2)
  75. assert_equal("test", bar.test)
  76. assert_equal("test", foo.test)
  77. Version.less_than("1.7") do
  78. assert_raise(NameError) { foo.test2 }
  79. end
  80. Version.greater_or_equal("1.7") do
  81. assert_raise(NoMethodError) { foo.test2 }
  82. end
  83. end
  84. class DisplayTest
  85. attr :val
  86. def write(obj)
  87. @val = "!#{obj.to_s}!"
  88. end
  89. end
  90. def test_display
  91. dt = DisplayTest.new
  92. assert_nil("hello".display(dt))
  93. assert_equal("!hello!", dt.val)
  94. save = $>
  95. begin
  96. $> = dt
  97. assert_nil("hello".display)
  98. assert_equal("!hello!", dt.val)
  99. ensure
  100. $> = save
  101. end
  102. end
  103. def test_dup
  104. s1 = CloneTest.new
  105. s1.str = "hello"
  106. s2 = s1.dup
  107. assert(s1.str == s2.str)
  108. assert(s1.str.__id__ == s2.str.__id__)
  109. assert(s1.__id__ != s2.__id__)
  110. end
  111. def test_eql?
  112. o1 = Object.new
  113. o2 = Object.new
  114. assert(o1.eql?(o1))
  115. assert(o2.eql?(o2))
  116. assert(!(o1.eql?(o2)))
  117. end
  118. def test_equal?
  119. o1 = Object.new
  120. o2 = Object.new
  121. assert(o1.equal?(o1))
  122. assert(o2.equal?(o2))
  123. assert(!(o1.equal?(o2)))
  124. end
  125. module ExtendTest1
  126. def et1
  127. "et1"
  128. end
  129. def et3
  130. "et3.1"
  131. end
  132. end
  133. module ExtendTest2
  134. def et2
  135. "et2"
  136. end
  137. def et3
  138. "et3.2"
  139. end
  140. end
  141. def test_extend
  142. s = "hello"
  143. assert(!defined?(s.et1))
  144. s.extend(ExtendTest1)
  145. assert_not_nil(defined?(s.et1))
  146. assert(!defined?(s.et2))
  147. assert_equal("et1", s.et1)
  148. assert_equal("et3.1", s.et3)
  149. s.extend(ExtendTest2)
  150. assert_not_nil(defined?(s.et2))
  151. assert_equal("et1", s.et1)
  152. assert_equal("et2", s.et2)
  153. assert_equal("et3.2", s.et3)
  154. t = "goodbye"
  155. t.extend(ExtendTest1)
  156. t.extend(ExtendTest2)
  157. assert_equal("et1", t.et1)
  158. assert_equal("et2", t.et2)
  159. assert_equal("et3.2", t.et3)
  160. t = "goodbye"
  161. t.extend(ExtendTest2)
  162. t.extend(ExtendTest1)
  163. assert_equal("et1", t.et1)
  164. assert_equal("et2", t.et2)
  165. assert_equal("et3.1", t.et3)
  166. end
  167. def test_freeze
  168. s = "hello"
  169. s[3] = "x"
  170. eval %q{ def s.m1() "m1" end }
  171. assert_equal("m1", s.m1)
  172. s.freeze
  173. assert(s.frozen?)
  174. assert_raise(TypeError) { s[3] = 'y' }
  175. assert_raise(TypeError) { eval %q{ def s.m1() "m1" end } }
  176. assert_equal("helxo", s)
  177. end
  178. def test_frozen?
  179. s = "hello"
  180. assert(!s.frozen?)
  181. assert(!self.frozen?)
  182. s.freeze
  183. assert(s.frozen?)
  184. end
  185. def test_hash
  186. assert_instance_of(Fixnum, "hello".hash)
  187. s1 = "hello"
  188. s2 = "hello"
  189. assert(s1.__id__ != s2.__id__)
  190. assert(s1.eql?(s2))
  191. assert(s1.hash == s2.hash)
  192. s1[2] = 'x'
  193. assert(s1.hash != s2.hash)
  194. end
  195. def test_id
  196. objs = []
  197. ObjectSpace.each_object { |obj| objs << obj.__id__ }
  198. s1 = objs.size
  199. assert_equal(s1, objs.uniq.size)
  200. assert_equal(1.__id__, (3-2).__id__)
  201. assert_instance_of(Fixnum, 1.__id__)
  202. end
  203. def test_inspect
  204. assert_instance_of(String, 1.inspect)
  205. assert_instance_of(String, /a/.inspect)
  206. assert_instance_of(String, "hello".inspect)
  207. assert_instance_of(String, self.inspect)
  208. end
  209. def test_instance_eval
  210. s = "hello"
  211. assert_equal(s, s.instance_eval { self } )
  212. assert_equal("HELLO", s.instance_eval("upcase"))
  213. end
  214. def test_instance_of?
  215. s = "hello"
  216. assert(s.instance_of?(String))
  217. assert(!s.instance_of?(Object))
  218. assert(!s.instance_of?(Class))
  219. assert(self.instance_of?(TestKernel))
  220. end
  221. class IVTest1
  222. end
  223. class IVTest2
  224. def initialize
  225. @var1 = 1
  226. @var2 = 2
  227. end
  228. end
  229. def test_instance_variables
  230. o = IVTest1.new
  231. assert_equal([], o.instance_variables)
  232. o = IVTest2.new
  233. assert_bag_equal(%w(@var1 @var2), o.instance_variables)
  234. end
  235. def test_is_a?
  236. s = "hello"
  237. assert(s.is_a?(String))
  238. assert(s.is_a?(Object))
  239. assert(!s.is_a?(Class))
  240. assert(self.is_a?(TestKernel))
  241. assert(TestKernel.is_a?(Class))
  242. assert(TestKernel.is_a?(Module))
  243. assert(TestKernel.is_a?(Object))
  244. a = []
  245. assert(a.is_a?(Array))
  246. assert(a.is_a?(Enumerable))
  247. end
  248. def test_kind_of?
  249. s = "hello"
  250. assert(s.kind_of?(String))
  251. assert(s.kind_of?(Object))
  252. assert(!s.kind_of?(Class))
  253. assert(self.kind_of?(TestKernel))
  254. assert(TestKernel.kind_of?(Class))
  255. assert(TestKernel.kind_of?(Module))
  256. assert(TestKernel.kind_of?(Object))
  257. a = []
  258. assert(a.kind_of?(Array))
  259. assert(a.kind_of?(Enumerable))
  260. end
  261. def MethodTest1
  262. "mt1"
  263. end
  264. def MethodTest2(a, b, c)
  265. a + b + c
  266. end
  267. def test_method
  268. assert_raise(NameError) { self.method(:wombat) }
  269. m = self.method("MethodTest1")
  270. assert_instance_of(Method, m)
  271. assert_equal("mt1", m.call)
  272. assert_raise(ArgumentError) { m.call(1, 2, 3) }
  273. m = self.method("MethodTest2")
  274. assert_instance_of(Method, m)
  275. assert_equal(6, m.call(1, *[2, 3]))
  276. assert_raise(ArgumentError) { m.call(1, 3) }
  277. end
  278. class MethodMissing
  279. def method_missing(m, *a)
  280. return [m, a]
  281. end
  282. def mm
  283. return "mm"
  284. end
  285. end
  286. def test_method_missing
  287. mm = MethodMissing.new
  288. assert_equal("mm", mm.mm)
  289. assert_equal([ :dave, []], mm.dave)
  290. assert_equal([ :dave, [1, 2, 3]], mm.dave(1, *[2, 3]))
  291. end
  292. class MethodsTest
  293. def MethodsTest.singleton
  294. end
  295. def one
  296. end
  297. def two
  298. end
  299. def three
  300. end
  301. def four
  302. end
  303. private :two
  304. protected :three
  305. end
  306. def test_methods
  307. assert_bag_equal(TestKernel.instance_methods(true), self.methods)
  308. assert_bag_equal(%w(one three four) + Object.instance_methods(true),
  309. MethodsTest.new.methods)
  310. end
  311. def test_nil?
  312. assert(!self.nil?)
  313. assert(nil.nil?)
  314. a = []
  315. assert(a[99].nil?)
  316. end
  317. class PrivateMethods < MethodsTest
  318. def five
  319. end
  320. def six
  321. end
  322. def seven
  323. end
  324. private :six
  325. protected :seven
  326. end
  327. def test_private_methods
  328. assert_bag_equal(%w(two six) + Object.new.private_methods,
  329. PrivateMethods.new.private_methods)
  330. end
  331. def test_protected_methods
  332. assert_bag_equal(%w(three seven) + Object.new.protected_methods,
  333. PrivateMethods.new.protected_methods)
  334. end
  335. def test_public_methods
  336. assert_bag_equal(TestKernel.instance_methods(true), self.public_methods)
  337. assert_bag_equal(%w(one four) + Object.instance_methods(true),
  338. MethodsTest.new.public_methods)
  339. end
  340. def test_respond_to?
  341. assert(self.respond_to?(:test_respond_to?))
  342. assert(!self.respond_to?(:TEST_respond_to?))
  343. mt = PrivateMethods.new
  344. # public
  345. assert(mt.respond_to?("five"))
  346. assert(mt.respond_to?(:one))
  347. assert(mt.respond_to?("five", true))
  348. assert(mt.respond_to?(:one, false))
  349. # protected
  350. assert(mt.respond_to?("seven"))
  351. assert(mt.respond_to?(:three))
  352. assert(mt.respond_to?("seven", true))
  353. assert(mt.respond_to?(:three, false))
  354. #private
  355. assert(!mt.respond_to?(:two))
  356. assert(!mt.respond_to?("six"))
  357. assert(mt.respond_to?(:two, true))
  358. assert(mt.respond_to?("six", true))
  359. end
  360. def test_send
  361. t = SendTest.new
  362. assert_equal("send1", t.send(:send_test1))
  363. assert_equal(99, t.send("send_test2", 44, 55))
  364. end
  365. def test_singleton_methods
  366. assert_equal(%w(singleton), MethodsTest.singleton_methods)
  367. assert_equal(%w(singleton), PrivateMethods.singleton_methods)
  368. mt = MethodsTest.new
  369. assert_equal([], mt.singleton_methods)
  370. eval "def mt.wombat() end"
  371. assert_equal(%w(wombat), mt.singleton_methods)
  372. end
  373. def test_taint
  374. a = "hello"
  375. assert(!a.tainted?)
  376. assert_equal(a, a.taint)
  377. assert(a.tainted?)
  378. end
  379. def test_tainted?
  380. a = "hello"
  381. assert(!a.tainted?)
  382. assert_equal(a, a.taint)
  383. assert(a.tainted?)
  384. end
  385. def test_to_a
  386. Version.less_than("1.7.2") do
  387. o = Object.new
  388. assert_equal([o], o.to_a) # rest tested in individual classes
  389. end
  390. end
  391. def test_to_s
  392. o = Object.new
  393. assert_match(/^#<Object:0x[0-9a-f]+>/, o.to_s)
  394. end
  395. def test_type
  396. assert_instance_of(Class, self.class)
  397. assert_equal(TestKernel, self.class)
  398. assert_equal(String, "hello".class)
  399. assert_equal(Bignum, (10**40).class)
  400. end
  401. def test_untaint
  402. a = "hello"
  403. assert(!a.tainted?)
  404. assert_equal(a, a.taint)
  405. assert(a.tainted?)
  406. assert_equal(a, a.untaint)
  407. assert(!a.tainted?)
  408. a = "hello"
  409. assert(!a.tainted?)
  410. assert_equal(a, a.untaint)
  411. assert(!a.tainted?)
  412. end
  413. class Caster
  414. def to_a
  415. [4, 5, 6]
  416. end
  417. def to_f
  418. 2.34
  419. end
  420. def to_i
  421. 99
  422. end
  423. def to_s
  424. "Hello"
  425. end
  426. end
  427. def test_s_Array
  428. Version.less_than("1.7.2") do
  429. assert_equal([], Array(nil))
  430. end
  431. assert_equal([1, 2, 3], Array([1, 2, 3]))
  432. assert_equal([1, 2, 3], Array(1..3))
  433. assert_equal([4, 5, 6], Array(Caster.new))
  434. end
  435. def test_s_Float
  436. assert_instance_of(Float, Float(1))
  437. assert_flequal(1, Float(1))
  438. assert_flequal(1.23, Float('1.23'))
  439. assert_flequal(2.34, Float(Caster.new))
  440. end
  441. def test_s_Integer
  442. assert_instance_of(Fixnum, Integer(1))
  443. assert_instance_of(Bignum, Integer(10**30))
  444. assert_equal(123, Integer(123.99))
  445. assert_equal(-123, Integer(-123.99))
  446. a = Integer(1.0e30) - 10**30
  447. assert(a.abs < 10**20)
  448. assert_equal(99, Integer(Caster.new))
  449. end
  450. def test_s_String
  451. assert_instance_of(String, String(123))
  452. assert_equal("123", String(123))
  453. assert_equal("123.45", String(123.45))
  454. assert_equal("123", String([1, 2, 3]))
  455. assert_equal("Hello", String(Caster.new))
  456. end
  457. def test_s_BACKTICK
  458. assert_equal("hello\n", `echo hello`)
  459. assert_equal(0, $?)
  460. MsWin32.dont do
  461. assert_equal("", `not_a_valid_command 2>/dev/null`)
  462. end
  463. MsWin32.only do
  464. assert_equal("", `not_a_valid_command 2>nul`)
  465. end
  466. assert($? != 0)
  467. assert_equal("hello\n", %x{echo hello})
  468. assert_equal(0, $?)
  469. MsWin32.dont do
  470. assert_equal("", %x{not_a_valid_command 2>/dev/null})
  471. end
  472. MsWin32.only do
  473. assert_equal("", %x{not_a_valid_command 2>nul})
  474. end
  475. assert($? != 0)
  476. end
  477. def test_s_abort
  478. p = IO.popen("#$interpreter -e 'abort;exit 99'")
  479. p.close
  480. assert_equal(1<<8, $?)
  481. end
  482. def test_s_at_exit
  483. script = %{at_exit {puts "world"};at_exit {puts "cruel"};puts "goodbye";exit 99}
  484. p = IO.popen("#$interpreter -e '#{script}'")
  485. begin
  486. assert_equal("goodbye\n", p.gets)
  487. assert_equal("cruel\n", p.gets)
  488. assert_equal("world\n", p.gets)
  489. ensure
  490. p.close
  491. assert_equal(99<<8, $?)
  492. end
  493. end
  494. def test_s_autoload
  495. File.open("_dummy.rb", "w") do |f|
  496. f.print <<-EOM
  497. module Module_Test
  498. VAL = 123
  499. end
  500. EOM
  501. end
  502. assert(!defined? Module_Test)
  503. autoload(:Module_Test, "./_dummy.rb")
  504. assert_not_nil(defined? Module_Test::VAL)
  505. assert_equal(123, Module_Test::VAL)
  506. assert($".include?("./_dummy.rb"))#"
  507. File.delete("./_dummy.rb")
  508. end
  509. def bindproc(val)
  510. return binding
  511. end
  512. def test_s_binding
  513. val = 123
  514. b = binding
  515. assert_instance_of(Binding, b)
  516. assert_equal(123, eval("val", b))
  517. b = bindproc(321)
  518. assert_equal(321, eval("val", b))
  519. end
  520. def blocker1
  521. return block_given?
  522. end
  523. def blocker2(&p)
  524. return block_given?
  525. end
  526. def test_s_block_given?
  527. assert(!blocker1())
  528. assert(!blocker2())
  529. assert(blocker1() { 1 })
  530. assert(blocker2() { 1 })
  531. end
  532. def callcc_test(n)
  533. cont = nil
  534. callcc { |cont|
  535. return [cont, n]
  536. }
  537. n -= 1
  538. return [n.zero? ? nil : cont, n ]
  539. end
  540. def test_s_callcc
  541. res = nil
  542. cont = nil
  543. assert_equal(2,
  544. callcc { |cont|
  545. res = 1
  546. res = 2
  547. })
  548. assert_equal(2, res)
  549. res = nil
  550. assert_equal(99,
  551. callcc { |cont|
  552. res = 1
  553. cont.call 99
  554. res = 2
  555. })
  556. assert_equal(1, res)
  557. # Test gotos!
  558. callcc { |cont| res = 0 }
  559. res += 1
  560. cont.call if res < 4
  561. assert_equal(4, res)
  562. # Test reactivating procedures
  563. n = 4
  564. cont, res = callcc_test(4)
  565. assert_equal(n, res)
  566. n -= 1
  567. puts cont.call if cont
  568. end
  569. def caller_test
  570. return caller
  571. end
  572. def test_s_caller
  573. c = caller_test
  574. assert_match(%r{TestKernel.rb:#{__LINE__-1}:in `test_s_caller'}, c[0])
  575. end #`
  576. def catch_test
  577. throw :c, 456;
  578. 789;
  579. end
  580. def test_s_catch
  581. assert_equal(123, catch(:c) { a = 1; 123 })
  582. assert_equal(321, catch(:c) { a = 1; throw :c, 321; 123 })
  583. assert_equal(456, catch(:c) { a = 1; catch_test; 123 })
  584. assert_equal(456, catch(:c) { catch(:d) { catch_test; 123 } } )
  585. end
  586. def test_s_chomp
  587. $_ = "hello"
  588. assert_equal("hello", chomp)
  589. assert_equal("hello", chomp('aaa'))
  590. assert_equal("he", chomp('llo'))
  591. assert_equal("he", $_)
  592. a = "hello\n"
  593. $_ = a
  594. assert_equal("hello", chomp)
  595. assert_equal("hello", $_)
  596. assert_equal("hello\n", a)
  597. end
  598. def test_s_chomp!
  599. $_ = "hello"
  600. assert_equal(nil, chomp!)
  601. assert_equal(nil, chomp!('aaa'))
  602. assert_equal("he", chomp!('llo'))
  603. assert_equal("he", $_)
  604. a = "hello\n"
  605. $_ = a
  606. assert_equal("hello", chomp!)
  607. assert_equal("hello", $_)
  608. assert_equal("hello", a)
  609. end
  610. def test_s_chop
  611. a = "hi"
  612. $_ = a
  613. assert_equal("h", chop)
  614. assert_equal("h", $_)
  615. assert_equal("", chop)
  616. assert_equal("", $_)
  617. assert_equal("", chop)
  618. assert_equal("hi", a)
  619. $_ = "hi\n"
  620. assert_equal("hi", chop)
  621. $_ = "hi\r\n"
  622. assert_equal("hi", chop)
  623. $_ = "hi\n\r"
  624. assert_equal("hi\n", chop)
  625. end
  626. def test_s_chop!
  627. a = "hi"
  628. $_ = a
  629. assert_equal("h", chop!)
  630. assert_equal("h", $_)
  631. assert_equal("", chop!)
  632. assert_equal("", $_)
  633. assert_equal(nil, chop!)
  634. assert_equal("", $_)
  635. assert_equal("", a)
  636. $_ = "hi\n"
  637. assert_equal("hi", chop!)
  638. $_ = "hi\r\n"
  639. assert_equal("hi", chop!)
  640. $_ = "hi\n\r"
  641. assert_equal("hi\n", chop!)
  642. end
  643. def test_s_eval
  644. assert_equal(123, eval("100 + 20 + 3"))
  645. val = 123
  646. assert_equal(123, eval("val", binding))
  647. assert_equal(321, eval("val", bindproc(321)))
  648. skipping("Check of eval with file name")
  649. begin
  650. eval "1
  651. burble", binding, "gumby", 321
  652. rescue Exception => detail
  653. end
  654. end
  655. def test_s_exec
  656. open("xyzzy.dat", "w") { |f| f.puts "stuff" }
  657. tf = Tempfile.new("tf")
  658. begin
  659. # all in one string - wildcards get expanded
  660. tf.puts 'exec("echo xy*y.dat")'
  661. tf.close
  662. IO.popen("#$interpreter #{tf.path}") do |p|
  663. assert_equal("xyzzy.dat\n", p.gets)
  664. end
  665. # with two parameters, the '*' doesn't get expanded
  666. tf.open
  667. tf.puts 'exec("echo", "xy*y.dat")'
  668. tf.close
  669. IO.popen("#$interpreter #{tf.path}") do |p|
  670. assert_equal("xy*y.dat\n", p.gets)
  671. end
  672. ensure
  673. tf.close(true)
  674. File.unlink "xyzzy.dat" if p
  675. end
  676. end
  677. def test_s_exit
  678. begin
  679. exit
  680. fail("No exception raised")
  681. rescue SystemExit
  682. assert(true)
  683. rescue Exception
  684. fail("Bad exception: #$!")
  685. end
  686. p = IO.popen("#$interpreter -e 'exit'")
  687. p.close
  688. assert_equal(0, $?)
  689. p = IO.popen("#$interpreter -e 'exit 123'")
  690. p.close
  691. assert_equal(123 << 8, $?)
  692. end
  693. def test_s_exit!
  694. tf = Tempfile.new("tf")
  695. tf.puts %{
  696. begin
  697. exit! 99
  698. exit 1
  699. rescue SystemExit
  700. exit 2
  701. rescue Exception
  702. exit 3
  703. end
  704. exit 4}
  705. tf.close
  706. IO.popen("#$interpreter #{tf.path}").close
  707. assert_equal(99<<8, $?)
  708. IO.popen("#$interpreter -e 'exit!'").close
  709. Version.less_than("1.8.1") do
  710. assert_equal(0xff << 8, $?)
  711. end
  712. Version.greater_or_equal("1.8.1") do
  713. assert_equal(1 << 8, $?)
  714. end
  715. IO.popen("#$interpreter -e 'exit! 123'").close
  716. assert_equal(123 << 8, $?)
  717. ensure
  718. tf.close(true)
  719. end
  720. def test_s_fail
  721. begin
  722. fail
  723. rescue StandardError
  724. assert(true)
  725. rescue Exception
  726. fail("Wrong exception raised")
  727. end
  728. begin
  729. fail "Wombat"
  730. rescue StandardError => detail
  731. assert_equal("Wombat", detail.message)
  732. rescue Exception
  733. fail("Wrong exception raised")
  734. end
  735. assert_raise(NotImplementedError) { fail NotImplementedError }
  736. begin
  737. fail "Wombat"
  738. fail("No exception")
  739. rescue StandardError => detail
  740. assert_equal("Wombat", detail.message)
  741. rescue Exception
  742. fail("Wrong exception raised")
  743. end
  744. begin
  745. fail NotImplementedError, "Wombat"
  746. fail("No exception")
  747. rescue NotImplementedError => detail
  748. assert_equal("Wombat", detail.message)
  749. rescue Exception
  750. fail("Wrong exception raised")
  751. end
  752. bt = %w(one two three)
  753. begin
  754. fail NotImplementedError, "Wombat", bt
  755. fail("No exception")
  756. rescue NotImplementedError => detail
  757. assert_equal("Wombat", detail.message)
  758. assert_equal(bt, detail.backtrace)
  759. rescue Exception
  760. fail("Wrong exception raised")
  761. end
  762. end
  763. MsWin32.dont do
  764. def test_s_fork
  765. f = fork
  766. if f.nil?
  767. File.open("_pid", "w") {|f| f.puts $$}
  768. exit 99
  769. end
  770. begin
  771. Process.wait
  772. assert_equal(99<<8, $?)
  773. File.open("_pid") do |file|
  774. assert_equal(file.gets.to_i, f)
  775. end
  776. ensure
  777. File.delete("_pid")
  778. end
  779. f = fork do
  780. File.open("_pid", "w") {|f| f.puts $$}
  781. end
  782. begin
  783. Process.wait
  784. assert_equal(0<<8, $?)
  785. File.open("_pid") do |file|
  786. assert_equal(file.gets.to_i, f)
  787. end
  788. ensure
  789. File.delete("_pid")
  790. end
  791. end
  792. end
  793. def test_s_format
  794. assert_equal("00123", format("%05d", 123))
  795. assert_equal("123 |00000001", format("%-5s|%08x", 123, 1))
  796. x = format("%3s %-4s%%foo %.0s%5d %#x%c%3.1f %b %x %X %#b %#x %#X",
  797. "hi",
  798. 123,
  799. "never seen",
  800. 456,
  801. 0,
  802. ?A,
  803. 3.0999,
  804. 11,
  805. 171,
  806. 171,
  807. 11,
  808. 171,
  809. 171)
  810. assert_equal(' hi 123 %foo 456 0x0A3.1 1011 ab AB 0b1011 0xab 0XAB', x)
  811. end
  812. def setupFiles
  813. setupTestDir
  814. File.open("_test/_file1", "w") do |f|
  815. f.puts "0: Line 1"
  816. f.puts "1: Line 2"
  817. end
  818. File.open("_test/_file2", "w") do |f|
  819. f.puts "2: Line 1"
  820. f.puts "3: Line 2"
  821. end
  822. ARGV.replace ["_test/_file1", "_test/_file2" ]
  823. end
  824. def teardownFiles
  825. teardownTestDir
  826. end
  827. def test_s_gets1
  828. setupFiles
  829. begin
  830. count = 0
  831. while gets
  832. num = $_[0..1].to_i
  833. assert_equal(count, num)
  834. count += 1
  835. end
  836. assert_equal(4, count)
  837. ensure
  838. teardownFiles
  839. end
  840. end
  841. def test_s_gets2
  842. setupFiles
  843. begin
  844. count = 0
  845. while gets(nil)
  846. split(/\n/).each do |line|
  847. num = line[0..1].to_i
  848. assert_equal(count, num)
  849. count += 1
  850. end
  851. end
  852. assert_equal(4, count)
  853. ensure
  854. teardownFiles
  855. end
  856. end
  857. def test_s_gets3
  858. setupFiles
  859. begin
  860. count = 0
  861. while gets(' ')
  862. count += 1
  863. end
  864. assert_equal(10, count)
  865. ensure
  866. teardownFiles
  867. end
  868. end
  869. def test_s_global_variables
  870. g1 = global_variables
  871. assert_instance_of(Array, g1)
  872. assert_instance_of(String, g1[0])
  873. assert(!g1.include?("$fred"))
  874. eval "$fred = 1"
  875. g2 = global_variables
  876. assert(g2.include?("$fred"))
  877. assert_equal(["$fred"], g2 - g1)
  878. end
  879. def test_s_gsub
  880. $_ = "hello"
  881. assert_equal("h*ll*", gsub(/[aeiou]/, '*'))
  882. assert_equal("h*ll*", $_)
  883. $_ = "hello"
  884. assert_equal("h<e>ll<o>", gsub(/([aeiou])/, '<\1>'))
  885. assert_equal("h<e>ll<o>", $_)
  886. $_ = "hello"
  887. assert_equal("104 101 108 108 111 ", gsub(/./) {
  888. |s| s[0].to_s+' '})
  889. assert_equal("104 101 108 108 111 ", $_)
  890. $_ = "hello"
  891. assert_equal("HELL-o", gsub(/(hell)(.)/) {
  892. |s| $1.upcase + '-' + $2
  893. })
  894. assert_equal("HELL-o", $_)
  895. $_ = "hello"
  896. $_.taint
  897. assert_equal(true, (gsub(/./,'X').tainted?))
  898. assert_equal(true, $_.tainted?)
  899. end
  900. def test_s_gsub!
  901. $_ = "hello"
  902. assert_equal("h*ll*", gsub!(/[aeiou]/, '*'))
  903. assert_equal("h*ll*", $_)
  904. $_ = "hello"
  905. assert_equal("h<e>ll<o>", gsub!(/([aeiou])/, '<\1>'))
  906. assert_equal("h<e>ll<o>", $_)
  907. $_ = "hello"
  908. assert_equal("104 101 108 108 111 ", gsub!(/./) {
  909. |s| s[0].to_s+' '})
  910. assert_equal("104 101 108 108 111 ", $_)
  911. $_ = "hello"
  912. assert_equal("HELL-o", gsub!(/(hell)(.)/) {
  913. |s| $1.upcase + '-' + $2
  914. })
  915. assert_equal("HELL-o", $_)
  916. $_ = "hello"
  917. assert_equal(nil, gsub!(/x/, 'y'))
  918. assert_equal("hello", $_)
  919. $_ = "hello"
  920. $_.taint
  921. assert_equal(true, (gsub!(/./,'X').tainted?))
  922. assert_equal(true, $_.tainted?)
  923. end
  924. def iterator_test(&b)
  925. return iterator?
  926. end
  927. def test_s_iterator?
  928. assert(iterator_test { 1 })
  929. assert(!iterator_test)
  930. end
  931. def test_s_lambda
  932. a = lambda { "hello" }
  933. assert_equal("hello", a.call)
  934. a = lambda { |s| "there " + s }
  935. assert_equal("there Dave", a.call("Dave"))
  936. end
  937. def test_s_load
  938. File.open("_dummy_load.rb", "w") do |f|
  939. f.print <<-EOM
  940. module Module_Load
  941. VAL = 234
  942. end
  943. EOM
  944. end
  945. assert(!defined? Module_Load)
  946. load("./_dummy_load.rb")
  947. assert_not_nil(defined? Module_Load::VAL)
  948. assert_equal(234, Module_Load::VAL)
  949. assert(!$".include?("./_dummy_load.rb"))#"
  950. # Prove it's reloaded
  951. File.open("_dummy_load.rb", "w") do |f|
  952. f.print <<-EOM
  953. module Module_Load
  954. VAL1 = 456
  955. end
  956. EOM
  957. end
  958. load("./_dummy_load.rb")
  959. assert_equal(456, Module_Load::VAL1)
  960. # check that the sandbox works
  961. File.open("_dummy_load.rb", "w") do |f|
  962. f.print <<-EOM
  963. GLOBAL_VAL = 789
  964. EOM
  965. end
  966. load("./_dummy_load.rb", true)
  967. assert(!defined? GLOBAL_VAL)
  968. load("./_dummy_load.rb", false)
  969. assert_not_nil(defined? GLOBAL_VAL)
  970. assert_equal(789, GLOBAL_VAL)
  971. File.delete("./_dummy_load.rb")
  972. end
  973. def local_variable_test(c)
  974. d = 2
  975. local_variables
  976. end
  977. def test_s_local_variables
  978. assert_bag_equal(%w(a), local_variables)
  979. eval "b = 1"
  980. assert_bag_equal(%w(a b), local_variables)
  981. assert_bag_equal(%w(c d), local_variable_test(1))
  982. a = 1
  983. end
  984. # This is a lame test--can we do better?
  985. def test_s_loop
  986. a = 0
  987. loop do
  988. a += 1
  989. break if a > 4
  990. end
  991. assert_equal(5, a)
  992. end
  993. # regular files
  994. def test_s_open1
  995. setupTestDir
  996. begin
  997. file1 = "_test/_file1"
  998. assert_raise(Errno::ENOENT) { File.open("_gumby") }
  999. # test block/non block forms
  1000. f = open(file1)
  1001. begin
  1002. assert_instance_of(File, f)
  1003. ensure
  1004. f.close
  1005. end
  1006. assert_nil(open(file1) { |f| assert_equal(File, f.class)})
  1007. # test modes
  1008. modes = [
  1009. %w( r w r+ w+ a a+ ),
  1010. [ File::RDONLY,
  1011. File::WRONLY | File::CREAT,
  1012. File::RDWR,
  1013. File::RDWR + File::TRUNC + File::CREAT,
  1014. File::WRONLY + File::APPEND + File::CREAT,
  1015. File::RDWR + File::APPEND + File::CREAT
  1016. ]]
  1017. for modeset in modes
  1018. sys("rm -f #{file1}")
  1019. sys("touch #{file1}")
  1020. mode = modeset.shift # "r"
  1021. # file: empty
  1022. open(file1, mode) { |f|
  1023. assert_nil(f.gets)
  1024. assert_raise(IOError) { f.puts "wombat" }
  1025. }
  1026. mode = modeset.shift # "w"
  1027. # file: empty
  1028. open(file1, mode) { |f|
  1029. assert_nil(f.puts("wombat"))
  1030. assert_raise(IOError) { f.gets }
  1031. }
  1032. mode = modeset.shift # "r+"
  1033. # file: wombat
  1034. open(file1, mode) { |f|
  1035. assert_equal("wombat\n", f.gets)
  1036. assert_nil(f.puts("koala"))
  1037. f.rewind
  1038. assert_equal("wombat\n", f.gets)
  1039. assert_equal("koala\n", f.gets)
  1040. }
  1041. mode = modeset.shift # "w+"
  1042. # file: wombat/koala
  1043. open(file1, mode) { |f|
  1044. assert_nil(f.gets)
  1045. assert_nil(f.puts("koala"))
  1046. f.rewind
  1047. assert_equal("koala\n", f.gets)
  1048. }
  1049. mode = modeset.shift # "a"
  1050. # file: koala
  1051. open(file1, mode) { |f|
  1052. assert_nil(f.puts("wombat"))
  1053. assert_raise(IOError) { f.gets }
  1054. }
  1055. mode = modeset.shift # "a+"
  1056. # file: koala/wombat
  1057. open(file1, mode) { |f|
  1058. assert_nil(f.puts("wallaby"))
  1059. f.rewind
  1060. assert_equal("koala\n", f.gets)
  1061. assert_equal("wombat\n", f.gets)
  1062. assert_equal("wallaby\n", f.gets)
  1063. }
  1064. end
  1065. # Now try creating files
  1066. filen = "_test/_filen"
  1067. open(filen, "w") {}
  1068. begin
  1069. assert(File.exists?(filen))
  1070. ensure
  1071. File.delete(filen)
  1072. end
  1073. Version.greater_or_equal("1.7") do
  1074. open(filen, "w", 0444) {}
  1075. begin
  1076. assert(File.exists?(filen))
  1077. Cygwin.known_problem do
  1078. assert_equal(0444 & ~File.umask, File.stat(filen).mode & 0777)
  1079. end
  1080. ensure
  1081. WindowsNative.or_variant do
  1082. # to be able to delete the file on Windows
  1083. File.chmod(0666, filen)
  1084. end
  1085. File.delete(filen)
  1086. end
  1087. end
  1088. ensure
  1089. teardownTestDir # also does a chdir
  1090. end
  1091. end
  1092. def setup_s_open2
  1093. setupTestDir
  1094. @file = "_test/_10lines"
  1095. File.open(@file, "w") do |f|
  1096. 10.times { |i| f.printf "%02d: This is a line\n", i }
  1097. end
  1098. end
  1099. # pipes
  1100. def test_s_open2
  1101. setup_s_open2
  1102. begin
  1103. assert_nil(open("| echo hello") do |f|
  1104. assert_equal("hello\n", f.gets)
  1105. end)
  1106. # READ
  1107. p = open("|#$interpreter -e 'puts readlines' <#@file")
  1108. begin
  1109. count = 0
  1110. p.each do |line|
  1111. num = line[0..1].to_i
  1112. assert_equal(count, num)
  1113. count += 1
  1114. end
  1115. assert_equal(10, count)
  1116. ensure
  1117. p.close
  1118. end
  1119. # READ with block
  1120. res = open("|#$interpreter -e 'puts readlines' <#@file") do |p|
  1121. count = 0
  1122. p.each do |line|
  1123. num = line[0..1].to_i
  1124. assert_equal(count, num)
  1125. count += 1
  1126. end
  1127. assert_equal(10, count)
  1128. end
  1129. assert_nil(res)
  1130. # WRITE
  1131. p = open("|#$interpreter -e 'puts readlines' >#@file", "w")
  1132. begin
  1133. 5.times { |i| p.printf "Line %d\n", i }
  1134. ensure
  1135. p.close
  1136. end
  1137. count = 0
  1138. IO.foreach(@file) do |line|
  1139. num = line.chomp[-1,1].to_i
  1140. assert_equal(count, num)
  1141. count += 1
  1142. end
  1143. assert_equal(5, count)
  1144. # Spawn an interpreter
  1145. MsWin32.dont do
  1146. parent = $$
  1147. p = open("|-")
  1148. if p
  1149. begin
  1150. assert_equal(parent, $$)
  1151. assert_equal("Hello\n", p.gets)
  1152. ensure
  1153. p.close
  1154. end
  1155. else
  1156. assert_equal(parent, Process.ppid)
  1157. puts "Hello"
  1158. exit
  1159. end
  1160. end
  1161. # Spawn an interpreter - WRITE
  1162. MsWin32.dont do
  1163. parent = $$
  1164. pipe = open("|-", "w")
  1165. if pipe
  1166. begin
  1167. assert_equal(parent, $$)
  1168. pipe.puts "12"
  1169. Process.wait
  1170. assert_equal(12, $?>>8)
  1171. ensure
  1172. pipe.close
  1173. end
  1174. else
  1175. buff = $stdin.gets
  1176. exit buff.to_i
  1177. end
  1178. end
  1179. # Spawn an interpreter - READWRITE
  1180. MsWin32.dont do
  1181. parent = $$
  1182. p = open("|-", "w+")
  1183. if p
  1184. begin
  1185. assert_equal(parent, $$)
  1186. p.puts "Hello\n"
  1187. assert_equal("Goodbye\n", p.gets)
  1188. Process.wait
  1189. ensure
  1190. p.close
  1191. end
  1192. else
  1193. puts "Goodbye" if $stdin.gets == "Hello\n"
  1194. exit
  1195. end
  1196. end
  1197. ensure
  1198. teardownTestDir
  1199. end
  1200. end
  1201. MacOS.only do
  1202. undef test_s_open2
  1203. end
  1204. def test_s_p
  1205. tf = Tempfile.new("tf")
  1206. begin
  1207. tf.puts %{
  1208. class PTest2
  1209. def inspect
  1210. "ptest2"
  1211. end
  1212. end
  1213. p 1
  1214. p PTest2.new
  1215. exit}
  1216. tf.close
  1217. IO.popen("#$interpreter #{tf.path}") do |pipe|
  1218. assert_equal("1\n", pipe.gets)
  1219. assert_equal("ptest2\n", pipe.gets)
  1220. end
  1221. ensure
  1222. tf.close(true)
  1223. end
  1224. end
  1225. def test_s_print
  1226. tf = Tempfile.new("tf")
  1227. begin
  1228. tf.puts %{
  1229. class PrintTest
  1230. def to_s
  1231. "printtest"
  1232. end
  1233. end
  1234. print 1
  1235. print PrintTest.new
  1236. print "\n"
  1237. $, = ":"
  1238. print 1, "cat", PrintTest.new, "\n"
  1239. exit}
  1240. tf.close
  1241. IO.popen("#$interpreter #{tf.path}") do |pipe|
  1242. assert_equal("1printtest\n", pipe.gets)
  1243. assert_equal("1:cat:printtest:\n", pipe.gets)
  1244. end
  1245. ensure
  1246. tf.close(true)
  1247. end
  1248. end
  1249. def test_s_printf
  1250. tf = Tempfile.new("tf")
  1251. begin
  1252. tf.puts %{
  1253. printf("%05d\n", 123)
  1254. printf("%-5s|%08x\n", 123, 1)
  1255. printf("%3s %-4s%%foo %.0s%5d %#x%c%3.1f %b %x %X %#b %#x %#X\n",
  1256. "hi",
  1257. 123,
  1258. "never seen",
  1259. 456,
  1260. 0,
  1261. ?A,
  1262. 3.0999,
  1263. 11,
  1264. 171,
  1265. 171,
  1266. 11,
  1267. 171,
  1268. 171)
  1269. exit}
  1270. tf.close
  1271. IO.popen("#$interpreter #{tf.path}") do |pipe|
  1272. assert_equal("00123\n", pipe.gets)
  1273. assert_equal("123 |00000001\n", pipe.gets)
  1274. assert_equal(" hi 123 %foo 456 0x0A3.1 1011 ab AB 0b1011 0xab 0XAB\n",
  1275. pipe.gets)
  1276. end
  1277. ensure
  1278. tf.close(true)
  1279. end
  1280. end
  1281. def test_s_proc
  1282. a = proc { "hello" }
  1283. assert_equal("hello", a.call)
  1284. a = proc { |s| "there " + s }
  1285. assert_equal("there Dave", a.call("Dave"))
  1286. end
  1287. def test_s_putc
  1288. setupTestDir
  1289. fname = "_test/_op"
  1290. begin
  1291. File.open(fname, "wb") do |file|
  1292. file.putc "A"
  1293. 0.upto(255) { |ch| file.putc ch }
  1294. end
  1295. File.open(fname, "rb") do |file|
  1296. assert_equal(?A, file.getc)
  1297. 0.upto(255) { |ch| assert_equal(ch, file.getc) }
  1298. end
  1299. ensure
  1300. teardownTestDir
  1301. end
  1302. end
  1303. class PrintTest
  1304. def to_s
  1305. "printtest"
  1306. end
  1307. end
  1308. def test_s_puts
  1309. setupTestDir
  1310. fname = "_test/_op"
  1311. begin
  1312. File.open(fname, "w") do |file|
  1313. file.puts "line 1", "line 2"
  1314. file.puts PrintTest.new
  1315. file.puts 4
  1316. end
  1317. File.open(fname) do |file|
  1318. assert_equal("line 1\n", file.gets)
  1319. assert_equal("line 2\n", file.gets)
  1320. assert_equal("printtest\n", file.gets)
  1321. assert_equal("4\n", file.gets)
  1322. end
  1323. ensure
  1324. teardownTestDir
  1325. end
  1326. end
  1327. def test_s_raise
  1328. begin
  1329. raise
  1330. rescue StandardError
  1331. assert(true)
  1332. rescue Exception
  1333. fail("Wrong exception raised")
  1334. end
  1335. begin
  1336. raise "Wombat"
  1337. rescue StandardError => detail
  1338. assert_equal("Wombat", detail.message)
  1339. rescue Exception
  1340. fail("Wrong exception raised")
  1341. end
  1342. assert_raise(NotImplementedError) { raise NotImplementedError }
  1343. begin
  1344. raise "Wombat"
  1345. fail("No exception")
  1346. rescue StandardError => detail
  1347. assert_equal("Wombat", detail.message)
  1348. rescue Exception
  1349. fail("Wrong exception")
  1350. end
  1351. begin
  1352. raise NotImplementedError, "Wombat"
  1353. fail("No exception")
  1354. rescue NotImplementedError => detail
  1355. assert_equal("Wombat", detail.message)
  1356. rescue Exception
  1357. raise
  1358. end
  1359. bt = %w(one two three)
  1360. begin
  1361. raise NotImplementedError, "Wombat", bt
  1362. fail("No exception")
  1363. rescue NotImplementedError => detail
  1364. assert_equal("Wombat", detail.message)
  1365. assert_equal(bt, detail.backtrace)
  1366. rescue Exception
  1367. raise
  1368. end
  1369. if defined? Process.kill
  1370. x = 0
  1371. trap "SIGINT", proc {|sig| x = 2}
  1372. Process.kill "SIGINT", $$
  1373. sleep 0.1
  1374. assert_equal(2, x)
  1375. trap "SIGINT", proc {raise "Interrupt"}
  1376. x = nil
  1377. begin
  1378. Process.kill "SIGINT", $$
  1379. sleep 0.1
  1380. rescue
  1381. x = $!
  1382. end
  1383. assert_not_nil(x)
  1384. assert_not_nil(/Interrupt/ =~ x.to_s)
  1385. end
  1386. end
  1387. def rand_test(limit, result_type, bucket_scale, bucket_max, average)
  1388. n = rand(limit)
  1389. assert_instance_of(result_type, n)
  1390. repeat = 10000
  1391. sum = 0
  1392. min = 2**30
  1393. max = -1
  1394. buckets = [0] * bucket_max
  1395. sumstep = 0
  1396. repeat.times do
  1397. last, n = n, rand(limit)
  1398. sumstep += (n-last).abs
  1399. min = n if min > n
  1400. max = n if max < n
  1401. sum += n
  1402. buckets[bucket_scale.call(n)] += 1
  1403. end
  1404. # Normalize the limit
  1405. limit = limit.to_i
  1406. limit = 1 if limit == 0
  1407. # Check the mean is about right
  1408. assert(min >= 0.0)
  1409. assert(max < limit)
  1410. avg = Float(sum) / Float(repeat)
  1411. if (avg < Float(average)*0.95 or avg > Float(average)*1.05)
  1412. $stderr.puts "
  1413. I am about to fail a test, but the failure may be purely
  1414. a statistical coincidence. Try a difference see and see if
  1415. if still happens."
  1416. fail("Average out of range (got #{avg}, expected #{average}")
  1417. end
  1418. # Now do the same for the average difference
  1419. avgstep = Float(sumstep) / Float(repeat)
  1420. expstep = Float(limit)/3.0
  1421. if (avgstep < Float(expstep)*0.95 or avgstep > Float(expstep)*1.05)
  1422. $stderr.puts "
  1423. I am about to fail a test, but the failure may be purely
  1424. a statistical coincidence. Try a difference see and see if
  1425. if still happens."
  1426. fail("Avg. step out of range (got #{avgstep}, expected #{expstep}")
  1427. end
  1428. # check that no bucket has les than repeats/100/2 or more than
  1429. # repeats/100*1.5
  1430. expected = repeat/bucket_max
  1431. low = expected/2
  1432. high = (expected*3)/2
  1433. buckets.each_with_index do |item, index|
  1434. assert(item > low && item < high,
  1435. "Bucket[#{index}] has #{item} entries. Expected roughly #{expected}")
  1436. end
  1437. end
  1438. # Now the same, but with integers
  1439. def test_s_rand
  1440. rand_test( 0, Float, proc {|n| (100*n).to_i }, 100, 0.5)
  1441. rand_test(100, Fixnum, proc {|n| n }, 100, 49.5)
  1442. rand_test( 50, Fixnum, proc {|n| n }, 50, 24.5)
  1443. rand_test(500, Fixnum, proc {|n| n/5 }, 100, 249)
  1444. end
  1445. def test_s_readline1
  1446. setupFiles
  1447. begin
  1448. count = 0
  1449. 4.times do |count|
  1450. line = readline
  1451. num = line[0..1].to_i
  1452. assert_equal(count, num)
  1453. count += 1
  1454. end
  1455. assert_raise(EOFError) { readline }
  1456. ensure
  1457. teardownFiles
  1458. end
  1459. end
  1460. def test_s_readline2
  1461. setupFiles
  1462. begin
  1463. count = 0
  1464. contents = readline(nil)
  1465. contents.split(/\n/).each do |line|
  1466. num = line[0..1].to_i
  1467. assert_equal(count, num)
  1468. count += 1
  1469. end
  1470. assert_equal(2, count)
  1471. contents = readline(nil)
  1472. contents.split(/\n/).each do |line|
  1473. num = line[0..1].to_i
  1474. assert_equal(count, num)
  1475. count += 1
  1476. end
  1477. assert_equal(4, count)
  1478. assert_raise(EOFError) { readline }
  1479. ensure
  1480. teardownFiles
  1481. end
  1482. end
  1483. def test_s_readline3
  1484. setupFiles
  1485. begin
  1486. count = 0
  1487. 10.times do |count|
  1488. thing = readline(' ')
  1489. count += 1
  1490. end
  1491. assert_raise(EOFError) { readline }
  1492. ensure
  1493. teardownFiles
  1494. end
  1495. end
  1496. def test_s_readlines1
  1497. setupFiles
  1498. begin
  1499. lines = readlines
  1500. assert_equal(4, lines.size)
  1501. ensure
  1502. teardownFiles
  1503. end
  1504. end
  1505. def test_s_readlines2
  1506. setupFiles
  1507. begin
  1508. lines = readlines(nil)
  1509. assert_equal(2, lines.size)
  1510. ensure
  1511. teardownFiles
  1512. end
  1513. end
  1514. def test_s_require
  1515. assert_raise(LoadError) { require("gumby") }
  1516. File.open("_dummy_req.rb", "w") do |f|
  1517. f.print <<-EOM
  1518. module Module_Require
  1519. VAL = 234
  1520. end
  1521. EOM
  1522. end
  1523. assert(!defined? Module_Require)
  1524. assert_not_nil(require("./_dummy_req.rb"))
  1525. assert_not_nil(defined? Module_Require::VAL)
  1526. assert_equal(234, Module_Require::VAL)
  1527. assert($".include?("./_dummy_req.rb"))#"
  1528. # Prove it isn;t reloaded
  1529. File.open("_dummy_req.rb", "w") do |f|
  1530. f.print <<-EOM
  1531. module Module_Require
  1532. VAL1 = 456
  1533. end
  1534. EOM
  1535. end
  1536. assert(!require("./_dummy_req.rb"))
  1537. assert(!defined? Module_Require::VAL1)
  1538. File.delete("./_dummy_req.rb")
  1539. end
  1540. def make_file(dirname, filename, number, &block)
  1541. if FileTest.directory?(dirname)
  1542. File.delete(*Dir[File.join(dirname, "**")])
  1543. Dir.rmdir(dirname)
  1544. end
  1545. Dir.mkdir(dirname)
  1546. File.open(File.join(dirname, filename), "w") do |f|
  1547. f.print <<-EOM
  1548. module Module_Require
  1549. VAL1 = #{number}
  1550. end
  1551. EOM
  1552. end
  1553. block.call
  1554. ensure
  1555. File.delete(*Dir[File.join(dirname, "**")])
  1556. Dir.rmdir(dirname)
  1557. end
  1558. def test_s_require_changedpath
  1559. old = $:.clone
  1560. begin
  1561. dirname1 = "_dummy_dir1"
  1562. dirname2 = "_dummy_dir2"
  1563. filename = 'a.rb'
  1564. make_file(dirname1, filename, 1) do
  1565. make_file(dirname2, filename, 2) do
  1566. assert(!$".include?(filename))
  1567. $:.unshift(dirname1)
  1568. assert(require(filename))
  1569. # the next line proves that Ruby excludes files, even though
  1570. # we have changed the path, and the originally loaded file no
  1571. # longer is first in the path.
  1572. $:.unshift(dirname2)
  1573. assert(!require(filename))
  1574. end
  1575. end
  1576. ensure
  1577. $:.clear; $:.concat(old) # restore path
  1578. end
  1579. end
  1580. def test_s_scan
  1581. $_ = "cruel world"
  1582. assert_equal(["cruel","world"], scan(/\w+/))
  1583. assert_equal(["cru", "el ","wor"], scan(/.../))
  1584. assert_equal([["cru"], ["el "],["wor"]], scan(/(...)/))
  1585. res=[]
  1586. assert_equal($_, scan(/\w+/) { |w| res << w })
  1587. assert_equal(["cruel","world"], res)
  1588. res=[]
  1589. assert_equal($_, scan(/.../) { |w| res << w })
  1590. assert_equal(["cru", "el ","wor"], res)
  1591. res=[]
  1592. assert_equal($_, scan(/(...)/) { |w| res << w })
  1593. assert_equal([["cru"], ["el "],["wor"]], res)
  1594. assert_equal("cruel world", $_)
  1595. end
  1596. # Need a better test here
  1597. def test_s_select
  1598. assert_nil(select(nil, nil, nil, 0))
  1599. assert_raise(ArgumentError) { select(nil, nil, nil, -1) }
  1600. tf = Tempfile.new("tf")
  1601. tf.close
  1602. begin
  1603. File.open(tf.path) do |file|
  1604. res = select([file], [$stdout, $stderr], [], 1)
  1605. assert_equal([[file], [$stdout, $stderr], []], res)
  1606. end
  1607. ensure
  1608. tf.close(true)
  1609. end
  1610. end
  1611. def trace_func(*params)
  1612. params.slice!(4) # Can't check the binding
  1613. @res << params
  1614. end
  1615. def trace_func_test(file, line)
  1616. __LINE__
  1617. end
  1618. def test_s_set_trace_func
  1619. @res = []
  1620. line = __LINE__
  1621. set_trace_func(proc {|*a| trace_func(*a) })
  1622. innerLine = trace_func_test(__FILE__, __LINE__)
  1623. set_trace_func(nil)
  1624. assert_equal(["line", __FILE__, line+2, :test_s_set_trace_func, TestKernel],
  1625. @res.shift)
  1626. Version.less_than("1.8.0") do
  1627. if defined? Object.allocate
  1628. assert_equal(["c-call", __FILE__, line+2, :allocate, String],
  1629. @res.shift)
  1630. assert_equal(["c-return", __FILE__, line+2, :allocate, String],
  1631. @res.shift)
  1632. end
  1633. end
  1634. assert_equal(["call", __FILE__, innerLine-1, :trace_func_test, TestKernel],
  1635. @res.shift)
  1636. assert_equal(["line", __FILE__, innerLine, :trace_func_test, TestKernel],
  1637. @res.shift)
  1638. assert_equal("return", @res.shift[0])
  1639. end
  1640. class SMATest
  1641. @@sms = []
  1642. def SMATest.singleton_method_added(id)
  1643. @@sms << id.id2name
  1644. end
  1645. def getsms() @@sms end
  1646. def SMATest.b() end
  1647. end
  1648. def SMATest.c() end
  1649. def test_s_singleton_method_added
  1650. assert_bag_equal(%w(singleton_method_added b c), SMATest.new.getsms)
  1651. end
  1652. def test_s_sleep
  1653. s1 = Time.now
  1654. 11.times { sleep 0.1 }
  1655. s2 = Time.now
  1656. assert((s2-s1) >= 1)
  1657. assert((s2-s1) <= 3)
  1658. duration = sleep(0.1)
  1659. assert_instance_of(Fixnum, duration)
  1660. assert(duration >= 0 && duration < 2)
  1661. # Does Thread.run interrupt a sleep
  1662. pThread = Thread.current
  1663. Thread.new { sleep 1; pThread.run }
  1664. s1 = Time.now
  1665. duration = sleep 999
  1666. s2 = Time.now
  1667. assert(duration >= 0 && duration <= 2, "#{duration} not in 0..2")
  1668. assert((s2-s1) >= 0)
  1669. assert((s2-s1) <= 3)
  1670. end
  1671. def test_s_split
  1672. assert_equal(nil,$;)
  1673. $_ = " a b\t c "
  1674. assert_equal(["a", "b", "c"], split)
  1675. assert_equal(["a", "b", "c"], split(" "))
  1676. $_ = " a | b | c "
  1677. assert_equal([" a "," b "," c "], split("|"))
  1678. $_ = "aXXbXXcXX"
  1679. assert_equal(["a", "b", "c"], split(/X./))
  1680. $_ = "abc"
  1681. assert_equal(["a", "b", "c"], split(//))
  1682. $_ = "a|b|c"
  1683. assert_equal(["a|b|c"], split('|',1))
  1684. assert_equal(["a", "b|c"], split('|',2))
  1685. assert_equal(["a","b","c"], split('|',3))
  1686. $_ = "a|b|c|"
  1687. assert_equal(["a","b","c",""], split('|',-1))
  1688. $_ = "a|b|c||"
  1689. assert_equal(["a","b","c","",""], split('|',-1))
  1690. $_ = "a||b|c|"
  1691. assert_equal(["a","", "b", "c"], split('|'))
  1692. assert_equal(["a","", "b", "c",""], split('|',-1))
  1693. end
  1694. def test_s_sprintf
  1695. assert_equal("00123", sprintf("%05d", 123))
  1696. assert_equal("123 |00000001", sprintf("%-5s|%08x", 123, 1))
  1697. x = sprintf("%3s %-4s%%foo %.0s%5d %#x%c%3.1f %b %x %X %#b %#x %#X",
  1698. "hi",
  1699. 123,
  1700. "never seen",
  1701. 456,
  1702. 0,
  1703. ?A,
  1704. 3.0999,
  1705. 11,
  1706. 171,
  1707. 171,
  1708. 11,
  1709. 171,
  1710. 171)
  1711. assert_equal(' hi 123 %foo 456 0x0A3.1 1011 ab AB 0b1011 0xab 0XAB', x)
  1712. end
  1713. def test_s_srand
  1714. # Check that srand with an argument always returns the same value
  1715. [ 0, 123, 45678980].each do |seed|
  1716. srand(seed)
  1717. expected = rand(2**30)
  1718. 5.times do
  1719. assert_equal(seed, srand(seed))
  1720. assert_equal(expected, rand(2**30))
  1721. end
  1722. end
  1723. # Now check that the seed is random if called with no argument
  1724. keys = {}
  1725. values = {}
  1726. dups = 0
  1727. 100.times do
  1728. oldSeed = srand
  1729. dups += 1 if keys[oldSeed]
  1730. keys[oldSeed] = 1
  1731. value = rand(2**30)
  1732. dups += 1 if values[value]
  1733. values[value] = 1
  1734. end
  1735. # this is a crap shoot, but more than 2 dups is suspicious
  1736. assert(dups <= 2, "srand may not be randomized.")
  1737. # and check that the seed is randomized for different runs of Ruby
  1738. values = {}
  1739. 5.times do
  1740. val = `#$interpreter -e "puts rand(2**30)"`
  1741. assert($? == 0)
  1742. val = val.to_i
  1743. assert_nil(values[val])
  1744. values[val] = 1
  1745. end
  1746. end
  1747. def test_s_sub
  1748. $_ = "hello"
  1749. assert_equal("hello", sub(/x/,'*'))
  1750. assert_equal("hello", $_)
  1751. $_ = "hello"
  1752. assert_equal("h*llo", sub(/[aeiou]/,'*'))
  1753. assert_equal("h*llo", $_)
  1754. $_ = "hello"
  1755. assert_equal("h<e>llo", sub(/([aeiou])/,'<\1>'))
  1756. assert_equal("h<e>llo", $_)
  1757. $_ = "hello"
  1758. assert_equal("104 ello", sub(/./) { |s| s[0].to_s+' '})
  1759. assert_equal("104 ello", $_)
  1760. $_ = "hello"
  1761. assert_equal("HELL-o", sub(/(hell)(.)/) {|s| $1.upcase + '-' + $2})
  1762. assert_equal("HELL-o", $_)
  1763. $_ = "hello".taint
  1764. assert(sub(/./,'X').tainted?)
  1765. end
  1766. def test_s_sub!
  1767. $_ = "hello"
  1768. assert_equal(nil, sub!(/x/,'*'))
  1769. assert_equal("hello", $_)
  1770. $_ = "hello"
  1771. assert_equal("h*llo", sub!(/[aeiou]/,'*'))
  1772. assert_equal("h*llo", $_)
  1773. $_ = "hello"
  1774. assert_equal("h<e>llo", sub!(/([aeiou])/,'<\1>'))
  1775. assert_equal("h<e>llo", $_)
  1776. $_ = "hello"
  1777. assert_equal("104 ello", sub!(/./) { |s| s[0].to_s+' '})
  1778. assert_equal("104 ello", $_)
  1779. $_ = "hello"
  1780. assert_equal("HELL-o", sub!(/(hell)(.)/) {|s| $1.upcase + '-' + $2})
  1781. assert_equal("HELL-o", $_)
  1782. $_ = "hello".taint
  1783. assert(sub!(/./,'X').tainted?)
  1784. end
  1785. def test_s_syscall
  1786. skipping("platform specific")
  1787. end
  1788. def test_s_system
  1789. open("xyzzy.dat", "w") { |f| f.puts "stuff" }
  1790. tf = Tempfile.new("tf")
  1791. begin
  1792. # all in one string - wildcards get expanded
  1793. tf.puts 'system("echo xy*y.dat")'
  1794. tf.close
  1795. IO.popen("#$interpreter #{tf.path}") do |p|
  1796. assert_equal("xyzzy.dat\n", p.gets)
  1797. end
  1798. # with two parameters, the '*' doesn't get expanded
  1799. tf.open
  1800. tf.puts 'system("echo", "xy*y.dat")'
  1801. tf.close
  1802. IO.popen("#$interpreter #{tf.path}") do |p|
  1803. assert_equal("xy*y.dat\n", p.gets)
  1804. end
  1805. ensure
  1806. tf.close(true)
  1807. File.unlink "xyzzy.dat" if p
  1808. end
  1809. Version.less_than("1.9.0") do
  1810. system("____this_is_a_bad command____")
  1811. assert($? != 0)
  1812. end
  1813. Version.greater_or_equal("1.9.0") do
  1814. assert_raise(Errno::ENOENT) {
  1815. system("____this_is_a_bad command____")
  1816. }
  1817. end
  1818. end
  1819. # def test_s_test
  1820. # # in TestKernelTest
  1821. # end
  1822. def test_s_throw
  1823. # tested by test_s_catch
  1824. end
  1825. def test_s_trace_var
  1826. val = nil
  1827. p = proc { |val| }
  1828. trace_var(:$_, p)
  1829. $_ = "123"
  1830. assert_equal($_, val)
  1831. $_ = nil
  1832. assert_equal($_, val)
  1833. untrace_var("$_")
  1834. $_ = "123"
  1835. assert_equal(nil, val)
  1836. assert_equal("123", $_)
  1837. end
  1838. def test_s_trap
  1839. res = nil
  1840. lastProc = proc { res = 1 }
  1841. # 1. Check that an exception is thrown if we wait for a child and
  1842. # there is no child.
  1843. # "IGNORE" discards child termination status (but apparently not
  1844. # under Cygwin/W2k
  1845. Unix.only do
  1846. trap "CHLD", "IGNORE"
  1847. pid = fork
  1848. exit unless pid
  1849. sleep 1 # ensure child has exited (ish)
  1850. assert_raise(Errno::ECHILD) { Process.wait }
  1851. end
  1852. # 2. check that we run a proc as a handler when a child
  1853. # terminates
  1854. MsWin32.dont do
  1855. trap("SIGCHLD", lastProc)
  1856. fork { ; }
  1857. Process.wait
  1858. assert_equal(1, res)
  1859. end
  1860. # 3. Reset the signal handler (checking it returns the previous
  1861. # value) and ensure that the proc doesn't get called
  1862. MsWin32.dont do
  1863. assert_equal(lastProc, trap("SIGCHLD", "DEFAULT"))
  1864. res = nil
  1865. fork { ; }
  1866. Process.wait
  1867. assert_nil(res)
  1868. end
  1869. # 4. test EXIT handling
  1870. IO.popen(%{#$interpreter -e 'trap "EXIT", "exit! 123";exit 99'}).close
  1871. assert_equal(123<<8, $?)
  1872. end
  1873. def test_s_untrace_var1
  1874. trace_var(:$_, "puts 99")
  1875. p = proc { |val| }
  1876. trace_var("$_", p)
  1877. assert_bag_equal(["puts 99", p], untrace_var(:$_))
  1878. assert_equal([], untrace_var(:$_))
  1879. end
  1880. def test_s_untrace_var2
  1881. trace_var(:$_, "puts 99")
  1882. p = proc { |val| }
  1883. trace_var("$_", p)
  1884. assert_bag_equal(["puts 99", p], untrace_var(:$_))
  1885. end
  1886. def test_gvar_alias
  1887. $foo = 3
  1888. eval "alias $bar $foo"
  1889. assert_equal(3, $bar)
  1890. $bar = 4
  1891. assert_equal(4, $foo)
  1892. end
  1893. def test_svar_alias
  1894. eval "alias $foo $_"
  1895. $_ = 1
  1896. assert_equal(1, $foo)
  1897. $foo = 2
  1898. assert_equal(2, $_)
  1899. end
  1900. end