* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / test / irb / test_color_printer.rb
blob93ec700146556471a10c54315fbaa794e2214945
1 # frozen_string_literal: false
2 require 'test/unit'
3 require 'irb/color_printer'
4 require 'rubygems'
5 require 'stringio'
7 module TestIRB
8   class TestColorPrinter < Test::Unit::TestCase
9     CLEAR     = "\e[0m"
10     BOLD      = "\e[1m"
11     RED       = "\e[31m"
12     GREEN     = "\e[32m"
13     BLUE      = "\e[34m"
14     CYAN      = "\e[36m"
16     def setup
17       @get_screen_size = Reline.method(:get_screen_size)
18       Reline.instance_eval { undef :get_screen_size }
19       def Reline.get_screen_size
20         [36, 80]
21       end
22     end
24     def teardown
25       Reline.instance_eval { undef :get_screen_size }
26       Reline.define_singleton_method(:get_screen_size, @get_screen_size)
27     end
29     IRBTestColorPrinter = Struct.new(:a)
31     def test_color_printer
32       unless ripper_lexer_scan_supported?
33         pend 'Ripper::Lexer#scan is supported in Ruby 2.7+'
34       end
35       {
36         1 => "#{BLUE}#{BOLD}1#{CLEAR}\n",
37         "a\nb" => %[#{RED}#{BOLD}"#{CLEAR}#{RED}a\\nb#{CLEAR}#{RED}#{BOLD}"#{CLEAR}\n],
38         IRBTestColorPrinter.new('test') => "#{GREEN}#<struct TestIRB::TestColorPrinter::IRBTestColorPrinter#{CLEAR} a#{GREEN}=#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}#{RED}test#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}#{GREEN}>#{CLEAR}\n",
39         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",
40         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",
41       }.each do |object, result|
42         actual = with_term { IRB::ColorPrinter.pp(object, '') }
43         assert_equal(result, actual, "Case: IRB::ColorPrinter.pp(#{object.inspect}, '')")
44       end
45     end
47     private
49     def ripper_lexer_scan_supported?
50       Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7.0')
51     end
53     def with_term
54       stdout = $stdout
55       io = StringIO.new
56       def io.tty?; true; end
57       $stdout = io
59       env = ENV.to_h.dup
60       ENV['TERM'] = 'xterm-256color'
62       yield
63     ensure
64       $stdout = stdout
65       ENV.replace(env) if env
66     end
67   end
68 end