Advertisement
cd62131

cout with test

Oct 30th, 2017
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.24 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. def cout(*args)
  4.   raise 'no args' if args.empty?
  5.   format = args.shift
  6.   out = ''
  7.   until format.empty?
  8.     if m = format.match(/%(.)/)
  9.       out << m.pre_match
  10.       case m[1]
  11.       when '%'
  12.         out << '%'
  13.       when 'd'
  14.         raise 'few args' if args.empty?
  15.         out << args.shift.to_i.to_s
  16.       else
  17.         raise "illegal input: \"#{m[1]}\""
  18.       end
  19.       format = m.post_match
  20.     else
  21.       break
  22.     end
  23.   end
  24.   raise 'unmatch %' if format.include? '%'
  25.   raise "too many args: #{args}" unless args.empty?
  26.   puts out << format
  27. end
  28.  
  29. require 'test/unit'
  30. class TestCout < Test::Unit::TestCase
  31.   def capture_cout(*args)
  32.     if args.empty?
  33.       capture_output do
  34.         cout
  35.       end
  36.     else
  37.       capture_output do
  38.         cout *args
  39.       end
  40.     end
  41.   end
  42.   def test_cout
  43.     assert_raise_message('unmatch %') { capture_cout '%' }
  44.     assert_raise_message('too many args: [2]') { capture_cout 'abc%d', 1, 2 }
  45.     assert_raise_message('few args') { capture_cout 'abc%d' }
  46.     assert_raise_message('illegal input: "i"') { capture_cout '%d %i', 1, 2 }
  47.     assert_raise_message('no args') { capture_cout }
  48.     assert_equal ["1 etc.\n", ''], capture_cout('%d etc.', 1)
  49.   end
  50. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement