1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00
ruby--ruby/test/ruby/test_rubyoptions.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

https://github.com/ruby/actions/runs/500526558?check_suite_focus=true#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

1074 lines
34 KiB
Ruby

# -*- coding: us-ascii -*-
require 'test/unit'
require 'timeout'
require 'tmpdir'
require 'tempfile'
require_relative '../lib/jit_support'
class TestRubyOptions < Test::Unit::TestCase
NO_JIT_DESCRIPTION =
if RubyVM::MJIT.enabled? # checking -DMJIT_FORCE_ENABLE
RUBY_DESCRIPTION.sub(/\+JIT /, '')
else
RUBY_DESCRIPTION
end
def write_file(filename, content)
File.open(filename, "w") {|f|
f << content
}
end
def with_tmpchdir
Dir.mktmpdir {|d|
d = File.realpath(d)
Dir.chdir(d) {
yield d
}
}
end
def test_source_file
assert_in_out_err([], "", [], [])
end
def test_usage
assert_in_out_err(%w(-h)) do |r, e|
assert_operator(r.size, :<=, 25)
longer = r[1..-1].select {|x| x.size > 80}
assert_equal([], longer)
assert_equal([], e)
end
end
def test_usage_long
assert_in_out_err(%w(--help)) do |r, e|
longer = r[1..-1].select {|x| x.size > 80}
assert_equal([], longer)
assert_equal([], e)
end
end
def test_option_variables
assert_in_out_err(["-e", 'p [$-p, $-l, $-a]']) do |r, e|
assert_equal(["[false, false, false]"], r)
assert_equal([], e)
end
assert_in_out_err(%w(-p -l -a -e) + ['p [$-p, $-l, $-a]'],
"foo\nbar\nbaz") do |r, e|
assert_equal(
[ '[true, true, true]', 'foo',
'[true, true, true]', 'bar',
'[true, true, true]', 'baz' ], r)
assert_equal([], e)
end
end
def test_warning
save_rubyopt = ENV['RUBYOPT']
ENV['RUBYOPT'] = nil
assert_in_out_err(%w(-W0 -e) + ['p $-W'], "", %w(0), [])
assert_in_out_err(%w(-W1 -e) + ['p $-W'], "", %w(1), [])
assert_in_out_err(%w(-Wx -e) + ['p $-W'], "", %w(1), [])
assert_in_out_err(%w(-W -e) + ['p $-W'], "", %w(2), [])
assert_in_out_err(%w(-w -W0 -e) + ['p $-W'], "", %w(0), [])
assert_in_out_err(%w(-W:deprecated -e) + ['p Warning[:deprecated]'], "", %w(true), [])
assert_in_out_err(%w(-W:no-deprecated -e) + ['p Warning[:deprecated]'], "", %w(false), [])
assert_in_out_err(%w(-W:experimental -e) + ['p Warning[:experimental]'], "", %w(true), [])
assert_in_out_err(%w(-W:no-experimental -e) + ['p Warning[:experimental]'], "", %w(false), [])
assert_in_out_err(%w(-W:qux), "", [], /unknown warning category: `qux'/)
ensure
ENV['RUBYOPT'] = save_rubyopt
end
def test_debug
assert_in_out_err(["--disable-gems", "-de", "p $DEBUG"], "", %w(true), [])
assert_in_out_err(["--disable-gems", "--debug", "-e", "p $DEBUG"],
"", %w(true), [])
end
q = Regexp.method(:quote)
VERSION_PATTERN =
case RUBY_ENGINE
when 'jruby'
/^jruby #{q[RUBY_ENGINE_VERSION]} \(#{q[RUBY_VERSION]}\).*? \[#{
q[RbConfig::CONFIG["host_os"]]}-#{q[RbConfig::CONFIG["host_cpu"]]}\]$/
else
/^ruby #{q[RUBY_VERSION]}(?:[p ]|dev|rc).*? \[#{q[RUBY_PLATFORM]}\]$/
end
private_constant :VERSION_PATTERN
VERSION_PATTERN_WITH_JIT =
case RUBY_ENGINE
when 'ruby'
/^ruby #{q[RUBY_VERSION]}(?:[p ]|dev|rc).*? \+JIT \[#{q[RUBY_PLATFORM]}\]$/
else
VERSION_PATTERN
end
private_constant :VERSION_PATTERN_WITH_JIT
def test_verbose
assert_in_out_err(["-vve", ""]) do |r, e|
assert_match(VERSION_PATTERN, r[0])
if RubyVM::MJIT.enabled? && !mjit_force_enabled? # checking -DMJIT_FORCE_ENABLE
assert_equal(NO_JIT_DESCRIPTION, r[0])
else
assert_equal(RUBY_DESCRIPTION, r[0])
end
assert_equal([], e)
end
assert_in_out_err(%w(--verbose -e) + ["p $VERBOSE"], "", %w(true), [])
assert_in_out_err(%w(--verbose), "", [], [])
end
def test_copyright
assert_in_out_err(%w(--copyright), "",
/^ruby - Copyright \(C\) 1993-\d+ Yukihiro Matsumoto$/, [])
assert_in_out_err(%w(--verbose -e) + ["p $VERBOSE"], "", %w(true), [])
end
def test_enable
if JITSupport.supported?
assert_in_out_err(%w(--enable all -e) + [""], "", [], [])
assert_in_out_err(%w(--enable-all -e) + [""], "", [], [])
assert_in_out_err(%w(--enable=all -e) + [""], "", [], [])
end
assert_in_out_err(%w(--enable foobarbazqux -e) + [""], "", [],
/unknown argument for --enable: `foobarbazqux'/)
assert_in_out_err(%w(--enable), "", [], /missing argument for --enable/)
end
def test_disable
assert_in_out_err(%w(--disable all -e) + [""], "", [], [])
assert_in_out_err(%w(--disable-all -e) + [""], "", [], [])
assert_in_out_err(%w(--disable=all -e) + [""], "", [], [])
assert_in_out_err(%w(--disable foobarbazqux -e) + [""], "", [],
/unknown argument for --disable: `foobarbazqux'/)
assert_in_out_err(%w(--disable), "", [], /missing argument for --disable/)
assert_in_out_err(%w(--disable-gems -e) + ['p defined? Gem'], "", ["nil"], [])
assert_in_out_err(%w(--disable-did_you_mean -e) + ['p defined? DidYouMean'], "", ["nil"], [])
assert_in_out_err(%w(--disable-gems -e) + ['p defined? DidYouMean'], "", ["nil"], [])
end
def test_kanji
assert_in_out_err(%w(-KU), "p '\u3042'") do |r, e|
assert_equal("\"\u3042\"", r.join.force_encoding(Encoding::UTF_8))
end
line = '-eputs"\xc2\xa1".encoding'
env = {'RUBYOPT' => nil}
assert_in_out_err([env, '-Ke', line], "", ["EUC-JP"], [])
assert_in_out_err([env, '-KE', line], "", ["EUC-JP"], [])
assert_in_out_err([env, '-Ks', line], "", ["Windows-31J"], [])
assert_in_out_err([env, '-KS', line], "", ["Windows-31J"], [])
assert_in_out_err([env, '-Ku', line], "", ["UTF-8"], [])
assert_in_out_err([env, '-KU', line], "", ["UTF-8"], [])
assert_in_out_err([env, '-Kn', line], "", ["ASCII-8BIT"], [])
assert_in_out_err([env, '-KN', line], "", ["ASCII-8BIT"], [])
assert_in_out_err([env, '-wKe', line], "", ["EUC-JP"], /-K/)
end
def test_version
assert_in_out_err(%w(--version)) do |r, e|
assert_match(VERSION_PATTERN, r[0])
if RubyVM::MJIT.enabled? # checking -DMJIT_FORCE_ENABLE
assert_equal(EnvUtil.invoke_ruby(['-e', 'print RUBY_DESCRIPTION'], '', true).first, r[0])
else
assert_equal(RUBY_DESCRIPTION, r[0])
end
assert_equal([], e)
end
return if RbConfig::CONFIG["MJIT_SUPPORT"] == 'no'
[
%w(--version --jit --disable=jit),
%w(--version --enable=jit --disable=jit),
%w(--version --enable-jit --disable-jit),
].each do |args|
assert_in_out_err(args) do |r, e|
assert_match(VERSION_PATTERN, r[0])
assert_match(NO_JIT_DESCRIPTION, r[0])
assert_equal([], e)
end
end
if JITSupport.supported?
[
%w(--version --jit),
%w(--version --enable=jit),
%w(--version --enable-jit),
].each do |args|
assert_in_out_err(args) do |r, e|
assert_match(VERSION_PATTERN_WITH_JIT, r[0])
if RubyVM::MJIT.enabled? # checking -DMJIT_FORCE_ENABLE
assert_equal(RUBY_DESCRIPTION, r[0])
else
assert_equal(EnvUtil.invoke_ruby(['--jit', '-e', 'print RUBY_DESCRIPTION'], '', true).first, r[0])
end
assert_equal([], e)
end
end
end
end
def test_eval
assert_in_out_err(%w(-e), "", [], /no code specified for -e \(RuntimeError\)/)
end
def test_require
require "pp"
assert_in_out_err(%w(-r pp -e) + ["pp 1"], "", %w(1), [])
assert_in_out_err(%w(-rpp -e) + ["pp 1"], "", %w(1), [])
assert_in_out_err(%w(-ep\ 1 -r), "", %w(1), [])
assert_in_out_err(%w(-r), "", [], [])
rescue LoadError
end
def test_include
d = Dir.tmpdir
assert_in_out_err(["-I" + d, "-e", ""], "", [], [])
assert_in_out_err(["-I", d, "-e", ""], "", [], [])
end
def test_separator
assert_in_out_err(%w(-000 -e) + ["print gets"], "foo\nbar\0baz", %W(foo bar\0baz), [])
assert_in_out_err(%w(-0141 -e) + ["print gets"], "foo\nbar\0baz", %w(foo ba), [])
assert_in_out_err(%w(-0e) + ["print gets"], "foo\nbar\0baz", %W(foo bar\0), [])
assert_in_out_err(%w(-00 -e) + ["p gets, gets"], "foo\nbar\n\nbaz\nzot\n\n\n", %w("foo\nbar\n\n" "baz\nzot\n\n"), [])
assert_in_out_err(%w(-00 -e) + ["p gets, gets"], "foo\nbar\n\n\n\nbaz\n", %w("foo\nbar\n\n" "baz\n"), [])
end
def test_autosplit
assert_in_out_err(%w(-W0 -an -F: -e) + ["p $F"], "foo:bar:baz\nqux:quux:quuux\n",
['["foo", "bar", "baz\n"]', '["qux", "quux", "quuux\n"]'], [])
end
def test_chdir
assert_in_out_err(%w(-C), "", [], /Can't chdir/)
assert_in_out_err(%w(-C test_ruby_test_rubyoptions_foobarbazqux), "", [], /Can't chdir/)
d = Dir.tmpdir
assert_in_out_err(["-C", d, "-e", "puts Dir.pwd"]) do |r, e|
assert_file.identical?(r.join, d)
assert_equal([], e)
end
end
def test_yydebug
assert_in_out_err(["-ye", ""]) do |r, e|
assert_not_equal([], r)
assert_equal([], e)
end
assert_in_out_err(%w(--yydebug -e) + [""]) do |r, e|
assert_not_equal([], r)
assert_equal([], e)
end
end
def test_encoding
assert_in_out_err(%w(--encoding), "", [], /missing argument for --encoding/)
assert_in_out_err(%w(--encoding test_ruby_test_rubyoptions_foobarbazqux), "", [],
/unknown encoding name - test_ruby_test_rubyoptions_foobarbazqux \(RuntimeError\)/)
if /mswin|mingw|aix|android/ =~ RUBY_PLATFORM &&
(str = "\u3042".force_encoding(Encoding.find("external"))).valid_encoding?
# This result depends on locale because LANG=C doesn't affect locale
# on Windows.
# On AIX, the source encoding of stdin with LANG=C is ISO-8859-1,
# which allows \u3042.
out, err = [str], []
else
out, err = [], /invalid multibyte char/
end
assert_in_out_err(%w(-Eutf-8), "puts '\u3042'", out, err)
assert_in_out_err(%w(--encoding utf-8), "puts '\u3042'", out, err)
end
def test_syntax_check
assert_in_out_err(%w(-c -e a=1+1 -e !a), "", ["Syntax OK"], [])
end
def test_invalid_option
assert_in_out_err(%w(--foobarbazqux), "", [], /invalid option --foobarbazqux/)
assert_in_out_err(%W(-\r -e) + [""], "", [], [])
assert_in_out_err(%W(-\rx), "", [], /invalid option -\\r \(-h will show valid options\) \(RuntimeError\)/)
assert_in_out_err(%W(-\x01), "", [], /invalid option -\\x01 \(-h will show valid options\) \(RuntimeError\)/)
assert_in_out_err(%w(-Z), "", [], /invalid option -Z \(-h will show valid options\) \(RuntimeError\)/)
end
def test_rubyopt
rubyopt_orig = ENV['RUBYOPT']
ENV['RUBYOPT'] = ' - -'
assert_in_out_err([], "", [], [])
ENV['RUBYOPT'] = '-e "p 1"'
assert_in_out_err([], "", [], /invalid switch in RUBYOPT: -e \(RuntimeError\)/)
ENV['RUBYOPT'] = '-Eus-ascii -KN'
assert_in_out_err(%w(-Eutf-8 -KU), "p '\u3042'") do |r, e|
assert_equal("\"\u3042\"", r.join.force_encoding(Encoding::UTF_8))
assert_equal([], e)
end
ENV['RUBYOPT'] = '-w'
assert_in_out_err(%w(), "p $VERBOSE", ["true"])
assert_in_out_err(%w(-W1), "p $VERBOSE", ["false"])
assert_in_out_err(%w(-W0), "p $VERBOSE", ["nil"])
ENV['RUBYOPT'] = '-W:deprecated'
assert_in_out_err(%w(), "p Warning[:deprecated]", ["true"])
ENV['RUBYOPT'] = '-W:no-deprecated'
assert_in_out_err(%w(), "p Warning[:deprecated]", ["false"])
ENV['RUBYOPT'] = '-W:experimental'
assert_in_out_err(%w(), "p Warning[:experimental]", ["true"])
ENV['RUBYOPT'] = '-W:no-experimental'
assert_in_out_err(%w(), "p Warning[:experimental]", ["false"])
ENV['RUBYOPT'] = '-W:qux'
assert_in_out_err(%w(), "", [], /unknown warning category: `qux'/)
ensure
if rubyopt_orig
ENV['RUBYOPT'] = rubyopt_orig
else
ENV.delete('RUBYOPT')
end
end
def test_search
rubypath_orig = ENV['RUBYPATH']
path_orig = ENV['PATH']
Tempfile.create(["test_ruby_test_rubyoption", ".rb"]) {|t|
t.puts "p 1"
t.close
@verbose = $VERBOSE
$VERBOSE = nil
path, name = File.split(t.path)
ENV['PATH'] = (path_orig && RbConfig::CONFIG['LIBPATHENV'] == 'PATH') ?
[path, path_orig].join(File::PATH_SEPARATOR) : path
assert_in_out_err(%w(-S) + [name], "", %w(1), [])
ENV['PATH'] = path_orig
ENV['RUBYPATH'] = path
assert_in_out_err(%w(-S) + [name], "", %w(1), [])
}
ensure
if rubypath_orig
ENV['RUBYPATH'] = rubypath_orig
else
ENV.delete('RUBYPATH')
end
if path_orig
ENV['PATH'] = path_orig
else
ENV.delete('PATH')
end
$VERBOSE = @verbose
end
def test_shebang
assert_in_out_err([], "#! /test_r_u_b_y_test_r_u_b_y_options_foobarbazqux\r\np 1\r\n",
[], /: no Ruby script found in input/)
assert_in_out_err([], "#! /test_r_u_b_y_test_r_u_b_y_options_foobarbazqux -foo -bar\r\np 1\r\n",
[], /: no Ruby script found in input/)
warning = /mswin|mingw/ =~ RUBY_PLATFORM ? [] : /shebang line ending with \\r/
assert_in_out_err([{'RUBYOPT' => nil}], "#!ruby -KU -Eutf-8\r\np \"\u3042\"\r\n",
["\"\u3042\""], warning,
encoding: Encoding::UTF_8)
bug4118 = '[ruby-dev:42680]'
assert_in_out_err(%w[], "#!/bin/sh\n""#!shebang\n""#!ruby\n""puts __LINE__\n",
%w[4], [], bug4118)
assert_in_out_err(%w[-x], "#!/bin/sh\n""#!shebang\n""#!ruby\n""puts __LINE__\n",
%w[4], [], bug4118)
assert_ruby_status(%w[], "#! ruby -- /", '[ruby-core:82267] [Bug #13786]')
assert_ruby_status(%w[], "#!")
assert_in_out_err(%w[-c], "#!", ["Syntax OK"])
end
def test_flag_in_shebang
Tempfile.create(%w"pflag .rb") do |script|
code = "#!ruby -p"
script.puts(code)
script.close
assert_in_out_err([script.path, script.path], '', [code])
end
Tempfile.create(%w"sflag .rb") do |script|
script.puts("#!ruby -s")
script.puts("p $abc")
script.close
assert_in_out_err([script.path, "-abc=foo"], '', ['"foo"'])
end
end
def test_sflag
assert_in_out_err(%w(- -abc -def=foo -ghi-jkl -- -xyz),
"#!ruby -s\np [$abc, $def, $ghi_jkl, defined?($xyz)]\n",
['[true, "foo", true, nil]'], [])
assert_in_out_err(%w(- -#), "#!ruby -s\n", [],
/invalid name for global variable - -# \(NameError\)/)
assert_in_out_err(%w(- -#=foo), "#!ruby -s\n", [],
/invalid name for global variable - -# \(NameError\)/)
end
def test_assignment_in_conditional
Tempfile.create(["test_ruby_test_rubyoption", ".rb"]) {|t|
t.puts "if a = 1"
t.puts "end"
t.puts "0.times do"
t.puts " if b = 2"
t.puts " a += b"
t.puts " end"
t.puts "end"
t.flush
warning = ' warning: found `= literal\' in conditional, should be =='
err = ["#{t.path}:1:#{warning}",
"#{t.path}:4:#{warning}",
]
bug2136 = '[ruby-dev:39363]'
assert_in_out_err(["-w", t.path], "", [], err, bug2136)
assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err, bug2136)
t.rewind
t.truncate(0)
t.puts "if a = ''; end"
t.puts "if a = []; end"
t.puts "if a = [1]; end"
t.puts "if a = [a]; end"
t.puts "if a = {}; end"
t.puts "if a = {1=>2}; end"
t.puts "if a = {3=>a}; end"
t.flush
err = ["#{t.path}:1:#{warning}",
"#{t.path}:2:#{warning}",
"#{t.path}:3:#{warning}",
"#{t.path}:5:#{warning}",
"#{t.path}:6:#{warning}",
]
feature4299 = '[ruby-dev:43083]'
assert_in_out_err(["-w", t.path], "", [], err, feature4299)
assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err, feature4299)
}
end
def test_indentation_check
all_assertions do |a|
Tempfile.create(["test_ruby_test_rubyoption", ".rb"]) do |t|
[
"begin", "if false", "for _ in []", "while false",
"def foo", "class X", "module M",
["-> do", "end"], ["-> {", "}"],
["if false;", "else ; end"],
["if false;", "elsif false ; end"],
["begin", "rescue ; end"],
["begin rescue", "else ; end"],
["begin", "ensure ; end"],
[" case nil", "when true; end"],
["case nil; when true", "end"],
["if false;", "end", "if true\nelse ", "end"],
["else", " end", "_ = if true\n"],
].each do
|b, e = 'end', pre = nil, post = nil|
src = ["#{pre}#{b}\n", " #{e}\n#{post}"]
k = b[/\A\s*(\S+)/, 1]
e = e[/\A\s*(\S+)/, 1]
n = 2
n += pre.count("\n") if pre
a.for("no directives with #{src}") do
err = ["#{t.path}:#{n}: warning: mismatched indentations at '#{e}' with '#{k}' at #{n-1}"]
t.rewind
t.truncate(0)
t.puts src
t.flush
assert_in_out_err(["-w", t.path], "", [], err)
assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err)
end
a.for("false directive with #{src}") do
t.rewind
t.truncate(0)
t.puts "# -*- warn-indent: false -*-"
t.puts src
t.flush
assert_in_out_err(["-w", t.path], "", [], [], '[ruby-core:25442]')
end
a.for("false and true directives with #{src}") do
err = ["#{t.path}:#{n+2}: warning: mismatched indentations at '#{e}' with '#{k}' at #{n+1}"]
t.rewind
t.truncate(0)
t.puts "# -*- warn-indent: false -*-"
t.puts "# -*- warn-indent: true -*-"
t.puts src
t.flush
assert_in_out_err(["-w", t.path], "", [], err, '[ruby-core:25442]')
end
a.for("false directives after #{src}") do
t.rewind
t.truncate(0)
t.puts "# -*- warn-indent: true -*-"
t.puts src[0]
t.puts "# -*- warn-indent: false -*-"
t.puts src[1]
t.flush
assert_in_out_err(["-w", t.path], "", [], [], '[ruby-core:25442]')
end
a.for("BOM with #{src}") do
err = ["#{t.path}:#{n}: warning: mismatched indentations at '#{e}' with '#{k}' at #{n-1}"]
t.rewind
t.truncate(0)
t.print "\u{feff}"
t.puts src
t.flush
assert_in_out_err(["-w", t.path], "", [], err)
assert_in_out_err(["-wr", t.path, "-e", ""], "", [], err)
end
end
end
end
end
def test_notfound
notexist = "./notexist.rb"
dir, *rubybin = RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME', 'EXEEXT')
rubybin = "#{dir}/#{rubybin.join('')}"
rubybin.tr!('/', '\\') if /mswin|mingw/ =~ RUBY_PLATFORM
rubybin = Regexp.quote(rubybin)
pat = Regexp.quote(notexist)
bug1573 = '[ruby-core:23717]'
assert_file.not_exist?(notexist)
assert_in_out_err(["-r", notexist, "-ep"], "", [], /.* -- #{pat} \(LoadError\)/, bug1573)
assert_in_out_err([notexist], "", [], /#{rubybin}:.* -- #{pat} \(LoadError\)/, bug1573)
end
def test_program_name
ruby = EnvUtil.rubybin
IO.popen([ruby, '-e', 'print $0']) {|f|
assert_equal('-e', f.read)
}
IO.popen([ruby, '-'], 'r+') {|f|
f << 'print $0'
f.close_write
assert_equal('-', f.read)
}
Dir.mktmpdir {|d|
n1 = File.join(d, 't1')
open(n1, 'w') {|f| f << 'print $0' }
IO.popen([ruby, n1]) {|f|
assert_equal(n1, f.read)
}
if File.respond_to? :symlink
n2 = File.join(d, 't2')
begin
File.symlink(n1, n2)
rescue Errno::EACCES
else
IO.popen([ruby, n2]) {|f|
assert_equal(n2, f.read)
}
end
end
Dir.chdir(d) {
n3 = '-e'
open(n3, 'w') {|f| f << 'print $0' }
IO.popen([ruby, '--', n3]) {|f|
assert_equal(n3, f.read)
}
n4 = '-'
IO.popen([ruby, '--', n4], 'r+') {|f|
f << 'print $0'
f.close_write
assert_equal(n4, f.read)
}
}
}
end
if /linux|freebsd|netbsd|openbsd|darwin/ =~ RUBY_PLATFORM
PSCMD = EnvUtil.find_executable("ps", "-o", "command", "-p", $$.to_s) {|out| /ruby/=~out}
PSCMD&.pop
end
def test_set_program_name
skip "platform dependent feature" unless defined?(PSCMD) and PSCMD
with_tmpchdir do
write_file("test-script", "$0 = 'hello world'; /test-script/ =~ Process.argv0 or $0 = 'Process.argv0 changed!'; sleep 60")
pid = spawn(EnvUtil.rubybin, "test-script")
ps = nil
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
stop = now + 30
begin
sleep 0.1
ps = `#{PSCMD.join(' ')} #{pid}`
break if /hello world/ =~ ps
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
end until Process.wait(pid, Process::WNOHANG) || now > stop
assert_match(/hello world/, ps)
assert_operator now, :<, stop
Process.kill :KILL, pid
EnvUtil.timeout(5) { Process.wait(pid) }
end
end
def test_setproctitle
skip "platform dependent feature" unless defined?(PSCMD) and PSCMD
assert_separately([], "#{<<-"{#"}\n#{<<-'};'}")
{#
assert_raise(ArgumentError) do
Process.setproctitle("hello\0")
end
};
with_tmpchdir do
write_file("test-script", "$_0 = $0.dup; Process.setproctitle('hello world'); $0 == $_0 or Process.setproctitle('$0 changed!'); sleep 60")
pid = spawn(EnvUtil.rubybin, "test-script")
ps = nil
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
stop = now + 30
begin
sleep 0.1
ps = `#{PSCMD.join(' ')} #{pid}`
break if /hello world/ =~ ps
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
end until Process.wait(pid, Process::WNOHANG) || now > stop
assert_match(/hello world/, ps)
assert_operator now, :<, stop
Process.kill :KILL, pid
Timeout.timeout(5) { Process.wait(pid) }
end
end
module SEGVTest
opts = {}
unless /mswin|mingw/ =~ RUBY_PLATFORM
opts[:rlimit_core] = 0
end
ExecOptions = opts.freeze
ExpectedStderrList = [
%r(
-e:(?:1:)?\s\[BUG\]\sSegmentation\sfault.*\n
)x,
%r(
#{ Regexp.quote(NO_JIT_DESCRIPTION) }\n\n
)x,
%r(
(?:--\s(?:.+\n)*\n)?
--\sControl\sframe\sinformation\s-+\n
(?:(?:c:.*\n)|(?:^\s+.+\n))*
\n
)x,
%r(
(?:
--\sRuby\slevel\sbacktrace\sinformation\s----------------------------------------\n
(?:-e:1:in\s\`(?:block\sin\s)?<main>\'\n)*
-e:1:in\s\`kill\'\n
\n
)?
)x,
%r(
(?:--\sMachine(?:.+\n)*\n)?
)x,
%r(
(?:
--\sC\slevel\sbacktrace\sinformation\s-------------------------------------------\n
(?:(?:.*\s)?\[0x\h+\].*\n|.*:\d+\n)*\n
)?
)x,
%r(
(?:--\sOther\sruntime\sinformation\s-+\n
(?:.*\n)*
)?
)x,
]
end
def assert_segv(args, message=nil)
test_stdin = ""
opt = SEGVTest::ExecOptions.dup
list = SEGVTest::ExpectedStderrList
assert_in_out_err(args, test_stdin, //, list, encoding: "ASCII-8BIT", **opt)
end
def test_segv_test
assert_segv(["--disable-gems", "-e", "Process.kill :SEGV, $$"])
end
def test_segv_loaded_features
bug7402 = '[ruby-core:49573]'
status = assert_segv(['-e', 'END {Process.kill :SEGV, $$}',
'-e', 'class Bogus; def to_str; exit true; end; end',
'-e', '$".clear',
'-e', '$".unshift Bogus.new',
'-e', '(p $"; abort) unless $".size == 1',
])
assert_not_predicate(status, :success?, "segv but success #{bug7402}")
end
def test_segv_setproctitle
bug7597 = '[ruby-dev:46786]'
Tempfile.create(["test_ruby_test_bug7597", ".rb"]) {|t|
t.write "f" * 100
t.flush
assert_segv(["--disable-gems", "-e", "$0=ARGV[0]; Process.kill :SEGV, $$", t.path], bug7597)
}
end
def test_DATA
Tempfile.create(["test_ruby_test_rubyoption", ".rb"]) {|t|
t.puts "puts DATA.read.inspect"
t.puts "__END__"
t.puts "foo"
t.puts "bar"
t.puts "baz"
t.flush
assert_in_out_err([t.path], "", %w("foo\\nbar\\nbaz\\n"), [])
}
end
def test_unused_variable
feature3446 = '[ruby-dev:41620]'
assert_in_out_err(["-we", "a=1"], "", [], [], feature3446)
assert_in_out_err(["-we", "def foo\n a=1\nend"], "", [], ["-e:2: warning: assigned but unused variable - a"], feature3446)
assert_in_out_err(["-we", "def foo\n eval('a=1')\nend"], "", [], [], feature3446)
assert_in_out_err(["-we", "1.times do\n a=1\nend"], "", [], [], feature3446)
assert_in_out_err(["-we", "def foo\n 1.times do\n a=1\n end\nend"], "", [], ["-e:3: warning: assigned but unused variable - a"], feature3446)
assert_in_out_err(["-we", "def foo\n"" 1.times do |a| end\n""end"], "", [], [])
feature6693 = '[ruby-core:46160]'
assert_in_out_err(["-we", "def foo\n _a=1\nend"], "", [], [], feature6693)
bug7408 = '[ruby-core:49659]'
assert_in_out_err(["-we", "def foo\n a=1\n :a\nend"], "", [], ["-e:2: warning: assigned but unused variable - a"], bug7408)
feature7730 = '[ruby-core:51580]'
assert_in_out_err(["-w", "-"], "a=1", [], ["-:1: warning: assigned but unused variable - a"], feature7730)
assert_in_out_err(["-w", "-"], "eval('a=1')", [], [], feature7730)
end
def test_script_from_stdin
begin
require 'pty'
require 'io/console'
rescue LoadError
return
end
require 'timeout'
result = nil
IO.pipe {|r, w|
begin
PTY.open {|m, s|
s.echo = false
m.print("\C-d")
pid = spawn(EnvUtil.rubybin, :in => s, :out => w)
w.close
assert_nothing_raised('[ruby-dev:37798]') do
result = EnvUtil.timeout(3) {r.read}
end
Process.wait pid
}
rescue RuntimeError
skip $!
end
}
assert_equal("", result, '[ruby-dev:37798]')
IO.pipe {|r, w|
PTY.open {|m, s|
s.echo = false
pid = spawn(EnvUtil.rubybin, :in => s, :out => w)
w.close
m.print("$stdin.read; p $stdin.gets\n\C-d")
m.print("abc\n\C-d")
m.print("zzz\n")
result = r.read
Process.wait pid
}
}
assert_equal("\"zzz\\n\"\n", result, '[ruby-core:30910]')
end
def test_unmatching_glob
bug3851 = '[ruby-core:32478]'
a = "a[foo"
Dir.mktmpdir do |dir|
open(File.join(dir, a), "w") {|f| f.puts("p 42")}
assert_in_out_err(["-C", dir, a], "", ["42"], [], bug3851)
File.unlink(File.join(dir, a))
assert_in_out_err(["-C", dir, a], "", [], /LoadError/, bug3851)
end
end
case RUBY_PLATFORM
when /mswin|mingw/
def test_command_line_glob_nonascii
bug10555 = '[ruby-dev:48752] [Bug #10555]'
name = "\u{3042}.txt"
expected = name.encode("external") rescue "?.txt"
with_tmpchdir do |dir|
open(name, "w") {}
assert_in_out_err(["-e", "puts ARGV", "?.txt"], "", [expected], [],
bug10555, encoding: "external")
end
end
def test_command_line_progname_nonascii
bug10555 = '[ruby-dev:48752] [Bug #10555]'
name = expected = nil
unless (0x80..0x10000).any? {|c|
name = c.chr(Encoding::UTF_8)
expected = name.encode("locale") rescue nil
}
skip "can't make locale name"
end
name << ".rb"
expected << ".rb"
with_tmpchdir do |dir|
open(name, "w") {|f| f.puts "puts File.basename($0)"}
assert_in_out_err([name], "", [expected], [],
bug10555, encoding: "locale")
end
end
def test_command_line_glob_with_dir
bug10941 = '[ruby-core:68430] [Bug #10941]'
with_tmpchdir do |dir|
Dir.mkdir('test')
assert_in_out_err(["-e", "", "test/*"], "", [], [], bug10941)
end
end
Ougai = %W[\u{68ee}O\u{5916}.txt \u{68ee 9d0e 5916}.txt \u{68ee 9dd7 5916}.txt]
def test_command_line_glob_noncodepage
with_tmpchdir do |dir|
Ougai.each {|f| open(f, "w") {}}
assert_in_out_err(["-Eutf-8", "-e", "puts ARGV", "*"], "", Ougai, encoding: "utf-8")
ougai = Ougai.map {|f| f.encode("external", replace: "?")}
assert_in_out_err(["-e", "puts ARGV", "*.txt"], "", ougai)
end
end
def assert_e_script_encoding(str, args = [])
cmds = [
EnvUtil::LANG_ENVS.inject({}) {|h, k| h[k] = ENV[k]; h},
*args,
'-e', "s = '#{str}'",
'-e', 'puts s.encoding.name',
'-e', 'puts s.dump',
]
assert_in_out_err(cmds, "", [str.encoding.name, str.dump], [],
"#{str.encoding}:#{str.dump} #{args.inspect}")
end
# tested codepages: 437 850 852 855 932 65001
# Since the codepage is shared all processes per conhost.exe, do
# not chcp, or parallel test may break.
def test_locale_codepage
locale = Encoding.find("locale")
list = %W"\u{c7} \u{452} \u{3066 3059 3068}"
list.each do |s|
assert_e_script_encoding(s, %w[-U])
end
list.each do |s|
s = s.encode(locale) rescue next
assert_e_script_encoding(s)
assert_e_script_encoding(s, %W[-E#{locale.name}])
end
end
when /cygwin/
def test_command_line_non_ascii
assert_separately([{"LC_ALL"=>"ja_JP.SJIS"}, "-", "\u{3042}".encode("SJIS")], <<-"end;")
bug12184 = '[ruby-dev:49519] [Bug #12184]'
a = ARGV[0]
assert_equal([Encoding::SJIS, 130, 160], [a.encoding, *a.bytes], bug12184)
end;
end
end
def test_script_is_directory
feature2408 = '[ruby-core:26925]'
assert_in_out_err(%w[.], "", [], /Is a directory -- \./, feature2408)
end
def test_pflag_gsub
bug7157 = '[ruby-core:47967]'
assert_in_out_err(['-p', '-e', 'gsub(/t.*/){"TEST"}'], %[test], %w[TEST], [], bug7157)
end
def test_pflag_sub
bug7157 = '[ruby-core:47967]'
assert_in_out_err(['-p', '-e', 'sub(/t.*/){"TEST"}'], %[test], %w[TEST], [], bug7157)
end
def assert_norun_with_rflag(*opt)
bug10435 = "[ruby-dev:48712] [Bug #10435]: should not run with #{opt} option"
stderr = []
Tempfile.create(%w"bug10435- .rb") do |script|
dir, base = File.split(script.path)
script.puts "abort ':run'"
script.close
opts = ['-C', dir, '-r', "./#{base}", *opt]
_, e = assert_in_out_err([*opts, '-ep'], "", //)
stderr.concat(e) if e
stderr << "---"
_, e = assert_in_out_err([*opts, base], "", //)
stderr.concat(e) if e
end
assert_not_include(stderr, ":run", bug10435)
end
def test_dump_syntax_with_rflag
assert_norun_with_rflag('-c')
assert_norun_with_rflag('--dump=syntax')
end
def test_dump_yydebug_with_rflag
assert_norun_with_rflag('-y')
assert_norun_with_rflag('--dump=yydebug')
end
def test_dump_parsetree_with_rflag
assert_norun_with_rflag('--dump=parsetree')
assert_norun_with_rflag('--dump=parsetree', '-e', '#frozen-string-literal: true')
end
def test_dump_insns_with_rflag
assert_norun_with_rflag('--dump=insns')
end
def test_frozen_string_literal
all_assertions do |a|
[["disable", "false"], ["enable", "true"]].each do |opt, exp|
%W[frozen_string_literal frozen-string-literal].each do |arg|
key = "#{opt}=#{arg}"
negopt = exp == "true" ? "disable" : "enable"
env = {"RUBYOPT"=>"--#{negopt}=#{arg}"}
a.for(key) do
assert_in_out_err([env, "--disable=gems", "--#{key}"], 'p("foo".frozen?)', [exp])
end
end
end
%W"disable enable".product(%W[false true]) do |opt, exp|
a.for("#{opt}=>#{exp}") do
assert_in_out_err(["-w", "--disable=gems", "--#{opt}=frozen-string-literal"], <<-"end;", [exp])
#-*- frozen-string-literal: #{exp} -*-
p("foo".frozen?)
end;
end
end
end
end
def test_frozen_string_literal_debug
with_debug_pat = /created at/
wo_debug_pat = /can\'t modify frozen String: "\w+" \(FrozenError\)\n\z/
frozen = [
["--enable-frozen-string-literal", true],
["--disable-frozen-string-literal", false],
[nil, false],
]
debugs = [
["--debug-frozen-string-literal", true],
["--debug=frozen-string-literal", true],
["--debug", true],
[nil, false],
]
opts = ["--disable=gems"]
frozen.product(debugs) do |(opt1, freeze), (opt2, debug)|
opt = opts + [opt1, opt2].compact
err = !freeze ? [] : debug ? with_debug_pat : wo_debug_pat
[
['"foo" << "bar"', err],
['"foo#{123}bar" << "bar"', err],
['+"foo#{123}bar" << "bar"', []],
['-"foo#{123}bar" << "bar"', freeze && debug ? with_debug_pat : wo_debug_pat],
].each do |code, expected|
assert_in_out_err(opt, code, [], expected, [opt, code])
end
end
end
def test___dir__encoding
lang = {"LC_ALL"=>ENV["LC_ALL"]||ENV["LANG"]}
with_tmpchdir do
testdir = "\u30c6\u30b9\u30c8"
Dir.mkdir(testdir)
Dir.chdir(testdir) do
open("test.rb", "w") do |f|
f.puts <<-END
if __FILE__.encoding == __dir__.encoding
p true
else
puts "__FILE__: \#{__FILE__.encoding}, __dir__: \#{__dir__.encoding}"
end
END
end
r, = EnvUtil.invoke_ruby([lang, "test.rb"], "", true)
assert_equal "true", r.chomp, "the encoding of __FILE__ and __dir__ should be same"
end
end
end
def test_cwd_encoding
with_tmpchdir do
testdir = "\u30c6\u30b9\u30c8"
Dir.mkdir(testdir)
Dir.chdir(testdir) do
File.write("a.rb", "require './b'")
File.write("b.rb", "puts 'ok'")
assert_ruby_status([{"RUBYLIB"=>"."}, *%w[-E cp932:utf-8 a.rb]])
end
end
end
def test_null_script
skip "#{IO::NULL} is not a character device" unless File.chardev?(IO::NULL)
assert_in_out_err([IO::NULL], success: true)
end
def test_jit_debug
# mswin uses prebuilt precompiled header. Thus it does not show a pch compilation log to check "-O0 -O1".
if JITSupport.supported? && !RUBY_PLATFORM.match?(/mswin/)
env = { 'MJIT_SEARCH_BUILD_DIR' => 'true' }
assert_in_out_err([env, "--jit-debug=-O0 -O1", "--jit-verbose=2", "" ], "", [], /-O0 -O1/)
end
end
private
def mjit_force_enabled?
"#{RbConfig::CONFIG['CFLAGS']} #{RbConfig::CONFIG['CPPFLAGS']}".match?(/(\A|\s)-D ?MJIT_FORCE_ENABLE\b/)
end
end