|
| 1 | +# frozen_string_literal: false |
| 2 | +require 'test/unit' |
| 3 | +require 'irb/color_printer' |
| 4 | +require 'rubygems' |
| 5 | +require 'stringio' |
| 6 | + |
| 7 | +module TestIRB |
| 8 | + class TestColorPrinter < Test::Unit::TestCase |
| 9 | + CLEAR = "\e[0m" |
| 10 | + BOLD = "\e[1m" |
| 11 | + UNDERLINE = "\e[4m" |
| 12 | + REVERSE = "\e[7m" |
| 13 | + RED = "\e[31m" |
| 14 | + GREEN = "\e[32m" |
| 15 | + YELLOW = "\e[33m" |
| 16 | + BLUE = "\e[34m" |
| 17 | + MAGENTA = "\e[35m" |
| 18 | + CYAN = "\e[36m" |
| 19 | + |
| 20 | + def setup |
| 21 | + @get_screen_size = Reline.method(:get_screen_size) |
| 22 | + Reline.instance_eval { undef :get_screen_size } |
| 23 | + def Reline.get_screen_size |
| 24 | + [36, 80] |
| 25 | + end |
| 26 | + end |
| 27 | + |
| 28 | + def teardown |
| 29 | + Reline.instance_eval { undef :get_screen_size } |
| 30 | + Reline.define_singleton_method(:get_screen_size, @get_screen_size) |
| 31 | + end |
| 32 | + |
| 33 | + IRBTestColorPrinter = Struct.new(:a) |
| 34 | + |
| 35 | + def test_color_printer |
| 36 | + unless ripper_lexer_scan_supported? |
| 37 | + skip 'Ripper::Lexer#scan is supported in Ruby 2.7+' |
| 38 | + end |
| 39 | + { |
| 40 | + 1 => "#{BLUE}#{BOLD}1#{CLEAR}\n", |
| 41 | + IRBTestColorPrinter.new('test') => "#{GREEN}#<struct TestIRB::TestColorPrinter::IRBTestColorPrinter#{CLEAR} a#{GREEN}=#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}#{RED}test#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}#{GREEN}>#{CLEAR}\n", |
| 42 | + Ripper::Lexer.new('1').scan => "[#{GREEN}#<Ripper::Lexer::Elem:#{CLEAR} on_int@1:0 END token: #{RED}#{BOLD}\"#{CLEAR}#{RED}1#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}#{GREEN}>#{CLEAR}]\n", |
| 43 | + Class.new{define_method(:pretty_print){|q| q.text("[__FILE__, __LINE__, __ENCODING__]")}}.new => "[#{CYAN}#{BOLD}__FILE__#{CLEAR}, #{CYAN}#{BOLD}__LINE__#{CLEAR}, #{CYAN}#{BOLD}__ENCODING__#{CLEAR}]\n", |
| 44 | + }.each do |object, result| |
| 45 | + actual = with_term { IRB::ColorPrinter.pp(object, '') } |
| 46 | + assert_equal(result, actual, "Case: IRB::ColorPrinter.pp(#{object.inspect}, '')") |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + private |
| 51 | + |
| 52 | + def ripper_lexer_scan_supported? |
| 53 | + Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7.0') |
| 54 | + end |
| 55 | + |
| 56 | + def with_term |
| 57 | + stdout = $stdout |
| 58 | + io = StringIO.new |
| 59 | + def io.tty?; true; end |
| 60 | + $stdout = io |
| 61 | + |
| 62 | + env = ENV.to_h.dup |
| 63 | + ENV['TERM'] = 'xterm-256color' |
| 64 | + |
| 65 | + yield |
| 66 | + ensure |
| 67 | + $stdout = stdout |
| 68 | + ENV.replace(env) if env |
| 69 | + end |
| 70 | + end |
| 71 | +end |
0 commit comments