$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'test_helper' require 'stringio' include IterationLab class RubyLabsTest < Test::Unit::TestCase def test_00_banner print "\nRubyLabs" end # A test array is an array of randomly selected integers. A method named random # should return a number that is guaranteed to be in the array, when passed the # :success option, or a number that is not in the array, when passed :fail def test_01_arrays a = TestArray.new(10) assert a.length == 10 assert a.include?(a.random(:success)) assert !a.include?(a.random(:fail)) end # Simple test to make sure log2 is defined... def test_02_log2 assert_equal 3.0, log2(8) end # Test min and max methods def test_03_minmax assert_equal 10, min(10,20) assert_equal 10, min(20,10) assert_equal 20, max(10,20) assert_equal 20, max(20,10) end # This test just makes sure the time method runs -- no way to really test to # see if the result is accurate def test_04_time assert_not_nil time { min(10,20) } end # Capture the listing of the 'less' method (from IterationLab); it should have # three lines of Ruby code, with a 'def', 'return', and 'end' def test_05_listing oldout = $stdout newout = StringIO.new $stdout = newout Source.listing :less $stdout = oldout lines = newout.string.split("\n") assert_equal 3, lines.length assert_match /1:\s+def less/, lines[0] assert_match /2:\s+return/, lines[1] assert_match /3:\s+end/, lines[2] end # This test sets a "counting probe" on the method named 'less' in the IterationLab # module, and then counts how many times 'less' is called. def test_06_count assert Source.clear assert Source.probe :less, 2, :count n = count { less(10,20) } assert_equal 1, n end # Same as above, except the probe prints a message to stdout. Capture the message # to make sure the probe mechanism works. def test_07_trace oldout = $stdout newout = StringIO.new assert Source.probe :less, 2, "puts 'got it'" $stdout = newout res = trace { less(10,20) } $stdout = oldout assert res assert_equal "got it", newout.string.chomp end # Priority Queue test def test_08_priority_queue pq = PriorityQueue.new [5, 15, 10, 20, 0].each { |x| pq << x } assert_equal 5, pq.length assert_equal 0, pq[0] assert_equal 20, pq[-1] assert_equal 0, pq.shift assert_equal 4, pq.length assert_raise(NoMethodError) { pq[0] = 100 } end # 'ord' method -- maps upper and lower case letters to 0..25, others return # self (i.e. ASCII code) def test_09_ord assert_equal 0, ?A.ord assert_equal 25, ?Z.ord assert_equal 0, ?a.ord assert_equal 25, ?z.ord assert_equal ?:.ord, ?: end end