ruby/test/readline/test_readline.rb
aycabta 0057fe4063
Ruby 2.7 backport about IRB (#2990)
* [ruby/reline] Sort completion list

#### Legacy mode:

  ```console
  $ irb --legacy
  irb(main):001:0> l[TAB][TAB]
  lambda           load             local_variables  loop
  ```

#### Before this patch:

  ```console
  $ irb
  irb(main):001:0> l[TAB][TAB]
  local_variables
  loop
  lambda
  load
  ```

#### After this patch:

  ```console
  $ irb
  irb(main):001:0> l[TAB][TAB]
  lambda
  load
  local_variables
  loop
  ```

6074069c7d

* Drop an invalid char as UTF-8

* Add test_completion_with_indent_and_completer_quote_characters

This is for 8a705245e5.

* [ruby/irb] Add tests for RubyLex

The set_auto_indent method calculates the correct number of spaces for
indenting a line. We think there might be a few bugs in this method so
we are testing the current functionality to make sure nothing breaks
when we address those bugs.

Example test failure:

```
  1) Failure:
TestIRB::TestRubyLex#test_auto_indent [/Users/Ben/Projects/irb/test/irb/test_ruby_lex.rb:75]:
Calculated the wrong number of spaces for:
 def each_top_level_statement
  initialize_input
  catch(:TERM_INPUT) do
    loop do
      begin
        prompt
        unless l = lex
          throw :TERM_INPUT if @line == ''
        else
.
<10> expected but was
<12>.
```

752d5597ab

* [ruby/reline] Degenerate the terminal size to [$LINES, $COLUMNS] if it is unknown

This is a workaround for https://github.com/ruby/irb/issues/50

5725677d1a

* [ruby/irb] Fix newline depth with multiple braces

This commit fixes the check_newline_depth_difference method to multiple
open braces on one line into account. Before this change we were
subtracting from the depth in check_newline_depth_difference on
every open brace. This is the right thing to do if the opening and
closing brace are on the same line. For example in a method definition we
have an opening and closing parentheses we want to add 1 to our depth,
and then remove it.

```
def foo()
end
```

However this isn't the correct behavior when the brace spans multiple
lines. If a brace spans multiple lines we don't want to subtract from
check_newline_depth_difference and we want to treat the braces the same
way as we do `end` and allow check_corresponding_token_depth to pop the
correct depth.

Example of bad behavior:

```
def foo()
  [
  ]
puts 'bar'
end
```

Example of desired behavior:

```
def foo()
  [
  ]
  puts 'bar'
end
```

7dc8af01e0

* text/readline/test_readline.rb - fix skip on Reline (#2743)

TestRelineAsReadline#test_input_metachar passes on MinGW

* Add "require 'openstruct'" what is forgotten

* [ruby/irb] Fix lib name of OpenStruct

1f3a84ab6b

* Add load path and require for ruby/ruby

* Rescue EOFError

If C-d is pressed before IRB is ready, IRB crashes because EOFError occurs.

* Complete indented and quoted string correctly

  def foo
    ''.upca[TAB]

This will be completed to be:

  def foo
  ''.upcase

The indent was gone. This commit fixes the bug.

* [ruby/irb] Fix crashing when multiple open braces per line

https://github.com/ruby/irb/issues/55

If we had put multiple open braces on a line the with no closing brace
spaces_of_nest array keeps getting '0' added to it. This means that when
we pop off of this array we are saying that we should be in position zero
for the next line. This is an issue because we don't always want to be
in position 0 after a closing brace.

Example:
```
[[[
]
]
]
```
In the above example the 'spaces_of_nest' array looks like this after
the first line is entered: [0,0,0]. We really want to be indented 4
spaces for the 1st closing brace 2 for the 2nd and 0 for the 3rd. i.e.
we want it to be: [0,2,4].

We also saw this issue with a heredoc inside of an array.

```
[<<FOO]
hello
FOO
```

80c69c8272

* Support history-size in .inputrc correctly

* Introduce an abstracted structure about the encoding of Reline

The command prompt on Windows always uses Unicode to take input and print
output but most Reline implementation depends on Encoding.default_external.
This commit introduces an abstracted structure about the encoding of Reline.

* Remove an unused setting variable

* Use Reline.encoding_system_needs if exists

* Add tests for vi_insert and vi_add

* Implement vi_insert_at_bol and vi_add_at_eol

* [ruby/reline] Implement vi_to_next_char

066ecb0a21

* [ruby/reline] Implement vi_prev_char and vi_to_prev_char

0ad3ee63fa

* [ruby/readline-ext] Include ruby/assert.h in ruby/ruby.h so that assertions can be there

4d44c12832

* Stop using minitest dependent methods

* Skip a test that uses assert_ruby_status if it doesn't exist

* Use omit instead of skip

* Check DONT_RUN_RELINE_TEST envvar

* [ruby/irb] Add newline_before_multiline_output

9eb1801a66

* [ruby/irb] Fix compatibility with rails before 5.2

Rails before 5.2 added Array#append as an alias to Array#<< ,
so that it expects only one argument.
However ruby-2.5 added Array#append as an alias to Array#push
which takes any number of arguments.

If irb completion is used in `rails c` (for example "IO.<tab>")
it fails with:
  irb/completion.rb:206:in `<<': wrong number of arguments (given 3, expected 1) (ArgumentError)

Using Array#push instead of Array#append fixes compatibility.

5b7bbf9c34

* Reline: Use a more robust detection of MinTTY

The previous detection per get_screen_size fails when stdout is passed
to a pipe. That is the case when running ruby tests in parallel ("-j" switch).
In this case Reline believes that it's running on MinTTY and the tests
are running with ANSI IOGate instead of the Windows adapter on MINGW.
So parallel test results were different to that of a single process.
This commit fixes these differencies.

The code is taken from git sources and translated to ruby.
NtQueryObject() is replaced by GetFileInformationByHandleEx(), because
NtQueryObject() is undocumented and is more difficult to use:
  c5a03b1e29/compat/winansi.c (L558)

* Reline: Fix changed test results due to change to UTF-8 on Windows

In commit f8ea2860b0 the Reline encoding
for native windows console was changed to hardcoded UTF-8.
This caused failures in reline and readline tests, but they were hidden,
because parallel ruby tests incorrectly used Reline::ANSI as IOGate.
Tests failures were raised in single process mode, but not with -j switch.

This patch corrects encodings on native Windows console.

* [ruby/irb] [ruby/irb] Rewrite an expression to detect multiline

ed5cf375a6

5b7bbf9c34

* [ruby/reline] Implement vi_change_meta

8538e0e10f

* Always refer to Reline::IOGate.encoding

* Always use UTF-8 for Reline::GeneralIO on Windows

* Use test_mode on Reline::History::Test for encoding

* [ruby/reline] Support GNOME style Home/End key sequences [Bug #16510]

788f0df845

* [ruby/irb] Add a new easter egg: dancing ruby

e37dc7e58e

* [ruby/irb] Exclude useless files from RDoc

8f1ab2400c

* [ruby/irb] Exclude useless files from RDoc

* Fix inaccuracy in encoding tests

These tests assume
  Encoding.find('locale') == Encoding.find('external')
and fail if they are distinct.

* [ruby/reline] Fix Reline::Windows#scroll_down

I mistook Right and Bottom.

8be401c5f5

* [ruby/reline] Bypass cursor down when a char is rendered at eol on Windows

A newline is automatically inserted if a character is rendered at eol on
Windows command prompt.

4bfea07e4a

* [ruby/reline] Organize special keys escape sequences

41deb1a3d9

* [ruby/readline-ext] Remove unnecessary -I$(top_srcdir) when it's an individual gem

efaca4a5f4

* [ruby/readline-ext] Check TestRelineAsReadline existance

c0a6303168

* [ruby/readline-ext] The ruby/assert.h is adopted by Ruby 2.7 or later

106c31fc1b

* Revert "[ruby/readline-ext] Include ruby/assert.h in ruby/ruby.h so that assertions can be there"

This reverts commit 425b2064d3.

This cherry-pick was a mistake.

* [ruby/readline-ext] Use require check instead of DONT_RUN_RELINE_TEST env

1df99d1481

* [ruby/readline-ext] Add spec.extensions

8c33abb13c

* [ruby/readline-ext] Use rake/extensiokntask to build

b0b5f709bd

* Fix readline build dependency

* [ruby/irb] Add test_complete_symbol

dbbf086c1f

* [ruby/irb] Check doc namespace correctly

IRB::InputCompletor::PerfectMatchedProc crashes when doc not found because a
variable name was incorrect.

889fd4928f

* [ruby/irb] Fix auto indent with closed brace

A closed brace in auto-indent shouldn't affect the next brace in the same line,
but it behaves like below:

  p() {
    }

It's a bug.

fbe59e344f

* [ruby/irb] Use 0.step instead of (..0).each for Ruby 2.5

5d628ca40e

* Revert "[ruby/irb] Add test_complete_symbol"

This reverts commit 3af3431c2c.

* [ruby/irb] fix reserved words and completion for them

6184b227ad

* Add test_complete_symbol

The previous version of the test method used a symbol, ":abcdefg" to complete
but longer symbols that can be completed are defined by other test methods of
other libs.

* test/irb/test_completion.rb: suppress a warning: unused literal ignored

* [ruby/reline] Use IO#write instead of IO#print

IO#print always adds a string of $\ automatically.

a93119c847

* [ruby/irb] Version 1.2.2

a71753f15a

* [ruby/reline] Version 0.1.3

ea2b182466

* [ruby/irb] Include easter-egg.rb in gemspec

`irb` doesn't run because this file isn't included in the gem.
73cda56d25

* [ruby/irb] Version 1.2.3

dd56e06df5

* support multi-run test for test_readline.rb

* [ruby/irb] `yield` outside method definition is a syntax error

dbc7b059c7

* test/readline - allow ENV control of test class creation

In ruby/ruby, the tests run on both readline & reline by creating four test classes:
```
TestReadline
TestReadlineHistory

TestRelineAsReadline
TestRelineAsReadlineHistory
```

Reline inports the test files and uses them in its CI.  Adding the ENV control allows it to only run the `TestRelineAsReadline` classes.

* Omit test_using_quoting_detection_proc_with_multibyte_input temporarily for random order test

* support random order test.

test_readline:
  HISTORY should be empty.

test_using_quoting_detection_proc:
test_using_quoting_detection_proc_with_multibyte_input:
  Readline.completer_quote_characters= and
  Readline.completer_word_break_characters= doesn't accept nil,
  so skip if previous values are nil.

* Set Readline.completion_append_character = nil always

GNU Readline add a white space when Readline.completion_append_character is
not initialized.

* Fix a typo [ci skip]

* skip test if Reline.completion_proc is nil.

Some other tests can set Reline.completion_proc, so if it is nil,
simply skip this test.

* Reset Reline.point

TestRelineAsReadline#test_insert_text expects Readline.point == 0
at the beginning of the test, but a test violate this assumption.

* Convert incompatible encoding symbol names

* Ignore incompatible convert of symbols

* Add workaround for test-bundler failure

500526558 (step):16:127
```
Failures:

  1) Bundler.setup when Bundler is bundled doesn't blow up
     Failure/Error: expect(err).to be_empty

       expected `"fatal: not a git repository (or any of the parent directories): .git\nfatal: not a git repository (o...the parent directories): .git\nfatal: not a git repository (or any of the parent directories): .git".empty?` to return true, got false

       Commands:
       $ /home/runner/work/actions/actions/snapshot-master/ruby \
         -I/home/runner/work/actions/actions/snapshot-master/lib:/home/runner/work/actions/actions/snapshot-master/spec/bundler \
         -rsupport/hax -rsupport/artifice/fail \
         /home/runner/work/actions/actions/snapshot-master/libexec/bundle install --retry 0
       Resolving dependencies...
       Using bundler 2.1.4
       Bundle complete! 1 Gemfile dependency, 1 gem now installed.
       Use `bundle info [gemname]` to see where a bundled gem is installed.
       fatal: not a git repository (or any of the parent directories): .git
       fatal: not a git repository (or any of the parent directories): .git
       fatal: not a git repository (or any of the parent directories): .git
       # $? => 0

       $ /home/runner/work/actions/actions/snapshot-master/ruby \
         -I/home/runner/work/actions/actions/snapshot-master/lib:/home/runner/work/actions/actions/snapshot-master/spec/bundler \
         -rsupport/hax -rsupport/artifice/fail \
         /home/runner/work/actions/actions/snapshot-master/libexec/bundle exec ruby -e \
         require\ \'bundler\'\;\ Bundler.setup
       fatal: not a git repository (or any of the parent directories): .git
       fatal: not a git repository (or any of the parent directories): .git
       fatal: not a git repository (or any of the parent directories): .git
       # $? => 0
     # ./spec/bundler/runtime/setup_spec.rb:1056:in `block (3 levels) in <top (required)>'
     # ./spec/bundler/spec_helper.rb:111:in `block (3 levels) in <top (required)>'
     # ./spec/bundler/spec_helper.rb:111:in `block (2 levels) in <top (required)>'
     # ./spec/bundler/spec_helper.rb:78:in `block (2 levels) in <top (required)>'
make: *** [yes-test-bundler] Error 1
```

* [ruby/irb] Unnamed groups are not captured when named groups are used

0a641a69b0

* [ruby/reline] Work with wrong $/ value correctly

962ebf5a1b

* [ruby/irb] Detect multiple lines output simplify

The old implementation performance test code:

    require 'objspace'
    puts "%.5g MB" % (ObjectSpace.memsize_of_all * 0.001 * 0.001)
    /\A.*\Z/ !~ ('abc' * 20_000_000)
    puts "%.5g MB" % (ObjectSpace.memsize_of_all * 0.001 * 0.001)

and run `time test.rb`:

    2.5868 MB
    62.226 MB

    real    0m1.307s
    user    0m0.452s
    sys     0m0.797s

The new implementation performance test code:

    require 'objspace'
    puts "%.5g MB" % (ObjectSpace.memsize_of_all * 0.001 * 0.001)
    ('abc' * 20_000_000).include?("\n")
    puts "%.5g MB" % (ObjectSpace.memsize_of_all * 0.001 * 0.001)

and run `time test.rb`:

    2.5861 MB
    62.226 MB

    real    0m0.132s
    user    0m0.088s
    sys     0m0.042s

40d6610baf

* [ruby/reline] Suppress error in case INPUTRC env is empty

bce7e7562b

* [ruby/reline] Add yamatanooroti rendering test

f092519525

* [ruby/reline] Rename test suite name of yamatanooroti test

b0f32f5de4

* [ruby/reline] Add a comment why rescue yamatanooroti loading error on the test

2a8061daec

* [ruby/irb] Suppress crashing when EncodingError has occurred without lineno

13572d8cdc

* [ruby/reline] Suppress error when check ambiguous char width in LANG=C

623dffdd75

* [ruby/io-console] Enable only interrupt bits on `intr: true`

baaf929041

* [ruby/io-console] bump up to 0.5.4

* [ruby/io-console] Update the minimum requirement of Ruby version

73e7b6318a

* [ruby/io-console] Filter Ruby engine name rather than just /ruby/

This breaks tests using this path on JRuby because the `jruby`
executable turns into `jjruby` after the sub.

e5951aa34c

* [ruby/io-console] bump up to 0.5.5

* [ruby/io-console] Prefer keyword arguments

5facbfc4c8

* [ruby/io-console] [DOC] Improved about `intr:`

82b630cd79

* [ruby/io-console] Just ignore the extension on other than CRuby

41b6f09574

* [ruby/io-console] bump up to 0.5.6

Co-authored-by: KOBAYASHI Shuji <shuujii@gmail.com>
Co-authored-by: Ben <kanobt61@gmail.com>
Co-authored-by: Yusuke Endoh <mame@ruby-lang.org>
Co-authored-by: MSP-Greg <MSP-Greg@users.noreply.github.com>
Co-authored-by: Nobuyoshi Nakada <nobu@ruby-lang.org>
Co-authored-by: Kenta Murata <mrkn@mrkn.jp>
Co-authored-by: Lars Kanis <lars@greiz-reinsdorf.de>
Co-authored-by: Lars Kanis <kanis@comcard.de>
Co-authored-by: Alan Wu <XrXr@users.noreply.github.com>
Co-authored-by: Hiroshi SHIBATA <hsbt@ruby-lang.org>
Co-authored-by: Nobuhiro IMAI <nov@yo.rim.or.jp>
Co-authored-by: Nick Lewis <nick@puppet.com>
Co-authored-by: S-H-GAMELINKS <gamelinks007@gmail.com>
Co-authored-by: Koichi Sasada <ko1@atdot.net>
Co-authored-by: Kazuhiro NISHIYAMA <zn@mbf.nifty.com>
Co-authored-by: Charles Oliver Nutter <headius@headius.com>
2020-03-30 19:09:50 +09:00

794 lines
24 KiB
Ruby

# frozen_string_literal: false
require_relative "helper"
require "test/unit"
require "tempfile"
require "timeout"
module BasetestReadline
INPUTRC = "INPUTRC"
SAVED_ENV = %w[COLUMNS LINES]
def setup
@saved_env = ENV.values_at(*SAVED_ENV)
@inputrc, ENV[INPUTRC] = ENV[INPUTRC], IO::NULL
end
def teardown
ENV[INPUTRC] = @inputrc
Readline.instance_variable_set("@completion_proc", nil)
begin
Readline.delete_text
Readline.point = 0
rescue NotImplementedError
end
Readline.special_prefixes = ""
Readline.completion_append_character = nil
Readline.input = nil
Readline.output = nil
SAVED_ENV.each_with_index {|k, i| ENV[k] = @saved_env[i] }
end
def test_readline
Readline::HISTORY.clear
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
with_temp_stdio do |stdin, stdout|
stdin.write("hello\n")
stdin.close
stdout.flush
line = replace_stdio(stdin.path, stdout.path) {
Readline.readline("> ", true)
}
assert_equal("hello", line)
assert_equal(true, line.tainted?) if RUBY_VERSION < '2.7'
stdout.rewind
assert_equal("> ", stdout.read(2))
assert_equal(1, Readline::HISTORY.length)
assert_equal("hello", Readline::HISTORY[0])
# Work around lack of SecurityError in Reline
# test mode with tainted prompt.
# Also skip test on Ruby 2.7+, where $SAFE/taint is deprecated.
if RUBY_VERSION < '2.7' && defined?(TestRelineAsReadline) && !kind_of?(TestRelineAsReadline)
begin
Thread.start {
$SAFE = 1
assert_raise(SecurityError) do
replace_stdio(stdin.path, stdout.path) do
Readline.readline("> ".taint)
end
end
}.join
ensure
$SAFE = 0
end
end
end
end
# line_buffer
# point
def test_line_buffer__point
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
omit "GNU Readline has special behaviors" if defined?(Reline) and Readline == Reline
begin
Readline.line_buffer
Readline.point
rescue NotImplementedError
return
end
with_temp_stdio do |stdin, stdout|
actual_text = nil
actual_line_buffer = nil
actual_point = nil
Readline.completion_proc = ->(text) {
actual_text = text
actual_point = Readline.point
actual_line_buffer = Readline.line_buffer
stdin.write(" finish\n")
stdin.flush
stdout.flush
return ["complete"]
}
stdin.write("first second\t")
stdin.flush
Readline.completion_append_character = " "
replace_stdio(stdin.path, stdout.path) {
Readline.readline("> ", false)
}
assert_equal("second", actual_text)
assert_equal("first second", actual_line_buffer)
assert_equal(12, actual_point)
assert_equal("first complete finish", Readline.line_buffer)
assert_equal(Encoding.find("locale"), Readline.line_buffer.encoding)
assert_equal(true, Readline.line_buffer.tainted?) if RUBY_VERSION < '2.7'
assert_equal(22, Readline.point)
stdin.rewind
stdout.rewind
stdin.write("first second\t")
stdin.flush
Readline.completion_append_character = nil
replace_stdio(stdin.path, stdout.path) {
Readline.readline("> ", false)
}
assert_equal("second", actual_text)
assert_equal("first second", actual_line_buffer)
assert_equal(12, actual_point)
assert_equal("first complete finish", Readline.line_buffer)
assert_equal(Encoding.find("locale"), Readline.line_buffer.encoding)
assert_equal(true, Readline.line_buffer.tainted?) if RUBY_VERSION < '2.7'
assert_equal(21, Readline.point)
end
end
def test_input=
assert_raise(TypeError) do
Readline.input = "This is not a file."
end
end
def test_output=
assert_raise(TypeError) do
Readline.output = "This is not a file."
end
end
def test_completion_proc
expected = proc { |input| input }
Readline.completion_proc = expected
assert_equal(expected, Readline.completion_proc)
assert_raise(ArgumentError) do
Readline.completion_proc = "This does not have call method."
end
end
def test_completion_case_fold
expected = [true, false, "string", {"a" => "b"}]
expected.each do |e|
Readline.completion_case_fold = e
assert_equal(e, Readline.completion_case_fold)
end
end
def test_completion_proc_empty_result
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
with_temp_stdio do |stdin, stdout|
stdin.write("first\t")
stdin.flush
Readline.completion_proc = ->(text) {[]}
line1 = line2 = nil
replace_stdio(stdin.path, stdout.path) {
assert_nothing_raised(NoMemoryError) {line1 = Readline.readline("> ")}
stdin.write("\n")
stdin.flush
assert_nothing_raised(NoMemoryError) {line2 = Readline.readline("> ")}
}
assert_equal("first", line1)
assert_equal("", line2)
begin
assert_equal("", Readline.line_buffer)
rescue NotimplementedError
end
end
end
def test_get_screen_size
begin
res = Readline.get_screen_size
assert(res.is_a?(Array))
rows, columns = *res
assert(rows.is_a?(Integer))
assert(rows >= 0)
assert(columns.is_a?(Integer))
assert(columns >= 0)
rescue NotImplementedError
end
end
# vi_editing_mode
# emacs_editing_mode
def test_editing_mode
begin
assert_equal(false, Readline.vi_editing_mode?)
assert_equal(true, Readline.emacs_editing_mode?)
assert_equal(nil, Readline.vi_editing_mode)
assert_equal(true, Readline.vi_editing_mode?)
assert_equal(false, Readline.emacs_editing_mode?)
assert_equal(nil, Readline.vi_editing_mode)
assert_equal(true, Readline.vi_editing_mode?)
assert_equal(false, Readline.emacs_editing_mode?)
assert_equal(nil, Readline.emacs_editing_mode)
assert_equal(false, Readline.vi_editing_mode?)
assert_equal(true, Readline.emacs_editing_mode?)
assert_equal(nil, Readline.emacs_editing_mode)
assert_equal(false, Readline.vi_editing_mode?)
assert_equal(true, Readline.emacs_editing_mode?)
rescue NotImplementedError
end
end
def test_completion_append_character
begin
enc = get_default_internal_encoding
data_expected = [
["x", "x"],
["xyx", "x"],
[" ", " "],
["\t", "\t"],
]
data_expected.each do |(data, expected)|
Readline.completion_append_character = data
assert_equal(expected, Readline.completion_append_character)
assert_equal(enc, Readline.completion_append_character.encoding)
end
Readline.completion_append_character = ""
assert_equal(nil, Readline.completion_append_character)
rescue NotImplementedError
end
end
def test_completion_encoding
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
bug5941 = '[Bug #5941]'
append_character = Readline.completion_append_character
Readline.completion_append_character = ""
completion_case_fold = Readline.completion_case_fold
locale = get_default_internal_encoding
if locale == Encoding::UTF_8
enc1 = Encoding::EUC_JP
else
enc1 = Encoding::UTF_8
end
results = nil
Readline.completion_proc = ->(text) {results}
[%W"\u{3042 3042} \u{3042 3044}", %W"\u{fe5b fe5b} \u{fe5b fe5c}"].any? do |w|
begin
results = w.map {|s| s.encode(locale)}
rescue Encoding::UndefinedConversionError
end
end or
begin
"\xa1\xa2".encode(Encoding::UTF_8, locale)
rescue
else
results = %W"\xa1\xa1 \xa1\xa2".map {|s| s.force_encoding(locale)}
end or
begin
return if assert_under_utf8
omit("missing test for locale #{locale.name}")
end
expected = results[0][0...1]
Readline.completion_case_fold = false
assert_equal(expected, with_pipe {|r, w| w << "\t"}, bug5941)
Readline.completion_case_fold = true
assert_equal(expected, with_pipe {|r, w| w << "\t"}, bug5941)
results.map! {|s| s.encode(enc1)}
assert_raise(Encoding::CompatibilityError, bug5941) do
with_pipe {|r, w| w << "\t"}
end
ensure
return if /EditLine/n.match(Readline::VERSION)
Readline.completion_case_fold = completion_case_fold
Readline.completion_append_character = append_character
end
# basic_word_break_characters
# completer_word_break_characters
# basic_quote_characters
# completer_quote_characters
# filename_quote_characters
# special_prefixes
def test_some_characters_methods
end
def test_closed_outstream
bug5803 = '[ruby-dev:45043]'
IO.pipe do |r, w|
Readline.input = r
Readline.output = w
(w << "##\t").close
assert_raise(IOError, bug5803) {Readline.readline}
end
end
def test_pre_input_hook
begin
pr = proc {}
Readline.pre_input_hook = pr
assert_equal(pr, Readline.pre_input_hook)
Readline.pre_input_hook = nil
assert_nil(Readline.pre_input_hook)
rescue NotImplementedError
end
end
def test_point
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
assert_equal(0, Readline.point)
Readline.insert_text('12345')
assert_equal(5, Readline.point)
assert_equal(4, Readline.point=(4))
Readline.insert_text('abc')
assert_equal(7, Readline.point)
assert_equal('1234abc5', Readline.line_buffer)
rescue NotImplementedError
end
def test_insert_text
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
str = "test_insert_text"
assert_equal(0, Readline.point)
assert_equal(Readline, Readline.insert_text(str))
assert_equal(str, Readline.line_buffer)
assert_equal(16, Readline.point)
assert_equal(get_default_internal_encoding,
Readline.line_buffer.encoding)
Readline.delete_text(1, 3)
assert_equal("t_insert_text", Readline.line_buffer)
Readline.delete_text(11)
assert_equal("t_insert_te", Readline.line_buffer)
Readline.delete_text(-3...-1)
assert_equal("t_inserte", Readline.line_buffer)
Readline.delete_text(-3..-1)
assert_equal("t_inse", Readline.line_buffer)
Readline.delete_text(3..-3)
assert_equal("t_ise", Readline.line_buffer)
Readline.delete_text(3, 1)
assert_equal("t_ie", Readline.line_buffer)
Readline.delete_text(1..1)
assert_equal("tie", Readline.line_buffer)
Readline.delete_text(1...2)
assert_equal("te", Readline.line_buffer)
Readline.delete_text
assert_equal("", Readline.line_buffer)
rescue NotImplementedError
end
def test_delete_text
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
str = "test_insert_text"
assert_equal(0, Readline.point)
assert_equal(Readline, Readline.insert_text(str))
assert_equal(16, Readline.point)
assert_equal(str, Readline.line_buffer)
Readline.delete_text
if !defined?(Reline) or Readline != Reline
# NOTE: unexpected but GNU Readline's spec
assert_equal(16, Readline.point)
assert_equal("", Readline.line_buffer)
assert_equal(Readline, Readline.insert_text(str))
assert_equal(32, Readline.point)
assert_equal("", Readline.line_buffer)
end
rescue NotImplementedError
end
def test_modify_text_in_pre_input_hook
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
with_temp_stdio {|stdin, stdout|
begin
stdin.write("world\n")
stdin.close
Readline.pre_input_hook = proc do
assert_equal("", Readline.line_buffer)
Readline.insert_text("hello ")
Readline.redisplay
end
replace_stdio(stdin.path, stdout.path) do
line = Readline.readline("> ")
assert_equal("hello world", line)
end
# Readline 4.3 doesn't include inserted text or input
# Reline's rendering logic is tricky
if Readline::VERSION != '4.3' and (!defined?(Reline) or Readline != Reline)
assert_equal("> hello world\n", stdout.read)
end
stdout.close
rescue NotImplementedError
ensure
begin
Readline.pre_input_hook = nil
rescue NotImplementedError
end
end
}
end
def test_input_metachar
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
# test will pass on Windows reline, but not readline
omit "Won't pass on mingw readline.so using 8.0.001" if /mingw/ =~ RUBY_PLATFORM and defined?(TestReadline) and kind_of?(TestReadline)
omit 'Needs GNU Readline 6 or later' if /mswin|mingw/ =~ RUBY_PLATFORM and defined?(TestReadline) and kind_of?(TestReadline) and Readline::VERSION < '6.0'
bug6601 = '[ruby-core:45682]'
Readline::HISTORY << "hello"
wo = nil
line = with_pipe do |r, w|
wo = w.dup
wo.write("\C-re\ef\n")
end
assert_equal("hello", line, bug6601)
ensure
wo&.close
return if /EditLine/n.match(Readline::VERSION)
Readline.delete_text
Readline::HISTORY.clear
end
def test_input_metachar_multibyte
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
unless Encoding.find("locale") == Encoding::UTF_8
return if assert_under_utf8
omit 'this test needs UTF-8 locale'
end
bug6602 = '[ruby-core:45683]'
Readline::HISTORY << "\u3042\u3093"
Readline::HISTORY << "\u3044\u3093"
Readline::HISTORY << "\u3046\u3093"
open(IO::NULL, 'w') do |null|
IO.pipe do |r, w|
Readline.input = r
Readline.output = null
w << "\cr\u3093\n\n"
w << "\cr\u3042\u3093"
w.reopen(IO::NULL)
assert_equal("\u3046\u3093", Readline.readline("", true), bug6602)
Timeout.timeout(2) do
assert_equal("\u3042\u3093", Readline.readline("", true), bug6602)
end
assert_equal(nil, Readline.readline("", true), bug6602)
end
end
ensure
return if /EditLine/n.match(Readline::VERSION)
Readline.delete_text
Readline::HISTORY.clear
end
def test_refresh_line
omit "Only when refresh_line exists" unless Readline.respond_to?(:refresh_line)
omit unless respond_to?(:assert_ruby_status)
bug6232 = '[ruby-core:43957] [Bug #6232] refresh_line after set_screen_size'
with_temp_stdio do |stdin, stdout|
replace_stdio(stdin.path, stdout.path) do
assert_ruby_status(%w[-rreadline -], <<-'end;', bug6232)
Readline.set_screen_size(40, 80)
Readline.refresh_line
end;
end
end
end
def test_setting_quoting_detection_proc
return unless Readline.respond_to?(:quoting_detection_proc=)
expected = proc { |text, index| false }
Readline.quoting_detection_proc = expected
assert_equal(expected, Readline.quoting_detection_proc)
assert_raise(ArgumentError) do
Readline.quoting_detection_proc = "This does not have call method."
end
end
def test_using_quoting_detection_proc
saved_completer_quote_characters = Readline.completer_quote_characters
saved_completer_word_break_characters = Readline.completer_word_break_characters
# skip if previous value is nil because Readline... = nil is not allowed.
skip unless saved_completer_quote_characters
skip unless saved_completer_word_break_characters
return unless Readline.respond_to?(:quoting_detection_proc=)
begin
passed_text = nil
line = nil
with_temp_stdio do |stdin, stdout|
replace_stdio(stdin.path, stdout.path) do
Readline.completion_proc = ->(text) do
passed_text = text
['completion'].map { |i|
i.encode(Encoding.default_external)
}
end
Readline.completer_quote_characters = '\'"'
Readline.completer_word_break_characters = ' '
Readline.quoting_detection_proc = ->(text, index) do
index > 0 && text[index-1] == '\\'
end
stdin.write("first second\\ third\t")
stdin.flush
line = Readline.readline('> ', false)
end
end
assert_equal('second\\ third', passed_text)
assert_equal('first completion', line.chomp(' '))
ensure
Readline.completer_quote_characters = saved_completer_quote_characters
Readline.completer_word_break_characters = saved_completer_word_break_characters
end
end
def test_using_quoting_detection_proc_with_multibyte_input
Readline.completion_append_character = nil
saved_completer_quote_characters = Readline.completer_quote_characters
saved_completer_word_break_characters = Readline.completer_word_break_characters
# skip if previous value is nil because Readline... = nil is not allowed.
skip unless saved_completer_quote_characters
skip unless saved_completer_word_break_characters
return unless Readline.respond_to?(:quoting_detection_proc=)
unless get_default_internal_encoding == Encoding::UTF_8
return if assert_under_utf8
omit 'this test needs UTF-8 locale'
end
begin
passed_text = nil
escaped_char_indexes = []
line = nil
with_temp_stdio do |stdin, stdout|
replace_stdio(stdin.path, stdout.path) do
Readline.completion_proc = ->(text) do
passed_text = text
['completion'].map { |i|
i.encode(Encoding.default_external)
}
end
Readline.completer_quote_characters = '\'"'
Readline.completer_word_break_characters = ' '
Readline.quoting_detection_proc = ->(text, index) do
escaped = index > 0 && text[index-1] == '\\'
escaped_char_indexes << index if escaped
escaped
end
stdin.write("\u3042\u3093 second\\ third\t")
stdin.flush
line = Readline.readline('> ', false)
end
end
assert_equal([10], escaped_char_indexes)
assert_equal('second\\ third', passed_text)
assert_equal("\u3042\u3093 completion#{Readline.completion_append_character}", line)
ensure
Readline.completer_quote_characters = saved_completer_quote_characters
Readline.completer_word_break_characters = saved_completer_word_break_characters
end
end
def test_simple_completion
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
line = nil
open(IO::NULL, 'w') do |null|
IO.pipe do |r, w|
Readline.input = r
Readline.output = null
Readline.completion_proc = ->(text) do
['abcde', 'abc12'].map { |i|
i.encode(get_default_internal_encoding)
}
end
w.write("a\t\n")
w.flush
line = Readline.readline('> ', false)
end
end
assert_equal('abc', line)
end
def test_completion_with_completion_append_character
omit "Skip Editline" if /EditLine/n.match(Readline::VERSION)
omit "Readline.completion_append_character is not implemented" unless Readline.respond_to?(:completion_append_character=)
line = nil
append_character = Readline.completion_append_character
open(IO::NULL, 'w') do |null|
IO.pipe do |r, w|
Readline.input = r
Readline.output = null
Readline.completion_append_character = '!'
Readline.completion_proc = ->(text) do
['abcde'].map { |i|
i.encode(get_default_internal_encoding)
}
end
w.write("a\t\n")
w.flush
line = Readline.readline('> ', false)
end
end
assert_equal('abcde!', line)
ensure
return if /EditLine/n.match(Readline::VERSION)
return unless Readline.respond_to?(:completion_append_character=)
Readline.completion_append_character = append_character
end
def test_completion_quote_character_completing_unquoted_argument
return unless Readline.respond_to?(:completion_quote_character)
quote_character = "original value"
Readline.completion_proc = -> (_) do
quote_character = Readline.completion_quote_character
[]
end
Readline.completer_quote_characters = "'\""
with_temp_stdio do |stdin, stdout|
replace_stdio(stdin.path, stdout.path) do
stdin.write("input\t")
stdin.flush
Readline.readline("> ", false)
end
end
assert_nil(quote_character)
end
def test_completion_quote_character_completing_quoted_argument
return unless Readline.respond_to?(:completion_quote_character)
quote_character = "original value"
Readline.completion_proc = -> (_) do
quote_character = Readline.completion_quote_character
[]
end
Readline.completer_quote_characters = "'\""
with_temp_stdio do |stdin, stdout|
replace_stdio(stdin.path, stdout.path) do
stdin.write("'input\t")
stdin.flush
Readline.readline("> ", false)
end
end
assert_equal("'", quote_character)
end
def test_completion_quote_character_after_completion
return unless Readline.respond_to?(:completion_quote_character)
if /solaris/i =~ RUBY_PLATFORM
# http://rubyci.s3.amazonaws.com/solaris11s-sunc/ruby-trunk/log/20181228T102505Z.fail.html.gz
omit 'This test does not succeed on Oracle Developer Studio for now'
end
omit 'Needs GNU Readline 6 or later' if /mswin|mingw/ =~ RUBY_PLATFORM and defined?(TestReadline) and kind_of?(TestReadline) and Readline::VERSION < '6.0'
Readline.completion_proc = -> (_) { [] }
Readline.completer_quote_characters = "'\""
with_temp_stdio do |stdin, stdout|
replace_stdio(stdin.path, stdout.path) do
stdin.write("'input\t")
stdin.flush
Readline.readline("> ", false)
end
end
assert_nil(Readline.completion_quote_character)
end
private
def replace_stdio(stdin_path, stdout_path)
open(stdin_path, "r"){|stdin|
open(stdout_path, "w"){|stdout|
orig_stdin = STDIN.dup
orig_stdout = STDOUT.dup
orig_stderr = STDERR.dup
STDIN.reopen(stdin)
STDOUT.reopen(stdout)
STDERR.reopen(stdout)
begin
Readline.input = STDIN
Readline.output = STDOUT
yield
ensure
STDERR.reopen(orig_stderr)
STDIN.reopen(orig_stdin)
STDOUT.reopen(orig_stdout)
orig_stdin.close
orig_stdout.close
orig_stderr.close
end
}
}
end
def with_temp_stdio
Tempfile.create("test_readline_stdin") {|stdin|
Tempfile.create("test_readline_stdout") {|stdout|
yield stdin, stdout
if /mswin|mingw/ =~ RUBY_PLATFORM
# needed since readline holds refs to tempfiles, can't delete on Windows
Readline.input = STDIN
Readline.output = STDOUT
end
}
}
end
def with_pipe
stderr = nil
IO.pipe do |r, w|
yield(r, w)
Readline.input = r
Readline.output = w.reopen(IO::NULL)
stderr = STDERR.dup
STDERR.reopen(w)
Readline.readline
end
ensure
if stderr
STDERR.reopen(stderr)
stderr.close
end
Readline.input = STDIN
Readline.output = STDOUT
end
def get_default_internal_encoding
return Encoding.default_internal || Encoding.find("locale")
end
def assert_under_utf8
return false if ENV['LC_ALL'] == 'UTF-8'
loc = caller_locations(1, 1)[0].base_label.to_s
assert_separately([{"LC_ALL"=>"UTF-8"}, "-r", __FILE__], <<SRC)
#omit "test \#{ENV['LC_ALL']}"
#{self.class.name}.new(#{loc.dump}).run(Test::Unit::Runner.new)
SRC
return true
end
end
class TestReadline < Test::Unit::TestCase
include BasetestReadline
def setup
use_ext_readline
super
end
end if defined?(ReadlineSo) && ENV["TEST_READLINE_OR_RELINE"] != "Reline"
class TestRelineAsReadline < Test::Unit::TestCase
include BasetestReadline
def setup
use_lib_reline
super
end
def get_default_internal_encoding
if RUBY_PLATFORM =~ /mswin|mingw/
Encoding.default_internal || Encoding::UTF_8
else
super
end
end
end if defined?(Reline) && ENV["TEST_READLINE_OR_RELINE"] != "Readline"