repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/parser.rb | lib/slim/parser.rb | # frozen_string_literal: true
module Slim
# Parses Slim code and transforms it to a Temple expression
# @api private
class Parser < Temple::Parser
define_options :file,
:default_tag,
tabsize: 4,
code_attr_delims: {
'(' => ')',
'[' => ']',
'{' => '}',
},
attr_list_delims: {
'(' => ')',
'[' => ']',
'{' => '}',
},
shortcut: {
'#' => { attr: 'id' },
'.' => { attr: 'class' }
},
splat_prefix: '*'
class SyntaxError < StandardError
attr_reader :error, :file, :line, :lineno, :column
def initialize(error, file, line, lineno, column)
@error = error
@file = file || '(__TEMPLATE__)'
@line = line.to_s
@lineno = lineno
@column = column
end
def to_s
line = @line.lstrip
column = @column + line.size - @line.size
%{#{error}
#{file}, Line #{lineno}, Column #{@column}
#{line}
#{' ' * column}^
}
end
end
def initialize(opts = {})
super
@attr_list_delims = options[:attr_list_delims]
@code_attr_delims = options[:code_attr_delims]
tabsize = options[:tabsize]
if tabsize > 1
@tab_re = /\G((?: {#{tabsize}})*) {0,#{tabsize - 1}}\t/
@tab = '\1' + ' ' * tabsize
else
@tab_re = "\t"
@tab = ' '
end
@tag_shortcut, @attr_shortcut, @additional_attrs = {}, {}, {}
options[:shortcut].each do |k,v|
raise ArgumentError, 'Shortcut requires :tag and/or :attr' unless (v[:attr] || v[:tag]) && (v.keys - [:attr, :tag, :additional_attrs]).empty?
@tag_shortcut[k] = v[:tag] || options[:default_tag]
if v.include?(:attr) || v.include?(:additional_attrs)
raise ArgumentError, 'You can only use special characters for attribute shortcuts' if k =~ /(\p{Word}|-)/
end
if v.include?(:attr)
@attr_shortcut[k] = v[:attr].is_a?(Proc) ? v[:attr] : [v[:attr]].flatten
end
if v.include?(:additional_attrs)
@additional_attrs[k] = v[:additional_attrs]
end
end
keys = Regexp.union @attr_shortcut.keys.sort_by { |k| -k.size }
@attr_shortcut_re = /\A(#{keys}+)((?:\p{Word}|-|\/\d+|:(\w|-)+)*)/
keys = Regexp.union @tag_shortcut.keys.sort_by { |k| -k.size }
@tag_re = /\A(?:#{keys}|\*(?=[^\s]+)|(\p{Word}(?:\p{Word}|:|-)*\p{Word}|\p{Word}+))/
keys = Regexp.escape @code_attr_delims.keys.join
@code_attr_delims_re = /\A[#{keys}]/
keys = Regexp.escape @attr_list_delims.keys.join
@attr_list_delims_re = /\A\s*([#{keys}])/
@embedded_re = /\A(#{Regexp.union(Embedded.engines.keys.map(&:to_s))})(?:\s*(?:(.*)))?:(\s*)/
keys = Regexp.escape ('"\'></='.split(//) + @attr_list_delims.flatten + @code_attr_delims.flatten).uniq.join
@attr_name = "\\A\\s*([^\\0\\s#{keys}]+)"
@quoted_attr_re = /#{@attr_name}\s*=(=?)\s*("|')/
@code_attr_re = /#{@attr_name}\s*=(=?)\s*/
splat_prefix = Regexp.escape(options[:splat_prefix])
splat_regexp_source = '\A\s*' + splat_prefix + '(?=[^\s]+)'
@splat_attrs_regexp = Regexp.new(splat_regexp_source)
end
# Compile string to Temple expression
#
# @param [String] str Slim code
# @return [Array] Temple expression representing the code
def call(str)
result = [:multi]
reset(str.split(/\r?\n/), [result])
parse_line while next_line
reset
result
end
protected
def reset(lines = nil, stacks = nil)
# Since you can indent however you like in Slim, we need to keep a list
# of how deeply indented you are. For instance, in a template like this:
#
# doctype # 0 spaces
# html # 0 spaces
# head # 1 space
# title # 4 spaces
#
# indents will then contain [0, 1, 4] (when it's processing the last line.)
#
# We uses this information to figure out how many steps we must "jump"
# out when we see an de-indented line.
@indents = []
# Whenever we want to output something, we'll *always* output it to the
# last stack in this array. So when there's a line that expects
# indentation, we simply push a new stack onto this array. When it
# processes the next line, the content will then be outputted into that
# stack.
@stacks = stacks
@lineno = 0
@lines = lines
@line = @orig_line = nil
end
def next_line
if @lines.empty?
@orig_line = @line = nil
else
@orig_line = @lines.shift
@lineno += 1
@line = @orig_line.dup
end
end
def get_indent(line)
# Figure out the indentation. Kinda ugly/slow way to support tabs,
# but remember that this is only done at parsing time.
line[/\A[ \t]*/].gsub(@tab_re, @tab).size
end
def parse_line
if @line =~ /\A\s*\Z/
@stacks.last << [:newline]
return
end
indent = get_indent(@line)
# Choose first indentation yourself
@indents << indent if @indents.empty?
# Remove the indentation
@line.lstrip!
# If there's more stacks than indents, it means that the previous
# line is expecting this line to be indented.
expecting_indentation = @stacks.size > @indents.size
if indent > @indents.last
# This line was actually indented, so we'll have to check if it was
# supposed to be indented or not.
syntax_error!('Unexpected indentation') unless expecting_indentation
@indents << indent
else
# This line was *not* indented more than the line before,
# so we'll just forget about the stack that the previous line pushed.
@stacks.pop if expecting_indentation
# This line was deindented.
# Now we're have to go through the all the indents and figure out
# how many levels we've deindented.
while indent < @indents.last && @indents.size > 1
@indents.pop
@stacks.pop
end
# This line's indentation happens to lie "between" two other line's
# indentation:
#
# hello
# world
# this # <- This should not be possible!
syntax_error!('Malformed indentation') if indent != @indents.last
end
parse_line_indicators
end
def parse_line_indicators
case @line
when /\A\/!( ?)/
# HTML comment
@stacks.last << [:html, :comment, [:slim, :text, :verbatim, parse_text_block($', @indents.last + $1.size + 2)]]
when /\A\/\[\s*(.*?)\s*\]\s*\Z/
# HTML conditional comment
block = [:multi]
@stacks.last << [:html, :condcomment, $1, block]
@stacks << block
when /\A\//
# Slim comment
parse_comment_block
when /\A([\|'])([<>]{1,2}(?: |\z)| ?)/
# Found verbatim text block.
leading_ws = $2.include?('<'.freeze)
trailing_ws = ($1 == "'") || $2.include?('>'.freeze)
@stacks.last << [:static, ' '] if leading_ws
@stacks.last << [:slim, :text, :verbatim, parse_text_block($', @indents.last + $2.count(' ') + 1)]
@stacks.last << [:static, ' '] if trailing_ws
when /\A</
# Inline html
block = [:multi]
@stacks.last << [:multi, [:slim, :interpolate, @line], block]
@stacks << block
when /\A-/
# Found a code block.
# We expect the line to be broken or the next line to be indented.
@line.slice!(0)
block = [:multi]
@stacks.last << [:slim, :control, parse_broken_line, block]
@stacks << block
when /\A=(=?)([<>]*)/
# Found an output block.
# We expect the line to be broken or the next line to be indented.
@line = $'
leading_ws = $2.include?('<'.freeze)
trailing_ws = $2.include?('>'.freeze)
block = [:multi]
@stacks.last << [:static, ' '] if leading_ws
@stacks.last << [:slim, :output, $1.empty?, parse_broken_line, block]
@stacks.last << [:static, ' '] if trailing_ws
@stacks << block
when @embedded_re
# Embedded template detected. It is treated as block.
@line = $2
attrs = parse_attributes
@stacks.last << [:slim, :embedded, $1, parse_text_block($', @orig_line.size - $'.size + $2.size), attrs]
when /\Adoctype\b/
# Found doctype declaration
@stacks.last << [:html, :doctype, $'.strip]
when @tag_re
# Found a HTML tag.
@line = $' if $1
parse_tag($&)
else
unknown_line_indicator
end
@stacks.last << [:newline]
end
# Unknown line indicator found. Overwrite this method if
# you want to add line indicators to the Slim parser.
# The default implementation throws a syntax error.
def unknown_line_indicator
syntax_error! 'Unknown line indicator'
end
def parse_comment_block
while !@lines.empty? && (@lines.first =~ /\A\s*\Z/ || get_indent(@lines.first) > @indents.last)
next_line
@stacks.last << [:newline]
end
end
def parse_text_block(first_line = nil, text_indent = nil)
result = [:multi]
if !first_line || first_line.empty?
text_indent = nil
else
result << [:slim, :interpolate, first_line]
end
empty_lines = 0
until @lines.empty?
if @lines.first =~ /\A\s*\Z/
next_line
result << [:newline]
empty_lines += 1 if text_indent
else
indent = get_indent(@lines.first)
break if indent <= @indents.last
if empty_lines > 0
result << [:slim, :interpolate, "\n" * empty_lines]
empty_lines = 0
end
next_line
@line.lstrip!
# The text block lines must be at least indented
# as deep as the first line.
offset = text_indent ? indent - text_indent : 0
if offset < 0
text_indent += offset
offset = 0
end
result << [:newline] << [:slim, :interpolate, (text_indent ? "\n" : '') + (' ' * offset) + @line]
# The indentation of first line of the text block
# determines the text base indentation.
text_indent ||= indent
end
end
result
end
def parse_broken_line
broken_line = @line.strip
while broken_line =~ /[,\\]\Z/
expect_next_line
broken_line << "\n" << @line
end
broken_line
end
def parse_tag(tag)
if @tag_shortcut[tag]
@line.slice!(0, tag.size) unless @attr_shortcut[tag]
tag = @tag_shortcut[tag]
end
# Find any shortcut attributes
attributes = [:html, :attrs]
while @line =~ @attr_shortcut_re
# The class/id attribute is :static instead of :slim :interpolate,
# because we don't want text interpolation in .class or #id shortcut
syntax_error!('Illegal shortcut') unless shortcut = @attr_shortcut[$1]
if shortcut.is_a?(Proc)
shortcut.call($2).each { |a, v| attributes << [:html, :attr, a, [:static, v]] }
else
shortcut.each {|a| attributes << [:html, :attr, a, [:static, $2]] }
end
if additional_attr_pairs = @additional_attrs[$1]
additional_attr_pairs.each do |k,v|
attributes << [:html, :attr, k.to_s, [:static, v]]
end
end
@line = $'
end
@line =~ /\A[<>']*/
@line = $'
trailing_ws = $&.include?('>'.freeze)
leading_ws = $&.include?('<'.freeze)
parse_attributes(attributes)
tag = [:html, :tag, tag, attributes]
@stacks.last << [:static, ' '] if leading_ws
@stacks.last << tag
@stacks.last << [:static, ' '] if trailing_ws
case @line
when /\A\s*:\s*/
# Block expansion
@line = $'
if @line =~ @embedded_re
# Parse attributes
@line = $2
attrs = parse_attributes
tag << [:slim, :embedded, $1, parse_text_block($', @orig_line.size - $'.size + $2.size), attrs]
else
(@line =~ @tag_re) || syntax_error!('Expected tag')
@line = $' if $1
content = [:multi]
tag << content
i = @stacks.size
@stacks << content
parse_tag($&)
@stacks.delete_at(i)
end
when /\A\s*=(=?)(['<>]*)/
# Handle output code
@line = $'
trailing_ws2 = $2.include?('>'.freeze)
block = [:multi]
@stacks.last.insert(-2, [:static, ' ']) if !leading_ws && $2.include?('<'.freeze)
tag << [:slim, :output, $1 != '=', parse_broken_line, block]
@stacks.last << [:static, ' '] if !trailing_ws && trailing_ws2
@stacks << block
when /\A\s*\/\s*/
# Closed tag. Do nothing
@line = $'
syntax_error!('Unexpected text after closed tag') unless @line.empty?
when /\A\s*\Z/
# Empty content
content = [:multi]
tag << content
@stacks << content
when /\A ?/
# Text content
tag << [:slim, :text, :inline, parse_text_block($', @orig_line.size - $'.size)]
end
end
def parse_attributes(attributes = [:html, :attrs])
# Check to see if there is a delimiter right after the tag name
delimiter = nil
if @line =~ @attr_list_delims_re
delimiter = @attr_list_delims[$1]
@line = $'
end
if delimiter
boolean_attr_re = /#{@attr_name}(?=(\s|#{Regexp.escape delimiter}|\Z))/
end_re = /\A\s*#{Regexp.escape delimiter}/
end
while true
case @line
when @splat_attrs_regexp
# Splat attribute
@line = $'
attributes << [:slim, :splat, parse_ruby_code(delimiter)]
when @quoted_attr_re
# Value is quoted (static)
@line = $'
attributes << [:html, :attr, $1,
[:escape, $2.empty?, [:slim, :interpolate, parse_quoted_attribute($3)]]]
when @code_attr_re
# Value is ruby code
@line = $'
name = $1
escape = $2.empty?
value = parse_ruby_code(delimiter)
syntax_error!('Invalid empty attribute') if value.empty?
attributes << [:html, :attr, name, [:slim, :attrvalue, escape, value]]
else
break unless delimiter
case @line
when boolean_attr_re
# Boolean attribute
@line = $'
attributes << [:html, :attr, $1, [:multi]]
when end_re
# Find ending delimiter
@line = $'
break
else
# Found something where an attribute should be
@line.lstrip!
syntax_error!('Expected attribute') unless @line.empty?
# Attributes span multiple lines
@stacks.last << [:newline]
syntax_error!("Expected closing delimiter #{delimiter}") if @lines.empty?
next_line
end
end
end
attributes || [:html, :attrs]
end
def parse_ruby_code(outer_delimiter)
code, count, delimiter, close_delimiter = ''.dup, 0, nil, nil
# Attribute ends with space or attribute delimiter
end_re = /\A[\s#{Regexp.escape outer_delimiter.to_s}]/
until @line.empty? || (count == 0 && @line =~ end_re)
if @line =~ /\A[,\\]\Z/
code << @line << "\n"
expect_next_line
else
if count > 0
if @line[0] == delimiter[0]
count += 1
elsif @line[0] == close_delimiter[0]
count -= 1
end
elsif @line =~ @code_attr_delims_re
count = 1
delimiter, close_delimiter = $&, @code_attr_delims[$&]
end
code << @line.slice!(0)
end
end
syntax_error!("Expected closing delimiter #{close_delimiter}") if count != 0
code
end
def parse_quoted_attribute(quote)
value, count = ''.dup, 0
until count == 0 && @line[0] == quote[0]
if @line =~ /\A(\\)?\Z/
value << ($1 ? ' ' : "\n")
expect_next_line
else
if @line[0] == '{'
count += 1
elsif @line[0] == '}'
count -= 1
end
value << @line.slice!(0)
end
end
@line.slice!(0)
value
end
# Helper for raising exceptions
def syntax_error!(message)
raise SyntaxError.new(message, options[:file], @orig_line, @lineno,
@orig_line && @line ? @orig_line.size - @line.size : 0)
rescue SyntaxError => ex
# HACK: Manipulate stacktrace for Rails and other frameworks
# to find the right file.
ex.backtrace.unshift "#{options[:file]}:#{@lineno}"
raise
end
def expect_next_line
next_line || syntax_error!('Unexpected end of file')
@line.strip!
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/erb_converter.rb | lib/slim/erb_converter.rb | # frozen_string_literal: true
require 'slim'
module Slim
# Slim to ERB converter
#
# @example Conversion
# Slim::ERBConverter.new(options).call(slim_code) # outputs erb_code
#
# @api public
class ERBConverter < Engine
replace :StaticMerger, Temple::Filters::CodeMerger
replace :Generator, Temple::Generators::ERB
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/translator.rb | lib/slim/translator.rb | # frozen_string_literal: true
require 'slim'
module Slim
# @api private
class Translator < Filter
define_options :tr,
tr_mode: :dynamic,
tr_fn: '_'
if defined?(::I18n)
set_options tr_fn: '::Slim::Translator.i18n_text',
tr: true
elsif defined?(::GetText)
set_options tr_fn: '::GetText._',
tr: true
elsif defined?(::FastGettext)
set_options tr_fn: '::FastGettext::Translation._',
tr: true
end
def self.i18n_text(text)
I18n.t!(text)
rescue I18n::MissingTranslationData
text
end
def self.i18n_key(text)
key = text.parameterize.underscore
I18n.t!(key)
rescue I18n::MissingTranslationData
text
end
def call(exp)
options[:tr] ? super : exp
end
def initialize(opts = {})
super
case options[:tr_mode]
when :static
@translator = StaticTranslator.new(tr_fn: options[:tr_fn])
when :dynamic
@translator = DynamicTranslator.new(tr_fn: options[:tr_fn])
else
raise ArgumentError, "Invalid translator mode #{options[:tr_mode].inspect}"
end
end
def on_slim_text(type, exp)
[:slim, :text, type, @translator.call(exp)]
end
private
class StaticTranslator < Filter
define_options :tr_fn
def initialize(opts = {})
super
@translate = eval("proc {|string| #{options[:tr_fn]}(string) }")
end
def call(exp)
@text, @captures = ''.dup, []
result = compile(exp)
text = @translate.call(@text)
while text =~ /%(\d+)/
result << [:static, $`] << @captures[$1.to_i - 1]
text = $'
end
result << [:static, text]
end
def on_static(text)
@text << text
[:multi]
end
def on_slim_output(escape, code, content)
@captures << [:slim, :output, escape, code, content]
@text << "%#{@captures.size}"
[:multi]
end
end
class DynamicTranslator < Filter
define_options :tr_fn
def call(exp)
@captures_count, @captures_var, @text = 0, unique_name, ''.dup
result = compile(exp)
if @captures_count > 0
result.insert(1, [:code, "#{@captures_var}=[]"])
result << [:slim, :output, false, "#{options[:tr_fn]}(#{@text.inspect}).gsub(/%(\\d+)/) { #{@captures_var}[$1.to_i-1] }", [:multi]]
else
result << [:slim, :output, false, "#{options[:tr_fn]}(#{@text.inspect})", [:multi]]
end
end
def on_static(text)
@text << text
[:multi]
end
def on_slim_output(escape, code, content)
@captures_count += 1
@text << "%#{@captures_count}"
[:capture, "#{@captures_var}[#{@captures_count - 1}]", [:slim, :output, escape, code, content]]
end
end
end
end
Slim::Engine.before Slim::EndInserter, Slim::Translator
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/railtie.rb | lib/slim/railtie.rb | # frozen_string_literal: true
module Slim
class Railtie < ::Rails::Railtie
initializer 'initialize slim template handler' do
ActiveSupport.on_load(:action_view) do
Slim::RailsTemplate = Temple::Templates::Rails(Slim::Engine,
register_as: :slim,
# Use rails-specific generator. This is necessary
# to support block capturing and streaming.
generator: Temple::Generators::RailsOutputBuffer,
# Disable the internal slim capturing.
# Rails takes care of the capturing by itself.
disable_capture: true,
streaming: true)
end
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/logic_less.rb | lib/slim/logic_less.rb | # frozen_string_literal: true
require 'slim'
require 'slim/logic_less/filter'
require 'slim/logic_less/context'
Slim::Engine.after Slim::Interpolation, Slim::LogicLess
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/code_attributes.rb | lib/slim/code_attributes.rb | # frozen_string_literal: true
module Slim
# @api private
class CodeAttributes < Filter
define_options :merge_attrs
# Handle attributes expression `[:html, :attrs, *attrs]`
#
# @param [Array] attrs Array of temple expressions
# @return [Array] Compiled temple expression
def on_html_attrs(*attrs)
[:multi, *attrs.map { |a| compile(a) }]
end
# Handle attribute expression `[:html, :attr, name, value]`
#
# @param [String] name Attribute name
# @param [Array] value Value expression
# @return [Array] Compiled temple expression
def on_html_attr(name, value)
if value[0] == :slim && value[1] == :attrvalue && !options[:merge_attrs][name]
# We handle the attribute as a boolean attribute
escape, code = value[2], value[3]
case code
when 'true'
[:html, :attr, name, [:multi]]
when 'false', 'nil'
[:multi]
else
tmp = unique_name
[:multi,
[:code, "#{tmp} = #{code}"],
[:if, tmp,
[:if, "#{tmp} == true",
[:html, :attr, name, [:multi]],
[:html, :attr, name, [:escape, escape, [:dynamic, tmp]]]]]]
end
else
# Attribute with merging
@attr = name
super
end
end
# Handle attribute expression `[:slim, :attrvalue, escape, code]`
#
# @param [Boolean] escape Escape html
# @param [String] code Ruby code
# @return [Array] Compiled temple expression
def on_slim_attrvalue(escape, code)
# We perform attribute merging on Array values
if delimiter = options[:merge_attrs][@attr]
tmp = unique_name
[:multi,
[:code, "#{tmp} = #{code}"],
[:if, "Array === #{tmp}",
[:multi,
[:code, "#{tmp} = #{tmp}.flatten"],
[:code, "#{tmp}.map!(&:to_s)"],
[:code, "#{tmp}.reject!(&:empty?)"],
[:escape, escape, [:dynamic, "#{tmp}.join(#{delimiter.inspect})"]]],
[:escape, escape, [:dynamic, tmp]]]]
else
[:escape, escape, [:dynamic, code]]
end
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/controls.rb | lib/slim/controls.rb | # frozen_string_literal: true
module Slim
# @api private
class Controls < Filter
define_options :disable_capture
IF_RE = /\A(if|unless)\b|\bdo\s*(\|[^\|]*\|)?\s*$/
# Handle control expression `[:slim, :control, code, content]`
#
# @param [String] code Ruby code
# @param [Array] content Temple expression
# @return [Array] Compiled temple expression
def on_slim_control(code, content)
[:multi,
[:code, code],
compile(content)]
end
# Handle output expression `[:slim, :output, escape, code, content]`
#
# @param [Boolean] escape Escape html
# @param [String] code Ruby code
# @param [Array] content Temple expression
# @return [Array] Compiled temple expression
def on_slim_output(escape, code, content)
if code =~ IF_RE
tmp = unique_name
[:multi,
# Capture the result of the code in a variable. We can't do
# `[:dynamic, code]` because it's probably not a complete
# expression (which is a requirement for Temple).
[:block, "#{tmp} = #{code}",
# Capture the content of a block in a separate buffer. This means
# that `yield` will not output the content to the current buffer,
# but rather return the output.
#
# The capturing can be disabled with the option :disable_capture.
# Output code in the block writes directly to the output buffer then.
# Rails handles this by replacing the output buffer for helpers.
options[:disable_capture] ? compile(content) : [:capture, unique_name, compile(content)]],
# Output the content.
[:escape, escape, [:dynamic, tmp]]]
else
[:multi, [:escape, escape, [:dynamic, code]], content]
end
end
# Handle text expression `[:slim, :text, type, content]`
#
# @param [Symbol] type Text type
# @param [Array] content Temple expression
# @return [Array] Compiled temple expression
def on_slim_text(type, content)
compile(content)
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/smart.rb | lib/slim/smart.rb | # frozen_string_literal: true
require 'slim'
require 'slim/smart/filter'
require 'slim/smart/escaper'
require 'slim/smart/parser'
Slim::Engine.replace Slim::Parser, Slim::Smart::Parser
Slim::Engine.after Slim::Smart::Parser, Slim::Smart::Filter
Slim::Engine.after Slim::Interpolation, Slim::Smart::Escaper
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/template.rb | lib/slim/template.rb | # frozen_string_literal: true
module Slim
# Tilt template implementation for Slim
# @api public
Template = Temple::Templates::Tilt(Slim::Engine, register_as: :slim)
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/engine.rb | lib/slim/engine.rb | # frozen_string_literal: true
# The Slim module contains all Slim related classes (e.g. Engine, Parser).
# Plugins might also reside within the Slim module (e.g. Include, Smart).
# @api public
module Slim
# Slim engine which transforms slim code to executable ruby code
# @api public
class Engine < Temple::Engine
# This overwrites some Temple default options or sets default options for Slim specific filters.
# It is recommended to set the default settings only once in the code and avoid duplication. Only use
# `define_options` when you have to override some default settings.
define_options pretty: false,
sort_attrs: true,
format: :xhtml,
attr_quote: '"',
merge_attrs: {'class' => ' '},
generator: Temple::Generators::StringBuffer,
default_tag: 'div'
filter :Encoding
filter :RemoveBOM
use Slim::Parser
use Slim::Embedded
use Slim::Interpolation
use Slim::Splat::Filter
use Slim::DoInserter
use Slim::EndInserter
use Slim::Controls
html :AttributeSorter
html :AttributeMerger
use Slim::CodeAttributes
use(:AttributeRemover) { Temple::HTML::AttributeRemover.new(remove_empty_attrs: options[:merge_attrs].keys) }
html :Pretty
filter :Ambles
filter :Escapable
filter :StaticAnalyzer
filter :ControlFlow
filter :MultiFlattener
filter :StaticMerger
use(:Generator) { options[:generator] }
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/do_inserter.rb | lib/slim/do_inserter.rb | # frozen_string_literal: true
module Slim
# In Slim you don't need the do keyword sometimes. This
# filter adds the missing keyword.
#
# - 10.times
# | Hello
#
# @api private
class DoInserter < Filter
BLOCK_REGEX = /(\A(if|unless|else|elsif|when|in|begin|rescue|ensure|case)\b)|\bdo\s*(\|[^\|]*\|\s*)?\Z/
# Handle control expression `[:slim, :control, code, content]`
#
# @param [String] code Ruby code
# @param [Array] content Temple expression
# @return [Array] Compiled temple expression
def on_slim_control(code, content)
code += ' do' unless code =~ BLOCK_REGEX || empty_exp?(content)
[:slim, :control, code, compile(content)]
end
# Handle output expression `[:slim, :output, escape, code, content]`
#
# @param [Boolean] escape Escape html
# @param [String] code Ruby code
# @param [Array] content Temple expression
# @return [Array] Compiled temple expression
def on_slim_output(escape, code, content)
code += ' do' unless code =~ BLOCK_REGEX || empty_exp?(content)
[:slim, :output, escape, code, compile(content)]
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/smart/filter.rb | lib/slim/smart/filter.rb | # frozen_string_literal: true
module Slim
module Smart
# Perform newline processing in the
# expressions `[:slim, :text, type, Expression]`.
#
# @api private
class Filter < ::Slim::Filter
define_options smart_text: true,
smart_text_end_chars: '([{',
smart_text_begin_chars: ',.;:!?)]}'
def initialize(opts = {})
super
@active = @prepend = @append = false
@prepend_re = /\A#{chars_re(options[:smart_text_begin_chars])}/
@append_re = /#{chars_re(options[:smart_text_end_chars])}\Z/
end
def call(exp)
if options[:smart_text]
super
else
exp
end
end
def on_multi(*exps)
# The [:multi] blocks serve two purposes.
# On outer level, they collect the building blocks like
# tags, verbatim text, and implicit/explicit text.
# Within a text block, they collect the individual
# lines in [:slim, :interpolate, string] blocks.
#
# Our goal here is to decide when we want to prepend and
# append newlines to those individual interpolated lines.
# We basically want the text to come out as it was originally entered,
# while removing newlines next to the enclosing tags.
#
# On outer level, we choose to prepend every time, except
# right after the opening tag or after other text block.
# We also use the append flag to recognize the last expression
# before the closing tag, as we don't want to append newline there.
#
# Within text block, we prepend only before the first line unless
# the outer level tells us not to, and we append only after the last line,
# unless the outer level tells us it is the last line before the closing tag.
# Of course, this is later subject to the special begin/end characters
# which may further suppress the newline at the corresponding line boundary.
# Also note that the lines themselves are already correctly separated by newlines,
# so we don't have to worry about that at all.
block = [:multi]
prev = nil
last_exp = exps.reject { |exp| exp.first == :newline }.last unless @active && @append
exps.each do |exp|
@append = exp.equal?(last_exp)
if @active
@prepend = false if prev
else
@prepend = prev && (prev.first != :slim || prev[1] != :text)
end
block << compile(exp)
prev = exp unless exp.first == :newline
end
block
end
def on_slim_text(type, content)
@active = type != :verbatim
[:slim, :text, type, compile(content)]
ensure
@active = false
end
def on_slim_text_inline(content)
# Inline text is not wrapped in multi block, so set it up as if it was.
@prepend = false
@append = true
on_slim_text(:inline, content)
end
def on_slim_interpolate(string)
if @active
string = "\n" + string if @prepend && string !~ @prepend_re
string += "\n" if @append && string !~ @append_re
end
[:slim, :interpolate, string]
end
private
def chars_re(string)
Regexp.union(string.split(//))
end
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/smart/parser.rb | lib/slim/smart/parser.rb | # frozen_string_literal: true
module Slim
module Smart
# @api private
class Parser < ::Slim::Parser
define_options implicit_text: true
def initialize(opts = {})
super
word_re = options[:implicit_text] ? '[_a-z0-9]' : '\p{Word}'
attr_keys = Regexp.union(@attr_shortcut.keys.sort_by { |k| -k.size })
@attr_shortcut_re = /\A(#{attr_keys}+)((?:\p{Word}|-)*)/
tag_keys = Regexp.union((@tag_shortcut.keys - @attr_shortcut.keys).sort_by { |k| -k.size })
@tag_re = /\A(?:#{attr_keys}(?=-*\p{Word})|#{tag_keys}|\*(?=[^\s]+)|(#{word_re}(?:#{word_re}|:|-)*#{word_re}|#{word_re}+))/
end
def unknown_line_indicator
if @line =~ /\A>( ?)/
# Found explicit text block.
@stacks.last << [:slim, :text, :explicit, parse_text_block($', @indents.last + $1.size + 1)]
else
unless options[:implicit_text]
syntax_error! 'Illegal shortcut' if @line =~ @attr_shortcut_re
super
end
# Found implicit smart text block.
if line = @lines.first
indent = (line =~ /\A\s*\Z/ ? @indents.last + 1 : get_indent(line))
end
@stacks.last << [:slim, :text, :implicit, parse_text_block(@line, indent)]
end
end
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/smart/escaper.rb | lib/slim/smart/escaper.rb | # frozen_string_literal: true
module Slim
module Smart
# Perform smart entity escaping in the
# expressions `[:slim, :text, type, Expression]`.
#
# @api private
class Escaper < ::Slim::Filter
define_options smart_text_escaping: true
def call(exp)
if options[:smart_text_escaping]
super
else
exp
end
end
def on_slim_text(type, content)
[:escape, type != :verbatim, [:slim, :text, type, compile(content)]]
end
def on_static(string)
# Prevent obvious &foo; and Ӓ and ÿ entities from escaping.
block = [:multi]
until string.empty?
case string
when /\A&([a-z][a-z0-9]*|#x[0-9a-f]+|#\d+);/i
# Entity.
block << [:escape, false, [:static, $&]]
string = $'
when /\A&?[^&]*/
# Other text.
block << [:static, $&]
string = $'
end
end
block
end
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/splat/filter.rb | lib/slim/splat/filter.rb | # frozen_string_literal: true
module Slim
module Splat
# @api private
class Filter < ::Slim::Filter
define_options :merge_attrs, :attr_quote, :sort_attrs, :default_tag, :format, :disable_capture,
hyphen_attrs: %w(data aria), use_html_safe: ''.respond_to?(:html_safe?),
hyphen_underscore_attrs: false
def call(exp)
@splat_options = nil
exp = compile(exp)
if @splat_options
opts = options.to_hash.reject { |k, v| !Filter.options.valid_key?(k) }.inspect
[:multi, [:code, "#{@splat_options} = #{opts}"], exp]
else
exp
end
end
# Handle tag expression `[:html, :tag, name, attrs, content]`
#
# @param [String] name Tag name
# @param [Array] attrs Temple expression
# @param [Array] content Temple expression
# @return [Array] Compiled temple expression
def on_html_tag(name, attrs, content = nil)
return super if name != '*'
builder, block = make_builder(attrs[2..-1])
if content
[:multi,
block,
[:slim, :output, false,
"#{builder}.build_tag #{empty_exp?(content) ? '{}' : 'do'}",
compile(content)]]
else
[:multi,
block,
[:dynamic, "#{builder}.build_tag"]]
end
end
# Handle attributes expression `[:html, :attrs, *attrs]`
#
# @param [Array] attrs Array of temple expressions
# @return [Array] Compiled temple expression
def on_html_attrs(*attrs)
if attrs.any? { |attr| splat?(attr) }
builder, block = make_builder(attrs)
[:multi,
block,
[:dynamic, "#{builder}.build_attrs"]]
else
super
end
end
protected
def splat?(attr)
# Splat attribute given
attr[0] == :slim && attr[1] == :splat ||
# Hyphenated attribute also needs splat handling
(attr[0] == :html && attr[1] == :attr && options[:hyphen_attrs].include?(attr[2]) &&
attr[3][0] == :slim && attr[3][1] == :attrvalue)
end
def make_builder(attrs)
@splat_options ||= unique_name
builder = unique_name
result = [:multi, [:code, "#{builder} = ::Slim::Splat::Builder.new(#{@splat_options})"]]
attrs.each do |attr|
result <<
if attr[0] == :html && attr[1] == :attr
if attr[3][0] == :slim && attr[3][1] == :attrvalue
[:code, "#{builder}.code_attr(#{attr[2].inspect}, #{attr[3][2]}, (#{attr[3][3]}))"]
else
tmp = unique_name
[:multi,
[:capture, tmp, compile(attr[3])],
[:code, "#{builder}.attr(#{attr[2].inspect}, #{tmp})"]]
end
elsif attr[0] == :slim && attr[1] == :splat
[:code, "#{builder}.splat_attrs((#{attr[2]}))"]
else
attr
end
end
[builder, result]
end
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/splat/builder.rb | lib/slim/splat/builder.rb | # frozen_string_literal: true
module Slim
class InvalidAttributeNameError < StandardError; end
module Splat
# @api private
class Builder
# https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
INVALID_ATTRIBUTE_NAME_REGEX = /[ \0"'>\/=]/
def initialize(options)
@options = options
@attrs = {}
end
def code_attr(name, escape, value)
if delim = @options[:merge_attrs][name]
value = Array === value ? value.join(delim) : value.to_s
attr(name, escape_html(escape, value)) unless value.empty?
elsif @options[:hyphen_attrs].include?(name) && Hash === value
hyphen_attr(name, escape, value)
elsif value != false && value != nil
attr(name, escape_html(escape, value))
end
end
def splat_attrs(splat)
splat.each do |name, value|
code_attr(name.to_s, true, value)
end
end
def attr(name, value)
if name =~ INVALID_ATTRIBUTE_NAME_REGEX
raise InvalidAttributeNameError, "Invalid attribute name '#{name}' was rendered"
end
if @attrs[name]
if delim = @options[:merge_attrs][name]
@attrs[name] = @attrs[name].to_s + delim + value.to_s
else
raise("Multiple #{name} attributes specified")
end
else
@attrs[name] = value
end
end
def build_tag(&block)
tag = @attrs.delete('tag').to_s
tag = @options[:default_tag] if tag.empty?
if block
content = capture_block_content(&block)
"<#{tag}#{build_attrs}>#{content}</#{tag}>"
else
"<#{tag}#{build_attrs} />"
end
end
def build_attrs
attrs = @options[:sort_attrs] ? @attrs.sort_by(&:first) : @attrs
attrs.map do |k, v|
if v == true
if @options[:format] == :xhtml
" #{k}=#{@options[:attr_quote]}#{@options[:attr_quote]}"
else
" #{k}"
end
else
" #{k}=#{@options[:attr_quote]}#{v}#{@options[:attr_quote]}"
end
end.join
end
private
# Captures block content using the appropriate capturing mechanism.
#
# If we have Slim capturing disabled and the scope defines the method `capture` (i.e. Rails)
# we use this method to capture the content.
#
# Otherwise we just use normal Slim capturing (yield).
#
# See https://github.com/slim-template/slim/issues/591
# https://github.com/slim-template/slim#helpers-capturing-and-includes
def capture_block_content(&block)
if @options[:disable_capture] && (scope = block.binding.eval('self')).respond_to?(:capture)
scope.capture(&block)
else
yield
end
end
def hyphen_attr(name, escape, value)
if Hash === value
if @options[:hyphen_underscore_attrs]
value.each do |n, v|
hyphen_attr("#{name}-#{n.to_s.tr('_', '-')}", escape, v)
end
else
value.each do |n, v|
hyphen_attr("#{name}-#{n}", escape, v)
end
end
else
attr(name, escape_html(escape, value))
end
end
def escape_html(escape, value)
return value if !escape || value == true
@options[:use_html_safe] ? Temple::Utils.escape_html_safe(value) : Temple::Utils.escape_html(value)
end
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/logic_less/filter.rb | lib/slim/logic_less/filter.rb | # frozen_string_literal: true
module Slim
# Handle logic less mode
# This filter can be activated with the option "logic_less"
# @api private
class LogicLess < Filter
# Default dictionary access order, change it with the option :dictionary_access
DEFAULT_ACCESS_ORDER = [:symbol, :string, :method, :instance_variable].freeze
define_options logic_less: true,
dictionary: 'self',
dictionary_access: DEFAULT_ACCESS_ORDER
def initialize(opts = {})
super
access = [options[:dictionary_access]].flatten.compact
access.each do |type|
raise ArgumentError, "Invalid dictionary access #{type.inspect}" unless DEFAULT_ACCESS_ORDER.include?(type)
end
raise ArgumentError, 'Option dictionary access is missing' if access.empty?
@access = access.inspect
end
def call(exp)
if options[:logic_less]
@context = unique_name
[:multi,
[:code, "#{@context} = ::Slim::LogicLess::Context.new(#{options[:dictionary]}, #{@access})"],
super]
else
exp
end
end
# Interpret control blocks as sections or inverted sections
def on_slim_control(name, content)
method =
if name =~ /\A!\s*(.*)/
name = $1
'inverted_section'
else
'section'
end
[:block, "#{@context}.#{method}(#{name.to_sym.inspect}) do", compile(content)]
end
def on_slim_output(escape, name, content)
[:slim, :output, escape, empty_exp?(content) ? access(name) :
"#{@context}.lambda(#{name.to_sym.inspect}) do", compile(content)]
end
def on_slim_attrvalue(escape, value)
[:slim, :attrvalue, escape, access(value)]
end
def on_slim_splat(code)
[:slim, :splat, access(code)]
end
def on_dynamic(code)
raise Temple::FilterError, 'Embedded code is forbidden in logic less mode'
end
def on_code(code)
raise Temple::FilterError, 'Embedded code is forbidden in logic less mode'
end
private
def access(name)
case name
when 'yield'
'yield'
when 'self'
"#{@context}.to_s"
else
"#{@context}[#{name.to_sym.inspect}]"
end
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
slim-template/slim | https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/logic_less/context.rb | lib/slim/logic_less/context.rb | # frozen_string_literal: true
module Slim
class LogicLess
# @api private
class Context
def initialize(dict, lookup)
@scope = [Scope.new(dict, lookup)]
end
def [](name)
scope[name]
end
def lambda(name)
scope.lambda(name) do |*dict|
if dict.empty?
yield
else
new_scope do
dict.inject(''.dup) do |result, d|
scope.dict = d
result << yield
end
end
end
end
end
def section(name)
dict = scope[name]
if dict && !(dict.respond_to?(:empty?) && dict.empty?)
if !dict.respond_to?(:has_key?) && dict.respond_to?(:each)
new_scope do
dict.each do |d|
scope.dict = d
yield
end
end
else
new_scope(dict) { yield }
end
end
end
def inverted_section(name)
dict = scope[name]
yield if !dict || (dict.respond_to?(:empty?) && dict.empty?)
end
def to_s
scope.to_s
end
private
class Scope
attr_reader :lookup
attr_writer :dict
def initialize(dict, lookup, parent = nil)
@dict, @lookup, @parent = dict, lookup, parent
end
def lambda(name, &block)
@lookup.each do |lookup|
case lookup
when :method
return @dict.public_send(name, &block) if @dict.respond_to?(name, false)
when :symbol
return @dict[name].call(&block) if has_key?(name)
when :string
return @dict[name.to_s].call(&block) if has_key?(name.to_s)
when :instance_variable
var_name = "@#{name}"
return @dict.instance_variable_get(var_name).call(&block) if instance_variable?(var_name)
end
end
@parent.lambda(name, &block) if @parent
end
def [](name)
@lookup.each do |lookup|
case lookup
when :method
return @dict.public_send(name) if @dict.respond_to?(name, false)
when :symbol
return @dict[name] if has_key?(name)
when :string
return @dict[name.to_s] if has_key?(name.to_s)
when :instance_variable
var_name = "@#{name}"
return @dict.instance_variable_get(var_name) if instance_variable?(var_name)
end
end
@parent[name] if @parent
end
def to_s
@dict.to_s
end
private
def has_key?(name)
@dict.respond_to?(:has_key?) && @dict.has_key?(name)
end
def instance_variable?(name)
@dict.instance_variable_defined?(name)
rescue NameError
false
end
end
def scope
@scope.last
end
def new_scope(dict = nil)
@scope << Scope.new(dict, scope.lookup, scope)
yield
ensure
@scope.pop
end
end
end
end
| ruby | MIT | d387587ae364f489b3e23126e204907a0b134bd3 | 2026-01-04T15:43:07.251246Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/helpers.rb | spec/helpers.rb | require 'uri'
module Helpers
# @param [Hash] opts A hash of methods, passed directly to the double
# definition. Use this to stub other required methods.
#
# @return double for Net::HTTPResponse
def res_double(opts={})
instance_double('Net::HTTPResponse', {to_hash: {}, body: 'response body'}.merge(opts))
end
# Given a Net::HTTPResponse or double and a Request or double, create a
# RestClient::Response object.
#
# @param net_http_res_double an rspec double for Net::HTTPResponse
# @param request A RestClient::Request or rspec double
#
# @return [RestClient::Response]
#
def response_from_res_double(net_http_res_double, request=nil, duration: 1)
request ||= request_double()
start_time = Time.now - duration
response = RestClient::Response.create(net_http_res_double.body, net_http_res_double, request, start_time)
# mock duration to ensure it gets the value we expect
allow(response).to receive(:duration).and_return(duration)
response
end
# Redirect stderr to a string for the duration of the passed block.
def fake_stderr
original_stderr = $stderr
$stderr = StringIO.new
yield
$stderr.string
ensure
$stderr = original_stderr
end
# Create a double for RestClient::Request
def request_double(url: 'http://example.com', method: 'get')
instance_double('RestClient::Request',
url: url, uri: URI.parse(url), method: method, user: nil, password: nil,
cookie_jar: HTTP::CookieJar.new, redirection_history: nil,
args: {url: url, method: method})
end
def test_image_path
File.dirname(__FILE__) + "/ISS.jpg"
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/spec_helper.rb | spec/spec_helper.rb | require 'webmock/rspec'
require 'rest-client'
require_relative './helpers'
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.raise_errors_for_deprecations!
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
# always run with ruby warnings enabled
# TODO: figure out why this is so obscenely noisy (rspec bug?)
# config.warnings = true
# add helpers
config.include Helpers, :include_helpers
config.mock_with :rspec do |mocks|
mocks.yield_receiver_to_any_instance_implementation_blocks = true
end
end
# always run with ruby warnings enabled (see above)
$VERBOSE = true
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/integration/_lib.rb | spec/integration/_lib.rb | require_relative '../spec_helper'
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/integration/request_spec.rb | spec/integration/request_spec.rb | require_relative '_lib'
describe RestClient::Request do
before(:all) do
WebMock.disable!
end
after(:all) do
WebMock.enable!
end
describe "ssl verification" do
it "is successful with the correct ca_file" do
request = RestClient::Request.new(
:method => :get,
:url => 'https://www.mozilla.org',
:ssl_ca_file => File.join(File.dirname(__FILE__), "certs", "digicert.crt")
)
expect { request.execute }.to_not raise_error
end
it "is successful with the correct ca_path" do
request = RestClient::Request.new(
:method => :get,
:url => 'https://www.mozilla.org',
:ssl_ca_path => File.join(File.dirname(__FILE__), "capath_digicert")
)
expect { request.execute }.to_not raise_error
end
# TODO: deprecate and remove RestClient::SSLCertificateNotVerified and just
# pass through OpenSSL::SSL::SSLError directly. See note in
# lib/restclient/request.rb.
#
# On OS X, this test fails since Apple has patched OpenSSL to always fall
# back on the system CA store.
it "is unsuccessful with an incorrect ca_file", :unless => RestClient::Platform.mac_mri? do
request = RestClient::Request.new(
:method => :get,
:url => 'https://www.mozilla.org',
:ssl_ca_file => File.join(File.dirname(__FILE__), "certs", "verisign.crt")
)
expect { request.execute }.to raise_error(RestClient::SSLCertificateNotVerified)
end
# On OS X, this test fails since Apple has patched OpenSSL to always fall
# back on the system CA store.
it "is unsuccessful with an incorrect ca_path", :unless => RestClient::Platform.mac_mri? do
request = RestClient::Request.new(
:method => :get,
:url => 'https://www.mozilla.org',
:ssl_ca_path => File.join(File.dirname(__FILE__), "capath_verisign")
)
expect { request.execute }.to raise_error(RestClient::SSLCertificateNotVerified)
end
it "is successful using the default system cert store" do
request = RestClient::Request.new(
:method => :get,
:url => 'https://www.mozilla.org',
:verify_ssl => true,
)
expect {request.execute }.to_not raise_error
end
it "executes the verify_callback" do
ran_callback = false
request = RestClient::Request.new(
:method => :get,
:url => 'https://www.mozilla.org',
:verify_ssl => true,
:ssl_verify_callback => lambda { |preverify_ok, store_ctx|
ran_callback = true
preverify_ok
},
)
expect {request.execute }.to_not raise_error
expect(ran_callback).to eq(true)
end
it "fails verification when the callback returns false",
:unless => RestClient::Platform.mac_mri? do
request = RestClient::Request.new(
:method => :get,
:url => 'https://www.mozilla.org',
:verify_ssl => true,
:ssl_verify_callback => lambda { |preverify_ok, store_ctx| false },
)
expect { request.execute }.to raise_error(RestClient::SSLCertificateNotVerified)
end
it "succeeds verification when the callback returns true",
:unless => RestClient::Platform.mac_mri? do
request = RestClient::Request.new(
:method => :get,
:url => 'https://www.mozilla.org',
:verify_ssl => true,
:ssl_ca_file => File.join(File.dirname(__FILE__), "certs", "verisign.crt"),
:ssl_verify_callback => lambda { |preverify_ok, store_ctx| true },
)
expect { request.execute }.to_not raise_error
end
end
describe "timeouts" do
it "raises OpenTimeout when it hits an open timeout" do
request = RestClient::Request.new(
:method => :get,
:url => 'http://www.mozilla.org',
:open_timeout => 1e-10,
)
expect { request.execute }.to(
raise_error(RestClient::Exceptions::OpenTimeout))
end
it "raises ReadTimeout when it hits a read timeout via :read_timeout" do
request = RestClient::Request.new(
:method => :get,
:url => 'https://www.mozilla.org',
:read_timeout => 1e-10,
)
expect { request.execute }.to(
raise_error(RestClient::Exceptions::ReadTimeout))
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/integration/integration_spec.rb | spec/integration/integration_spec.rb | # -*- coding: utf-8 -*-
require_relative '_lib'
require 'base64'
describe RestClient do
it "a simple request" do
body = 'abc'
stub_request(:get, "www.example.com").to_return(:body => body, :status => 200)
response = RestClient.get "www.example.com"
expect(response.code).to eq 200
expect(response.body).to eq body
end
it "a 404" do
body = "Ho hai ! I'm not here !"
stub_request(:get, "www.example.com").to_return(:body => body, :status => 404)
begin
RestClient.get "www.example.com"
raise
rescue RestClient::ResourceNotFound => e
expect(e.http_code).to eq 404
expect(e.response.code).to eq 404
expect(e.response.body).to eq body
expect(e.http_body).to eq body
end
end
describe 'charset parsing' do
it 'handles utf-8' do
body = "λ".force_encoding('ASCII-8BIT')
stub_request(:get, "www.example.com").to_return(
:body => body, :status => 200, :headers => {
'Content-Type' => 'text/plain; charset=UTF-8'
})
response = RestClient.get "www.example.com"
expect(response.encoding).to eq Encoding::UTF_8
expect(response.valid_encoding?).to eq true
end
it 'handles windows-1252' do
body = "\xff".force_encoding('ASCII-8BIT')
stub_request(:get, "www.example.com").to_return(
:body => body, :status => 200, :headers => {
'Content-Type' => 'text/plain; charset=windows-1252'
})
response = RestClient.get "www.example.com"
expect(response.encoding).to eq Encoding::WINDOWS_1252
expect(response.encode('utf-8')).to eq "ÿ"
expect(response.valid_encoding?).to eq true
end
it 'handles binary' do
body = "\xfe".force_encoding('ASCII-8BIT')
stub_request(:get, "www.example.com").to_return(
:body => body, :status => 200, :headers => {
'Content-Type' => 'application/octet-stream; charset=binary'
})
response = RestClient.get "www.example.com"
expect(response.encoding).to eq Encoding::BINARY
expect {
response.encode('utf-8')
}.to raise_error(Encoding::UndefinedConversionError)
expect(response.valid_encoding?).to eq true
end
it 'handles euc-jp' do
body = "\xA4\xA2\xA4\xA4\xA4\xA6\xA4\xA8\xA4\xAA".
force_encoding(Encoding::BINARY)
body_utf8 = 'あいうえお'
expect(body_utf8.encoding).to eq Encoding::UTF_8
stub_request(:get, 'www.example.com').to_return(
:body => body, :status => 200, :headers => {
'Content-Type' => 'text/plain; charset=EUC-JP'
})
response = RestClient.get 'www.example.com'
expect(response.encoding).to eq Encoding::EUC_JP
expect(response.valid_encoding?).to eq true
expect(response.length).to eq 5
expect(response.encode('utf-8')).to eq body_utf8
end
it 'defaults to the default encoding' do
stub_request(:get, 'www.example.com').to_return(
body: 'abc', status: 200, headers: {
'Content-Type' => 'text/plain'
})
response = RestClient.get 'www.example.com'
# expect(response.encoding).to eq Encoding.default_external
expect(response.encoding).to eq Encoding::UTF_8
end
it 'handles invalid encoding' do
stub_request(:get, 'www.example.com').to_return(
body: 'abc', status: 200, headers: {
'Content-Type' => 'text; charset=plain'
})
response = RestClient.get 'www.example.com'
# expect(response.encoding).to eq Encoding.default_external
expect(response.encoding).to eq Encoding::UTF_8
end
it 'leaves images as binary' do
gif = Base64.strict_decode64('R0lGODlhAQABAAAAADs=')
stub_request(:get, 'www.example.com').to_return(
body: gif, status: 200, headers: {
'Content-Type' => 'image/gif'
})
response = RestClient.get 'www.example.com'
expect(response.encoding).to eq Encoding::BINARY
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/integration/httpbin_spec.rb | spec/integration/httpbin_spec.rb | require_relative '_lib'
require 'json'
require 'zlib'
describe RestClient::Request do
before(:all) do
WebMock.disable!
end
after(:all) do
WebMock.enable!
end
def default_httpbin_url
# add a hack to work around java/jruby bug
# java.lang.RuntimeException: Could not generate DH keypair with backtrace
# Also (2017-04-09) Travis Jruby versions have a broken CA keystore
if ENV['TRAVIS_RUBY_VERSION'] =~ /\Ajruby-/
'http://httpbin.org/'
else
'https://httpbin.org/'
end
end
def httpbin(suffix='')
url = ENV.fetch('HTTPBIN_URL', default_httpbin_url)
unless url.end_with?('/')
url += '/'
end
url + suffix
end
def execute_httpbin(suffix, opts={})
opts = {url: httpbin(suffix)}.merge(opts)
RestClient::Request.execute(opts)
end
def execute_httpbin_json(suffix, opts={})
JSON.parse(execute_httpbin(suffix, opts))
end
describe '.execute' do
it 'sends a user agent' do
data = execute_httpbin_json('user-agent', method: :get)
expect(data['user-agent']).to match(/rest-client/)
end
it 'receives cookies on 302' do
expect {
execute_httpbin('cookies/set?foo=bar', method: :get, max_redirects: 0)
}.to raise_error(RestClient::Found) { |ex|
expect(ex.http_code).to eq 302
expect(ex.response.cookies['foo']).to eq 'bar'
}
end
it 'passes along cookies through 302' do
data = execute_httpbin_json('cookies/set?foo=bar', method: :get)
expect(data).to have_key('cookies')
expect(data['cookies']['foo']).to eq 'bar'
end
it 'handles quote wrapped cookies' do
expect {
execute_httpbin('cookies/set?foo=' + CGI.escape('"bar:baz"'),
method: :get, max_redirects: 0)
}.to raise_error(RestClient::Found) { |ex|
expect(ex.http_code).to eq 302
expect(ex.response.cookies['foo']).to eq '"bar:baz"'
}
end
it 'sends basic auth' do
user = 'user'
pass = 'pass'
data = execute_httpbin_json("basic-auth/#{user}/#{pass}", method: :get, user: user, password: pass)
expect(data).to eq({'authenticated' => true, 'user' => user})
expect {
execute_httpbin_json("basic-auth/#{user}/#{pass}", method: :get, user: user, password: 'badpass')
}.to raise_error(RestClient::Unauthorized) { |ex|
expect(ex.http_code).to eq 401
}
end
it 'handles gzipped/deflated responses' do
[['gzip', 'gzipped'], ['deflate', 'deflated']].each do |encoding, var|
raw = execute_httpbin(encoding, method: :get)
begin
data = JSON.parse(raw)
rescue StandardError
puts "Failed to parse: " + raw.inspect
raise
end
expect(data['method']).to eq 'GET'
expect(data.fetch(var)).to be true
end
end
it 'does not uncompress response when accept-encoding is set' do
# == gzip ==
raw = execute_httpbin('gzip', method: :get, headers: {accept_encoding: 'gzip, deflate'})
# check for gzip magic number
expect(raw.body).to start_with("\x1F\x8B".b)
decoded = Zlib::GzipReader.new(StringIO.new(raw.body)).read
parsed = JSON.parse(decoded)
expect(parsed['method']).to eq 'GET'
expect(parsed.fetch('gzipped')).to be true
# == delate ==
raw = execute_httpbin('deflate', method: :get, headers: {accept_encoding: 'gzip, deflate'})
decoded = Zlib::Inflate.new.inflate(raw.body)
parsed = JSON.parse(decoded)
expect(parsed['method']).to eq 'GET'
expect(parsed.fetch('deflated')).to be true
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/raw_response_spec.rb | spec/unit/raw_response_spec.rb | require_relative '_lib'
describe RestClient::RawResponse do
before do
@tf = double("Tempfile", :read => "the answer is 42", :open => true, :rewind => true)
@net_http_res = double('net http response')
@request = double('restclient request', :redirection_history => nil)
@response = RestClient::RawResponse.new(@tf, @net_http_res, @request)
end
it "behaves like string" do
expect(@response.to_s).to eq 'the answer is 42'
end
it "exposes a Tempfile" do
expect(@response.file).to eq @tf
end
it "includes AbstractResponse" do
expect(RestClient::RawResponse.ancestors).to include(RestClient::AbstractResponse)
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/response_spec.rb | spec/unit/response_spec.rb | require_relative '_lib'
describe RestClient::Response, :include_helpers do
before do
@net_http_res = res_double(to_hash: {'Status' => ['200 OK']}, code: '200', body: 'abc')
@example_url = 'http://example.com'
@request = request_double(url: @example_url, method: 'get')
@response = response_from_res_double(@net_http_res, @request, duration: 1)
end
it "behaves like string" do
expect(@response.to_s).to eq 'abc'
expect(@response.to_str).to eq 'abc'
expect(@response).to receive(:warn)
expect(@response.to_i).to eq 0
end
it "accepts nil strings and sets it to empty for the case of HEAD" do
# TODO
expect(RestClient::Response.create(nil, @net_http_res, @request).to_s).to eq ""
end
describe 'header processing' do
it "test headers and raw headers" do
expect(@response.raw_headers["Status"][0]).to eq "200 OK"
expect(@response.headers[:status]).to eq "200 OK"
end
it 'handles multiple headers by joining with comma' do
net_http_res = res_double(to_hash: {'My-Header' => ['foo', 'bar']}, code: '200', body: nil)
example_url = 'http://example.com'
request = request_double(url: example_url, method: 'get')
response = response_from_res_double(net_http_res, request)
expect(response.raw_headers['My-Header']).to eq ['foo', 'bar']
expect(response.headers[:my_header]).to eq 'foo, bar'
end
end
describe "cookie processing" do
it "should correctly deal with one Set-Cookie header with one cookie inside" do
header_val = "main_page=main_page_no_rewrite; path=/; expires=Sat, 10-Jan-2037 15:03:14 GMT".freeze
net_http_res = double('net http response', :to_hash => {"etag" => ["\"e1ac1a2df945942ef4cac8116366baad\""], "set-cookie" => [header_val]})
response = RestClient::Response.create('abc', net_http_res, @request)
expect(response.headers[:set_cookie]).to eq [header_val]
expect(response.cookies).to eq({ "main_page" => "main_page_no_rewrite" })
end
it "should correctly deal with multiple cookies [multiple Set-Cookie headers]" do
net_http_res = double('net http response', :to_hash => {"etag" => ["\"e1ac1a2df945942ef4cac8116366baad\""], "set-cookie" => ["main_page=main_page_no_rewrite; path=/; expires=Sat, 10-Jan-2037 15:03:14 GMT", "remember_me=; path=/; expires=Sat, 10-Jan-2037 00:00:00 GMT", "user=somebody; path=/; expires=Sat, 10-Jan-2037 00:00:00 GMT"]})
response = RestClient::Response.create('abc', net_http_res, @request)
expect(response.headers[:set_cookie]).to eq ["main_page=main_page_no_rewrite; path=/; expires=Sat, 10-Jan-2037 15:03:14 GMT", "remember_me=; path=/; expires=Sat, 10-Jan-2037 00:00:00 GMT", "user=somebody; path=/; expires=Sat, 10-Jan-2037 00:00:00 GMT"]
expect(response.cookies).to eq({
"main_page" => "main_page_no_rewrite",
"remember_me" => "",
"user" => "somebody"
})
end
it "should correctly deal with multiple cookies [one Set-Cookie header with multiple cookies]" do
net_http_res = double('net http response', :to_hash => {"etag" => ["\"e1ac1a2df945942ef4cac8116366baad\""], "set-cookie" => ["main_page=main_page_no_rewrite; path=/; expires=Sat, 10-Jan-2037 15:03:14 GMT, remember_me=; path=/; expires=Sat, 10-Jan-2037 00:00:00 GMT, user=somebody; path=/; expires=Sat, 10-Jan-2037 00:00:00 GMT"]})
response = RestClient::Response.create('abc', net_http_res, @request)
expect(response.cookies).to eq({
"main_page" => "main_page_no_rewrite",
"remember_me" => "",
"user" => "somebody"
})
end
end
describe "exceptions processing" do
it "should return itself for normal codes" do
(200..206).each do |code|
net_http_res = res_double(:code => '200')
resp = RestClient::Response.create('abc', net_http_res, @request)
resp.return!
end
end
it "should throw an exception for other codes" do
RestClient::Exceptions::EXCEPTIONS_MAP.each_pair do |code, exc|
unless (200..207).include? code
net_http_res = res_double(:code => code.to_i)
resp = RestClient::Response.create('abc', net_http_res, @request)
allow(@request).to receive(:max_redirects).and_return(5)
expect { resp.return! }.to raise_error(exc)
end
end
end
end
describe "redirection" do
it "follows a redirection when the request is a get" do
stub_request(:get, 'http://some/resource').to_return(:body => '', :status => 301, :headers => {'Location' => 'http://new/resource'})
stub_request(:get, 'http://new/resource').to_return(:body => 'Foo')
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :get).body).to eq 'Foo'
end
it "keeps redirection history" do
stub_request(:get, 'http://some/resource').to_return(:body => '', :status => 301, :headers => {'Location' => 'http://new/resource'})
stub_request(:get, 'http://new/resource').to_return(:body => 'Foo')
r = RestClient::Request.execute(url: 'http://some/resource', method: :get)
expect(r.body).to eq 'Foo'
expect(r.history.length).to eq 1
expect(r.history.fetch(0)).to be_a(RestClient::Response)
expect(r.history.fetch(0).code).to be 301
end
it "follows a redirection and keep the parameters" do
stub_request(:get, 'http://some/resource').with(:headers => {'Accept' => 'application/json'}, :basic_auth => ['foo', 'bar']).to_return(:body => '', :status => 301, :headers => {'Location' => 'http://new/resource'})
stub_request(:get, 'http://new/resource').with(:headers => {'Accept' => 'application/json'}, :basic_auth => ['foo', 'bar']).to_return(:body => 'Foo')
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :get, :user => 'foo', :password => 'bar', :headers => {:accept => :json}).body).to eq 'Foo'
end
it "follows a redirection and keep the cookies" do
stub_request(:get, 'http://some/resource').to_return(:body => '', :status => 301, :headers => {'Set-Cookie' => 'Foo=Bar', 'Location' => 'http://some/new_resource', })
stub_request(:get, 'http://some/new_resource').with(:headers => {'Cookie' => 'Foo=Bar'}).to_return(:body => 'Qux')
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :get).body).to eq 'Qux'
end
it 'respects cookie domains on redirect' do
stub_request(:get, 'http://some.example.com/').to_return(:body => '', :status => 301,
:headers => {'Set-Cookie' => 'Foo=Bar', 'Location' => 'http://new.example.com/', })
stub_request(:get, 'http://new.example.com/').with(
:headers => {'Cookie' => 'passedthrough=1'}).to_return(:body => 'Qux')
expect(RestClient::Request.execute(:url => 'http://some.example.com/', :method => :get, cookies: [HTTP::Cookie.new('passedthrough', '1', domain: 'new.example.com', path: '/')]).body).to eq 'Qux'
end
it "doesn't follow a 301 when the request is a post" do
net_http_res = res_double(:code => 301)
response = response_from_res_double(net_http_res, request_double(method: 'post'))
expect {
response.return!
}.to raise_error(RestClient::MovedPermanently)
end
it "doesn't follow a 302 when the request is a post" do
net_http_res = res_double(:code => 302)
response = response_from_res_double(net_http_res, request_double(method: 'post'))
expect {
response.return!
}.to raise_error(RestClient::Found)
end
it "doesn't follow a 307 when the request is a post" do
net_http_res = res_double(:code => 307)
response = response_from_res_double(net_http_res, request_double(method: 'post'))
expect(response).not_to receive(:follow_redirection)
expect {
response.return!
}.to raise_error(RestClient::TemporaryRedirect)
end
it "doesn't follow a redirection when the request is a put" do
net_http_res = res_double(:code => 301)
response = response_from_res_double(net_http_res, request_double(method: 'put'))
expect {
response.return!
}.to raise_error(RestClient::MovedPermanently)
end
it "follows a redirection when the request is a post and result is a 303" do
stub_request(:put, 'http://some/resource').to_return(:body => '', :status => 303, :headers => {'Location' => 'http://new/resource'})
stub_request(:get, 'http://new/resource').to_return(:body => 'Foo')
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :put).body).to eq 'Foo'
end
it "follows a redirection when the request is a head" do
stub_request(:head, 'http://some/resource').to_return(:body => '', :status => 301, :headers => {'Location' => 'http://new/resource'})
stub_request(:head, 'http://new/resource').to_return(:body => 'Foo')
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :head).body).to eq 'Foo'
end
it "handles redirects with relative paths" do
stub_request(:get, 'http://some/resource').to_return(:body => '', :status => 301, :headers => {'Location' => 'index'})
stub_request(:get, 'http://some/index').to_return(:body => 'Foo')
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :get).body).to eq 'Foo'
end
it "handles redirects with relative path and query string" do
stub_request(:get, 'http://some/resource').to_return(:body => '', :status => 301, :headers => {'Location' => 'index?q=1'})
stub_request(:get, 'http://some/index?q=1').to_return(:body => 'Foo')
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :get).body).to eq 'Foo'
end
it "follow a redirection when the request is a get and the response is in the 30x range" do
stub_request(:get, 'http://some/resource').to_return(:body => '', :status => 301, :headers => {'Location' => 'http://new/resource'})
stub_request(:get, 'http://new/resource').to_return(:body => 'Foo')
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :get).body).to eq 'Foo'
end
it "follows no more than 10 redirections before raising error" do
stub_request(:get, 'http://some/redirect-1').to_return(:body => '', :status => 301, :headers => {'Location' => 'http://some/redirect-2'})
stub_request(:get, 'http://some/redirect-2').to_return(:body => '', :status => 301, :headers => {'Location' => 'http://some/redirect-2'})
expect {
RestClient::Request.execute(url: 'http://some/redirect-1', method: :get)
}.to raise_error(RestClient::MovedPermanently) { |ex|
ex.response.history.each {|r| expect(r).to be_a(RestClient::Response) }
expect(ex.response.history.length).to eq 10
}
expect(WebMock).to have_requested(:get, 'http://some/redirect-2').times(10)
end
it "follows no more than max_redirects redirections, if specified" do
stub_request(:get, 'http://some/redirect-1').to_return(:body => '', :status => 301, :headers => {'Location' => 'http://some/redirect-2'})
stub_request(:get, 'http://some/redirect-2').to_return(:body => '', :status => 301, :headers => {'Location' => 'http://some/redirect-2'})
expect {
RestClient::Request.execute(url: 'http://some/redirect-1', method: :get, max_redirects: 5)
}.to raise_error(RestClient::MovedPermanently) { |ex|
expect(ex.response.history.length).to eq 5
}
expect(WebMock).to have_requested(:get, 'http://some/redirect-2').times(5)
end
it "allows for manual following of redirects" do
stub_request(:get, 'http://some/redirect-1').to_return(:body => '', :status => 301, :headers => {'Location' => 'http://some/resource'})
stub_request(:get, 'http://some/resource').to_return(:body => 'Qux', :status => 200)
begin
RestClient::Request.execute(url: 'http://some/redirect-1', method: :get, max_redirects: 0)
rescue RestClient::MovedPermanently => err
resp = err.response.follow_redirection
else
raise 'notreached'
end
expect(resp.code).to eq 200
expect(resp.body).to eq 'Qux'
end
end
describe "logging" do
it "uses the request's logger" do
stub_request(:get, 'http://some/resource').to_return(body: 'potato', status: 200)
logger = double('logger', '<<' => true)
request = RestClient::Request.new(url: 'http://some/resource', method: :get, log: logger)
expect(logger).to receive(:<<)
request.execute
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/_lib.rb | spec/unit/_lib.rb | require_relative '../spec_helper'
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/request_spec.rb | spec/unit/request_spec.rb | require_relative './_lib'
describe RestClient::Request, :include_helpers do
before do
@request = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload')
@uri = double("uri")
allow(@uri).to receive(:request_uri).and_return('/resource')
allow(@uri).to receive(:hostname).and_return('some')
allow(@uri).to receive(:port).and_return(80)
@net = double("net::http base")
@http = double("net::http connection")
allow(Net::HTTP).to receive(:new).and_return(@net)
allow(@net).to receive(:start).and_yield(@http)
allow(@net).to receive(:use_ssl=)
allow(@net).to receive(:verify_mode=)
allow(@net).to receive(:verify_callback=)
allow(@net).to receive(:ciphers=)
allow(@net).to receive(:cert_store=)
RestClient.log = nil
end
it "accept */* mimetype" do
expect(@request.default_headers[:accept]).to eq '*/*'
end
it "processes a successful result" do
res = res_double
allow(res).to receive(:code).and_return("200")
allow(res).to receive(:body).and_return('body')
allow(res).to receive(:[]).with('content-encoding').and_return(nil)
expect(@request.send(:process_result, res, Time.now).body).to eq 'body'
expect(@request.send(:process_result, res, Time.now).to_s).to eq 'body'
end
it "doesn't classify successful requests as failed" do
203.upto(207) do |code|
res = res_double
allow(res).to receive(:code).and_return(code.to_s)
allow(res).to receive(:body).and_return("")
allow(res).to receive(:[]).with('content-encoding').and_return(nil)
expect(@request.send(:process_result, res, Time.now)).to be_empty
end
end
describe '.normalize_url' do
it "adds http:// to the front of resources specified in the syntax example.com/resource" do
expect(@request.normalize_url('example.com/resource')).to eq 'http://example.com/resource'
end
it 'adds http:// to resources containing a colon' do
expect(@request.normalize_url('example.com:1234')).to eq 'http://example.com:1234'
end
it 'does not add http:// to the front of https resources' do
expect(@request.normalize_url('https://example.com/resource')).to eq 'https://example.com/resource'
end
it 'does not add http:// to the front of capital HTTP resources' do
expect(@request.normalize_url('HTTP://example.com/resource')).to eq 'HTTP://example.com/resource'
end
it 'does not add http:// to the front of capital HTTPS resources' do
expect(@request.normalize_url('HTTPS://example.com/resource')).to eq 'HTTPS://example.com/resource'
end
it 'raises with invalid URI' do
expect {
RestClient::Request.new(method: :get, url: 'http://a@b:c')
}.to raise_error(URI::InvalidURIError)
expect {
RestClient::Request.new(method: :get, url: 'http://::')
}.to raise_error(URI::InvalidURIError)
end
end
describe "user - password" do
it "extracts the username and password when parsing http://user:password@example.com/" do
@request.send(:parse_url_with_auth!, 'http://joe:pass1@example.com/resource')
expect(@request.user).to eq 'joe'
expect(@request.password).to eq 'pass1'
end
it "extracts with escaping the username and password when parsing http://user:password@example.com/" do
@request.send(:parse_url_with_auth!, 'http://joe%20:pass1@example.com/resource')
expect(@request.user).to eq 'joe '
expect(@request.password).to eq 'pass1'
end
it "doesn't overwrite user and password (which may have already been set by the Resource constructor) if there is no user/password in the url" do
request = RestClient::Request.new(method: :get, url: 'http://example.com/resource', user: 'beth', password: 'pass2')
expect(request.user).to eq 'beth'
expect(request.password).to eq 'pass2'
end
it 'uses the username and password from the URL' do
request = RestClient::Request.new(method: :get, url: 'http://person:secret@example.com/resource')
expect(request.user).to eq 'person'
expect(request.password).to eq 'secret'
end
it 'overrides URL user/pass with explicit options' do
request = RestClient::Request.new(method: :get, url: 'http://person:secret@example.com/resource', user: 'beth', password: 'pass2')
expect(request.user).to eq 'beth'
expect(request.password).to eq 'pass2'
end
end
it "correctly formats cookies provided to the constructor" do
cookies_arr = [
HTTP::Cookie.new('session_id', '1', domain: 'example.com', path: '/'),
HTTP::Cookie.new('user_id', 'someone', domain: 'example.com', path: '/'),
]
jar = HTTP::CookieJar.new
cookies_arr.each {|c| jar << c }
# test Hash, HTTP::CookieJar, and Array<HTTP::Cookie> modes
[
{session_id: '1', user_id: 'someone'},
jar,
cookies_arr
].each do |cookies|
[true, false].each do |in_headers|
if in_headers
opts = {headers: {cookies: cookies}}
else
opts = {cookies: cookies}
end
request = RestClient::Request.new(method: :get, url: 'example.com', **opts)
expect(request).to receive(:default_headers).and_return({'Foo' => 'bar'})
expect(request.make_headers({})).to eq({'Foo' => 'bar', 'Cookie' => 'session_id=1; user_id=someone'})
expect(request.make_cookie_header).to eq 'session_id=1; user_id=someone'
expect(request.cookies).to eq({'session_id' => '1', 'user_id' => 'someone'})
expect(request.cookie_jar.cookies.length).to eq 2
expect(request.cookie_jar.object_id).not_to eq jar.object_id # make sure we dup it
end
end
# test with no cookies
request = RestClient::Request.new(method: :get, url: 'example.com')
expect(request).to receive(:default_headers).and_return({'Foo' => 'bar'})
expect(request.make_headers({})).to eq({'Foo' => 'bar'})
expect(request.make_cookie_header).to be_nil
expect(request.cookies).to eq({})
expect(request.cookie_jar.cookies.length).to eq 0
end
it 'strips out cookies set for a different domain name' do
jar = HTTP::CookieJar.new
jar << HTTP::Cookie.new('session_id', '1', domain: 'other.example.com', path: '/')
jar << HTTP::Cookie.new('user_id', 'someone', domain: 'other.example.com', path: '/')
request = RestClient::Request.new(method: :get, url: 'www.example.com', cookies: jar)
expect(request).to receive(:default_headers).and_return({'Foo' => 'bar'})
expect(request.make_headers({})).to eq({'Foo' => 'bar'})
expect(request.make_cookie_header).to eq nil
expect(request.cookies).to eq({})
expect(request.cookie_jar.cookies.length).to eq 2
end
it 'assumes default domain and path for cookies set by hash' do
request = RestClient::Request.new(method: :get, url: 'www.example.com', cookies: {'session_id' => '1'})
expect(request.cookie_jar.cookies.length).to eq 1
cookie = request.cookie_jar.cookies.first
expect(cookie).to be_a(HTTP::Cookie)
expect(cookie.domain).to eq('www.example.com')
expect(cookie.for_domain?).to be_truthy
expect(cookie.path).to eq('/')
end
it 'rejects or warns with contradictory cookie options' do
# same opt in two different places
expect {
RestClient::Request.new(method: :get, url: 'example.com',
cookies: {bar: '456'},
headers: {cookies: {foo: '123'}})
}.to raise_error(ArgumentError, /Cannot pass :cookies in Request.*headers/)
# :cookies opt and Cookie header
[
{cookies: {foo: '123'}, headers: {cookie: 'foo'}},
{cookies: {foo: '123'}, headers: {'Cookie' => 'foo'}},
{headers: {cookies: {foo: '123'}, cookie: 'foo'}},
{headers: {cookies: {foo: '123'}, 'Cookie' => 'foo'}},
].each do |opts|
expect(fake_stderr {
RestClient::Request.new(method: :get, url: 'example.com', **opts)
}).to match(/warning: overriding "Cookie" header with :cookies option/)
end
end
it "does not escape or unescape cookies" do
cookie = 'Foo%20:Bar%0A~'
@request = RestClient::Request.new(:method => 'get', :url => 'example.com',
:cookies => {:test => cookie})
expect(@request).to receive(:default_headers).and_return({'Foo' => 'bar'})
expect(@request.make_headers({})).to eq({
'Foo' => 'bar',
'Cookie' => "test=#{cookie}"
})
end
it "rejects cookie names containing invalid characters" do
# Cookie validity is something of a mess, but we should reject the worst of
# the RFC 6265 (4.1.1) prohibited characters such as control characters.
['foo=bar', 'foo;bar', "foo\nbar"].each do |cookie_name|
expect {
RestClient::Request.new(:method => 'get', :url => 'example.com',
:cookies => {cookie_name => 'value'})
}.to raise_error(ArgumentError, /\AInvalid cookie name/i)
end
cookie_name = ''
expect {
RestClient::Request.new(:method => 'get', :url => 'example.com',
:cookies => {cookie_name => 'value'})
}.to raise_error(ArgumentError, /cookie name cannot be empty/i)
end
it "rejects cookie values containing invalid characters" do
# Cookie validity is something of a mess, but we should reject the worst of
# the RFC 6265 (4.1.1) prohibited characters such as control characters.
["foo\tbar", "foo\nbar"].each do |cookie_value|
expect {
RestClient::Request.new(:method => 'get', :url => 'example.com',
:cookies => {'test' => cookie_value})
}.to raise_error(ArgumentError, /\AInvalid cookie value/i)
end
end
it 'warns when overriding existing headers via payload' do
expect(fake_stderr {
RestClient::Request.new(method: :post, url: 'example.com',
payload: {'foo' => 1}, headers: {content_type: :json})
}).to match(/warning: Overriding "Content-Type" header/i)
expect(fake_stderr {
RestClient::Request.new(method: :post, url: 'example.com',
payload: {'foo' => 1}, headers: {'Content-Type' => 'application/json'})
}).to match(/warning: Overriding "Content-Type" header/i)
expect(fake_stderr {
RestClient::Request.new(method: :post, url: 'example.com',
payload: '123456', headers: {content_length: '20'})
}).to match(/warning: Overriding "Content-Length" header/i)
expect(fake_stderr {
RestClient::Request.new(method: :post, url: 'example.com',
payload: '123456', headers: {'Content-Length' => '20'})
}).to match(/warning: Overriding "Content-Length" header/i)
end
it "does not warn when overriding user header with header derived from payload if those header values were identical" do
expect(fake_stderr {
RestClient::Request.new(method: :post, url: 'example.com',
payload: {'foo' => '123456'}, headers: { 'Content-Type' => 'application/x-www-form-urlencoded' })
}).not_to match(/warning: Overriding "Content-Type" header/i)
end
it 'does not warn for a normal looking payload' do
expect(fake_stderr {
RestClient::Request.new(method: :post, url: 'example.com', payload: 'payload')
RestClient::Request.new(method: :post, url: 'example.com', payload: 'payload', headers: {content_type: :json})
RestClient::Request.new(method: :post, url: 'example.com', payload: {'foo' => 'bar'})
}).to eq ''
end
it "uses netrc credentials" do
expect(Netrc).to receive(:read).and_return('example.com' => ['a', 'b'])
request = RestClient::Request.new(:method => :put, :url => 'http://example.com/', :payload => 'payload')
expect(request.user).to eq 'a'
expect(request.password).to eq 'b'
end
it "uses credentials in the url in preference to netrc" do
allow(Netrc).to receive(:read).and_return('example.com' => ['a', 'b'])
request = RestClient::Request.new(:method => :put, :url => 'http://joe%20:pass1@example.com/', :payload => 'payload')
expect(request.user).to eq 'joe '
expect(request.password).to eq 'pass1'
end
it "determines the Net::HTTP class to instantiate by the method name" do
expect(@request.net_http_request_class(:put)).to eq Net::HTTP::Put
end
describe "user headers" do
it "merges user headers with the default headers" do
expect(@request).to receive(:default_headers).and_return({:accept => '*/*'})
headers = @request.make_headers("Accept" => "application/json", :accept_encoding => 'gzip')
expect(headers).to have_key "Accept-Encoding"
expect(headers["Accept-Encoding"]).to eq "gzip"
expect(headers).to have_key "Accept"
expect(headers["Accept"]).to eq "application/json"
end
it "prefers the user header when the same header exists in the defaults" do
expect(@request).to receive(:default_headers).and_return({ '1' => '2' })
headers = @request.make_headers('1' => '3')
expect(headers).to have_key('1')
expect(headers['1']).to eq '3'
end
it "converts user headers to string before calling CGI::unescape which fails on non string values" do
expect(@request).to receive(:default_headers).and_return({ '1' => '2' })
headers = @request.make_headers('1' => 3)
expect(headers).to have_key('1')
expect(headers['1']).to eq '3'
end
end
describe "header symbols" do
it "converts header symbols from :content_type to 'Content-Type'" do
expect(@request).to receive(:default_headers).and_return({})
headers = @request.make_headers(:content_type => 'abc')
expect(headers).to have_key('Content-Type')
expect(headers['Content-Type']).to eq 'abc'
end
it "converts content-type from extension to real content-type" do
expect(@request).to receive(:default_headers).and_return({})
headers = @request.make_headers(:content_type => 'json')
expect(headers).to have_key('Content-Type')
expect(headers['Content-Type']).to eq 'application/json'
end
it "converts accept from extension(s) to real content-type(s)" do
expect(@request).to receive(:default_headers).and_return({})
headers = @request.make_headers(:accept => 'json, mp3')
expect(headers).to have_key('Accept')
expect(headers['Accept']).to eq 'application/json, audio/mpeg'
expect(@request).to receive(:default_headers).and_return({})
headers = @request.make_headers(:accept => :json)
expect(headers).to have_key('Accept')
expect(headers['Accept']).to eq 'application/json'
end
it "only convert symbols in header" do
expect(@request).to receive(:default_headers).and_return({})
headers = @request.make_headers({:foo_bar => 'value', "bar_bar" => 'value'})
expect(headers['Foo-Bar']).to eq 'value'
expect(headers['bar_bar']).to eq 'value'
end
it "converts header values to strings" do
expect(@request.make_headers('A' => 1)['A']).to eq '1'
end
end
it "executes by constructing the Net::HTTP object, headers, and payload and calling transmit" do
klass = double("net:http class")
expect(@request).to receive(:net_http_request_class).with('put').and_return(klass)
expect(klass).to receive(:new).and_return('result')
expect(@request).to receive(:transmit).with(@request.uri, 'result', kind_of(RestClient::Payload::Base))
@request.execute
end
it "IPv6: executes by constructing the Net::HTTP object, headers, and payload and calling transmit" do
@request = RestClient::Request.new(:method => :put, :url => 'http://[::1]/some/resource', :payload => 'payload')
klass = double("net:http class")
expect(@request).to receive(:net_http_request_class).with('put').and_return(klass)
if RUBY_VERSION >= "2.0.0"
expect(klass).to receive(:new).with(kind_of(URI), kind_of(Hash)).and_return('result')
else
expect(klass).to receive(:new).with(kind_of(String), kind_of(Hash)).and_return('result')
end
expect(@request).to receive(:transmit)
@request.execute
end
# TODO: almost none of these tests should actually call transmit, which is
# part of the private API
it "transmits the request with Net::HTTP" do
expect(@http).to receive(:request).with('req', 'payload')
expect(@request).to receive(:process_result)
@request.send(:transmit, @uri, 'req', 'payload')
end
# TODO: most of these payload tests are historical relics that actually
# belong in payload_spec.rb. Or we need new tests that actually cover the way
# that Request#initialize or Request#execute uses the payload.
describe "payload" do
it "sends nil payloads" do
expect(@http).to receive(:request).with('req', nil)
expect(@request).to receive(:process_result)
allow(@request).to receive(:response_log)
@request.send(:transmit, @uri, 'req', nil)
end
it "passes non-hash payloads straight through" do
expect(RestClient::Payload.generate("x").to_s).to eq "x"
end
it "converts a hash payload to urlencoded data" do
expect(RestClient::Payload.generate(:a => 'b c+d').to_s).to eq "a=b+c%2Bd"
end
it "accepts nested hashes in payload" do
payload = RestClient::Payload.generate(:user => { :name => 'joe', :location => { :country => 'USA', :state => 'CA' }}).to_s
expect(payload).to include('user[name]=joe')
expect(payload).to include('user[location][country]=USA')
expect(payload).to include('user[location][state]=CA')
end
end
it "set urlencoded content_type header on hash payloads" do
req = RestClient::Request.new(method: :post, url: 'http://some/resource', payload: {a: 1})
expect(req.processed_headers.fetch('Content-Type')).to eq 'application/x-www-form-urlencoded'
end
describe "credentials" do
it "sets up the credentials prior to the request" do
allow(@http).to receive(:request)
allow(@request).to receive(:process_result)
allow(@request).to receive(:response_log)
allow(@request).to receive(:user).and_return('joe')
allow(@request).to receive(:password).and_return('mypass')
expect(@request).to receive(:setup_credentials).with('req')
@request.send(:transmit, @uri, 'req', nil)
end
it "does not attempt to send any credentials if user is nil" do
allow(@request).to receive(:user).and_return(nil)
req = double("request")
expect(req).not_to receive(:basic_auth)
@request.send(:setup_credentials, req)
end
it "setup credentials when there's a user" do
allow(@request).to receive(:user).and_return('joe')
allow(@request).to receive(:password).and_return('mypass')
req = double("request")
expect(req).to receive(:basic_auth).with('joe', 'mypass')
@request.send(:setup_credentials, req)
end
it "does not attempt to send credentials if Authorization header is set" do
['Authorization', 'authorization', 'auTHORization', :authorization].each do |authorization|
headers = {authorization => 'Token abc123'}
request = RestClient::Request.new(method: :get, url: 'http://some/resource', headers: headers, user: 'joe', password: 'mypass')
req = double("net::http request")
expect(req).not_to receive(:basic_auth)
request.send(:setup_credentials, req)
end
end
end
it "catches EOFError and shows the more informative ServerBrokeConnection" do
allow(@http).to receive(:request).and_raise(EOFError)
expect { @request.send(:transmit, @uri, 'req', nil) }.to raise_error(RestClient::ServerBrokeConnection)
end
it "catches OpenSSL::SSL::SSLError and raise it back without more informative message" do
allow(@http).to receive(:request).and_raise(OpenSSL::SSL::SSLError)
expect { @request.send(:transmit, @uri, 'req', nil) }.to raise_error(OpenSSL::SSL::SSLError)
end
it "catches Timeout::Error and raise the more informative ReadTimeout" do
allow(@http).to receive(:request).and_raise(Timeout::Error)
expect { @request.send(:transmit, @uri, 'req', nil) }.to raise_error(RestClient::Exceptions::ReadTimeout)
end
it "catches Errno::ETIMEDOUT and raise the more informative ReadTimeout" do
allow(@http).to receive(:request).and_raise(Errno::ETIMEDOUT)
expect { @request.send(:transmit, @uri, 'req', nil) }.to raise_error(RestClient::Exceptions::ReadTimeout)
end
it "catches Net::ReadTimeout and raises RestClient's ReadTimeout",
:if => defined?(Net::ReadTimeout) do
allow(@http).to receive(:request).and_raise(Net::ReadTimeout)
expect { @request.send(:transmit, @uri, 'req', nil) }.to raise_error(RestClient::Exceptions::ReadTimeout)
end
it "catches Net::OpenTimeout and raises RestClient's OpenTimeout",
:if => defined?(Net::OpenTimeout) do
allow(@http).to receive(:request).and_raise(Net::OpenTimeout)
expect { @request.send(:transmit, @uri, 'req', nil) }.to raise_error(RestClient::Exceptions::OpenTimeout)
end
it "uses correct error message for ReadTimeout",
:if => defined?(Net::ReadTimeout) do
allow(@http).to receive(:request).and_raise(Net::ReadTimeout)
expect { @request.send(:transmit, @uri, 'req', nil) }.to raise_error(RestClient::Exceptions::ReadTimeout, 'Timed out reading data from server')
end
it "uses correct error message for OpenTimeout",
:if => defined?(Net::OpenTimeout) do
allow(@http).to receive(:request).and_raise(Net::OpenTimeout)
expect { @request.send(:transmit, @uri, 'req', nil) }.to raise_error(RestClient::Exceptions::OpenTimeout, 'Timed out connecting to server')
end
it "class method execute wraps constructor" do
req = double("rest request")
expect(RestClient::Request).to receive(:new).with(1 => 2).and_return(req)
expect(req).to receive(:execute)
RestClient::Request.execute(1 => 2)
end
describe "exception" do
it "raises Unauthorized when the response is 401" do
res = res_double(:code => '401', :[] => ['content-encoding' => ''], :body => '' )
expect { @request.send(:process_result, res, Time.now) }.to raise_error(RestClient::Unauthorized)
end
it "raises ResourceNotFound when the response is 404" do
res = res_double(:code => '404', :[] => ['content-encoding' => ''], :body => '' )
expect { @request.send(:process_result, res, Time.now) }.to raise_error(RestClient::ResourceNotFound)
end
it "raises RequestFailed otherwise" do
res = res_double(:code => '500', :[] => ['content-encoding' => ''], :body => '' )
expect { @request.send(:process_result, res, Time.now) }.to raise_error(RestClient::InternalServerError)
end
end
describe "block usage" do
it "returns what asked to" do
res = res_double(:code => '401', :[] => ['content-encoding' => ''], :body => '' )
expect(@request.send(:process_result, res, Time.now){|response, request| "foo"}).to eq "foo"
end
end
describe "proxy" do
before do
# unstub Net::HTTP creation since we need to test it
allow(Net::HTTP).to receive(:new).and_call_original
@proxy_req = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload')
end
it "creates a proxy class if a proxy url is given" do
allow(RestClient).to receive(:proxy).and_return("http://example.com/")
allow(RestClient).to receive(:proxy_set?).and_return(true)
expect(@proxy_req.net_http_object('host', 80).proxy?).to be true
end
it "creates a proxy class with the correct address if a IPv6 proxy url is given" do
allow(RestClient).to receive(:proxy).and_return("http://[::1]/")
allow(RestClient).to receive(:proxy_set?).and_return(true)
expect(@proxy_req.net_http_object('host', 80).proxy?).to be true
expect(@proxy_req.net_http_object('host', 80).proxy_address).to eq('::1')
end
it "creates a non-proxy class if a proxy url is not given" do
expect(@proxy_req.net_http_object('host', 80).proxy?).to be_falsey
end
it "disables proxy on a per-request basis" do
allow(RestClient).to receive(:proxy).and_return('http://example.com')
allow(RestClient).to receive(:proxy_set?).and_return(true)
expect(@proxy_req.net_http_object('host', 80).proxy?).to be true
disabled_req = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload', :proxy => nil)
expect(disabled_req.net_http_object('host', 80).proxy?).to be_falsey
end
it "sets proxy on a per-request basis" do
expect(@proxy_req.net_http_object('some', 80).proxy?).to be_falsey
req = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload', :proxy => 'http://example.com')
expect(req.net_http_object('host', 80).proxy?).to be true
end
it "overrides proxy from environment", if: RUBY_VERSION >= '2.0' do
allow(ENV).to receive(:[]).with("http_proxy").and_return("http://127.0.0.1")
allow(ENV).to receive(:[]).with("no_proxy").and_return(nil)
allow(ENV).to receive(:[]).with("NO_PROXY").and_return(nil)
allow(Netrc).to receive(:read).and_return({})
req = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload')
obj = req.net_http_object('host', 80)
expect(obj.proxy?).to be true
expect(obj.proxy_address).to eq '127.0.0.1'
# test original method .proxy?
req = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload', :proxy => nil)
obj = req.net_http_object('host', 80)
expect(obj.proxy?).to be_falsey
# stub RestClient.proxy_set? to peek into implementation
allow(RestClient).to receive(:proxy_set?).and_return(true)
req = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload')
obj = req.net_http_object('host', 80)
expect(obj.proxy?).to be_falsey
# test stubbed Net::HTTP.new
req = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload', :proxy => nil)
expect(Net::HTTP).to receive(:new).with('host', 80, nil, nil, nil, nil)
req.net_http_object('host', 80)
end
it "overrides global proxy with per-request proxy" do
allow(RestClient).to receive(:proxy).and_return('http://example.com')
allow(RestClient).to receive(:proxy_set?).and_return(true)
obj = @proxy_req.net_http_object('host', 80)
expect(obj.proxy?).to be true
expect(obj.proxy_address).to eq 'example.com'
req = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload', :proxy => 'http://127.0.0.1/')
expect(req.net_http_object('host', 80).proxy?).to be true
expect(req.net_http_object('host', 80).proxy_address).to eq('127.0.0.1')
end
end
describe "logging" do
it "logs a get request" do
log = RestClient.log = []
RestClient::Request.new(:method => :get, :url => 'http://url', :headers => {:user_agent => 'rest-client'}).log_request
expect(log[0]).to eq %Q{RestClient.get "http://url", "Accept"=>"*/*", "User-Agent"=>"rest-client"\n}
end
it "logs a post request with a small payload" do
log = RestClient.log = []
RestClient::Request.new(:method => :post, :url => 'http://url', :payload => 'foo', :headers => {:user_agent => 'rest-client'}).log_request
expect(log[0]).to eq %Q{RestClient.post "http://url", "foo", "Accept"=>"*/*", "Content-Length"=>"3", "User-Agent"=>"rest-client"\n}
end
it "logs a post request with a large payload" do
log = RestClient.log = []
RestClient::Request.new(:method => :post, :url => 'http://url', :payload => ('x' * 1000), :headers => {:user_agent => 'rest-client'}).log_request
expect(log[0]).to eq %Q{RestClient.post "http://url", 1000 byte(s) length, "Accept"=>"*/*", "Content-Length"=>"1000", "User-Agent"=>"rest-client"\n}
end
it "logs input headers as a hash" do
log = RestClient.log = []
RestClient::Request.new(:method => :get, :url => 'http://url', :headers => { :accept => 'text/plain', :user_agent => 'rest-client' }).log_request
expect(log[0]).to eq %Q{RestClient.get "http://url", "Accept"=>"text/plain", "User-Agent"=>"rest-client"\n}
end
it "logs a response including the status code, content type, and result body size in bytes" do
log = RestClient.log = []
res = res_double(code: '200', class: Net::HTTPOK, body: 'abcd')
allow(res).to receive(:[]).with('Content-type').and_return('text/html')
response = response_from_res_double(res, @request)
response.log_response
expect(log).to eq ["# => 200 OK | text/html 4 bytes, 1.00s\n"]
end
it "logs a response with a nil Content-type" do
log = RestClient.log = []
res = res_double(code: '200', class: Net::HTTPOK, body: 'abcd')
allow(res).to receive(:[]).with('Content-type').and_return(nil)
response = response_from_res_double(res, @request)
response.log_response
expect(log).to eq ["# => 200 OK | 4 bytes, 1.00s\n"]
end
it "logs a response with a nil body" do
log = RestClient.log = []
res = res_double(code: '200', class: Net::HTTPOK, body: nil)
allow(res).to receive(:[]).with('Content-type').and_return('text/html; charset=utf-8')
response = response_from_res_double(res, @request)
response.log_response
expect(log).to eq ["# => 200 OK | text/html 0 bytes, 1.00s\n"]
end
it 'does not log request password' do
log = RestClient.log = []
RestClient::Request.new(:method => :get, :url => 'http://user:password@url', :headers => {:user_agent => 'rest-client'}).log_request
expect(log[0]).to eq %Q{RestClient.get "http://user:REDACTED@url", "Accept"=>"*/*", "User-Agent"=>"rest-client"\n}
end
it 'logs to a passed logger, if provided' do
logger = double('logger', '<<' => true)
expect(logger).to receive(:<<)
RestClient::Request.new(:method => :get, :url => 'http://user:password@url', log: logger).log_request
end
end
it "strips the charset from the response content type" do
log = RestClient.log = []
res = res_double(code: '200', class: Net::HTTPOK, body: 'abcd')
allow(res).to receive(:[]).with('Content-type').and_return('text/html; charset=utf-8')
response = response_from_res_double(res, @request)
response.log_response
expect(log).to eq ["# => 200 OK | text/html 4 bytes, 1.00s\n"]
end
describe "timeout" do
it "does not set timeouts if not specified" do
@request = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload')
allow(@http).to receive(:request)
allow(@request).to receive(:process_result)
allow(@request).to receive(:response_log)
expect(@net).not_to receive(:read_timeout=)
expect(@net).not_to receive(:open_timeout=)
@request.send(:transmit, @uri, 'req', nil)
end
it 'sets read_timeout' do
@request = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload', :read_timeout => 123)
allow(@http).to receive(:request)
allow(@request).to receive(:process_result)
allow(@request).to receive(:response_log)
expect(@net).to receive(:read_timeout=).with(123)
@request.send(:transmit, @uri, 'req', nil)
end
it "sets open_timeout" do
@request = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload', :open_timeout => 123)
allow(@http).to receive(:request)
allow(@request).to receive(:process_result)
allow(@request).to receive(:response_log)
expect(@net).to receive(:open_timeout=).with(123)
@request.send(:transmit, @uri, 'req', nil)
end
it 'sets both timeouts with :timeout' do
@request = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload', :timeout => 123)
allow(@http).to receive(:request)
allow(@request).to receive(:process_result)
allow(@request).to receive(:response_log)
expect(@net).to receive(:open_timeout=).with(123)
expect(@net).to receive(:read_timeout=).with(123)
@request.send(:transmit, @uri, 'req', nil)
end
it 'supersedes :timeout with open/read_timeout' do
@request = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload', :timeout => 123, :open_timeout => 34, :read_timeout => 56)
allow(@http).to receive(:request)
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | true |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/exceptions_spec.rb | spec/unit/exceptions_spec.rb | require_relative '_lib'
describe RestClient::Exception do
it "returns a 'message' equal to the class name if the message is not set, because 'message' should not be nil" do
e = RestClient::Exception.new
expect(e.message).to eq "RestClient::Exception"
end
it "returns the 'message' that was set" do
e = RestClient::Exception.new
message = "An explicitly set message"
e.message = message
expect(e.message).to eq message
end
it "sets the exception message to ErrorMessage" do
expect(RestClient::ResourceNotFound.new.message).to eq 'Not Found'
end
it "contains exceptions in RestClient" do
expect(RestClient::Unauthorized.new).to be_a_kind_of(RestClient::Exception)
expect(RestClient::ServerBrokeConnection.new).to be_a_kind_of(RestClient::Exception)
end
end
describe RestClient::ServerBrokeConnection do
it "should have a default message of 'Server broke connection'" do
e = RestClient::ServerBrokeConnection.new
expect(e.message).to eq 'Server broke connection'
end
end
describe RestClient::RequestFailed do
before do
@response = double('HTTP Response', :code => '502')
end
it "stores the http response on the exception" do
response = "response"
begin
raise RestClient::RequestFailed, response
rescue RestClient::RequestFailed => e
expect(e.response).to eq response
end
end
it "http_code convenience method for fetching the code as an integer" do
expect(RestClient::RequestFailed.new(@response).http_code).to eq 502
end
it "http_body convenience method for fetching the body (decoding when necessary)" do
expect(RestClient::RequestFailed.new(@response).http_code).to eq 502
expect(RestClient::RequestFailed.new(@response).message).to eq 'HTTP status code 502'
end
it "shows the status code in the message" do
expect(RestClient::RequestFailed.new(@response).to_s).to match(/502/)
end
end
describe RestClient::ResourceNotFound do
it "also has the http response attached" do
response = "response"
begin
raise RestClient::ResourceNotFound, response
rescue RestClient::ResourceNotFound => e
expect(e.response).to eq response
end
end
it 'stores the body on the response of the exception' do
body = "body"
stub_request(:get, "www.example.com").to_return(:body => body, :status => 404)
begin
RestClient.get "www.example.com"
raise
rescue RestClient::ResourceNotFound => e
expect(e.response.body).to eq body
end
end
end
describe "backwards compatibility" do
it 'aliases RestClient::NotFound as ResourceNotFound' do
expect(RestClient::ResourceNotFound).to eq RestClient::NotFound
end
it 'aliases old names for HTTP 413, 414, 416' do
expect(RestClient::RequestEntityTooLarge).to eq RestClient::PayloadTooLarge
expect(RestClient::RequestURITooLong).to eq RestClient::URITooLong
expect(RestClient::RequestedRangeNotSatisfiable).to eq RestClient::RangeNotSatisfiable
end
it 'subclasses NotFound from RequestFailed, ExceptionWithResponse' do
expect(RestClient::NotFound).to be < RestClient::RequestFailed
expect(RestClient::NotFound).to be < RestClient::ExceptionWithResponse
end
it 'subclasses timeout from RestClient::RequestTimeout, RequestFailed, EWR' do
expect(RestClient::Exceptions::OpenTimeout).to be < RestClient::Exceptions::Timeout
expect(RestClient::Exceptions::ReadTimeout).to be < RestClient::Exceptions::Timeout
expect(RestClient::Exceptions::Timeout).to be < RestClient::RequestTimeout
expect(RestClient::Exceptions::Timeout).to be < RestClient::RequestFailed
expect(RestClient::Exceptions::Timeout).to be < RestClient::ExceptionWithResponse
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/restclient_spec.rb | spec/unit/restclient_spec.rb | require_relative '_lib'
describe RestClient do
describe "API" do
it "GET" do
expect(RestClient::Request).to receive(:execute).with(:method => :get, :url => 'http://some/resource', :headers => {})
RestClient.get('http://some/resource')
end
it "POST" do
expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => 'http://some/resource', :payload => 'payload', :headers => {})
RestClient.post('http://some/resource', 'payload')
end
it "PUT" do
expect(RestClient::Request).to receive(:execute).with(:method => :put, :url => 'http://some/resource', :payload => 'payload', :headers => {})
RestClient.put('http://some/resource', 'payload')
end
it "PATCH" do
expect(RestClient::Request).to receive(:execute).with(:method => :patch, :url => 'http://some/resource', :payload => 'payload', :headers => {})
RestClient.patch('http://some/resource', 'payload')
end
it "DELETE" do
expect(RestClient::Request).to receive(:execute).with(:method => :delete, :url => 'http://some/resource', :headers => {})
RestClient.delete('http://some/resource')
end
it "HEAD" do
expect(RestClient::Request).to receive(:execute).with(:method => :head, :url => 'http://some/resource', :headers => {})
RestClient.head('http://some/resource')
end
it "OPTIONS" do
expect(RestClient::Request).to receive(:execute).with(:method => :options, :url => 'http://some/resource', :headers => {})
RestClient.options('http://some/resource')
end
end
describe "logging" do
after do
RestClient.log = nil
end
it "uses << if the log is not a string" do
log = RestClient.log = []
expect(log).to receive(:<<).with('xyz')
RestClient.log << 'xyz'
end
it "displays the log to stdout" do
RestClient.log = 'stdout'
expect(STDOUT).to receive(:puts).with('xyz')
RestClient.log << 'xyz'
end
it "displays the log to stderr" do
RestClient.log = 'stderr'
expect(STDERR).to receive(:puts).with('xyz')
RestClient.log << 'xyz'
end
it "append the log to the requested filename" do
RestClient.log = '/tmp/restclient.log'
f = double('file handle')
expect(File).to receive(:open).with('/tmp/restclient.log', 'a').and_yield(f)
expect(f).to receive(:puts).with('xyz')
RestClient.log << 'xyz'
end
end
describe 'version' do
# test that there is a sane version number to avoid accidental 0.0.0 again
it 'has a version > 2.0.0.alpha, < 3.0' do
ver = Gem::Version.new(RestClient.version)
expect(Gem::Requirement.new('> 2.0.0.alpha', '< 3.0')).to be_satisfied_by(ver)
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/payload_spec.rb | spec/unit/payload_spec.rb | # encoding: binary
require_relative '_lib'
describe RestClient::Payload, :include_helpers do
context "Base Payload" do
it "should reset stream after to_s" do
payload = RestClient::Payload::Base.new('foobar')
expect(payload.to_s).to eq 'foobar'
expect(payload.to_s).to eq 'foobar'
end
end
context "A regular Payload" do
it "should use standard enctype as default content-type" do
expect(RestClient::Payload::UrlEncoded.new({}).headers['Content-Type']).
to eq 'application/x-www-form-urlencoded'
end
it "should form properly encoded params" do
expect(RestClient::Payload::UrlEncoded.new({:foo => 'bar'}).to_s).
to eq "foo=bar"
expect(["foo=bar&baz=qux", "baz=qux&foo=bar"]).to include(
RestClient::Payload::UrlEncoded.new({:foo => 'bar', :baz => 'qux'}).to_s)
end
it "should escape parameters" do
expect(RestClient::Payload::UrlEncoded.new({'foo + bar' => 'baz'}).to_s).
to eq "foo+%2B+bar=baz"
end
it "should properly handle hashes as parameter" do
expect(RestClient::Payload::UrlEncoded.new({:foo => {:bar => 'baz'}}).to_s).
to eq "foo[bar]=baz"
expect(RestClient::Payload::UrlEncoded.new({:foo => {:bar => {:baz => 'qux'}}}).to_s).
to eq "foo[bar][baz]=qux"
end
it "should handle many attributes inside a hash" do
parameters = RestClient::Payload::UrlEncoded.new({:foo => {:bar => 'baz', :baz => 'qux'}}).to_s
expect(parameters).to eq 'foo[bar]=baz&foo[baz]=qux'
end
it "should handle attributes inside an array inside an hash" do
parameters = RestClient::Payload::UrlEncoded.new({"foo" => [{"bar" => 'baz'}, {"bar" => 'qux'}]}).to_s
expect(parameters).to eq 'foo[][bar]=baz&foo[][bar]=qux'
end
it "should handle arrays inside a hash inside a hash" do
parameters = RestClient::Payload::UrlEncoded.new({"foo" => {'even' => [0, 2], 'odd' => [1, 3]}}).to_s
expect(parameters).to eq 'foo[even][]=0&foo[even][]=2&foo[odd][]=1&foo[odd][]=3'
end
it "should form properly use symbols as parameters" do
expect(RestClient::Payload::UrlEncoded.new({:foo => :bar}).to_s).
to eq "foo=bar"
expect(RestClient::Payload::UrlEncoded.new({:foo => {:bar => :baz}}).to_s).
to eq "foo[bar]=baz"
end
it "should properly handle arrays as repeated parameters" do
expect(RestClient::Payload::UrlEncoded.new({:foo => ['bar']}).to_s).
to eq "foo[]=bar"
expect(RestClient::Payload::UrlEncoded.new({:foo => ['bar', 'baz']}).to_s).
to eq "foo[]=bar&foo[]=baz"
end
it 'should not close if stream already closed' do
p = RestClient::Payload::UrlEncoded.new({'foo ' => 'bar'})
3.times {p.close}
end
end
context "A multipart Payload" do
it "should use standard enctype as default content-type" do
m = RestClient::Payload::Multipart.new({})
allow(m).to receive(:boundary).and_return(123)
expect(m.headers['Content-Type']).to eq 'multipart/form-data; boundary=123'
end
it 'should not error on close if stream already closed' do
m = RestClient::Payload::Multipart.new(:file => File.new(test_image_path))
3.times {m.close}
end
it "should form properly separated multipart data" do
m = RestClient::Payload::Multipart.new([[:bar, "baz"], [:foo, "bar"]])
expect(m.to_s).to eq <<-EOS
--#{m.boundary}\r
Content-Disposition: form-data; name="bar"\r
\r
baz\r
--#{m.boundary}\r
Content-Disposition: form-data; name="foo"\r
\r
bar\r
--#{m.boundary}--\r
EOS
end
it "should not escape parameters names" do
m = RestClient::Payload::Multipart.new([["bar ", "baz"]])
expect(m.to_s).to eq <<-EOS
--#{m.boundary}\r
Content-Disposition: form-data; name="bar "\r
\r
baz\r
--#{m.boundary}--\r
EOS
end
it "should form properly separated multipart data" do
f = File.new(test_image_path)
m = RestClient::Payload::Multipart.new({:foo => f})
expect(m.to_s).to eq <<-EOS
--#{m.boundary}\r
Content-Disposition: form-data; name="foo"; filename="ISS.jpg"\r
Content-Type: image/jpeg\r
\r
#{File.open(f.path, 'rb'){|bin| bin.read}}\r
--#{m.boundary}--\r
EOS
end
it "should ignore the name attribute when it's not set" do
f = File.new(test_image_path)
m = RestClient::Payload::Multipart.new({nil => f})
expect(m.to_s).to eq <<-EOS
--#{m.boundary}\r
Content-Disposition: form-data; filename="ISS.jpg"\r
Content-Type: image/jpeg\r
\r
#{File.open(f.path, 'rb'){|bin| bin.read}}\r
--#{m.boundary}--\r
EOS
end
it "should detect optional (original) content type and filename" do
f = File.new(test_image_path)
expect(f).to receive(:content_type).and_return('text/plain')
expect(f).to receive(:original_filename).and_return('foo.txt')
m = RestClient::Payload::Multipart.new({:foo => f})
expect(m.to_s).to eq <<-EOS
--#{m.boundary}\r
Content-Disposition: form-data; name="foo"; filename="foo.txt"\r
Content-Type: text/plain\r
\r
#{File.open(f.path, 'rb'){|bin| bin.read}}\r
--#{m.boundary}--\r
EOS
end
it "should handle hash in hash parameters" do
m = RestClient::Payload::Multipart.new({:bar => {:baz => "foo"}})
expect(m.to_s).to eq <<-EOS
--#{m.boundary}\r
Content-Disposition: form-data; name="bar[baz]"\r
\r
foo\r
--#{m.boundary}--\r
EOS
f = File.new(test_image_path)
f.instance_eval "def content_type; 'text/plain'; end"
f.instance_eval "def original_filename; 'foo.txt'; end"
m = RestClient::Payload::Multipart.new({:foo => {:bar => f}})
expect(m.to_s).to eq <<-EOS
--#{m.boundary}\r
Content-Disposition: form-data; name="foo[bar]"; filename="foo.txt"\r
Content-Type: text/plain\r
\r
#{File.open(f.path, 'rb'){|bin| bin.read}}\r
--#{m.boundary}--\r
EOS
end
it 'should correctly format hex boundary' do
allow(SecureRandom).to receive(:base64).with(12).and_return('TGs89+ttw/xna6TV')
f = File.new(test_image_path)
m = RestClient::Payload::Multipart.new({:foo => f})
expect(m.boundary).to eq('-' * 4 + 'RubyFormBoundary' + 'TGs89AttwBxna6TV')
end
end
context "streamed payloads" do
it "should properly determine the size of file payloads" do
f = File.new(test_image_path)
payload = RestClient::Payload.generate(f)
expect(payload.size).to eq 72_463
expect(payload.length).to eq 72_463
end
it "should properly determine the size of other kinds of streaming payloads" do
s = StringIO.new 'foo'
payload = RestClient::Payload.generate(s)
expect(payload.size).to eq 3
expect(payload.length).to eq 3
begin
f = Tempfile.new "rest-client"
f.write 'foo bar'
payload = RestClient::Payload.generate(f)
expect(payload.size).to eq 7
expect(payload.length).to eq 7
ensure
f.close
end
end
it "should have a closed? method" do
f = File.new(test_image_path)
payload = RestClient::Payload.generate(f)
expect(payload.closed?).to be_falsey
payload.close
expect(payload.closed?).to be_truthy
end
end
context "Payload generation" do
it "should recognize standard urlencoded params" do
expect(RestClient::Payload.generate({"foo" => 'bar'})).to be_kind_of(RestClient::Payload::UrlEncoded)
end
it "should recognize multipart params" do
f = File.new(test_image_path)
expect(RestClient::Payload.generate({"foo" => f})).to be_kind_of(RestClient::Payload::Multipart)
end
it "should be multipart if forced" do
expect(RestClient::Payload.generate({"foo" => "bar", :multipart => true})).to be_kind_of(RestClient::Payload::Multipart)
end
it "should handle deeply nested multipart" do
f = File.new(test_image_path)
params = {foo: RestClient::ParamsArray.new({nested: f})}
expect(RestClient::Payload.generate(params)).to be_kind_of(RestClient::Payload::Multipart)
end
it "should return data if no of the above" do
expect(RestClient::Payload.generate("data")).to be_kind_of(RestClient::Payload::Base)
end
it "should recognize nested multipart payloads in hashes" do
f = File.new(test_image_path)
expect(RestClient::Payload.generate({"foo" => {"file" => f}})).to be_kind_of(RestClient::Payload::Multipart)
end
it "should recognize nested multipart payloads in arrays" do
f = File.new(test_image_path)
expect(RestClient::Payload.generate({"foo" => [f]})).to be_kind_of(RestClient::Payload::Multipart)
end
it "should recognize file payloads that can be streamed" do
f = File.new(test_image_path)
expect(RestClient::Payload.generate(f)).to be_kind_of(RestClient::Payload::Streamed)
end
it "should recognize other payloads that can be streamed" do
expect(RestClient::Payload.generate(StringIO.new('foo'))).to be_kind_of(RestClient::Payload::Streamed)
end
# hashery gem introduces Hash#read convenience method. Existence of #read method used to determine of content is streameable :/
it "shouldn't treat hashes as streameable" do
expect(RestClient::Payload.generate({"foo" => 'bar'})).to be_kind_of(RestClient::Payload::UrlEncoded)
end
it "should recognize multipart payload wrapped in ParamsArray" do
f = File.new(test_image_path)
params = RestClient::ParamsArray.new([[:image, f]])
expect(RestClient::Payload.generate(params)).to be_kind_of(RestClient::Payload::Multipart)
end
it "should handle non-multipart payload wrapped in ParamsArray" do
params = RestClient::ParamsArray.new([[:arg, 'value1'], [:arg, 'value2']])
expect(RestClient::Payload.generate(params)).to be_kind_of(RestClient::Payload::UrlEncoded)
end
it "should pass through Payload::Base and subclasses unchanged" do
payloads = [
RestClient::Payload::Base.new('foobar'),
RestClient::Payload::UrlEncoded.new({:foo => 'bar'}),
RestClient::Payload::Streamed.new(File.new(test_image_path)),
RestClient::Payload::Multipart.new({myfile: File.new(test_image_path)}),
]
payloads.each do |payload|
expect(RestClient::Payload.generate(payload)).to equal(payload)
end
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/utils_spec.rb | spec/unit/utils_spec.rb | require_relative '_lib'
describe RestClient::Utils do
describe '.get_encoding_from_headers' do
it 'assumes no encoding by default for text' do
headers = {:content_type => 'text/plain'}
expect(RestClient::Utils.get_encoding_from_headers(headers)).
to eq nil
end
it 'returns nil on failures' do
expect(RestClient::Utils.get_encoding_from_headers(
{:content_type => 'blah'})).to eq nil
expect(RestClient::Utils.get_encoding_from_headers(
{})).to eq nil
expect(RestClient::Utils.get_encoding_from_headers(
{:content_type => 'foo; bar=baz'})).to eq nil
end
it 'handles various charsets' do
expect(RestClient::Utils.get_encoding_from_headers(
{:content_type => 'text/plain; charset=UTF-8'})).to eq 'UTF-8'
expect(RestClient::Utils.get_encoding_from_headers(
{:content_type => 'application/json; charset=ISO-8859-1'})).
to eq 'ISO-8859-1'
expect(RestClient::Utils.get_encoding_from_headers(
{:content_type => 'text/html; charset=windows-1251'})).
to eq 'windows-1251'
expect(RestClient::Utils.get_encoding_from_headers(
{:content_type => 'text/html; charset="UTF-16"'})).
to eq 'UTF-16'
end
end
describe '.cgi_parse_header' do
it 'parses headers', :unless => RUBY_VERSION.start_with?('2.0') do
expect(RestClient::Utils.cgi_parse_header('text/plain')).
to eq ['text/plain', {}]
expect(RestClient::Utils.cgi_parse_header('text/vnd.just.made.this.up')).
to eq ['text/vnd.just.made.this.up', {}]
expect(RestClient::Utils.cgi_parse_header('text/plain;charset=us-ascii')).
to eq ['text/plain', {'charset' => 'us-ascii'}]
expect(RestClient::Utils.cgi_parse_header('text/plain ; charset="us-ascii"')).
to eq ['text/plain', {'charset' => 'us-ascii'}]
expect(RestClient::Utils.cgi_parse_header(
'text/plain ; charset="us-ascii"; another=opt')).
to eq ['text/plain', {'charset' => 'us-ascii', 'another' => 'opt'}]
expect(RestClient::Utils.cgi_parse_header(
'foo/bar; filename="silly.txt"')).
to eq ['foo/bar', {'filename' => 'silly.txt'}]
expect(RestClient::Utils.cgi_parse_header(
'foo/bar; filename="strange;name"')).
to eq ['foo/bar', {'filename' => 'strange;name'}]
expect(RestClient::Utils.cgi_parse_header(
'foo/bar; filename="strange;name";size=123')).to eq \
['foo/bar', {'filename' => 'strange;name', 'size' => '123'}]
expect(RestClient::Utils.cgi_parse_header(
'foo/bar; name="files"; filename="fo\\"o;bar"')).to eq \
['foo/bar', {'name' => 'files', 'filename' => 'fo"o;bar'}]
end
end
describe '.encode_query_string' do
it 'handles simple hashes' do
{
{foo: 123, bar: 456} => 'foo=123&bar=456',
{'foo' => 123, 'bar' => 456} => 'foo=123&bar=456',
{foo: 'abc', bar: 'one two'} => 'foo=abc&bar=one+two',
{escaped: '1+2=3'} => 'escaped=1%2B2%3D3',
{'escaped + key' => 'foo'} => 'escaped+%2B+key=foo',
}.each_pair do |input, expected|
expect(RestClient::Utils.encode_query_string(input)).to eq expected
end
end
it 'handles simple arrays' do
{
{foo: [1, 2, 3]} => 'foo[]=1&foo[]=2&foo[]=3',
{foo: %w{a b c}, bar: [1, 2, 3]} => 'foo[]=a&foo[]=b&foo[]=c&bar[]=1&bar[]=2&bar[]=3',
{foo: ['one two', 3]} => 'foo[]=one+two&foo[]=3',
{'a+b' => [1,2,3]} => 'a%2Bb[]=1&a%2Bb[]=2&a%2Bb[]=3',
}.each_pair do |input, expected|
expect(RestClient::Utils.encode_query_string(input)).to eq expected
end
end
it 'handles nested hashes' do
{
{outer: {foo: 123, bar: 456}} => 'outer[foo]=123&outer[bar]=456',
{outer: {foo: [1, 2, 3], bar: 'baz'}} => 'outer[foo][]=1&outer[foo][]=2&outer[foo][]=3&outer[bar]=baz',
}.each_pair do |input, expected|
expect(RestClient::Utils.encode_query_string(input)).to eq expected
end
end
it 'handles null and empty values' do
{
{string: '', empty: nil, list: [], hash: {}, falsey: false } =>
'string=&empty&list&hash&falsey=false',
}.each_pair do |input, expected|
expect(RestClient::Utils.encode_query_string(input)).to eq expected
end
end
it 'handles nested nulls' do
{
{foo: {string: '', empty: nil}} => 'foo[string]=&foo[empty]',
}.each_pair do |input, expected|
expect(RestClient::Utils.encode_query_string(input)).to eq expected
end
end
it 'handles deep nesting' do
{
{coords: [{x: 1, y: 0}, {x: 2}, {x: 3}]} => 'coords[][x]=1&coords[][y]=0&coords[][x]=2&coords[][x]=3',
}.each_pair do |input, expected|
expect(RestClient::Utils.encode_query_string(input)).to eq expected
end
end
it 'handles multiple fields with the same name using ParamsArray' do
{
RestClient::ParamsArray.new([[:foo, 1], [:foo, 2], [:foo, 3]]) => 'foo=1&foo=2&foo=3',
}.each_pair do |input, expected|
expect(RestClient::Utils.encode_query_string(input)).to eq expected
end
end
it 'handles nested ParamsArrays' do
{
{foo: RestClient::ParamsArray.new([[:a, 1], [:a, 2]])} => 'foo[a]=1&foo[a]=2',
RestClient::ParamsArray.new([[:foo, {a: 1}], [:foo, {a: 2}]]) => 'foo[a]=1&foo[a]=2',
}.each_pair do |input, expected|
expect(RestClient::Utils.encode_query_string(input)).to eq expected
end
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/request2_spec.rb | spec/unit/request2_spec.rb | require_relative '_lib'
describe RestClient::Request, :include_helpers do
context 'params for GET requests' do
it "manage params for get requests" do
stub_request(:get, 'http://some/resource?a=b&c=d').with(:headers => {'Accept'=>'*/*', 'Foo'=>'bar'}).to_return(:body => 'foo', :status => 200)
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :get, :headers => {:foo => :bar, :params => {:a => :b, 'c' => 'd'}}).body).to eq 'foo'
stub_request(:get, 'http://some/resource').with(:headers => {'Accept'=>'*/*', 'Foo'=>'bar'}).to_return(:body => 'foo', :status => 200)
expect(RestClient::Request.execute(:url => 'http://some/resource', :method => :get, :headers => {:foo => :bar, :params => :a}).body).to eq 'foo'
end
it 'adds GET params when params are present in URL' do
stub_request(:get, 'http://some/resource?a=b&c=d').with(:headers => {'Accept'=>'*/*', 'Foo'=>'bar'}).to_return(:body => 'foo', :status => 200)
expect(RestClient::Request.execute(:url => 'http://some/resource?a=b', :method => :get, :headers => {:foo => :bar, :params => {:c => 'd'}}).body).to eq 'foo'
end
it 'encodes nested GET params' do
stub_request(:get, 'http://some/resource?a[foo][]=1&a[foo][]=2&a[bar]&b=foo+bar&math=2+%2B+2+%3D%3D+4').with(:headers => {'Accept'=>'*/*',}).to_return(:body => 'foo', :status => 200)
expect(RestClient::Request.execute(url: 'http://some/resource', method: :get, headers: {
params: {
a: {
foo: [1,2],
bar: nil,
},
b: 'foo bar',
math: '2 + 2 == 4',
}
}).body).to eq 'foo'
end
end
it "can use a block to process response" do
response_value = nil
block = proc do |http_response|
response_value = http_response.body
end
stub_request(:get, 'http://some/resource?a=b&c=d').with(:headers => {'Accept'=>'*/*', 'Foo'=>'bar'}).to_return(:body => 'foo', :status => 200)
RestClient::Request.execute(:url => 'http://some/resource', :method => :get, :headers => {:foo => :bar, :params => {:a => :b, 'c' => 'd'}}, :block_response => block)
expect(response_value).to eq "foo"
end
it 'closes payload if not nil' do
test_file = File.new(test_image_path)
stub_request(:post, 'http://some/resource').with(:headers => {'Accept'=>'*/*'}).to_return(:body => 'foo', :status => 200)
RestClient::Request.execute(:url => 'http://some/resource', :method => :post, :payload => {:file => test_file})
expect(test_file.closed?).to be true
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/params_array_spec.rb | spec/unit/params_array_spec.rb | require_relative '_lib'
describe RestClient::ParamsArray do
describe '.new' do
it 'accepts various types of containers' do
as_array = [[:foo, 123], [:foo, 456], [:bar, 789], [:empty, nil]]
[
[[:foo, 123], [:foo, 456], [:bar, 789], [:empty, nil]],
[{foo: 123}, {foo: 456}, {bar: 789}, {empty: nil}],
[{foo: 123}, {foo: 456}, {bar: 789}, {empty: nil}],
[{foo: 123}, [:foo, 456], {bar: 789}, {empty: nil}],
[{foo: 123}, [:foo, 456], {bar: 789}, [:empty]],
].each do |input|
expect(RestClient::ParamsArray.new(input).to_a).to eq as_array
end
expect(RestClient::ParamsArray.new([]).to_a).to eq []
expect(RestClient::ParamsArray.new([]).empty?).to eq true
end
it 'rejects various invalid input' do
expect {
RestClient::ParamsArray.new([[]])
}.to raise_error(IndexError)
expect {
RestClient::ParamsArray.new([[1,2,3]])
}.to raise_error(ArgumentError)
expect {
RestClient::ParamsArray.new([1,2,3])
}.to raise_error(NoMethodError)
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/abstract_response_spec.rb | spec/unit/abstract_response_spec.rb | require_relative '_lib'
describe RestClient::AbstractResponse, :include_helpers do
# Sample class implementing AbstractResponse used for testing.
class MyAbstractResponse
include RestClient::AbstractResponse
attr_accessor :size
def initialize(net_http_res, request)
response_set_vars(net_http_res, request, Time.now - 1)
end
end
before do
@net_http_res = res_double()
@request = request_double(url: 'http://example.com', method: 'get')
@response = MyAbstractResponse.new(@net_http_res, @request)
end
it "fetches the numeric response code" do
expect(@net_http_res).to receive(:code).and_return('200')
expect(@response.code).to eq 200
end
it "has a nice description" do
expect(@net_http_res).to receive(:to_hash).and_return({'Content-Type' => ['application/pdf']})
expect(@net_http_res).to receive(:code).and_return('200')
expect(@response.description).to eq "200 OK | application/pdf bytes\n"
end
describe '.beautify_headers' do
it "beautifies the headers by turning the keys to symbols" do
h = RestClient::AbstractResponse.beautify_headers('content-type' => [ 'x' ])
expect(h.keys.first).to eq :content_type
end
it "beautifies the headers by turning the values to strings instead of one-element arrays" do
h = RestClient::AbstractResponse.beautify_headers('x' => [ 'text/html' ] )
expect(h.values.first).to eq 'text/html'
end
it 'joins multiple header values by comma' do
expect(RestClient::AbstractResponse.beautify_headers(
{'My-Header' => ['one', 'two']}
)).to eq({:my_header => 'one, two'})
end
it 'leaves set-cookie headers as array' do
expect(RestClient::AbstractResponse.beautify_headers(
{'Set-Cookie' => ['cookie1=foo', 'cookie2=bar']}
)).to eq({:set_cookie => ['cookie1=foo', 'cookie2=bar']})
end
end
it "fetches the headers" do
expect(@net_http_res).to receive(:to_hash).and_return('content-type' => [ 'text/html' ])
expect(@response.headers).to eq({ :content_type => 'text/html' })
end
it "extracts cookies from response headers" do
expect(@net_http_res).to receive(:to_hash).and_return('set-cookie' => ['session_id=1; path=/'])
expect(@response.cookies).to eq({ 'session_id' => '1' })
end
it "extract strange cookies" do
expect(@net_http_res).to receive(:to_hash).and_return('set-cookie' => ['session_id=ZJ/HQVH6YE+rVkTpn0zvTQ==; path=/'])
expect(@response.headers).to eq({:set_cookie => ['session_id=ZJ/HQVH6YE+rVkTpn0zvTQ==; path=/']})
expect(@response.cookies).to eq({ 'session_id' => 'ZJ/HQVH6YE+rVkTpn0zvTQ==' })
end
it "doesn't escape cookies" do
expect(@net_http_res).to receive(:to_hash).and_return('set-cookie' => ['session_id=BAh7BzoNYXBwX25hbWUiEGFwcGxpY2F0aW9uOgpsb2dpbiIKYWRtaW4%3D%0A--08114ba654f17c04d20dcc5228ec672508f738ca; path=/'])
expect(@response.cookies).to eq({ 'session_id' => 'BAh7BzoNYXBwX25hbWUiEGFwcGxpY2F0aW9uOgpsb2dpbiIKYWRtaW4%3D%0A--08114ba654f17c04d20dcc5228ec672508f738ca' })
end
describe '.cookie_jar' do
it 'extracts cookies into cookie jar' do
expect(@net_http_res).to receive(:to_hash).and_return('set-cookie' => ['session_id=1; path=/'])
expect(@response.cookie_jar).to be_a HTTP::CookieJar
cookie = @response.cookie_jar.cookies.first
expect(cookie.domain).to eq 'example.com'
expect(cookie.name).to eq 'session_id'
expect(cookie.value).to eq '1'
expect(cookie.path).to eq '/'
end
it 'handles cookies when URI scheme is implicit' do
net_http_res = double('net http response')
expect(net_http_res).to receive(:to_hash).and_return('set-cookie' => ['session_id=1; path=/'])
request = double('request', url: 'example.com', uri: URI.parse('http://example.com'),
method: 'get', cookie_jar: HTTP::CookieJar.new, redirection_history: nil)
response = MyAbstractResponse.new(net_http_res, request)
expect(response.cookie_jar).to be_a HTTP::CookieJar
cookie = response.cookie_jar.cookies.first
expect(cookie.domain).to eq 'example.com'
expect(cookie.name).to eq 'session_id'
expect(cookie.value).to eq '1'
expect(cookie.path).to eq '/'
end
end
it "can access the net http result directly" do
expect(@response.net_http_res).to eq @net_http_res
end
describe "#return!" do
it "should return the response itself on 200-codes" do
expect(@net_http_res).to receive(:code).and_return('200')
expect(@response.return!).to be_equal(@response)
end
it "should raise RequestFailed on unknown codes" do
expect(@net_http_res).to receive(:code).and_return('1000')
expect { @response.return! }.to raise_error RestClient::RequestFailed
end
it "should raise an error on a redirection after non-GET/HEAD requests" do
expect(@net_http_res).to receive(:code).and_return('301')
expect(@request).to receive(:method).and_return('put')
expect(@response).not_to receive(:follow_redirection)
expect { @response.return! }.to raise_error RestClient::RequestFailed
end
it "should follow 302 redirect" do
expect(@net_http_res).to receive(:code).and_return('302')
expect(@response).to receive(:check_max_redirects).and_return('fake-check')
expect(@response).to receive(:follow_redirection).and_return('fake-redirection')
expect(@response.return!).to eq 'fake-redirection'
end
it "should gracefully handle 302 redirect with no location header" do
@net_http_res = res_double(code: 302)
@request = request_double()
@response = MyAbstractResponse.new(@net_http_res, @request)
expect(@response).to receive(:check_max_redirects).and_return('fake-check')
expect { @response.return! }.to raise_error RestClient::Found
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/resource_spec.rb | spec/unit/resource_spec.rb | require_relative '_lib'
describe RestClient::Resource do
before do
@resource = RestClient::Resource.new('http://some/resource', :user => 'jane', :password => 'mypass', :headers => {'X-Something' => '1'})
end
context "Resource delegation" do
it "GET" do
expect(RestClient::Request).to receive(:execute).with(:method => :get, :url => 'http://some/resource', :headers => {'X-Something' => '1'}, :user => 'jane', :password => 'mypass', :log => nil)
@resource.get
end
it "HEAD" do
expect(RestClient::Request).to receive(:execute).with(:method => :head, :url => 'http://some/resource', :headers => {'X-Something' => '1'}, :user => 'jane', :password => 'mypass', :log => nil)
@resource.head
end
it "POST" do
expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => 'http://some/resource', :payload => 'abc', :headers => {:content_type => 'image/jpg', 'X-Something' => '1'}, :user => 'jane', :password => 'mypass', :log => nil)
@resource.post 'abc', :content_type => 'image/jpg'
end
it "PUT" do
expect(RestClient::Request).to receive(:execute).with(:method => :put, :url => 'http://some/resource', :payload => 'abc', :headers => {:content_type => 'image/jpg', 'X-Something' => '1'}, :user => 'jane', :password => 'mypass', :log => nil)
@resource.put 'abc', :content_type => 'image/jpg'
end
it "PATCH" do
expect(RestClient::Request).to receive(:execute).with(:method => :patch, :url => 'http://some/resource', :payload => 'abc', :headers => {:content_type => 'image/jpg', 'X-Something' => '1'}, :user => 'jane', :password => 'mypass', :log => nil)
@resource.patch 'abc', :content_type => 'image/jpg'
end
it "DELETE" do
expect(RestClient::Request).to receive(:execute).with(:method => :delete, :url => 'http://some/resource', :headers => {'X-Something' => '1'}, :user => 'jane', :password => 'mypass', :log => nil)
@resource.delete
end
it "overrides resource headers" do
expect(RestClient::Request).to receive(:execute).with(:method => :get, :url => 'http://some/resource', :headers => {'X-Something' => '2'}, :user => 'jane', :password => 'mypass', :log => nil)
@resource.get 'X-Something' => '2'
end
end
it "can instantiate with no user/password" do
@resource = RestClient::Resource.new('http://some/resource')
end
it "is backwards compatible with previous constructor" do
@resource = RestClient::Resource.new('http://some/resource', 'user', 'pass')
expect(@resource.user).to eq 'user'
expect(@resource.password).to eq 'pass'
end
it "concatenates urls, inserting a slash when it needs one" do
expect(@resource.concat_urls('http://example.com', 'resource')).to eq 'http://example.com/resource'
end
it "concatenates urls, using no slash if the first url ends with a slash" do
expect(@resource.concat_urls('http://example.com/', 'resource')).to eq 'http://example.com/resource'
end
it "concatenates urls, using no slash if the second url starts with a slash" do
expect(@resource.concat_urls('http://example.com', '/resource')).to eq 'http://example.com/resource'
end
it "concatenates even non-string urls, :posts + 1 => 'posts/1'" do
expect(@resource.concat_urls(:posts, 1)).to eq 'posts/1'
end
it "offers subresources via []" do
parent = RestClient::Resource.new('http://example.com')
expect(parent['posts'].url).to eq 'http://example.com/posts'
end
it "transports options to subresources" do
parent = RestClient::Resource.new('http://example.com', :user => 'user', :password => 'password')
expect(parent['posts'].user).to eq 'user'
expect(parent['posts'].password).to eq 'password'
end
it "passes a given block to subresources" do
block = proc {|r| r}
parent = RestClient::Resource.new('http://example.com', &block)
expect(parent['posts'].block).to eq block
end
it "the block should be overrideable" do
block1 = proc {|r| r}
block2 = proc {|r| }
parent = RestClient::Resource.new('http://example.com', &block1)
# parent['posts', &block2].block.should eq block2 # ruby 1.9 syntax
expect(parent.send(:[], 'posts', &block2).block).to eq block2
expect(parent.send(:[], 'posts', &block2).block).not_to eq block1
end
# Test fails on jruby 9.1.[0-5].* due to
# https://github.com/jruby/jruby/issues/4217
it "the block should be overrideable in ruby 1.9 syntax",
:unless => (RUBY_ENGINE == 'jruby' && JRUBY_VERSION =~ /\A9\.1\.[0-5]\./) \
do
block1 = proc {|r| r}
block2 = ->(r) {}
parent = RestClient::Resource.new('http://example.com', &block1)
expect(parent['posts', &block2].block).to eq block2
expect(parent['posts', &block2].block).not_to eq block1
end
it "prints its url with to_s" do
expect(RestClient::Resource.new('x').to_s).to eq 'x'
end
describe 'block' do
it 'can use block when creating the resource' do
stub_request(:get, 'www.example.com').to_return(:body => '', :status => 404)
resource = RestClient::Resource.new('www.example.com') { |response, request| 'foo' }
expect(resource.get).to eq 'foo'
end
it 'can use block when executing the resource' do
stub_request(:get, 'www.example.com').to_return(:body => '', :status => 404)
resource = RestClient::Resource.new('www.example.com')
expect(resource.get { |response, request| 'foo' }).to eq 'foo'
end
it 'execution block override resource block' do
stub_request(:get, 'www.example.com').to_return(:body => '', :status => 404)
resource = RestClient::Resource.new('www.example.com') { |response, request| 'foo' }
expect(resource.get { |response, request| 'bar' }).to eq 'bar'
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/spec/unit/windows/root_certs_spec.rb | spec/unit/windows/root_certs_spec.rb | require_relative '../_lib'
describe 'RestClient::Windows::RootCerts',
:if => RestClient::Platform.windows? do
let(:x509_store) { RestClient::Windows::RootCerts.instance.to_a }
it 'should return at least one X509 certificate' do
expect(x509_store.to_a.size).to be >= 1
end
it 'should return an X509 certificate with a subject' do
x509 = x509_store.first
expect(x509.subject.to_s).to match(/CN=.*/)
end
it 'should return X509 certificate objects' do
x509_store.each do |cert|
expect(cert).to be_a(OpenSSL::X509::Certificate)
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient.rb | lib/restclient.rb | require 'net/http'
require 'openssl'
require 'stringio'
require 'uri'
require File.dirname(__FILE__) + '/restclient/version'
require File.dirname(__FILE__) + '/restclient/platform'
require File.dirname(__FILE__) + '/restclient/exceptions'
require File.dirname(__FILE__) + '/restclient/utils'
require File.dirname(__FILE__) + '/restclient/request'
require File.dirname(__FILE__) + '/restclient/abstract_response'
require File.dirname(__FILE__) + '/restclient/response'
require File.dirname(__FILE__) + '/restclient/raw_response'
require File.dirname(__FILE__) + '/restclient/resource'
require File.dirname(__FILE__) + '/restclient/params_array'
require File.dirname(__FILE__) + '/restclient/payload'
require File.dirname(__FILE__) + '/restclient/windows'
# This module's static methods are the entry point for using the REST client.
#
# # GET
# xml = RestClient.get 'http://example.com/resource'
# jpg = RestClient.get 'http://example.com/resource', :accept => 'image/jpg'
#
# # authentication and SSL
# RestClient.get 'https://user:password@example.com/private/resource'
#
# # POST or PUT with a hash sends parameters as a urlencoded form body
# RestClient.post 'http://example.com/resource', :param1 => 'one'
#
# # nest hash parameters
# RestClient.post 'http://example.com/resource', :nested => { :param1 => 'one' }
#
# # POST and PUT with raw payloads
# RestClient.post 'http://example.com/resource', 'the post body', :content_type => 'text/plain'
# RestClient.post 'http://example.com/resource.xml', xml_doc
# RestClient.put 'http://example.com/resource.pdf', File.read('my.pdf'), :content_type => 'application/pdf'
#
# # DELETE
# RestClient.delete 'http://example.com/resource'
#
# # retrieve the response http code and headers
# res = RestClient.get 'http://example.com/some.jpg'
# res.code # => 200
# res.headers[:content_type] # => 'image/jpg'
#
# # HEAD
# RestClient.head('http://example.com').headers
#
# To use with a proxy, just set RestClient.proxy to the proper http proxy:
#
# RestClient.proxy = "http://proxy.example.com/"
#
# Or inherit the proxy from the environment:
#
# RestClient.proxy = ENV['http_proxy']
#
# For live tests of RestClient, try using http://rest-test.heroku.com, which echoes back information about the rest call:
#
# >> RestClient.put 'http://rest-test.heroku.com/resource', :foo => 'baz'
# => "PUT http://rest-test.heroku.com/resource with a 7 byte payload, content type application/x-www-form-urlencoded {\"foo\"=>\"baz\"}"
#
module RestClient
def self.get(url, headers={}, &block)
Request.execute(:method => :get, :url => url, :headers => headers, &block)
end
def self.post(url, payload, headers={}, &block)
Request.execute(:method => :post, :url => url, :payload => payload, :headers => headers, &block)
end
def self.patch(url, payload, headers={}, &block)
Request.execute(:method => :patch, :url => url, :payload => payload, :headers => headers, &block)
end
def self.put(url, payload, headers={}, &block)
Request.execute(:method => :put, :url => url, :payload => payload, :headers => headers, &block)
end
def self.delete(url, headers={}, &block)
Request.execute(:method => :delete, :url => url, :headers => headers, &block)
end
def self.head(url, headers={}, &block)
Request.execute(:method => :head, :url => url, :headers => headers, &block)
end
def self.options(url, headers={}, &block)
Request.execute(:method => :options, :url => url, :headers => headers, &block)
end
# A global proxy URL to use for all requests. This can be overridden on a
# per-request basis by passing `:proxy` to RestClient::Request.
def self.proxy
@proxy ||= nil
end
def self.proxy=(value)
@proxy = value
@proxy_set = true
end
# Return whether RestClient.proxy was set explicitly. We use this to
# differentiate between no value being set and a value explicitly set to nil.
#
# @return [Boolean]
#
def self.proxy_set?
@proxy_set ||= false
end
# Setup the log for RestClient calls.
# Value should be a logger but can can be stdout, stderr, or a filename.
# You can also configure logging by the environment variable RESTCLIENT_LOG.
def self.log= log
@@log = create_log log
end
# Create a log that respond to << like a logger
# param can be 'stdout', 'stderr', a string (then we will log to that file) or a logger (then we return it)
def self.create_log param
if param
if param.is_a? String
if param == 'stdout'
stdout_logger = Class.new do
def << obj
STDOUT.puts obj
end
end
stdout_logger.new
elsif param == 'stderr'
stderr_logger = Class.new do
def << obj
STDERR.puts obj
end
end
stderr_logger.new
else
file_logger = Class.new do
attr_writer :target_file
def << obj
File.open(@target_file, 'a') { |f| f.puts obj }
end
end
logger = file_logger.new
logger.target_file = param
logger
end
else
param
end
end
end
@@env_log = create_log ENV['RESTCLIENT_LOG']
@@log = nil
def self.log # :nodoc:
@@env_log || @@log
end
@@before_execution_procs = []
# Add a Proc to be called before each request in executed.
# The proc parameters will be the http request and the request params.
def self.add_before_execution_proc &proc
raise ArgumentError.new('block is required') unless proc
@@before_execution_procs << proc
end
# Reset the procs to be called before each request is executed.
def self.reset_before_execution_procs
@@before_execution_procs = []
end
def self.before_execution_procs # :nodoc:
@@before_execution_procs
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/rest_client.rb | lib/rest_client.rb | # This file exists for backward compatbility with require 'rest_client'
require File.dirname(__FILE__) + '/restclient'
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/rest-client.rb | lib/rest-client.rb | # More logical way to require 'rest-client'
require File.dirname(__FILE__) + '/restclient'
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/resource.rb | lib/restclient/resource.rb | module RestClient
# A class that can be instantiated for access to a RESTful resource,
# including authentication.
#
# Example:
#
# resource = RestClient::Resource.new('http://some/resource')
# jpg = resource.get(:accept => 'image/jpg')
#
# With HTTP basic authentication:
#
# resource = RestClient::Resource.new('http://protected/resource', :user => 'user', :password => 'password')
# resource.delete
#
# With a timeout (seconds):
#
# RestClient::Resource.new('http://slow', :read_timeout => 10)
#
# With an open timeout (seconds):
#
# RestClient::Resource.new('http://behindfirewall', :open_timeout => 10)
#
# You can also use resources to share common headers. For headers keys,
# symbols are converted to strings. Example:
#
# resource = RestClient::Resource.new('http://some/resource', :headers => { :client_version => 1 })
#
# This header will be transported as X-Client-Version (notice the X prefix,
# capitalization and hyphens)
#
# Use the [] syntax to allocate subresources:
#
# site = RestClient::Resource.new('http://example.com', :user => 'adam', :password => 'mypasswd')
# site['posts/1/comments'].post 'Good article.', :content_type => 'text/plain'
#
class Resource
attr_reader :url, :options, :block
def initialize(url, options={}, backwards_compatibility=nil, &block)
@url = url
@block = block
if options.class == Hash
@options = options
else # compatibility with previous versions
@options = { :user => options, :password => backwards_compatibility }
end
end
def get(additional_headers={}, &block)
headers = (options[:headers] || {}).merge(additional_headers)
Request.execute(options.merge(
:method => :get,
:url => url,
:headers => headers,
:log => log), &(block || @block))
end
def head(additional_headers={}, &block)
headers = (options[:headers] || {}).merge(additional_headers)
Request.execute(options.merge(
:method => :head,
:url => url,
:headers => headers,
:log => log), &(block || @block))
end
def post(payload, additional_headers={}, &block)
headers = (options[:headers] || {}).merge(additional_headers)
Request.execute(options.merge(
:method => :post,
:url => url,
:payload => payload,
:headers => headers,
:log => log), &(block || @block))
end
def put(payload, additional_headers={}, &block)
headers = (options[:headers] || {}).merge(additional_headers)
Request.execute(options.merge(
:method => :put,
:url => url,
:payload => payload,
:headers => headers,
:log => log), &(block || @block))
end
def patch(payload, additional_headers={}, &block)
headers = (options[:headers] || {}).merge(additional_headers)
Request.execute(options.merge(
:method => :patch,
:url => url,
:payload => payload,
:headers => headers,
:log => log), &(block || @block))
end
def delete(additional_headers={}, &block)
headers = (options[:headers] || {}).merge(additional_headers)
Request.execute(options.merge(
:method => :delete,
:url => url,
:headers => headers,
:log => log), &(block || @block))
end
def to_s
url
end
def user
options[:user]
end
def password
options[:password]
end
def headers
options[:headers] || {}
end
def read_timeout
options[:read_timeout]
end
def open_timeout
options[:open_timeout]
end
def log
options[:log] || RestClient.log
end
# Construct a subresource, preserving authentication.
#
# Example:
#
# site = RestClient::Resource.new('http://example.com', 'adam', 'mypasswd')
# site['posts/1/comments'].post 'Good article.', :content_type => 'text/plain'
#
# This is especially useful if you wish to define your site in one place and
# call it in multiple locations:
#
# def orders
# RestClient::Resource.new('http://example.com/orders', 'admin', 'mypasswd')
# end
#
# orders.get # GET http://example.com/orders
# orders['1'].get # GET http://example.com/orders/1
# orders['1/items'].delete # DELETE http://example.com/orders/1/items
#
# Nest resources as far as you want:
#
# site = RestClient::Resource.new('http://example.com')
# posts = site['posts']
# first_post = posts['1']
# comments = first_post['comments']
# comments.post 'Hello', :content_type => 'text/plain'
#
def [](suburl, &new_block)
case
when block_given? then self.class.new(concat_urls(url, suburl), options, &new_block)
when block then self.class.new(concat_urls(url, suburl), options, &block)
else self.class.new(concat_urls(url, suburl), options)
end
end
def concat_urls(url, suburl) # :nodoc:
url = url.to_s
suburl = suburl.to_s
if url.slice(-1, 1) == '/' or suburl.slice(0, 1) == '/'
url + suburl
else
"#{url}/#{suburl}"
end
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/platform.rb | lib/restclient/platform.rb | require 'rbconfig'
module RestClient
module Platform
# Return true if we are running on a darwin-based Ruby platform. This will
# be false for jruby even on OS X.
#
# @return [Boolean]
def self.mac_mri?
RUBY_PLATFORM.include?('darwin')
end
# Return true if we are running on Windows.
#
# @return [Boolean]
#
def self.windows?
# Ruby only sets File::ALT_SEPARATOR on Windows, and the Ruby standard
# library uses that to test what platform it's on.
!!File::ALT_SEPARATOR
end
# Return true if we are running on jruby.
#
# @return [Boolean]
#
def self.jruby?
# defined on mri >= 1.9
RUBY_ENGINE == 'jruby'
end
def self.architecture
"#{RbConfig::CONFIG['host_os']} #{RbConfig::CONFIG['host_cpu']}"
end
def self.ruby_agent_version
case RUBY_ENGINE
when 'jruby'
"jruby/#{JRUBY_VERSION} (#{RUBY_VERSION}p#{RUBY_PATCHLEVEL})"
else
"#{RUBY_ENGINE}/#{RUBY_VERSION}p#{RUBY_PATCHLEVEL}"
end
end
def self.default_user_agent
"rest-client/#{VERSION} (#{architecture}) #{ruby_agent_version}"
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/version.rb | lib/restclient/version.rb | module RestClient
VERSION_INFO = [2, 1, 0].freeze
VERSION = VERSION_INFO.map(&:to_s).join('.').freeze
def self.version
VERSION
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/exceptions.rb | lib/restclient/exceptions.rb | module RestClient
# Hash of HTTP status code => message.
#
# 1xx: Informational - Request received, continuing process
# 2xx: Success - The action was successfully received, understood, and
# accepted
# 3xx: Redirection - Further action must be taken in order to complete the
# request
# 4xx: Client Error - The request contains bad syntax or cannot be fulfilled
# 5xx: Server Error - The server failed to fulfill an apparently valid
# request
#
# @see
# http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
#
STATUSES = {100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing', #WebDAV
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information', # http/1.1
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status', #WebDAV
208 => 'Already Reported', # RFC5842
226 => 'IM Used', # RFC3229
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other', # http/1.1
304 => 'Not Modified',
305 => 'Use Proxy', # http/1.1
306 => 'Switch Proxy', # no longer used
307 => 'Temporary Redirect', # http/1.1
308 => 'Permanent Redirect', # RFC7538
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Payload Too Large', # RFC7231 (renamed, see below)
414 => 'URI Too Long', # RFC7231 (renamed, see below)
415 => 'Unsupported Media Type',
416 => 'Range Not Satisfiable', # RFC7233 (renamed, see below)
417 => 'Expectation Failed',
418 => 'I\'m A Teapot', #RFC2324
421 => 'Too Many Connections From This IP',
422 => 'Unprocessable Entity', #WebDAV
423 => 'Locked', #WebDAV
424 => 'Failed Dependency', #WebDAV
425 => 'Unordered Collection', #WebDAV
426 => 'Upgrade Required',
428 => 'Precondition Required', #RFC6585
429 => 'Too Many Requests', #RFC6585
431 => 'Request Header Fields Too Large', #RFC6585
449 => 'Retry With', #Microsoft
450 => 'Blocked By Windows Parental Controls', #Microsoft
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage', #WebDAV
508 => 'Loop Detected', # RFC5842
509 => 'Bandwidth Limit Exceeded', #Apache
510 => 'Not Extended',
511 => 'Network Authentication Required', # RFC6585
}
STATUSES_COMPATIBILITY = {
# The RFCs all specify "Not Found", but "Resource Not Found" was used in
# earlier RestClient releases.
404 => ['ResourceNotFound'],
# HTTP 413 was renamed to "Payload Too Large" in RFC7231.
413 => ['RequestEntityTooLarge'],
# HTTP 414 was renamed to "URI Too Long" in RFC7231.
414 => ['RequestURITooLong'],
# HTTP 416 was renamed to "Range Not Satisfiable" in RFC7233.
416 => ['RequestedRangeNotSatisfiable'],
}
# This is the base RestClient exception class. Rescue it if you want to
# catch any exception that your request might raise
# You can get the status code by e.http_code, or see anything about the
# response via e.response.
# For example, the entire result body (which is
# probably an HTML error page) is e.response.
class Exception < RuntimeError
attr_accessor :response
attr_accessor :original_exception
attr_writer :message
def initialize response = nil, initial_response_code = nil
@response = response
@message = nil
@initial_response_code = initial_response_code
end
def http_code
# return integer for compatibility
if @response
@response.code.to_i
else
@initial_response_code
end
end
def http_headers
@response.headers if @response
end
def http_body
@response.body if @response
end
def to_s
message
end
def message
@message || default_message
end
def default_message
self.class.name
end
end
# Compatibility
class ExceptionWithResponse < RestClient::Exception
end
# The request failed with an error code not managed by the code
class RequestFailed < ExceptionWithResponse
def default_message
"HTTP status code #{http_code}"
end
def to_s
message
end
end
# RestClient exception classes. TODO: move all exceptions into this module.
#
# We will a create an exception for each status code, see
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
#
module Exceptions
# Map http status codes to the corresponding exception class
EXCEPTIONS_MAP = {}
end
# Create HTTP status exception classes
STATUSES.each_pair do |code, message|
klass = Class.new(RequestFailed) do
send(:define_method, :default_message) {"#{http_code ? "#{http_code} " : ''}#{message}"}
end
klass_constant = const_set(message.delete(' \-\''), klass)
Exceptions::EXCEPTIONS_MAP[code] = klass_constant
end
# Create HTTP status exception classes used for backwards compatibility
STATUSES_COMPATIBILITY.each_pair do |code, compat_list|
klass = Exceptions::EXCEPTIONS_MAP.fetch(code)
compat_list.each do |old_name|
const_set(old_name, klass)
end
end
module Exceptions
# We have to split the Exceptions module like we do here because the
# EXCEPTIONS_MAP is under Exceptions, but we depend on
# RestClient::RequestTimeout below.
# Base class for request timeouts.
#
# NB: Previous releases of rest-client would raise RequestTimeout both for
# HTTP 408 responses and for actual connection timeouts.
class Timeout < RestClient::RequestTimeout
def initialize(message=nil, original_exception=nil)
super(nil, nil)
self.message = message if message
self.original_exception = original_exception if original_exception
end
end
# Timeout when connecting to a server. Typically wraps Net::OpenTimeout (in
# ruby 2.0 or greater).
class OpenTimeout < Timeout
def default_message
'Timed out connecting to server'
end
end
# Timeout when reading from a server. Typically wraps Net::ReadTimeout (in
# ruby 2.0 or greater).
class ReadTimeout < Timeout
def default_message
'Timed out reading data from server'
end
end
end
# The server broke the connection prior to the request completing. Usually
# this means it crashed, or sometimes that your network connection was
# severed before it could complete.
class ServerBrokeConnection < RestClient::Exception
def initialize(message = 'Server broke connection')
super nil, nil
self.message = message
end
end
class SSLCertificateNotVerified < RestClient::Exception
def initialize(message = 'SSL certificate not verified')
super nil, nil
self.message = message
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/utils.rb | lib/restclient/utils.rb | require 'http/accept'
module RestClient
# Various utility methods
module Utils
# Return encoding from an HTTP header hash.
#
# We use the RFC 7231 specification and do not impose a default encoding on
# text. This differs from the older RFC 2616 behavior, which specifies
# using ISO-8859-1 for text/* content types without a charset.
#
# Strings will use the default encoding when this method returns nil. This
# default is likely to be UTF-8 for Ruby >= 2.0
#
# @param headers [Hash<Symbol,String>]
#
# @return [String, nil] Return the string encoding or nil if no header is
# found.
#
# @example
# >> get_encoding_from_headers({:content_type => 'text/plain; charset=UTF-8'})
# => "UTF-8"
#
def self.get_encoding_from_headers(headers)
type_header = headers[:content_type]
return nil unless type_header
# TODO: remove this hack once we drop support for Ruby 2.0
if RUBY_VERSION.start_with?('2.0')
_content_type, params = deprecated_cgi_parse_header(type_header)
if params.include?('charset')
return params.fetch('charset').gsub(/(\A["']*)|(["']*\z)/, '')
end
else
begin
_content_type, params = cgi_parse_header(type_header)
rescue HTTP::Accept::ParseError
return nil
else
params['charset']
end
end
end
# Parse a Content-Type like header.
#
# Return the main content-type and a hash of params.
#
# @param [String] line
# @return [Array(String, Hash)]
#
def self.cgi_parse_header(line)
types = HTTP::Accept::MediaTypes.parse(line)
if types.empty?
raise HTTP::Accept::ParseError.new("Found no types in header line")
end
[types.first.mime_type, types.first.parameters]
end
# Parse semi-colon separated, potentially quoted header string iteratively.
#
# @private
#
# @deprecated This method is deprecated and only exists to support Ruby
# 2.0, which is not supported by HTTP::Accept.
#
# @todo remove this method when dropping support for Ruby 2.0
#
def self._cgi_parseparam(s)
return enum_for(__method__, s) unless block_given?
while s[0] == ';'
s = s[1..-1]
ends = s.index(';')
while ends && ends > 0 \
&& (s[0...ends].count('"') -
s[0...ends].scan('\"').count) % 2 != 0
ends = s.index(';', ends + 1)
end
if ends.nil?
ends = s.length
end
f = s[0...ends]
yield f.strip
s = s[ends..-1]
end
nil
end
# Parse a Content-Type like header.
#
# Return the main content-type and a hash of options.
#
# This method was ported directly from Python's cgi.parse_header(). It
# probably doesn't read or perform particularly well in ruby.
# https://github.com/python/cpython/blob/3.4/Lib/cgi.py#L301-L331
#
# @param [String] line
# @return [Array(String, Hash)]
#
# @deprecated This method is deprecated and only exists to support Ruby
# 2.0, which is not supported by HTTP::Accept.
#
# @todo remove this method when dropping support for Ruby 2.0
#
def self.deprecated_cgi_parse_header(line)
parts = _cgi_parseparam(';' + line)
key = parts.next
pdict = {}
begin
while (p = parts.next)
i = p.index('=')
if i
name = p[0...i].strip.downcase
value = p[i+1..-1].strip
if value.length >= 2 && value[0] == '"' && value[-1] == '"'
value = value[1...-1]
value = value.gsub('\\\\', '\\').gsub('\\"', '"')
end
pdict[name] = value
end
end
rescue StopIteration
end
[key, pdict]
end
# Serialize a ruby object into HTTP query string parameters.
#
# There is no standard for doing this, so we choose our own slightly
# idiosyncratic format. The output closely matches the format understood by
# Rails, Rack, and PHP.
#
# If you don't want handling of complex objects and only want to handle
# simple flat hashes, you may want to use `URI.encode_www_form` instead,
# which implements HTML5-compliant URL encoded form data.
#
# @param [Hash,ParamsArray] object The object to serialize
#
# @return [String] A string appropriate for use as an HTTP query string
#
# @see {flatten_params}
#
# @see URI.encode_www_form
#
# @see See also Object#to_query in ActiveSupport
# @see http://php.net/manual/en/function.http-build-query.php
# http_build_query in PHP
# @see See also Rack::Utils.build_nested_query in Rack
#
# Notable differences from the ActiveSupport implementation:
#
# - Empty hash and empty array are treated the same as nil instead of being
# omitted entirely from the output. Rather than disappearing, they will
# appear to be nil instead.
#
# It's most common to pass a Hash as the object to serialize, but you can
# also use a ParamsArray if you want to be able to pass the same key with
# multiple values and not use the rack/rails array convention.
#
# @since 2.0.0
#
# @example Simple hashes
# >> encode_query_string({foo: 123, bar: 456})
# => 'foo=123&bar=456'
#
# @example Simple arrays
# >> encode_query_string({foo: [1,2,3]})
# => 'foo[]=1&foo[]=2&foo[]=3'
#
# @example Nested hashes
# >> encode_query_string({outer: {foo: 123, bar: 456}})
# => 'outer[foo]=123&outer[bar]=456'
#
# @example Deeply nesting
# >> encode_query_string({coords: [{x: 1, y: 0}, {x: 2}, {x: 3}]})
# => 'coords[][x]=1&coords[][y]=0&coords[][x]=2&coords[][x]=3'
#
# @example Null and empty values
# >> encode_query_string({string: '', empty: nil, list: [], hash: {}})
# => 'string=&empty&list&hash'
#
# @example Nested nulls
# >> encode_query_string({foo: {string: '', empty: nil}})
# => 'foo[string]=&foo[empty]'
#
# @example Multiple fields with the same name using ParamsArray
# >> encode_query_string(RestClient::ParamsArray.new([[:foo, 1], [:foo, 2], [:foo, 3]]))
# => 'foo=1&foo=2&foo=3'
#
# @example Nested ParamsArray
# >> encode_query_string({foo: RestClient::ParamsArray.new([[:a, 1], [:a, 2]])})
# => 'foo[a]=1&foo[a]=2'
#
# >> encode_query_string(RestClient::ParamsArray.new([[:foo, {a: 1}], [:foo, {a: 2}]]))
# => 'foo[a]=1&foo[a]=2'
#
def self.encode_query_string(object)
flatten_params(object, true).map {|k, v| v.nil? ? k : "#{k}=#{v}" }.join('&')
end
# Transform deeply nested param containers into a flat array of [key,
# value] pairs.
#
# @example
# >> flatten_params({key1: {key2: 123}})
# => [["key1[key2]", 123]]
#
# @example
# >> flatten_params({key1: {key2: 123, arr: [1,2,3]}})
# => [["key1[key2]", 123], ["key1[arr][]", 1], ["key1[arr][]", 2], ["key1[arr][]", 3]]
#
# @param object [Hash, ParamsArray] The container to flatten
# @param uri_escape [Boolean] Whether to URI escape keys and values
# @param parent_key [String] Should not be passed (used for recursion)
#
def self.flatten_params(object, uri_escape=false, parent_key=nil)
unless object.is_a?(Hash) || object.is_a?(ParamsArray) ||
(parent_key && object.is_a?(Array))
raise ArgumentError.new('expected Hash or ParamsArray, got: ' + object.inspect)
end
# transform empty collections into nil, where possible
if object.empty? && parent_key
return [[parent_key, nil]]
end
# This is essentially .map(), but we need to do += for nested containers
object.reduce([]) { |result, item|
if object.is_a?(Array)
# item is already the value
k = nil
v = item
else
# item is a key, value pair
k, v = item
k = escape(k.to_s) if uri_escape
end
processed_key = parent_key ? "#{parent_key}[#{k}]" : k
case v
when Array, Hash, ParamsArray
result.concat flatten_params(v, uri_escape, processed_key)
else
v = escape(v.to_s) if uri_escape && v
result << [processed_key, v]
end
}
end
# Encode string for safe transport by URI or form encoding. This uses a CGI
# style escape, which transforms ` ` into `+` and various special
# characters into percent encoded forms.
#
# This calls URI.encode_www_form_component for the implementation. The only
# difference between this and CGI.escape is that it does not escape `*`.
# http://stackoverflow.com/questions/25085992/
#
# @see URI.encode_www_form_component
#
def self.escape(string)
URI.encode_www_form_component(string)
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/response.rb | lib/restclient/response.rb | module RestClient
# A Response from RestClient, you can access the response body, the code or the headers.
#
class Response < String
include AbstractResponse
# Return the HTTP response body.
#
# Future versions of RestClient will deprecate treating response objects
# directly as strings, so it will be necessary to call `.body`.
#
# @return [String]
#
def body
# Benchmarking suggests that "#{self}" is fastest, and that caching the
# body string in an instance variable doesn't make it enough faster to be
# worth the extra memory storage.
String.new(self)
end
# Convert the HTTP response body to a pure String object.
#
# @return [String]
def to_s
body
end
# Convert the HTTP response body to a pure String object.
#
# @return [String]
def to_str
body
end
def inspect
"<RestClient::Response #{code.inspect} #{body_truncated(10).inspect}>"
end
# Initialize a Response object. Because RestClient::Response is
# (unfortunately) a subclass of String for historical reasons,
# Response.create is the preferred initializer.
#
# @param [String, nil] body The response body from the Net::HTTPResponse
# @param [Net::HTTPResponse] net_http_res
# @param [RestClient::Request] request
# @param [Time] start_time
def self.create(body, net_http_res, request, start_time=nil)
result = self.new(body || '')
result.response_set_vars(net_http_res, request, start_time)
fix_encoding(result)
result
end
# Set the String encoding according to the 'Content-Type: charset' header,
# if possible.
def self.fix_encoding(response)
charset = RestClient::Utils.get_encoding_from_headers(response.headers)
encoding = nil
begin
encoding = Encoding.find(charset) if charset
rescue ArgumentError
if response.log
response.log << "No such encoding: #{charset.inspect}"
end
end
return unless encoding
response.force_encoding(encoding)
response
end
private
def body_truncated(length)
b = body
if b.length > length
b[0..length] + '...'
else
b
end
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/abstract_response.rb | lib/restclient/abstract_response.rb | require 'cgi'
require 'http-cookie'
module RestClient
module AbstractResponse
attr_reader :net_http_res, :request, :start_time, :end_time, :duration
def inspect
raise NotImplementedError.new('must override in subclass')
end
# Logger from the request, potentially nil.
def log
request.log
end
def log_response
return unless log
code = net_http_res.code
res_name = net_http_res.class.to_s.gsub(/\ANet::HTTP/, '')
content_type = (net_http_res['Content-type'] || '').gsub(/;.*\z/, '')
log << "# => #{code} #{res_name} | #{content_type} #{size} bytes, #{sprintf('%.2f', duration)}s\n"
end
# HTTP status code
def code
@code ||= @net_http_res.code.to_i
end
def history
@history ||= request.redirection_history || []
end
# A hash of the headers, beautified with symbols and underscores.
# e.g. "Content-type" will become :content_type.
def headers
@headers ||= AbstractResponse.beautify_headers(@net_http_res.to_hash)
end
# The raw headers.
def raw_headers
@raw_headers ||= @net_http_res.to_hash
end
# @param [Net::HTTPResponse] net_http_res
# @param [RestClient::Request] request
# @param [Time] start_time
def response_set_vars(net_http_res, request, start_time)
@net_http_res = net_http_res
@request = request
@start_time = start_time
@end_time = Time.now
if @start_time
@duration = @end_time - @start_time
else
@duration = nil
end
# prime redirection history
history
end
# Hash of cookies extracted from response headers.
#
# NB: This will return only cookies whose domain matches this request, and
# may not even return all of those cookies if there are duplicate names.
# Use the full cookie_jar for more nuanced access.
#
# @see #cookie_jar
#
# @return [Hash]
#
def cookies
hash = {}
cookie_jar.cookies(@request.uri).each do |cookie|
hash[cookie.name] = cookie.value
end
hash
end
# Cookie jar extracted from response headers.
#
# @return [HTTP::CookieJar]
#
def cookie_jar
return @cookie_jar if defined?(@cookie_jar) && @cookie_jar
jar = @request.cookie_jar.dup
headers.fetch(:set_cookie, []).each do |cookie|
jar.parse(cookie, @request.uri)
end
@cookie_jar = jar
end
# Return the default behavior corresponding to the response code:
#
# For 20x status codes: return the response itself
#
# For 30x status codes:
# 301, 302, 307: redirect GET / HEAD if there is a Location header
# 303: redirect, changing method to GET, if there is a Location header
#
# For all other responses, raise a response exception
#
def return!(&block)
case code
when 200..207
self
when 301, 302, 307
case request.method
when 'get', 'head'
check_max_redirects
follow_redirection(&block)
else
raise exception_with_response
end
when 303
check_max_redirects
follow_get_redirection(&block)
else
raise exception_with_response
end
end
def to_i
warn('warning: calling Response#to_i is not recommended')
super
end
def description
"#{code} #{STATUSES[code]} | #{(headers[:content_type] || '').gsub(/;.*$/, '')} #{size} bytes\n"
end
# Follow a redirection response by making a new HTTP request to the
# redirection target.
def follow_redirection(&block)
_follow_redirection(request.args.dup, &block)
end
# Follow a redirection response, but change the HTTP method to GET and drop
# the payload from the original request.
def follow_get_redirection(&block)
new_args = request.args.dup
new_args[:method] = :get
new_args.delete(:payload)
_follow_redirection(new_args, &block)
end
# Convert headers hash into canonical form.
#
# Header names will be converted to lowercase symbols with underscores
# instead of hyphens.
#
# Headers specified multiple times will be joined by comma and space,
# except for Set-Cookie, which will always be an array.
#
# Per RFC 2616, if a server sends multiple headers with the same key, they
# MUST be able to be joined into a single header by a comma. However,
# Set-Cookie (RFC 6265) cannot because commas are valid within cookie
# definitions. The newer RFC 7230 notes (3.2.2) that Set-Cookie should be
# handled as a special case.
#
# http://tools.ietf.org/html/rfc2616#section-4.2
# http://tools.ietf.org/html/rfc7230#section-3.2.2
# http://tools.ietf.org/html/rfc6265
#
# @param headers [Hash]
# @return [Hash]
#
def self.beautify_headers(headers)
headers.inject({}) do |out, (key, value)|
key_sym = key.tr('-', '_').downcase.to_sym
# Handle Set-Cookie specially since it cannot be joined by comma.
if key.downcase == 'set-cookie'
out[key_sym] = value
else
out[key_sym] = value.join(', ')
end
out
end
end
private
# Follow a redirection
#
# @param new_args [Hash] Start with this hash of arguments for the
# redirection request. The hash will be mutated, so be sure to dup any
# existing hash that should not be modified.
#
def _follow_redirection(new_args, &block)
# parse location header and merge into existing URL
url = headers[:location]
# cannot follow redirection if there is no location header
unless url
raise exception_with_response
end
# handle relative redirects
unless url.start_with?('http')
url = URI.parse(request.url).merge(url).to_s
end
new_args[:url] = url
new_args[:password] = request.password
new_args[:user] = request.user
new_args[:headers] = request.headers
new_args[:max_redirects] = request.max_redirects - 1
# pass through our new cookie jar
new_args[:cookies] = cookie_jar
# prepare new request
new_req = Request.new(new_args)
# append self to redirection history
new_req.redirection_history = history + [self]
# execute redirected request
new_req.execute(&block)
end
def check_max_redirects
if request.max_redirects <= 0
raise exception_with_response
end
end
def exception_with_response
begin
klass = Exceptions::EXCEPTIONS_MAP.fetch(code)
rescue KeyError
raise RequestFailed.new(self, code)
end
raise klass.new(self, code)
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/params_array.rb | lib/restclient/params_array.rb | module RestClient
# The ParamsArray class is used to represent an ordered list of [key, value]
# pairs. Use this when you need to include a key multiple times or want
# explicit control over parameter ordering.
#
# Most of the request payload & parameter functions normally accept a Hash of
# keys => values, which does not allow for duplicated keys.
#
# @see RestClient::Utils.encode_query_string
# @see RestClient::Utils.flatten_params
#
class ParamsArray
include Enumerable
# @param array [Array<Array>] An array of parameter key,value pairs. These
# pairs may be 2 element arrays [key, value] or single element hashes
# {key => value}. They may also be single element arrays to represent a
# key with no value.
#
# @example
# >> ParamsArray.new([[:foo, 123], [:foo, 456], [:bar, 789]])
# This will be encoded as "foo=123&foo=456&bar=789"
#
# @example
# >> ParamsArray.new({foo: 123, bar: 456})
# This is valid, but there's no reason not to just use the Hash directly
# instead of a ParamsArray.
#
#
def initialize(array)
@array = process_input(array)
end
def each(*args, &blk)
@array.each(*args, &blk)
end
def empty?
@array.empty?
end
private
def process_input(array)
array.map {|v| process_pair(v) }
end
# A pair may be:
# - A single element hash, e.g. {foo: 'bar'}
# - A two element array, e.g. ['foo', 'bar']
# - A one element array, e.g. ['foo']
#
def process_pair(pair)
case pair
when Hash
if pair.length != 1
raise ArgumentError.new("Bad # of fields for pair: #{pair.inspect}")
end
pair.to_a.fetch(0)
when Array
if pair.length > 2
raise ArgumentError.new("Bad # of fields for pair: #{pair.inspect}")
end
[pair.fetch(0), pair[1]]
else
# recurse, converting any non-array to an array
process_pair(pair.to_a)
end
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/request.rb | lib/restclient/request.rb | require 'tempfile'
require 'cgi'
require 'netrc'
require 'set'
begin
# Use mime/types/columnar if available, for reduced memory usage
require 'mime/types/columnar'
rescue LoadError
require 'mime/types'
end
module RestClient
# This class is used internally by RestClient to send the request, but you can also
# call it directly if you'd like to use a method not supported by the
# main API. For example:
#
# RestClient::Request.execute(:method => :head, :url => 'http://example.com')
#
# Mandatory parameters:
# * :method
# * :url
# Optional parameters (have a look at ssl and/or uri for some explanations):
# * :headers a hash containing the request headers
# * :cookies may be a Hash{String/Symbol => String} of cookie values, an
# Array<HTTP::Cookie>, or an HTTP::CookieJar containing cookies. These
# will be added to a cookie jar before the request is sent.
# * :user and :password for basic auth, will be replaced by a user/password available in the :url
# * :block_response call the provided block with the HTTPResponse as parameter
# * :raw_response return a low-level RawResponse instead of a Response
# * :log Set the log for this request only, overriding RestClient.log, if
# any.
# * :stream_log_percent (Only relevant with :raw_response => true) Customize
# the interval at which download progress is logged. Defaults to every
# 10% complete.
# * :max_redirects maximum number of redirections (default to 10)
# * :proxy An HTTP proxy URI to use for this request. Any value here
# (including nil) will override RestClient.proxy.
# * :verify_ssl enable ssl verification, possible values are constants from
# OpenSSL::SSL::VERIFY_*, defaults to OpenSSL::SSL::VERIFY_PEER
# * :read_timeout and :open_timeout are how long to wait for a response and
# to open a connection, in seconds. Pass nil to disable the timeout.
# * :timeout can be used to set both timeouts
# * :ssl_client_cert, :ssl_client_key, :ssl_ca_file, :ssl_ca_path,
# :ssl_cert_store, :ssl_verify_callback, :ssl_verify_callback_warnings
# * :ssl_version specifies the SSL version for the underlying Net::HTTP connection
# * :ssl_ciphers sets SSL ciphers for the connection. See
# OpenSSL::SSL::SSLContext#ciphers=
# * :before_execution_proc a Proc to call before executing the request. This
# proc, like procs from RestClient.before_execution_procs, will be
# called with the HTTP request and request params.
class Request
attr_reader :method, :uri, :url, :headers, :payload, :proxy,
:user, :password, :read_timeout, :max_redirects,
:open_timeout, :raw_response, :processed_headers, :args,
:ssl_opts
# An array of previous redirection responses
attr_accessor :redirection_history
def self.execute(args, & block)
new(args).execute(& block)
end
SSLOptionList = %w{client_cert client_key ca_file ca_path cert_store
version ciphers verify_callback verify_callback_warnings}
def inspect
"<RestClient::Request @method=#{@method.inspect}, @url=#{@url.inspect}>"
end
def initialize args
@method = normalize_method(args[:method])
@headers = (args[:headers] || {}).dup
if args[:url]
@url = process_url_params(normalize_url(args[:url]), headers)
else
raise ArgumentError, "must pass :url"
end
@user = @password = nil
parse_url_with_auth!(url)
# process cookie arguments found in headers or args
@cookie_jar = process_cookie_args!(@uri, @headers, args)
@payload = Payload.generate(args[:payload])
@user = args[:user] if args.include?(:user)
@password = args[:password] if args.include?(:password)
if args.include?(:timeout)
@read_timeout = args[:timeout]
@open_timeout = args[:timeout]
end
if args.include?(:read_timeout)
@read_timeout = args[:read_timeout]
end
if args.include?(:open_timeout)
@open_timeout = args[:open_timeout]
end
@block_response = args[:block_response]
@raw_response = args[:raw_response] || false
@stream_log_percent = args[:stream_log_percent] || 10
if @stream_log_percent <= 0 || @stream_log_percent > 100
raise ArgumentError.new(
"Invalid :stream_log_percent #{@stream_log_percent.inspect}")
end
@proxy = args.fetch(:proxy) if args.include?(:proxy)
@ssl_opts = {}
if args.include?(:verify_ssl)
v_ssl = args.fetch(:verify_ssl)
if v_ssl
if v_ssl == true
# interpret :verify_ssl => true as VERIFY_PEER
@ssl_opts[:verify_ssl] = OpenSSL::SSL::VERIFY_PEER
else
# otherwise pass through any truthy values
@ssl_opts[:verify_ssl] = v_ssl
end
else
# interpret all falsy :verify_ssl values as VERIFY_NONE
@ssl_opts[:verify_ssl] = OpenSSL::SSL::VERIFY_NONE
end
else
# if :verify_ssl was not passed, default to VERIFY_PEER
@ssl_opts[:verify_ssl] = OpenSSL::SSL::VERIFY_PEER
end
SSLOptionList.each do |key|
source_key = ('ssl_' + key).to_sym
if args.has_key?(source_key)
@ssl_opts[key.to_sym] = args.fetch(source_key)
end
end
# Set some other default SSL options, but only if we have an HTTPS URI.
if use_ssl?
# If there's no CA file, CA path, or cert store provided, use default
if !ssl_ca_file && !ssl_ca_path && !@ssl_opts.include?(:cert_store)
@ssl_opts[:cert_store] = self.class.default_ssl_cert_store
end
end
@log = args[:log]
@max_redirects = args[:max_redirects] || 10
@processed_headers = make_headers headers
@processed_headers_lowercase = Hash[@processed_headers.map {|k, v| [k.downcase, v]}]
@args = args
@before_execution_proc = args[:before_execution_proc]
end
def execute & block
# With 2.0.0+, net/http accepts URI objects in requests and handles wrapping
# IPv6 addresses in [] for use in the Host request header.
transmit uri, net_http_request_class(method).new(uri, processed_headers), payload, & block
ensure
payload.close if payload
end
# SSL-related options
def verify_ssl
@ssl_opts.fetch(:verify_ssl)
end
SSLOptionList.each do |key|
define_method('ssl_' + key) do
@ssl_opts[key.to_sym]
end
end
# Return true if the request URI will use HTTPS.
#
# @return [Boolean]
#
def use_ssl?
uri.is_a?(URI::HTTPS)
end
# Extract the query parameters and append them to the url
#
# Look through the headers hash for a :params option (case-insensitive,
# may be string or symbol). If present and the value is a Hash or
# RestClient::ParamsArray, *delete* the key/value pair from the headers
# hash and encode the value into a query string. Append this query string
# to the URL and return the resulting URL.
#
# @param [String] url
# @param [Hash] headers An options/headers hash to process. Mutation
# warning: the params key may be removed if present!
#
# @return [String] resulting url with query string
#
def process_url_params(url, headers)
url_params = nil
# find and extract/remove "params" key if the value is a Hash/ParamsArray
headers.delete_if do |key, value|
if key.to_s.downcase == 'params' &&
(value.is_a?(Hash) || value.is_a?(RestClient::ParamsArray))
if url_params
raise ArgumentError.new("Multiple 'params' options passed")
end
url_params = value
true
else
false
end
end
# build resulting URL with query string
if url_params && !url_params.empty?
query_string = RestClient::Utils.encode_query_string(url_params)
if url.include?('?')
url + '&' + query_string
else
url + '?' + query_string
end
else
url
end
end
# Render a hash of key => value pairs for cookies in the Request#cookie_jar
# that are valid for the Request#uri. This will not necessarily include all
# cookies if there are duplicate keys. It's safer to use the cookie_jar
# directly if that's a concern.
#
# @see Request#cookie_jar
#
# @return [Hash]
#
def cookies
hash = {}
@cookie_jar.cookies(uri).each do |c|
hash[c.name] = c.value
end
hash
end
# @return [HTTP::CookieJar]
def cookie_jar
@cookie_jar
end
# Render a Cookie HTTP request header from the contents of the @cookie_jar,
# or nil if the jar is empty.
#
# @see Request#cookie_jar
#
# @return [String, nil]
#
def make_cookie_header
return nil if cookie_jar.nil?
arr = cookie_jar.cookies(url)
return nil if arr.empty?
return HTTP::Cookie.cookie_value(arr)
end
# Process cookies passed as hash or as HTTP::CookieJar. For backwards
# compatibility, these may be passed as a :cookies option masquerading
# inside the headers hash. To avoid confusion, if :cookies is passed in
# both headers and Request#initialize, raise an error.
#
# :cookies may be a:
# - Hash{String/Symbol => String}
# - Array<HTTP::Cookie>
# - HTTP::CookieJar
#
# Passing as a hash:
# Keys may be symbols or strings. Values must be strings.
# Infer the domain name from the request URI and allow subdomains (as
# though '.example.com' had been set in a Set-Cookie header). Assume a
# path of '/'.
#
# RestClient::Request.new(url: 'http://example.com', method: :get,
# :cookies => {:foo => 'Value', 'bar' => '123'}
# )
#
# results in cookies as though set from the server by:
# Set-Cookie: foo=Value; Domain=.example.com; Path=/
# Set-Cookie: bar=123; Domain=.example.com; Path=/
#
# which yields a client cookie header of:
# Cookie: foo=Value; bar=123
#
# Passing as HTTP::CookieJar, which will be passed through directly:
#
# jar = HTTP::CookieJar.new
# jar.add(HTTP::Cookie.new('foo', 'Value', domain: 'example.com',
# path: '/', for_domain: false))
#
# RestClient::Request.new(..., :cookies => jar)
#
# @param [URI::HTTP] uri The URI for the request. This will be used to
# infer the domain name for cookies passed as strings in a hash. To avoid
# this implicit behavior, pass a full cookie jar or use HTTP::Cookie hash
# values.
# @param [Hash] headers The headers hash from which to pull the :cookies
# option. MUTATION NOTE: This key will be deleted from the hash if
# present.
# @param [Hash] args The options passed to Request#initialize. This hash
# will be used as another potential source for the :cookies key.
# These args will not be mutated.
#
# @return [HTTP::CookieJar] A cookie jar containing the parsed cookies.
#
def process_cookie_args!(uri, headers, args)
# Avoid ambiguity in whether options from headers or options from
# Request#initialize should take precedence by raising ArgumentError when
# both are present. Prior versions of rest-client claimed to give
# precedence to init options, but actually gave precedence to headers.
# Avoid that mess by erroring out instead.
if headers[:cookies] && args[:cookies]
raise ArgumentError.new(
"Cannot pass :cookies in Request.new() and in headers hash")
end
cookies_data = headers.delete(:cookies) || args[:cookies]
# return copy of cookie jar as is
if cookies_data.is_a?(HTTP::CookieJar)
return cookies_data.dup
end
# convert cookies hash into a CookieJar
jar = HTTP::CookieJar.new
(cookies_data || []).each do |key, val|
# Support for Array<HTTP::Cookie> mode:
# If key is a cookie object, add it to the jar directly and assert that
# there is no separate val.
if key.is_a?(HTTP::Cookie)
if val
raise ArgumentError.new("extra cookie val: #{val.inspect}")
end
jar.add(key)
next
end
if key.is_a?(Symbol)
key = key.to_s
end
# assume implicit domain from the request URI, and set for_domain to
# permit subdomains
jar.add(HTTP::Cookie.new(key, val, domain: uri.hostname.downcase,
path: '/', for_domain: true))
end
jar
end
# Generate headers for use by a request. Header keys will be stringified
# using `#stringify_headers` to normalize them as capitalized strings.
#
# The final headers consist of:
# - default headers from #default_headers
# - user_headers provided here
# - headers from the payload object (e.g. Content-Type, Content-Lenth)
# - cookie headers from #make_cookie_header
#
# BUG: stringify_headers does not alter the capitalization of headers that
# are passed as strings, it only normalizes those passed as symbols. This
# behavior will probably remain for a while for compatibility, but it means
# that the warnings that attempt to detect accidental header overrides may
# not always work.
# https://github.com/rest-client/rest-client/issues/599
#
# @param [Hash] user_headers User-provided headers to include
#
# @return [Hash<String, String>] A hash of HTTP headers => values
#
def make_headers(user_headers)
headers = stringify_headers(default_headers).merge(stringify_headers(user_headers))
# override headers from the payload (e.g. Content-Type, Content-Length)
if @payload
payload_headers = @payload.headers
# Warn the user if we override any headers that were previously
# present. This usually indicates that rest-client was passed
# conflicting information, e.g. if it was asked to render a payload as
# x-www-form-urlencoded but a Content-Type application/json was
# also supplied by the user.
payload_headers.each_pair do |key, val|
if headers.include?(key) && headers[key] != val
warn("warning: Overriding #{key.inspect} header " +
"#{headers.fetch(key).inspect} with #{val.inspect} " +
"due to payload")
end
end
headers.merge!(payload_headers)
end
# merge in cookies
cookies = make_cookie_header
if cookies && !cookies.empty?
if headers['Cookie']
warn('warning: overriding "Cookie" header with :cookies option')
end
headers['Cookie'] = cookies
end
headers
end
# The proxy URI for this request. If `:proxy` was provided on this request,
# use it over `RestClient.proxy`.
#
# Return false if a proxy was explicitly set and is falsy.
#
# @return [URI, false, nil]
#
def proxy_uri
if defined?(@proxy)
if @proxy
URI.parse(@proxy)
else
false
end
elsif RestClient.proxy_set?
if RestClient.proxy
URI.parse(RestClient.proxy)
else
false
end
else
nil
end
end
def net_http_object(hostname, port)
p_uri = proxy_uri
if p_uri.nil?
# no proxy set
Net::HTTP.new(hostname, port)
elsif !p_uri
# proxy explicitly set to none
Net::HTTP.new(hostname, port, nil, nil, nil, nil)
else
Net::HTTP.new(hostname, port,
p_uri.hostname, p_uri.port, p_uri.user, p_uri.password)
end
end
def net_http_request_class(method)
Net::HTTP.const_get(method.capitalize, false)
end
def net_http_do_request(http, req, body=nil, &block)
if body && body.respond_to?(:read)
req.body_stream = body
return http.request(req, nil, &block)
else
return http.request(req, body, &block)
end
end
# Normalize a URL by adding a protocol if none is present.
#
# If the string has no HTTP-like scheme (i.e. scheme followed by '//'), a
# scheme of 'http' will be added. This mimics the behavior of browsers and
# user agents like cURL.
#
# @param [String] url A URL string.
#
# @return [String]
#
def normalize_url(url)
url = 'http://' + url unless url.match(%r{\A[a-z][a-z0-9+.-]*://}i)
url
end
# Return a certificate store that can be used to validate certificates with
# the system certificate authorities. This will probably not do anything on
# OS X, which monkey patches OpenSSL in terrible ways to insert its own
# validation. On most *nix platforms, this will add the system certifcates
# using OpenSSL::X509::Store#set_default_paths. On Windows, this will use
# RestClient::Windows::RootCerts to look up the CAs trusted by the system.
#
# @return [OpenSSL::X509::Store]
#
def self.default_ssl_cert_store
cert_store = OpenSSL::X509::Store.new
cert_store.set_default_paths
# set_default_paths() doesn't do anything on Windows, so look up
# certificates using the win32 API.
if RestClient::Platform.windows?
RestClient::Windows::RootCerts.instance.to_a.uniq.each do |cert|
begin
cert_store.add_cert(cert)
rescue OpenSSL::X509::StoreError => err
# ignore duplicate certs
raise unless err.message == 'cert already in hash table'
end
end
end
cert_store
end
def redacted_uri
if uri.password
sanitized_uri = uri.dup
sanitized_uri.password = 'REDACTED'
sanitized_uri
else
uri
end
end
def redacted_url
redacted_uri.to_s
end
# Default to the global logger if there's not a request-specific one
def log
@log || RestClient.log
end
def log_request
return unless log
out = []
out << "RestClient.#{method} #{redacted_url.inspect}"
out << payload.short_inspect if payload
out << processed_headers.to_a.sort.map { |(k, v)| [k.inspect, v.inspect].join("=>") }.join(", ")
log << out.join(', ') + "\n"
end
# Return a hash of headers whose keys are capitalized strings
#
# BUG: stringify_headers does not fix the capitalization of headers that
# are already Strings. Leaving this behavior as is for now for
# backwards compatibility.
# https://github.com/rest-client/rest-client/issues/599
#
def stringify_headers headers
headers.inject({}) do |result, (key, value)|
if key.is_a? Symbol
key = key.to_s.split(/_/).map(&:capitalize).join('-')
end
if 'CONTENT-TYPE' == key.upcase
result[key] = maybe_convert_extension(value.to_s)
elsif 'ACCEPT' == key.upcase
# Accept can be composed of several comma-separated values
if value.is_a? Array
target_values = value
else
target_values = value.to_s.split ','
end
result[key] = target_values.map { |ext|
maybe_convert_extension(ext.to_s.strip)
}.join(', ')
else
result[key] = value.to_s
end
result
end
end
# Default headers set by RestClient. In addition to these headers, servers
# will receive headers set by Net::HTTP, such as Accept-Encoding and Host.
#
# @return [Hash<Symbol, String>]
def default_headers
{
:accept => '*/*',
:user_agent => RestClient::Platform.default_user_agent,
}
end
private
# Parse the `@url` string into a URI object and save it as
# `@uri`. Also save any basic auth user or password as @user and @password.
# If no auth info was passed, check for credentials in a Netrc file.
#
# @param [String] url A URL string.
#
# @return [URI]
#
# @raise URI::InvalidURIError on invalid URIs
#
def parse_url_with_auth!(url)
uri = URI.parse(url)
if uri.hostname.nil?
raise URI::InvalidURIError.new("bad URI(no host provided): #{url}")
end
@user = CGI.unescape(uri.user) if uri.user
@password = CGI.unescape(uri.password) if uri.password
if !@user && !@password
@user, @password = Netrc.read[uri.hostname]
end
@uri = uri
end
def print_verify_callback_warnings
warned = false
if RestClient::Platform.mac_mri?
warn('warning: ssl_verify_callback return code is ignored on OS X')
warned = true
end
if RestClient::Platform.jruby?
warn('warning: SSL verify_callback may not work correctly in jruby')
warn('see https://github.com/jruby/jruby/issues/597')
warned = true
end
warned
end
# Parse a method and return a normalized string version.
#
# Raise ArgumentError if the method is falsy, but otherwise do no
# validation.
#
# @param method [String, Symbol]
#
# @return [String]
#
# @see net_http_request_class
#
def normalize_method(method)
raise ArgumentError.new('must pass :method') unless method
method.to_s.downcase
end
def transmit uri, req, payload, & block
# We set this to true in the net/http block so that we can distinguish
# read_timeout from open_timeout. Now that we only support Ruby 2.0+,
# this is only needed for Timeout exceptions thrown outside of Net::HTTP.
established_connection = false
setup_credentials req
net = net_http_object(uri.hostname, uri.port)
net.use_ssl = uri.is_a?(URI::HTTPS)
net.ssl_version = ssl_version if ssl_version
net.ciphers = ssl_ciphers if ssl_ciphers
net.verify_mode = verify_ssl
net.cert = ssl_client_cert if ssl_client_cert
net.key = ssl_client_key if ssl_client_key
net.ca_file = ssl_ca_file if ssl_ca_file
net.ca_path = ssl_ca_path if ssl_ca_path
net.cert_store = ssl_cert_store if ssl_cert_store
# We no longer rely on net.verify_callback for the main SSL verification
# because it's not well supported on all platforms (see comments below).
# But do allow users to set one if they want.
if ssl_verify_callback
net.verify_callback = ssl_verify_callback
# Hilariously, jruby only calls the callback when cert_store is set to
# something, so make sure to set one.
# https://github.com/jruby/jruby/issues/597
if RestClient::Platform.jruby?
net.cert_store ||= OpenSSL::X509::Store.new
end
if ssl_verify_callback_warnings != false
if print_verify_callback_warnings
warn('pass :ssl_verify_callback_warnings => false to silence this')
end
end
end
if OpenSSL::SSL::VERIFY_PEER == OpenSSL::SSL::VERIFY_NONE
warn('WARNING: OpenSSL::SSL::VERIFY_PEER == OpenSSL::SSL::VERIFY_NONE')
warn('This dangerous monkey patch leaves you open to MITM attacks!')
warn('Try passing :verify_ssl => false instead.')
end
if defined? @read_timeout
if @read_timeout == -1
warn 'Deprecated: to disable timeouts, please use nil instead of -1'
@read_timeout = nil
end
net.read_timeout = @read_timeout
end
if defined? @open_timeout
if @open_timeout == -1
warn 'Deprecated: to disable timeouts, please use nil instead of -1'
@open_timeout = nil
end
net.open_timeout = @open_timeout
end
RestClient.before_execution_procs.each do |before_proc|
before_proc.call(req, args)
end
if @before_execution_proc
@before_execution_proc.call(req, args)
end
log_request
start_time = Time.now
tempfile = nil
net.start do |http|
established_connection = true
if @block_response
net_http_do_request(http, req, payload, &@block_response)
else
res = net_http_do_request(http, req, payload) { |http_response|
if @raw_response
# fetch body into tempfile
tempfile = fetch_body_to_tempfile(http_response)
else
# fetch body
http_response.read_body
end
http_response
}
process_result(res, start_time, tempfile, &block)
end
end
rescue EOFError
raise RestClient::ServerBrokeConnection
rescue Net::OpenTimeout => err
raise RestClient::Exceptions::OpenTimeout.new(nil, err)
rescue Net::ReadTimeout => err
raise RestClient::Exceptions::ReadTimeout.new(nil, err)
rescue Timeout::Error, Errno::ETIMEDOUT => err
# handling for non-Net::HTTP timeouts
if established_connection
raise RestClient::Exceptions::ReadTimeout.new(nil, err)
else
raise RestClient::Exceptions::OpenTimeout.new(nil, err)
end
rescue OpenSSL::SSL::SSLError => error
# TODO: deprecate and remove RestClient::SSLCertificateNotVerified and just
# pass through OpenSSL::SSL::SSLError directly.
#
# Exceptions in verify_callback are ignored [1], and jruby doesn't support
# it at all [2]. RestClient has to catch OpenSSL::SSL::SSLError and either
# re-throw it as is, or throw SSLCertificateNotVerified based on the
# contents of the message field of the original exception.
#
# The client has to handle OpenSSL::SSL::SSLError exceptions anyway, so
# we shouldn't make them handle both OpenSSL and RestClient exceptions.
#
# [1] https://github.com/ruby/ruby/blob/89e70fe8e7/ext/openssl/ossl.c#L238
# [2] https://github.com/jruby/jruby/issues/597
if error.message.include?("certificate verify failed")
raise SSLCertificateNotVerified.new(error.message)
else
raise error
end
end
def setup_credentials(req)
if user && !@processed_headers_lowercase.include?('authorization')
req.basic_auth(user, password)
end
end
def fetch_body_to_tempfile(http_response)
# Taken from Chef, which as in turn...
# Stolen from http://www.ruby-forum.com/topic/166423
# Kudos to _why!
tf = Tempfile.new('rest-client.')
tf.binmode
size = 0
total = http_response['Content-Length'].to_i
stream_log_bucket = nil
http_response.read_body do |chunk|
tf.write chunk
size += chunk.size
if log
if total == 0
log << "streaming %s %s (%d of unknown) [0 Content-Length]\n" % [@method.upcase, @url, size]
else
percent = (size * 100) / total
current_log_bucket, _ = percent.divmod(@stream_log_percent)
if current_log_bucket != stream_log_bucket
stream_log_bucket = current_log_bucket
log << "streaming %s %s %d%% done (%d of %d)\n" % [@method.upcase, @url, (size * 100) / total, size, total]
end
end
end
end
tf.close
tf
end
# @param res The Net::HTTP response object
# @param start_time [Time] Time of request start
def process_result(res, start_time, tempfile=nil, &block)
if @raw_response
unless tempfile
raise ArgumentError.new('tempfile is required')
end
response = RawResponse.new(tempfile, res, self, start_time)
else
response = Response.create(res.body, res, self, start_time)
end
response.log_response
if block_given?
block.call(response, self, res, & block)
else
response.return!(&block)
end
end
def parser
URI.const_defined?(:Parser) ? URI::Parser.new : URI
end
# Given a MIME type or file extension, return either a MIME type or, if
# none is found, the input unchanged.
#
# >> maybe_convert_extension('json')
# => 'application/json'
#
# >> maybe_convert_extension('unknown')
# => 'unknown'
#
# >> maybe_convert_extension('application/xml')
# => 'application/xml'
#
# @param ext [String]
#
# @return [String]
#
def maybe_convert_extension(ext)
unless ext =~ /\A[a-zA-Z0-9_@-]+\z/
# Don't look up strings unless they look like they could be a file
# extension known to mime-types.
#
# There currently isn't any API public way to look up extensions
# directly out of MIME::Types, but the type_for() method only strips
# off after a period anyway.
return ext
end
types = MIME::Types.type_for(ext)
if types.empty?
ext
else
types.first.content_type
end
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/payload.rb | lib/restclient/payload.rb | require 'tempfile'
require 'securerandom'
require 'stringio'
begin
# Use mime/types/columnar if available, for reduced memory usage
require 'mime/types/columnar'
rescue LoadError
require 'mime/types'
end
module RestClient
module Payload
extend self
def generate(params)
if params.is_a?(RestClient::Payload::Base)
# pass through Payload objects unchanged
params
elsif params.is_a?(String)
Base.new(params)
elsif params.is_a?(Hash)
if params.delete(:multipart) == true || has_file?(params)
Multipart.new(params)
else
UrlEncoded.new(params)
end
elsif params.is_a?(ParamsArray)
if _has_file?(params)
Multipart.new(params)
else
UrlEncoded.new(params)
end
elsif params.respond_to?(:read)
Streamed.new(params)
else
nil
end
end
def has_file?(params)
unless params.is_a?(Hash)
raise ArgumentError.new("Must pass Hash, not #{params.inspect}")
end
_has_file?(params)
end
def _has_file?(obj)
case obj
when Hash, ParamsArray
obj.any? {|_, v| _has_file?(v) }
when Array
obj.any? {|v| _has_file?(v) }
else
obj.respond_to?(:path) && obj.respond_to?(:read)
end
end
class Base
def initialize(params)
build_stream(params)
end
def build_stream(params)
@stream = StringIO.new(params)
@stream.seek(0)
end
def read(*args)
@stream.read(*args)
end
def to_s
result = read
@stream.seek(0)
result
end
def headers
{'Content-Length' => size.to_s}
end
def size
@stream.size
end
alias :length :size
def close
@stream.close unless @stream.closed?
end
def closed?
@stream.closed?
end
def to_s_inspect
to_s.inspect
end
def short_inspect
if size && size > 500
"#{size} byte(s) length"
else
to_s_inspect
end
end
end
class Streamed < Base
def build_stream(params = nil)
@stream = params
end
def size
if @stream.respond_to?(:size)
@stream.size
elsif @stream.is_a?(IO)
@stream.stat.size
end
end
# TODO (breaks compatibility): ought to use mime_for() to autodetect the
# Content-Type for stream objects that have a filename.
alias :length :size
end
class UrlEncoded < Base
def build_stream(params = nil)
@stream = StringIO.new(Utils.encode_query_string(params))
@stream.seek(0)
end
def headers
super.merge({'Content-Type' => 'application/x-www-form-urlencoded'})
end
end
class Multipart < Base
EOL = "\r\n"
def build_stream(params)
b = '--' + boundary
@stream = Tempfile.new('rest-client.multipart.')
@stream.binmode
@stream.write(b + EOL)
case params
when Hash, ParamsArray
x = Utils.flatten_params(params)
else
x = params
end
last_index = x.length - 1
x.each_with_index do |a, index|
k, v = * a
if v.respond_to?(:read) && v.respond_to?(:path)
create_file_field(@stream, k, v)
else
create_regular_field(@stream, k, v)
end
@stream.write(EOL + b)
@stream.write(EOL) unless last_index == index
end
@stream.write('--')
@stream.write(EOL)
@stream.seek(0)
end
def create_regular_field(s, k, v)
s.write("Content-Disposition: form-data; name=\"#{k}\"")
s.write(EOL)
s.write(EOL)
s.write(v)
end
def create_file_field(s, k, v)
begin
s.write("Content-Disposition: form-data;")
s.write(" name=\"#{k}\";") unless (k.nil? || k=='')
s.write(" filename=\"#{v.respond_to?(:original_filename) ? v.original_filename : File.basename(v.path)}\"#{EOL}")
s.write("Content-Type: #{v.respond_to?(:content_type) ? v.content_type : mime_for(v.path)}#{EOL}")
s.write(EOL)
while (data = v.read(8124))
s.write(data)
end
ensure
v.close if v.respond_to?(:close)
end
end
def mime_for(path)
mime = MIME::Types.type_for path
mime.empty? ? 'text/plain' : mime[0].content_type
end
def boundary
return @boundary if defined?(@boundary) && @boundary
# Use the same algorithm used by WebKit: generate 16 random
# alphanumeric characters, replacing `+` `/` with `A` `B` (included in
# the list twice) to round out the set of 64.
s = SecureRandom.base64(12)
s.tr!('+/', 'AB')
@boundary = '----RubyFormBoundary' + s
end
# for Multipart do not escape the keys
#
# Ostensibly multipart keys MAY be percent encoded per RFC 7578, but in
# practice no major browser that I'm aware of uses percent encoding.
#
# Further discussion of multipart encoding:
# https://github.com/rest-client/rest-client/pull/403#issuecomment-156976930
#
def handle_key key
key
end
def headers
super.merge({'Content-Type' => %Q{multipart/form-data; boundary=#{boundary}}})
end
def close
@stream.close!
end
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/raw_response.rb | lib/restclient/raw_response.rb | module RestClient
# The response from RestClient on a raw request looks like a string, but is
# actually one of these. 99% of the time you're making a rest call all you
# care about is the body, but on the occasion you want to fetch the
# headers you can:
#
# RestClient.get('http://example.com').headers[:content_type]
#
# In addition, if you do not use the response as a string, you can access
# a Tempfile object at res.file, which contains the path to the raw
# downloaded request body.
class RawResponse
include AbstractResponse
attr_reader :file, :request, :start_time, :end_time
def inspect
"<RestClient::RawResponse @code=#{code.inspect}, @file=#{file.inspect}, @request=#{request.inspect}>"
end
# @param [Tempfile] tempfile The temporary file containing the body
# @param [Net::HTTPResponse] net_http_res
# @param [RestClient::Request] request
# @param [Time] start_time
def initialize(tempfile, net_http_res, request, start_time=nil)
@file = tempfile
# reopen the tempfile so we can read it
@file.open
response_set_vars(net_http_res, request, start_time)
end
def to_s
body
end
def body
@file.rewind
@file.read
end
def size
file.size
end
end
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/windows.rb | lib/restclient/windows.rb | module RestClient
module Windows
end
end
if RestClient::Platform.windows?
require_relative './windows/root_certs'
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rest-client/rest-client | https://github.com/rest-client/rest-client/blob/2c72a2e77e2e87d25ff38feba0cf048d51bd5eca/lib/restclient/windows/root_certs.rb | lib/restclient/windows/root_certs.rb | require 'openssl'
require 'ffi'
# Adapted from Puppet, Copyright (c) Puppet Labs Inc,
# licensed under the Apache License, Version 2.0.
#
# https://github.com/puppetlabs/puppet/blob/bbe30e0a/lib/puppet/util/windows/root_certs.rb
# Represents a collection of trusted root certificates.
#
# @api public
class RestClient::Windows::RootCerts
include Enumerable
extend FFI::Library
typedef :ulong, :dword
typedef :uintptr_t, :handle
def initialize(roots)
@roots = roots
end
# Enumerates each root certificate.
# @yieldparam cert [OpenSSL::X509::Certificate] each root certificate
# @api public
def each
@roots.each {|cert| yield cert}
end
# Returns a new instance.
# @return [RestClient::Windows::RootCerts] object constructed from current root certificates
def self.instance
new(self.load_certs)
end
# Returns an array of root certificates.
#
# @return [Array<[OpenSSL::X509::Certificate]>] an array of root certificates
# @api private
def self.load_certs
certs = []
# This is based on a patch submitted to openssl:
# http://www.mail-archive.com/openssl-dev@openssl.org/msg26958.html
ptr = FFI::Pointer::NULL
store = CertOpenSystemStoreA(nil, "ROOT")
begin
while (ptr = CertEnumCertificatesInStore(store, ptr)) and not ptr.null?
context = CERT_CONTEXT.new(ptr)
cert_buf = context[:pbCertEncoded].read_bytes(context[:cbCertEncoded])
begin
certs << OpenSSL::X509::Certificate.new(cert_buf)
rescue => detail
warn("Failed to import root certificate: #{detail.inspect}")
end
end
ensure
CertCloseStore(store, 0)
end
certs
end
private
# typedef ULONG_PTR HCRYPTPROV_LEGACY;
# typedef void *HCERTSTORE;
class CERT_CONTEXT < FFI::Struct
layout(
:dwCertEncodingType, :dword,
:pbCertEncoded, :pointer,
:cbCertEncoded, :dword,
:pCertInfo, :pointer,
:hCertStore, :handle
)
end
# HCERTSTORE
# WINAPI
# CertOpenSystemStoreA(
# __in_opt HCRYPTPROV_LEGACY hProv,
# __in LPCSTR szSubsystemProtocol
# );
ffi_lib :crypt32
attach_function :CertOpenSystemStoreA, [:pointer, :string], :handle
# PCCERT_CONTEXT
# WINAPI
# CertEnumCertificatesInStore(
# __in HCERTSTORE hCertStore,
# __in_opt PCCERT_CONTEXT pPrevCertContext
# );
ffi_lib :crypt32
attach_function :CertEnumCertificatesInStore, [:handle, :pointer], :pointer
# BOOL
# WINAPI
# CertCloseStore(
# __in_opt HCERTSTORE hCertStore,
# __in DWORD dwFlags
# );
ffi_lib :crypt32
attach_function :CertCloseStore, [:handle, :dword], :bool
end
| ruby | MIT | 2c72a2e77e2e87d25ff38feba0cf048d51bd5eca | 2026-01-04T15:43:28.362144Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/group_spec.rb | spec/group_spec.rb | require "helper"
describe Thor::Group do
describe "command" do
it "allows to use private methods from parent class as commands" do
expect(ChildGroup.start).to eq(%w(bar foo baz))
expect(ChildGroup.new.baz("bar")).to eq("bar")
end
end
describe "#start" do
it "invokes all the commands under the Thor group" do
expect(MyCounter.start(%w(1 2 --third 3))).to eq([1, 2, 3, nil, nil, nil])
end
it "uses argument's default value" do
expect(MyCounter.start(%w(1 --third 3))).to eq([1, 2, 3, nil, nil, nil])
end
it "invokes all the commands in the Thor group and its parents" do
expect(BrokenCounter.start(%w(1 2 --third 3))).to eq([nil, 2, 3, false, 5, nil])
end
it "raises an error if a required argument is added after a non-required" do
expect do
MyCounter.argument(:foo, type: :string)
end.to raise_error(ArgumentError, 'You cannot have "foo" as required argument after the non-required argument "second".')
end
it "raises when an exception happens within the command call" do
if RUBY_VERSION < "3.4.0"
expect { BrokenCounter.start(%w(1 2 --fail)) }.to raise_error(NameError, /undefined local variable or method `this_method_does_not_exist'/)
else
expect { BrokenCounter.start(%w(1 2 --fail)) }.to raise_error(NameError, /undefined local variable or method 'this_method_does_not_exist'/)
end
end
it "raises an error when a Thor group command expects arguments" do
expect { WhinyGenerator.start }.to raise_error(ArgumentError, /thor wrong_arity takes 1 argument, but it should not/)
end
it "invokes help message if any of the shortcuts are given" do
expect(MyCounter).to receive(:help)
MyCounter.start(%w(-h))
end
end
describe "#desc" do
it "sets the description for a given class" do
expect(MyCounter.desc).to eq("Description:\n This generator runs three commands: one, two and three.\n")
end
it "can be inherited" do
expect(BrokenCounter.desc).to eq("Description:\n This generator runs three commands: one, two and three.\n")
end
it "can be nil" do
expect(WhinyGenerator.desc).to be nil
end
end
describe "#help" do
before do
@content = capture(:stdout) { MyCounter.help(Thor::Base.shell.new) }
end
it "provides usage information" do
expect(@content).to match(/my_counter N \[N\]/)
end
it "shows description" do
expect(@content).to match(/Description:/)
expect(@content).to match(/This generator runs three commands: one, two and three./)
end
it "shows options information" do
expect(@content).to match(/Options/)
expect(@content).to match(/\[\-\-third=THREE\]/)
end
end
describe "#invoke" do
before do
@content = capture(:stdout) { E.start }
end
it "allows to invoke a class from the class binding" do
expect(@content).to match(/1\n2\n3\n4\n5\n/)
end
it "shows invocation information to the user" do
expect(@content).to match(/invoke Defined/)
end
it "uses padding on status generated by the invoked class" do
expect(@content).to match(/finished counting/)
end
it "allows invocation to be configured with blocks" do
capture(:stdout) do
expect(F.start).to eq(["Valim, Jose"])
end
end
it "shows invoked options on help" do
content = capture(:stdout) { E.help(Thor::Base.shell.new) }
expect(content).to match(/Defined options:/)
expect(content).to match(/\[--unused\]/)
expect(content).to match(/# This option has no use/)
end
end
describe "#invoke_from_option" do
describe "with default type" do
before do
@content = capture(:stdout) { G.start }
end
it "allows to invoke a class from the class binding by a default option" do
expect(@content).to match(/1\n2\n3\n4\n5\n/)
end
it "does not invoke if the option is nil" do
expect(capture(:stdout) { G.start(%w(--skip-invoked)) }).not_to match(/invoke/)
end
it "prints a message if invocation cannot be found" do
content = capture(:stdout) { G.start(%w(--invoked unknown)) }
expect(content).to match(/error unknown \[not found\]/)
end
it "allows to invoke a class from the class binding by the given option" do
error = nil
content = capture(:stdout) do
error = capture(:stderr) do
G.start(%w(--invoked e))
end
end
expect(content).to match(/invoke e/)
expect(error).to match(/ERROR: "thor two" was called with arguments/)
end
it "shows invocation information to the user" do
expect(@content).to match(/invoke defined/)
end
it "uses padding on status generated by the invoked class" do
expect(@content).to match(/finished counting/)
end
it "shows invoked options on help" do
content = capture(:stdout) { G.help(Thor::Base.shell.new) }
expect(content).to match(/defined options:/)
expect(content).to match(/\[--unused\]/)
expect(content).to match(/# This option has no use/)
end
end
describe "with boolean type" do
before do
@content = capture(:stdout) { H.start }
end
it "allows to invoke a class from the class binding by a default option" do
expect(@content).to match(/1\n2\n3\n4\n5\n/)
end
it "does not invoke if the option is false" do
expect(capture(:stdout) { H.start(%w(--no-defined)) }).not_to match(/invoke/)
end
it "shows invocation information to the user" do
expect(@content).to match(/invoke defined/)
end
it "uses padding on status generated by the invoked class" do
expect(@content).to match(/finished counting/)
end
it "shows invoked options on help" do
content = capture(:stdout) { H.help(Thor::Base.shell.new) }
expect(content).to match(/defined options:/)
expect(content).to match(/\[--unused\]/)
expect(content).to match(/# This option has no use/)
end
end
end
describe "#command_exists?" do
it "returns true for a command that is defined in the class" do
expect(MyCounter.command_exists?("one")).to be true
end
it "returns false for a command that is not defined in the class" do
expect(MyCounter.command_exists?("zero")).to be false
end
end
describe "edge-cases" do
it "can handle boolean options followed by arguments" do
klass = Class.new(Thor::Group) do
desc "say hi to name"
argument :name, type: :string
class_option :loud, type: :boolean
def hi
self.name = name.upcase if options[:loud]
"Hi #{name}"
end
end
expect(klass.start(%w(jose))).to eq(["Hi jose"])
expect(klass.start(%w(jose --loud))).to eq(["Hi JOSE"])
expect(klass.start(%w(--loud jose))).to eq(["Hi JOSE"])
end
it "provides extra args as `args`" do
klass = Class.new(Thor::Group) do
desc "say hi to name"
argument :name, type: :string
class_option :loud, type: :boolean
def hi
self.name = name.upcase if options[:loud]
out = "Hi #{name}"
out << ": " << args.join(", ") unless args.empty?
out
end
end
expect(klass.start(%w(jose))).to eq(["Hi jose"])
expect(klass.start(%w(jose --loud))).to eq(["Hi JOSE"])
expect(klass.start(%w(--loud jose))).to eq(["Hi JOSE"])
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/no_warnings_spec.rb | spec/no_warnings_spec.rb | require "open3"
context "when $VERBOSE is enabled" do
it "prints no warnings" do
root = File.expand_path("..", __dir__)
_, err, = Open3.capture3("ruby -I #{root}/lib #{root}/spec/fixtures/verbose.thor")
expect(err).to be_empty
end
it "prints no warnings even when erroring" do
root = File.expand_path("..", __dir__)
_, err, = Open3.capture3("ruby -I #{root}/lib #{root}/spec/fixtures/verbose.thor noop")
expect(err).to_not match(/warning:/)
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/encoding_spec.rb | spec/encoding_spec.rb | require "helper"
require "thor/base"
describe "file's encoding" do
def load_thorfile(filename)
Thor::Util.load_thorfile(File.expand_path("./fixtures/#{filename}", __dir__))
end
it "respects explicit UTF-8" do
load_thorfile("encoding_with_utf8.thor")
expect(capture(:stdout) { Thor::Sandbox::EncodingWithUtf8.new.invoke(:encoding) }).to match(/ok/)
end
it "respects explicit non-UTF-8" do
load_thorfile("encoding_other.thor")
expect(capture(:stdout) { Thor::Sandbox::EncodingOther.new.invoke(:encoding) }).to match(/ok/)
end
it "has implicit UTF-8" do
load_thorfile("encoding_implicit.thor")
expect(capture(:stdout) { Thor::Sandbox::EncodingImplicit.new.invoke(:encoding) }).to match(/ok/)
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/quality_spec.rb | spec/quality_spec.rb | describe "The library itself" do
def check_for_spec_defs_with_single_quotes(filename)
failing_lines = []
File.readlines(filename).each_with_index do |line, number|
failing_lines << number + 1 if line =~ /^ *(describe|it|context) {1}'{1}/
end
"#{filename} uses inconsistent single quotes on lines #{failing_lines.join(', ')}" unless failing_lines.empty?
end
def check_for_tab_characters(filename)
failing_lines = []
File.readlines(filename).each_with_index do |line, number|
failing_lines << number + 1 if line =~ /\t/
end
"#{filename} has tab characters on lines #{failing_lines.join(', ')}" unless failing_lines.empty?
end
def check_for_extra_spaces(filename)
failing_lines = []
File.readlines(filename).each_with_index do |line, number|
next if line =~ /^\s+#.*\s+\n$/
failing_lines << number + 1 if line =~ /\s+\n$/
end
"#{filename} has spaces on the EOL on lines #{failing_lines.join(', ')}" unless failing_lines.empty?
end
RSpec::Matchers.define :be_well_formed do
failure_message do |actual|
actual.join("\n")
end
match(&:empty?)
end
it "has no malformed whitespace" do
exempt = /\.gitmodules|\.marshal|fixtures|vendor|spec|ssl_certs|LICENSE|.devcontainer/
error_messages = []
Dir.chdir(File.expand_path("../..", __FILE__)) do
`git ls-files`.split("\n").each do |filename|
next if filename =~ exempt
error_messages << check_for_tab_characters(filename)
error_messages << check_for_extra_spaces(filename)
end
end
expect(error_messages.compact).to be_well_formed
end
it "uses double-quotes consistently in specs" do
included = /spec/
error_messages = []
Dir.chdir(File.expand_path("../", __FILE__)) do
`git ls-files`.split("\n").each do |filename|
next unless filename =~ included
error_messages << check_for_spec_defs_with_single_quotes(filename)
end
end
expect(error_messages.compact).to be_well_formed
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/script_exit_status_spec.rb | spec/script_exit_status_spec.rb | describe "when the Thor class's exit_with_failure? method returns true" do
def thor_command(command)
gem_dir= File.expand_path("#{File.dirname(__FILE__)}/..")
lib_path= "#{gem_dir}/lib"
script_path= "#{gem_dir}/spec/fixtures/exit_status.thor"
ruby_lib= ENV["RUBYLIB"].nil? ? lib_path : "#{lib_path}:#{ENV['RUBYLIB']}"
full_command= "ruby #{script_path} #{command}"
r,w= IO.pipe
pid= spawn({"RUBYLIB" => ruby_lib},
full_command,
{out: w, err: [:child, :out]})
w.close
_, exit_status= Process.wait2(pid)
r.read
r.close
exit_status.exitstatus
end
it "a command that raises a Thor::Error exits with a status of 1" do
expect(thor_command("error")).to eq(1)
end
it "a command that does not raise a Thor::Error exits with a status of 0" do
expect(thor_command("ok")).to eq(0)
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/register_spec.rb | spec/register_spec.rb | require "helper"
class BoringVendorProvidedCLI < Thor
desc "boring", "do boring stuff"
def boring
puts "bored. <yawn>"
end
end
class ExcitingPluginCLI < Thor
desc "hooray", "say hooray!"
def hooray
puts "hooray!"
end
desc "fireworks", "exciting fireworks!"
def fireworks
puts "kaboom!"
end
end
class SuperSecretPlugin < Thor
default_command :squirrel
desc "squirrel", "All of secret squirrel's secrets"
def squirrel
puts "I love nuts"
end
end
class GroupPlugin < Thor::Group
desc "part one"
def part_one
puts "part one"
end
desc "part two"
def part_two
puts "part two"
end
end
class ClassOptionGroupPlugin < Thor::Group
class_option :who,
type: :string,
aliases: "-w",
default: "zebra"
end
class PluginInheritingFromClassOptionsGroup < ClassOptionGroupPlugin
desc "animal"
def animal
p options[:who]
end
end
class PluginWithDefault < Thor
desc "say MSG", "print MSG"
def say(msg)
puts msg
end
default_command :say
end
class PluginWithDefaultMultipleArguments < Thor
desc "say MSG [MSG]", "print multiple messages"
def say(*args)
puts args
end
default_command :say
end
class PluginWithDefaultcommandAndDeclaredArgument < Thor
desc "say MSG [MSG]", "print multiple messages"
argument :msg
def say
puts msg
end
default_command :say
end
class SubcommandWithDefault < Thor
default_command :default
desc "default", "default subcommand"
def default
puts "default"
end
desc "with_args", "subcommand with arguments"
def with_args(*args)
puts "received arguments: " + args.join(",")
end
end
BoringVendorProvidedCLI.register(
ExcitingPluginCLI,
"exciting",
"do exciting things",
"Various non-boring actions"
)
BoringVendorProvidedCLI.register(
SuperSecretPlugin,
"secret",
"secret stuff",
"Nothing to see here. Move along.",
hide: true
)
BoringVendorProvidedCLI.register(
GroupPlugin,
"groupwork",
"Do a bunch of things in a row",
"purple monkey dishwasher"
)
BoringVendorProvidedCLI.register(
PluginInheritingFromClassOptionsGroup,
"zoo",
"zoo [-w animal]",
"Shows a provided animal or just zebra"
)
BoringVendorProvidedCLI.register(
PluginWithDefault,
"say",
"say message",
"subcommands ftw"
)
BoringVendorProvidedCLI.register(
PluginWithDefaultMultipleArguments,
"say_multiple",
"say message",
"subcommands ftw"
)
BoringVendorProvidedCLI.register(
PluginWithDefaultcommandAndDeclaredArgument,
"say_argument",
"say message",
"subcommands ftw"
)
BoringVendorProvidedCLI.register(SubcommandWithDefault,
"subcommand", "subcommand", "Run subcommands")
describe ".register-ing a Thor subclass" do
it "registers the plugin as a subcommand" do
fireworks_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(exciting fireworks)) }
expect(fireworks_output).to eq("kaboom!\n")
end
it "includes the plugin's usage in the help" do
help_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(help)) }
expect(help_output).to include("do exciting things")
end
context "with a default command," do
it "invokes the default command correctly" do
output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(say hello)) }
expect(output).to include("hello")
end
it "invokes the default command correctly with multiple args" do
output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(say_multiple hello adam)) }
expect(output).to include("hello")
expect(output).to include("adam")
end
it "invokes the default command correctly with a declared argument" do
output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(say_argument hello)) }
expect(output).to include("hello")
end
it "displays the subcommand's help message" do
output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(subcommand help)) }
expect(output).to include("default subcommand")
expect(output).to include("subcommand with argument")
end
it "invokes commands with their actual args" do
output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(subcommand with_args actual_argument)) }
expect(output.strip).to eql("received arguments: actual_argument")
end
end
context "when $thor_runner is false" do
it "includes the plugin's subcommand name in subcommand's help" do
begin
$thor_runner = false
help_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(exciting)) }
expect(help_output).to include("thor exciting fireworks")
ensure
$thor_runner = true
end
end
end
context "when hidden" do
it "omits the hidden plugin's usage from the help" do
help_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(help)) }
expect(help_output).not_to include("secret stuff")
end
it "registers the plugin as a subcommand" do
secret_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(secret squirrel)) }
expect(secret_output).to eq("I love nuts\n")
end
end
end
describe ".register-ing a Thor::Group subclass" do
it "registers the group as a single command" do
group_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(groupwork)) }
expect(group_output).to eq("part one\npart two\n")
end
end
describe ".register-ing a Thor::Group subclass with class options" do
it "works w/o command options" do
group_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(zoo)) }
expect(group_output).to match(/zebra/)
end
it "works w/command options" do
group_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w(zoo -w lion)) }
expect(group_output).to match(/lion/)
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/thor_spec.rb | spec/thor_spec.rb | require "helper"
describe Thor do
describe "#method_option" do
it "sets options to the next method to be invoked" do
args = %w(foo bar --force)
_, options = MyScript.start(args)
expect(options).to eq("force" => true)
end
describe ":lazy_default" do
it "is absent when option is not specified" do
_, options = MyScript.start(%w(with_optional))
expect(options).to eq({})
end
it "sets a default that can be overridden for strings" do
_, options = MyScript.start(%w(with_optional --lazy))
expect(options).to eq("lazy" => "yes")
_, options = MyScript.start(%w(with_optional --lazy yesyes!))
expect(options).to eq("lazy" => "yesyes!")
end
it "sets a default that can be overridden for numerics" do
_, options = MyScript.start(%w(with_optional --lazy-numeric))
expect(options).to eq("lazy_numeric" => 42)
_, options = MyScript.start(%w(with_optional --lazy-numeric 20000))
expect(options).to eq("lazy_numeric" => 20_000)
end
it "sets a default that can be overridden for arrays" do
_, options = MyScript.start(%w(with_optional --lazy-array))
expect(options).to eq("lazy_array" => %w(eat at joes))
_, options = MyScript.start(%w(with_optional --lazy-array hello there))
expect(options).to eq("lazy_array" => %w(hello there))
end
it "sets a default that can be overridden for hashes" do
_, options = MyScript.start(%w(with_optional --lazy-hash))
expect(options).to eq("lazy_hash" => {"swedish" => "meatballs"})
_, options = MyScript.start(%w(with_optional --lazy-hash polish:sausage))
expect(options).to eq("lazy_hash" => {"polish" => "sausage"})
end
end
describe "when :for is supplied" do
it "updates an already defined command" do
_, options = MyChildScript.start(%w(animal horse --other=fish))
expect(options[:other]).to eq("fish")
end
describe "and the target is on the parent class" do
it "updates an already defined command" do
args = %w(example_default_command my_param --new-option=verified)
options = Scripts::MyScript.start(args)
expect(options[:new_option]).to eq("verified")
end
it "adds a command to the command list if the updated command is on the parent class" do
expect(Scripts::MyScript.commands["example_default_command"]).to be
end
it "clones the parent command" do
expect(Scripts::MyScript.commands["example_default_command"]).not_to eq(MyChildScript.commands["example_default_command"])
end
end
end
end
describe "#default_command" do
it "sets a default command" do
expect(MyScript.default_command).to eq("example_default_command")
end
it "invokes the default command if no command is specified" do
expect(MyScript.start([])).to eq("default command")
end
it "invokes the default command if no command is specified even if switches are given" do
expect(MyScript.start(%w(--with option))).to eq("with" => "option")
end
it "inherits the default command from parent" do
expect(MyChildScript.default_command).to eq("example_default_command")
end
end
describe "#stop_on_unknown_option!" do
my_script = Class.new(Thor) do
class_option "verbose", type: :boolean
class_option "mode", type: :string
stop_on_unknown_option! :exec
desc "exec", "Run a command"
def exec(*args)
[options, args]
end
desc "boring", "An ordinary command"
def boring(*args)
[options, args]
end
end
it "passes remaining args to command when it encounters a non-option" do
expect(my_script.start(%w(exec command --verbose))).to eq [{}, %w(command --verbose)]
end
it "passes remaining args to command when it encounters an unknown option" do
expect(my_script.start(%w(exec --foo command --bar))).to eq [{}, %w(--foo command --bar)]
end
it "still accepts options that are given before non-options" do
expect(my_script.start(%w(exec --verbose command --foo))).to eq [{"verbose" => true}, %w(command --foo)]
end
it "still accepts options that require a value" do
expect(my_script.start(%w(exec --mode rashly command))).to eq [{"mode" => "rashly"}, %w(command)]
end
it "still passes everything after -- to command" do
expect(my_script.start(%w(exec -- --verbose))).to eq [{}, %w(--verbose)]
end
it "still passes everything after -- to command, complex" do
expect(my_script.start(%w[exec command --mode z again -- --verbose more])).to eq [{}, %w[command --mode z again -- --verbose more]]
end
it "does not affect ordinary commands" do
expect(my_script.start(%w(boring command --verbose))).to eq [{"verbose" => true}, %w(command)]
end
context "when provided with multiple command names" do
klass = Class.new(Thor) do
stop_on_unknown_option! :foo, :bar
end
it "affects all specified commands" do
expect(klass.stop_on_unknown_option?(double(name: "foo"))).to be true
expect(klass.stop_on_unknown_option?(double(name: "bar"))).to be true
expect(klass.stop_on_unknown_option?(double(name: "baz"))).to be false
end
end
context "when invoked several times" do
klass = Class.new(Thor) do
stop_on_unknown_option! :foo
stop_on_unknown_option! :bar
end
it "affects all specified commands" do
expect(klass.stop_on_unknown_option?(double(name: "foo"))).to be true
expect(klass.stop_on_unknown_option?(double(name: "bar"))).to be true
expect(klass.stop_on_unknown_option?(double(name: "baz"))).to be false
end
end
it "doesn't break new" do
expect(my_script.new).to be_a(Thor)
end
context "along with check_unknown_options!" do
my_script2 = Class.new(Thor) do
class_option "verbose", type: :boolean
class_option "mode", type: :string
check_unknown_options!
stop_on_unknown_option! :exec
desc "exec", "Run a command"
def exec(*args)
[options, args]
end
def self.exit_on_failure?
false
end
end
it "passes remaining args to command when it encounters a non-option" do
expect(my_script2.start(%w[exec command --verbose])).to eq [{}, %w[command --verbose]]
end
it "does not accept if first non-option looks like an option, but only refuses that invalid option" do
expect(capture(:stderr) do
my_script2.start(%w[exec --foo command --bar])
end.strip).to eq("Unknown switches \"--foo\"")
end
it "still accepts options that are given before non-options" do
expect(my_script2.start(%w[exec --verbose command])).to eq [{"verbose" => true}, %w[command]]
end
it "still accepts when non-options are given after real options and argument" do
expect(my_script2.start(%w[exec --verbose command --foo])).to eq [{"verbose" => true}, %w[command --foo]]
end
it "does not accept when non-option looks like an option and is after real options" do
expect(capture(:stderr) do
my_script2.start(%w[exec --verbose --foo])
end.strip).to eq("Unknown switches \"--foo\"")
end
it "still accepts options that require a value" do
expect(my_script2.start(%w[exec --mode rashly command])).to eq [{"mode" => "rashly"}, %w[command]]
end
it "still passes everything after -- to command" do
expect(my_script2.start(%w[exec -- --verbose])).to eq [{}, %w[--verbose]]
end
it "still passes everything after -- to command, complex" do
expect(my_script2.start(%w[exec command --mode z again -- --verbose more])).to eq [{}, %w[command --mode z again -- --verbose more]]
end
end
end
describe "#check_unknown_options!" do
my_script = Class.new(Thor) do
class_option "verbose", type: :boolean
class_option "mode", type: :string
check_unknown_options!
desc "checked", "a command with checked"
def checked(*args)
[options, args]
end
def self.exit_on_failure?
false
end
end
it "still accept options and arguments" do
expect(my_script.start(%w[checked command --verbose])).to eq [{"verbose" => true}, %w[command]]
end
it "still accepts options that are given before arguments" do
expect(my_script.start(%w[checked --verbose command])).to eq [{"verbose" => true}, %w[command]]
end
it "does not accept if non-option that looks like an option is before the arguments" do
expect(capture(:stderr) do
my_script.start(%w[checked --foo command --bar])
end.strip).to eq("Unknown switches \"--foo\", \"--bar\"")
end
it "does not accept if non-option that looks like an option is after an argument" do
expect(capture(:stderr) do
my_script.start(%w[checked command --foo --bar])
end.strip).to eq("Unknown switches \"--foo\", \"--bar\"")
end
it "does not accept when non-option that looks like an option is after real options" do
expect(capture(:stderr) do
my_script.start(%w[checked --verbose --foo])
end.strip).to eq("Unknown switches \"--foo\"")
end
it "does not accept when non-option that looks like an option is before real options" do
expect(capture(:stderr) do
my_script.start(%w[checked --foo --verbose])
end.strip).to eq("Unknown switches \"--foo\"")
end
it "still accepts options that require a value" do
expect(my_script.start(%w[checked --mode rashly command])).to eq [{"mode" => "rashly"}, %w[command]]
end
it "still passes everything after -- to command" do
expect(my_script.start(%w[checked -- --verbose])).to eq [{}, %w[--verbose]]
end
it "still passes everything after -- to command, complex" do
expect(my_script.start(%w[checked command --mode z again -- --verbose more])).to eq [{"mode" => "z"}, %w[command again --verbose more]]
end
end
describe "#disable_required_check!" do
my_script = Class.new(Thor) do
class_option "foo", required: true
disable_required_check! :boring
desc "exec", "Run a command"
def exec(*args)
[options, args]
end
desc "boring", "An ordinary command"
def boring(*args)
[options, args]
end
def self.exit_on_failure?
false
end
end
it "does not check the required option in the given command" do
expect(my_script.start(%w(boring command))).to eq [{}, %w(command)]
end
it "does check the required option of the remaining command" do
content = capture(:stderr) { my_script.start(%w(exec command)) }
expect(content).to eq "No value provided for required options '--foo'\n"
end
it "does affects help by default" do
expect(my_script.disable_required_check?(double(name: "help"))).to be true
end
context "when provided with multiple command names" do
klass = Class.new(Thor) do
disable_required_check! :foo, :bar
end
it "affects all specified commands" do
expect(klass.disable_required_check?(double(name: "help"))).to be true
expect(klass.disable_required_check?(double(name: "foo"))).to be true
expect(klass.disable_required_check?(double(name: "bar"))).to be true
expect(klass.disable_required_check?(double(name: "baz"))).to be false
end
end
context "when invoked several times" do
klass = Class.new(Thor) do
disable_required_check! :foo
disable_required_check! :bar
end
it "affects all specified commands" do
expect(klass.disable_required_check?(double(name: "help"))).to be true
expect(klass.disable_required_check?(double(name: "foo"))).to be true
expect(klass.disable_required_check?(double(name: "bar"))).to be true
expect(klass.disable_required_check?(double(name: "baz"))).to be false
end
end
end
describe "#command_exists?" do
it "returns true for a command that is defined in the class" do
expect(MyScript.command_exists?("zoo")).to be true
expect(MyScript.command_exists?("name-with-dashes")).to be true
expect(MyScript.command_exists?("animal_prison")).to be true
end
it "returns false for a command that is not defined in the class" do
expect(MyScript.command_exists?("animal_heaven")).to be false
end
end
describe "#map" do
it "calls the alias of a method if one is provided" do
expect(MyScript.start(%w(-T fish))).to eq(%w(fish))
end
it "calls the alias of a method if several are provided via #map" do
expect(MyScript.start(%w(-f fish))).to eq(["fish", {}])
expect(MyScript.start(%w(--foo fish))).to eq(["fish", {}])
end
it "inherits all mappings from parent" do
expect(MyChildScript.default_command).to eq("example_default_command")
end
end
describe "#package_name" do
it "provides a proper description for a command when the package_name is assigned" do
content = capture(:stdout) { PackageNameScript.start(%w(help)) }
expect(content).to match(/Baboon commands:/m)
end
# TODO: remove this, might be redundant, just wanted to prove full coverage
it "provides a proper description for a command when the package_name is NOT assigned" do
content = capture(:stdout) { MyScript.start(%w(help)) }
expect(content).to match(/Commands:/m)
end
end
describe "#desc" do
it "provides description for a command" do
content = capture(:stdout) { MyScript.start(%w(help)) }
expect(content).to match(/thor my_script:zoo\s+# zoo around/m)
end
it "provides no namespace if $thor_runner is false" do
begin
$thor_runner = false
content = capture(:stdout) { MyScript.start(%w(help)) }
expect(content).to match(/thor zoo\s+# zoo around/m)
ensure
$thor_runner = true
end
end
describe "when :for is supplied" do
it "overwrites a previous defined command" do
expect(capture(:stdout) { MyChildScript.start(%w(help)) }).to match(/animal KIND \s+# fish around/m)
end
end
describe "when :hide is supplied" do
it "does not show the command in help" do
expect(capture(:stdout) { MyScript.start(%w(help)) }).not_to match(/this is hidden/m)
end
it "but the command is still invocable, does not show the command in help" do
expect(MyScript.start(%w(hidden yesyes))).to eq(%w(yesyes))
end
end
end
describe "#method_options" do
it "sets default options if called before an initializer" do
options = MyChildScript.class_options
expect(options[:force].type).to eq(:boolean)
expect(options[:param].type).to eq(:numeric)
end
it "overwrites default options if called on the method scope" do
args = %w(zoo --force --param feathers)
options = MyChildScript.start(args)
expect(options).to eq("force" => true, "param" => "feathers")
end
it "allows default options to be merged with method options" do
args = %w(animal bird --force --param 1.0 --other tweets)
arg, options = MyChildScript.start(args)
expect(arg).to eq("bird")
expect(options).to eq("force" => true, "param" => 1.0, "other" => "tweets")
end
end
describe "#method_exclusive" do
it "returns the exclusive option names for the class" do
cmd = MyOptionScript.commands["exclusive"]
exclusives = cmd.options_relation[:exclusive_option_names]
expect(exclusives.size).to be(2)
expect(exclusives.first).to eq(%w[one two three])
expect(exclusives.last).to eq(%w[after1 after2])
end
end
describe "#method_at_least_one" do
it "returns the at least one of option names for the class" do
cmd = MyOptionScript.commands["at_least_one"]
at_least_ones = cmd.options_relation[:at_least_one_option_names]
expect(at_least_ones.size).to be(2)
expect(at_least_ones.first).to eq(%w[one two three])
expect(at_least_ones.last).to eq(%w[after1 after2])
end
end
describe "#start" do
it "calls a no-param method when no params are passed" do
expect(MyScript.start(%w(zoo))).to eq(true)
end
it "calls a single-param method when a single param is passed" do
expect(MyScript.start(%w(animal fish))).to eq(%w(fish))
end
it "does not set options in attributes" do
expect(MyScript.start(%w(with_optional --all))).to eq([nil, {"all" => true}, []])
end
it "raises an error if the wrong number of params are provided" do
arity_asserter = lambda do |args, msg|
stderr = capture(:stderr) { Scripts::Arities.start(args) }
expect(stderr.strip).to eq(msg)
end
arity_asserter.call %w(zero_args one), 'ERROR: "thor zero_args" was called with arguments ["one"]
Usage: "thor scripts:arities:zero_args"'
arity_asserter.call %w(one_arg), 'ERROR: "thor one_arg" was called with no arguments
Usage: "thor scripts:arities:one_arg ARG"'
arity_asserter.call %w(one_arg one two), 'ERROR: "thor one_arg" was called with arguments ["one", "two"]
Usage: "thor scripts:arities:one_arg ARG"'
arity_asserter.call %w(one_arg one two), 'ERROR: "thor one_arg" was called with arguments ["one", "two"]
Usage: "thor scripts:arities:one_arg ARG"'
arity_asserter.call %w(two_args one), 'ERROR: "thor two_args" was called with arguments ["one"]
Usage: "thor scripts:arities:two_args ARG1 ARG2"'
arity_asserter.call %w(optional_arg one two), 'ERROR: "thor optional_arg" was called with arguments ["one", "two"]
Usage: "thor scripts:arities:optional_arg [ARG]"'
arity_asserter.call %w(multiple_usages), 'ERROR: "thor multiple_usages" was called with no arguments
Usage: "thor scripts:arities:multiple_usages ARG --foo"
"thor scripts:arities:multiple_usages ARG --bar"'
end
it "raises an error if the invoked command does not exist" do
expect(capture(:stderr) { Amazing.start(%w(animal)) }.strip).to eq('Could not find command "animal" in "amazing" namespace.')
end
it "calls method_missing if an unknown method is passed in" do
expect(MyScript.start(%w(unk hello))).to eq([:unk, %w(hello)])
end
it "does not call a private method no matter what" do
expect(capture(:stderr) { MyScript.start(%w(what)) }.strip).to eq('Could not find command "what" in "my_script" namespace.')
end
it "uses command default options" do
options = MyChildScript.start(%w(animal fish)).last
expect(options).to eq("other" => "method default")
end
it "raises when an exception happens within the command call" do
expect { MyScript.start(%w(call_myself_with_wrong_arity)) }.to raise_error(ArgumentError)
end
context "when the user enters an unambiguous substring of a command" do
it "invokes a command" do
expect(MyScript.start(%w(z))).to eq(MyScript.start(%w(zoo)))
end
it "invokes a command, even when there's an alias it resolves to the same command" do
expect(MyScript.start(%w(hi arg))).to eq(MyScript.start(%w(hidden arg)))
end
it "invokes an alias" do
expect(MyScript.start(%w(animal_pri))).to eq(MyScript.start(%w(zoo)))
end
it "invokes a command, even when there's a hidden command that makes invokation ambiguous" do
expect(MyScript.start(%w(potentially_))).to eq(MyScript.start(%w(potentially_ambiguous)))
end
end
context "when the user enters an ambiguous substring of a command" do
it "raises an exception and displays a message that explains the ambiguity" do
shell = Thor::Base.shell.new
expect(shell).to receive(:error).with("Ambiguous command call matches [call_myself_with_wrong_arity, call_unexistent_method]")
MyScript.start(%w(call), shell: shell)
end
it "raises an exception when there is an alias" do
shell = Thor::Base.shell.new
expect(shell).to receive(:error).with("Ambiguous command f matches [foo, fu]")
MyScript.start(%w(f), shell: shell)
end
end
end
describe "#help" do
def shell
@shell ||= Thor::Base.shell.new
end
describe "on general" do
before do
@content = capture(:stdout) { MyScript.help(shell) }
end
it "provides useful help info for the help method itself" do
expect(@content).to match(/help \[COMMAND\]\s+# Describe available commands/)
end
it "provides useful help info for a method with params" do
expect(@content).to match(/animal TYPE\s+# horse around/)
end
it "uses the maximum terminal size to show commands" do
expect(Thor::Shell::Terminal).to receive(:terminal_width).and_return(80)
content = capture(:stdout) { MyScript.help(shell) }
expect(content).to match(/aaa\.\.\.$/)
end
it "provides description for commands from classes in the same namespace" do
expect(@content).to match(/baz\s+# do some bazing/)
end
it "shows superclass commands" do
content = capture(:stdout) { MyChildScript.help(shell) }
expect(content).to match(/foo BAR \s+# do some fooing/)
end
it "shows class options information" do
content = capture(:stdout) { MyChildScript.help(shell) }
expect(content).to match(/Options\:/)
expect(content).to match(/\[\-\-param=N\]/)
end
it "injects class arguments into default usage" do
content = capture(:stdout) { Scripts::MyScript.help(shell) }
expect(content).to match(/zoo ACCESSOR \-\-param\=PARAM/)
end
it "prints class exclusive options" do
content = capture(:stdout) { MyClassOptionScript.help(shell) }
expect(content).to match(/Exclusive Options:\n\s+--one\s+--two\n/)
end
it "does not print class exclusive options" do
content = capture(:stdout) { Scripts::MyScript.help(shell) }
expect(content).not_to match(/Exclusive Options:/)
end
it "prints class at least one of requred options" do
content = capture(:stdout) { MyClassOptionScript.help(shell) }
expect(content).to match(/Required At Least One:\n\s+--three\s+--four\n/)
end
it "does not print class at least one of required options" do
content = capture(:stdout) { Scripts::MyScript.help(shell) }
expect(content).not_to match(/Required At Least One:/)
end
end
describe "for a specific command" do
it "provides full help info when talking about a specific command" do
expect(capture(:stdout) { MyScript.command_help(shell, "foo") }).to eq(<<-END)
Usage:
thor my_script:foo BAR
Options:
[--force] # Force to do some fooing
do some fooing
This is more info!
Everyone likes more info!
END
end
it "provides full help info when talking about a specific command with multiple usages" do
expect(capture(:stdout) { MyScript.command_help(shell, "baz") }).to eq(<<-END)
Usage:
thor my_script:baz THING
thor my_script:baz --all
Options:
[--all=ALL] # Do bazing for all the things
super cool
END
end
it "raises an error if the command can't be found" do
expect do
MyScript.command_help(shell, "unknown")
end.to raise_error(Thor::UndefinedCommandError, 'Could not find command "unknown" in "my_script" namespace.')
end
it "normalizes names before claiming they don't exist" do
expect(capture(:stdout) { MyScript.command_help(shell, "name-with-dashes") }).to match(/thor my_script:name-with-dashes/)
end
it "uses the long description if it exists" do
expect(capture(:stdout) { MyScript.command_help(shell, "long_description") }).to eq(<<-HELP)
Usage:
thor my_script:long_description
Description:
This is a really really really long description. Here you go. So very long.
It even has two paragraphs.
HELP
end
it "prints long description unwrapped if asked for" do
expect(capture(:stdout) { MyScript.command_help(shell, "long_description_unwrapped") }).to eq(<<-HELP)
Usage:
thor my_script:long_description
Description:
No added indentation, Inline
whatespace not merged,
Linebreaks preserved
and
indentation
too
HELP
end
it "doesn't assign the long description to the next command without one" do
expect(capture(:stdout) do
MyScript.command_help(shell, "name_with_dashes")
end).not_to match(/so very long/i)
end
it "prints exclusive and at least one options" do
message = expect(capture(:stdout) do
MyClassOptionScript.command_help(shell, "mix")
end)
message.to match(/Exclusive Options:\n\s+--five\s+--six\s+--seven\n\s+--one\s+--two/)
message.to match(/Required At Least One:\n\s+--five\s+--six\s+--seven\n\s+--three\s+--four/)
end
it "does not print exclusive and at least one options" do
message = expect(capture(:stdout) do
MyOptionScript.command_help(shell, "no_relations")
end)
message.not_to match(/Exclusive Options:/)
message.not_to match(/Rquired At Least One:/)
end
end
describe "instance method" do
it "calls the class method" do
expect(capture(:stdout) { MyScript.start(%w(help)) }).to match(/Commands:/)
end
it "calls the class method" do
expect(capture(:stdout) { MyScript.start(%w(help foo)) }).to match(/Usage:/)
end
end
context "with required class_options" do
let(:klass) do
Class.new(Thor) do
class_option :foo, required: true
desc "bar", "do something"
def bar; end
end
end
it "shows the command help" do
content = capture(:stdout) { klass.start(%w(help)) }
expect(content).to match(/Commands:/)
end
end
end
describe "subcommands" do
it "triggers a subcommand help when passed --help" do
parent = Class.new(Thor)
child = Class.new(Thor)
parent.desc "child", "child subcommand"
parent.subcommand "child", child
parent.desc "dummy", "dummy"
expect(child).to receive(:help).with(anything, anything)
parent.start ["child", "--help"]
end
end
describe "when creating commands" do
it "prints a warning if a public method is created without description or usage" do
expect(capture(:stdout) do
klass = Class.new(Thor)
klass.class_eval "def hello_from_thor; end"
end).to match(/\[WARNING\] Attempted to create command "hello_from_thor" without usage or description/)
end
it "does not print if overwriting a previous command" do
expect(capture(:stdout) do
klass = Class.new(Thor)
klass.class_eval "def help; end"
end).to be_empty
end
end
describe "edge-cases" do
it "can handle boolean options followed by arguments" do
klass = Class.new(Thor) do
method_option :loud, type: :boolean
desc "hi NAME", "say hi to name"
def hi(name)
name = name.upcase if options[:loud]
"Hi #{name}"
end
end
expect(klass.start(%w(hi jose))).to eq("Hi jose")
expect(klass.start(%w(hi jose --loud))).to eq("Hi JOSE")
expect(klass.start(%w(hi --loud jose))).to eq("Hi JOSE")
end
it "method_option raises an ArgumentError if name is not a Symbol or String" do
expect do
Class.new(Thor) do
method_option loud: true, type: :boolean
end
end.to raise_error(ArgumentError, "Expected a Symbol or String, got #{{loud: true, type: :boolean}}")
end
it "class_option raises an ArgumentError if name is not a Symbol or String" do
expect do
Class.new(Thor) do
class_option loud: true, type: :boolean
end
end.to raise_error(ArgumentError, "Expected a Symbol or String, got #{{loud: true, type: :boolean}}")
end
it "passes through unknown options" do
klass = Class.new(Thor) do
desc "unknown", "passing unknown options"
def unknown(*args)
args
end
end
expect(klass.start(%w(unknown foo --bar baz bat --bam))).to eq(%w(foo --bar baz bat --bam))
expect(klass.start(%w(unknown --bar baz))).to eq(%w(--bar baz))
end
it "does not pass through unknown options with strict args" do
klass = Class.new(Thor) do
strict_args_position!
desc "unknown", "passing unknown options"
def unknown(*args)
args
end
end
expect(klass.start(%w(unknown --bar baz))).to eq([])
expect(klass.start(%w(unknown foo --bar baz))).to eq(%w(foo))
end
it "strict args works in the inheritance chain" do
parent = Class.new(Thor) do
strict_args_position!
end
klass = Class.new(parent) do
desc "unknown", "passing unknown options"
def unknown(*args)
args
end
end
expect(klass.start(%w(unknown --bar baz))).to eq([])
expect(klass.start(%w(unknown foo --bar baz))).to eq(%w(foo))
end
it "issues a deprecation warning on incompatible types by default" do
expect do
Class.new(Thor) do
option "bar", type: :numeric, default: "foo"
end
end.to output(/^Deprecation warning/).to_stderr
end
it "allows incompatible types if allow_incompatible_default_type! is called" do
expect do
Class.new(Thor) do
allow_incompatible_default_type!
option "bar", type: :numeric, default: "foo"
end
end.not_to output.to_stderr
end
it "allows incompatible types if `check_default_type: false` is given" do
expect do
Class.new(Thor) do
option "bar", type: :numeric, default: "foo", check_default_type: false
end
end.not_to output.to_stderr
end
it "checks the default type when check_default_type! is called" do
expect do
Class.new(Thor) do
check_default_type!
option "bar", type: :numeric, default: "foo"
end
end.to raise_error(ArgumentError, "Expected numeric default value for '--bar'; got \"foo\" (string)")
end
it "send as a command name" do
expect(MyScript.start(%w(send))).to eq(true)
end
end
context "without an exit_on_failure? method" do
my_script = Class.new(Thor) do
desc "no arg", "do nothing"
def no_arg
end
end
it "outputs a deprecation warning on error" do
expect do
my_script.start(%w[no_arg one])
end.to output(/^Deprecation.*exit_on_failure/).to_stderr
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/actions_spec.rb | spec/actions_spec.rb | require "helper"
describe Thor::Actions do
def runner(options = {})
@runner ||= MyCounter.new([1], options, destination_root: destination_root)
end
def action(*args, &block)
capture(:stdout) { runner.send(*args, &block) }
end
def file
File.join(destination_root, "foo")
end
describe "on include" do
it "adds runtime options to the base class" do
expect(MyCounter.class_options.keys).to include(:pretend)
expect(MyCounter.class_options.keys).to include(:force)
expect(MyCounter.class_options.keys).to include(:quiet)
expect(MyCounter.class_options.keys).to include(:skip)
end
end
describe "#initialize" do
it "has default behavior invoke" do
expect(runner.behavior).to eq(:invoke)
end
it "can have behavior revoke" do
expect(MyCounter.new([1], {}, behavior: :revoke).behavior).to eq(:revoke)
end
it "when behavior is set to force, overwrite options" do
runner = MyCounter.new([1], {force: false, skip: true}, behavior: :force)
expect(runner.behavior).to eq(:invoke)
expect(runner.options.force).to be true
expect(runner.options.skip).not_to be true
end
it "when behavior is set to skip, overwrite options" do
runner = MyCounter.new([1], %w(--force), behavior: :skip)
expect(runner.behavior).to eq(:invoke)
expect(runner.options.force).not_to be true
expect(runner.options.skip).to be true
end
end
describe "accessors" do
describe "#destination_root=" do
it "gets the current directory and expands the path to set the root" do
base = MyCounter.new([1])
base.destination_root = "here"
expect(base.destination_root).to eq(File.expand_path(File.join(File.dirname(__FILE__), "..", "here")))
end
it "does not use the current directory if one is given" do
root = File.expand_path("/")
base = MyCounter.new([1])
base.destination_root = root
expect(base.destination_root).to eq(root)
end
it "uses the current directory if none is given" do
base = MyCounter.new([1])
expect(base.destination_root).to eq(File.expand_path(File.join(File.dirname(__FILE__), "..")))
end
end
describe "#relative_to_original_destination_root" do
it "returns the path relative to the absolute root" do
expect(runner.relative_to_original_destination_root(file)).to eq("foo")
end
it "does not remove dot if required" do
expect(runner.relative_to_original_destination_root(file, false)).to eq("./foo")
end
it "always use the absolute root" do
runner.inside("foo") do
expect(runner.relative_to_original_destination_root(file)).to eq("foo")
end
end
it "creates proper relative paths for absolute file location" do
expect(runner.relative_to_original_destination_root("/test/file")).to eq("/test/file")
end
it "doesn't remove the root path from the absolute path if it is not at the beginning" do
runner.destination_root = "/app"
expect(runner.relative_to_original_destination_root("/something/app/project")).to eq("/something/app/project")
end
it "doesn't removes the root path from the absolute path only if it is only the partial name of the directory" do
runner.destination_root = "/app"
expect(runner.relative_to_original_destination_root("/application/project")).to eq("/application/project")
end
it "removes the root path from the absolute path only once" do
runner.destination_root = "/app"
expect(runner.relative_to_original_destination_root("/app/app/project")).to eq("app/project")
end
it "does not fail with files containing regexp characters" do
runner = MyCounter.new([1], {}, destination_root: File.join(destination_root, "fo[o-b]ar"))
expect(runner.relative_to_original_destination_root("bar")).to eq("bar")
end
describe "#source_paths_for_search" do
it "add source_root to source_paths_for_search" do
expect(MyCounter.source_paths_for_search).to include(File.expand_path("fixtures", File.dirname(__FILE__)))
end
it "keeps only current source root in source paths" do
expect(ClearCounter.source_paths_for_search).to include(File.expand_path("fixtures/bundle", File.dirname(__FILE__)))
expect(ClearCounter.source_paths_for_search).not_to include(File.expand_path("fixtures", File.dirname(__FILE__)))
end
it "customized source paths should be before source roots" do
expect(ClearCounter.source_paths_for_search[0]).to eq(File.expand_path("fixtures/doc", File.dirname(__FILE__)))
expect(ClearCounter.source_paths_for_search[1]).to eq(File.expand_path("fixtures/bundle", File.dirname(__FILE__)))
end
it "keeps inherited source paths at the end" do
expect(ClearCounter.source_paths_for_search.last).to eq(File.expand_path("fixtures/broken", File.dirname(__FILE__)))
end
end
end
describe "#find_in_source_paths" do
it "raises an error if source path is empty" do
expect do
A.new.find_in_source_paths("foo")
end.to raise_error(Thor::Error, /Currently you have no source paths/)
end
it "finds a template inside the source path" do
expect(runner.find_in_source_paths("doc")).to eq(File.expand_path("doc", source_root))
expect { runner.find_in_source_paths("README") }.to raise_error(Thor::Error, /Could not find "README" in any of your source paths./)
new_path = File.join(source_root, "doc")
runner.instance_variable_set(:@source_paths, nil)
runner.source_paths.unshift(new_path)
expect(runner.find_in_source_paths("README")).to eq(File.expand_path("README", new_path))
end
end
end
describe "#inside" do
it "executes the block inside the given folder" do
runner.inside("foo") do
expect(Dir.pwd).to eq(file)
end
end
it "changes the base root" do
runner.inside("foo") do
expect(runner.destination_root).to eq(file)
end
end
it "creates the directory if it does not exist" do
runner.inside("foo") do
expect(File.exist?(file)).to be true
end
end
it "returns the value yielded by the block" do
expect(runner.inside("foo") { 123 }).to eq(123)
end
describe "when pretending" do
it "no directories should be created" do
runner.inside("bar", pretend: true) {}
expect(File.exist?("bar")).to be false
end
it "returns the value yielded by the block" do
expect(runner.inside("foo") { 123 }).to eq(123)
end
end
describe "when verbose" do
it "logs status" do
expect(capture(:stdout) do
runner.inside("foo", verbose: true) {}
end).to match(/inside foo/)
end
it "uses padding in next status" do
expect(capture(:stdout) do
runner.inside("foo", verbose: true) do
runner.say_status :cool, :padding
end
end).to match(/cool padding/)
end
it "removes padding after block" do
expect(capture(:stdout) do
runner.inside("foo", verbose: true) {}
runner.say_status :no, :padding
end).to match(/no padding/)
end
end
end
describe "#in_root" do
it "executes the block in the root folder" do
runner.inside("foo") do
runner.in_root { expect(Dir.pwd).to eq(destination_root) }
end
end
it "changes the base root" do
runner.inside("foo") do
runner.in_root { expect(runner.destination_root).to eq(destination_root) }
end
end
it "returns to the previous state" do
runner.inside("foo") do
runner.in_root {}
expect(runner.destination_root).to eq(file)
end
end
end
describe "#apply" do
before do
@template = <<-TEMPLATE.dup
@foo = "FOO"
say_status :cool, :padding
TEMPLATE
allow(@template).to receive(:read).and_return(@template)
@file = "/"
allow(File).to receive(:open).and_return(@template)
end
it "accepts a URL as the path" do
@file = "http://gist.github.com/103208.txt"
stub_request(:get, @file)
expect(runner).to receive(:apply).with(@file).and_return(@template)
action(:apply, @file)
end
it "accepts a secure URL as the path" do
@file = "https://gist.github.com/103208.txt"
stub_request(:get, @file)
expect(runner).to receive(:apply).with(@file).and_return(@template)
action(:apply, @file)
end
it "accepts a local file path with spaces" do
@file = File.expand_path("fixtures/path with spaces", File.dirname(__FILE__))
expect(File).to receive(:open).with(@file).and_return(@template)
action(:apply, @file)
end
it "opens a file and executes its content in the instance binding" do
action :apply, @file
expect(runner.instance_variable_get("@foo")).to eq("FOO")
end
it "applies padding to the content inside the file" do
expect(action(:apply, @file)).to match(/cool padding/)
end
it "logs its status" do
expect(action(:apply, @file)).to match(/ apply #{@file}\n/)
end
it "does not log status" do
content = action(:apply, @file, verbose: false)
expect(content).to match(/cool padding/)
expect(content).not_to match(/apply http/)
end
end
describe "#run" do
describe "when not pretending" do
before do
expect(runner).to receive(:system).with("ls")
end
it "executes the command given" do
action :run, "ls"
end
it "logs status" do
expect(action(:run, "ls")).to eq(" run ls from \".\"\n")
end
it "does not log status if required" do
expect(action(:run, "ls", verbose: false)).to be_empty
end
it "accepts a color as status" do
expect(runner.shell).to receive(:say_status).with(:run, 'ls from "."', :yellow)
action :run, "ls", verbose: :yellow
end
end
describe "when pretending" do
it "doesn't execute the command" do
runner = MyCounter.new([1], %w(--pretend))
expect(runner).not_to receive(:system)
runner.run("ls", verbose: false)
end
end
describe "when not capturing" do
it "aborts when abort_on_failure is given and command fails" do
expect { action :run, "false", abort_on_failure: true }.to raise_error(SystemExit)
end
it "succeeds when abort_on_failure is given and command succeeds" do
expect { action :run, "true", abort_on_failure: true }.not_to raise_error
end
it "supports env option" do
expect { action :run, "echo $BAR", env: {"BAR" => "foo"} }.to output("foo\n").to_stdout_from_any_process
end
end
describe "when capturing" do
it "aborts when abort_on_failure is given, capture is given and command fails" do
expect { action :run, "false", abort_on_failure: true, capture: true }.to raise_error(SystemExit)
end
it "succeeds when abort_on_failure is given and command succeeds" do
expect { action :run, "true", abort_on_failure: true, capture: true }.not_to raise_error
end
it "supports env option" do
silence(:stdout) do
expect(runner.run "echo $BAR", env: {"BAR" => "foo"}, capture: true).to eq("foo\n")
end
end
end
context "exit_on_failure? is true" do
before do
allow(MyCounter).to receive(:exit_on_failure?).and_return(true)
end
it "aborts when command fails even if abort_on_failure is not given" do
expect { action :run, "false" }.to raise_error(SystemExit)
end
it "does not abort when abort_on_failure is false even if the command fails" do
expect { action :run, "false", abort_on_failure: false }.not_to raise_error
end
end
end
describe "#run_ruby_script" do
before do
allow(Thor::Util).to receive(:ruby_command).and_return("/opt/jruby")
expect(runner).to receive(:system).with("/opt/jruby script.rb")
end
it "executes the ruby script" do
action :run_ruby_script, "script.rb"
end
it "logs status" do
expect(action(:run_ruby_script, "script.rb")).to eq(" run jruby script.rb from \".\"\n")
end
it "does not log status if required" do
expect(action(:run_ruby_script, "script.rb", verbose: false)).to be_empty
end
end
describe "#thor" do
it "executes the thor command" do
expect(runner).to receive(:system).with("thor list")
action :thor, :list, verbose: true
end
it "converts extra arguments to command arguments" do
expect(runner).to receive(:system).with("thor list foo bar")
action :thor, :list, "foo", "bar"
end
it "converts options hash to switches" do
expect(runner).to receive(:system).with("thor list foo bar --foo")
action :thor, :list, "foo", "bar", foo: true
expect(runner).to receive(:system).with("thor list --foo 1 2 3")
action :thor, :list, foo: [1, 2, 3]
end
it "logs status" do
expect(runner).to receive(:system).with("thor list")
expect(action(:thor, :list)).to eq(" run thor list from \".\"\n")
end
it "does not log status if required" do
expect(runner).to receive(:system).with("thor list --foo 1 2 3")
expect(action(:thor, :list, foo: [1, 2, 3], verbose: false)).to be_empty
end
it "captures the output when :capture is given" do
expect(runner).to receive(:run).with("list", hash_including(capture: true))
action :thor, :list, capture: true
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/sort_spec.rb | spec/sort_spec.rb | require "helper"
describe Thor do
def shell
@shell ||= Thor::Base.shell.new
end
describe "#sort - default" do
my_script = Class.new(Thor) do
desc "a", "First Command"
def a; end
desc "z", "Last Command"
def z; end
end
before do
@content = capture(:stdout) { my_script.help(shell) }
end
it "sorts them lexicographillay" do
expect(@content).to match(/:a.+:help.+:z/m)
end
end
describe "#sort - simple override" do
my_script = Class.new(Thor) do
desc "a", "First Command"
def a; end
desc "z", "Last Command"
def z; end
def self.sort_commands!(list)
list.sort!
list.reverse!
end
end
before do
@content = capture(:stdout) { my_script.help(shell) }
end
it "sorts them in reverse" do
expect(@content).to match(/:z.+:help.+:a/m)
end
end
describe "#sort - simple override" do
my_script = Class.new(Thor) do
desc "a", "First Command"
def a; end
desc "z", "Last Command"
def z; end
def self.sort_commands!(list)
list.sort_by! do |a,b|
a[0] == :help ? -1 : a[0] <=> b[0]
end
end
end
before do
@content = capture(:stdout) { my_script.help(shell) }
end
it "puts help first then sorts them lexicographillay" do
expect(@content).to match(/:help.+:a.+:z/m)
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/util_spec.rb | spec/util_spec.rb | require "helper"
module Thor::Util
def self.clear_user_home!
@@user_home = nil
end
end
describe Thor::Util do
describe "#find_by_namespace" do
it "returns 'default' if no namespace is given" do
expect(Thor::Util.find_by_namespace("")).to eq(Scripts::MyDefaults)
end
it "adds 'default' if namespace starts with :" do
expect(Thor::Util.find_by_namespace(":child")).to eq(Scripts::ChildDefault)
end
it "returns nil if the namespace can't be found" do
expect(Thor::Util.find_by_namespace("thor:core_ext:hash_with_indifferent_access")).to be nil
end
it "returns a class if it matches the namespace" do
expect(Thor::Util.find_by_namespace("app:broken:counter")).to eq(BrokenCounter)
end
it "matches classes default namespace" do
expect(Thor::Util.find_by_namespace("scripts:my_script")).to eq(Scripts::MyScript)
end
end
describe "#namespace_from_thor_class" do
it "replaces constant nesting with command namespacing" do
expect(Thor::Util.namespace_from_thor_class("Foo::Bar::Baz")).to eq("foo:bar:baz")
end
it "snake-cases component strings" do
expect(Thor::Util.namespace_from_thor_class("FooBar::BarBaz::BazBoom")).to eq("foo_bar:bar_baz:baz_boom")
end
it "accepts class and module objects" do
expect(Thor::Util.namespace_from_thor_class(Thor::CoreExt::HashWithIndifferentAccess)).to eq("thor:core_ext:hash_with_indifferent_access")
expect(Thor::Util.namespace_from_thor_class(Thor::Util)).to eq("thor:util")
end
it "removes Thor::Sandbox namespace" do
expect(Thor::Util.namespace_from_thor_class("Thor::Sandbox::Package")).to eq("package")
end
end
describe "#namespaces_in_content" do
it "returns an array of names of constants defined in the string" do
list = Thor::Util.namespaces_in_content("class Foo; class Bar < Thor; end; end; class Baz; class Bat; end; end")
expect(list).to include("foo:bar")
expect(list).not_to include("bar:bat")
end
it "doesn't put the newly-defined constants in the enclosing namespace" do
Thor::Util.namespaces_in_content("class Blat; end")
expect(defined?(Blat)).not_to be
expect(defined?(Thor::Sandbox::Blat)).to be
end
end
describe "#snake_case" do
it "preserves no-cap strings" do
expect(Thor::Util.snake_case("foo")).to eq("foo")
expect(Thor::Util.snake_case("foo_bar")).to eq("foo_bar")
end
it "downcases all-caps strings" do
expect(Thor::Util.snake_case("FOO")).to eq("foo")
expect(Thor::Util.snake_case("FOO_BAR")).to eq("foo_bar")
end
it "downcases initial-cap strings" do
expect(Thor::Util.snake_case("Foo")).to eq("foo")
end
it "replaces camel-casing with underscores" do
expect(Thor::Util.snake_case("FooBarBaz")).to eq("foo_bar_baz")
expect(Thor::Util.snake_case("Foo_BarBaz")).to eq("foo_bar_baz")
end
it "places underscores between multiple capitals" do
expect(Thor::Util.snake_case("ABClass")).to eq("a_b_class")
end
end
describe "#find_class_and_command_by_namespace" do
it "returns a Thor::Group class if full namespace matches" do
expect(Thor::Util.find_class_and_command_by_namespace("my_counter")).to eq([MyCounter, nil])
end
it "returns a Thor class if full namespace matches" do
expect(Thor::Util.find_class_and_command_by_namespace("thor")).to eq([Thor, nil])
end
it "returns a Thor class and the command name" do
expect(Thor::Util.find_class_and_command_by_namespace("thor:help")).to eq([Thor, "help"])
end
it "falls back in the namespace:command look up even if a full namespace does not match" do
Thor.const_set(:Help, Module.new)
expect(Thor::Util.find_class_and_command_by_namespace("thor:help")).to eq([Thor, "help"])
Thor.send :remove_const, :Help
end
it "falls back on the default namespace class if nothing else matches" do
expect(Thor::Util.find_class_and_command_by_namespace("test")).to eq([Scripts::MyDefaults, "test"])
end
it "returns correct Thor class and the command name when shared namespaces" do
expect(Thor::Util.find_class_and_command_by_namespace("fruits:apple")).to eq([Apple, "apple"])
expect(Thor::Util.find_class_and_command_by_namespace("fruits:pear")).to eq([Pear, "pear"])
end
it "returns correct Thor class and the command name with hypen when shared namespaces" do
expect(Thor::Util.find_class_and_command_by_namespace("fruits:rotten-apple")).to eq([Apple, "rotten-apple"])
end
it "returns correct Thor class and the associated alias command name when shared namespaces" do
expect(Thor::Util.find_class_and_command_by_namespace("fruits:ra")).to eq([Apple, "ra"])
end
end
describe "#thor_classes_in" do
it "returns thor classes inside the given class" do
expect(Thor::Util.thor_classes_in(MyScript)).to eq([MyScript::AnotherScript])
expect(Thor::Util.thor_classes_in(MyScript::AnotherScript)).to be_empty
end
end
describe "#user_home" do
before do
allow(ENV).to receive(:[])
Thor::Util.clear_user_home!
end
it "returns the user path if no variable is set on the environment" do
expect(Thor::Util.user_home).to eq(File.expand_path("~"))
end
it "returns the *nix system path if file cannot be expanded and separator does not exist" do
expect(File).to receive(:expand_path).with("~").and_raise(RuntimeError)
previous_value = File::ALT_SEPARATOR
capture(:stderr) { File.const_set(:ALT_SEPARATOR, false) }
expect(Thor::Util.user_home).to eq("/")
capture(:stderr) { File.const_set(:ALT_SEPARATOR, previous_value) }
end
it "returns the windows system path if file cannot be expanded and a separator exists" do
expect(File).to receive(:expand_path).with("~").and_raise(RuntimeError)
previous_value = File::ALT_SEPARATOR
capture(:stderr) { File.const_set(:ALT_SEPARATOR, true) }
expect(Thor::Util.user_home).to eq("C:/")
capture(:stderr) { File.const_set(:ALT_SEPARATOR, previous_value) }
end
it "returns HOME/.thor if set" do
allow(ENV).to receive(:[]).with("HOME").and_return("/home/user/")
expect(Thor::Util.user_home).to eq("/home/user/")
end
it "returns path with HOMEDRIVE and HOMEPATH if set" do
allow(ENV).to receive(:[]).with("HOMEDRIVE").and_return("D:/")
allow(ENV).to receive(:[]).with("HOMEPATH").and_return("Documents and Settings/James")
expect(Thor::Util.user_home).to eq("D:/Documents and Settings/James")
end
it "returns APPDATA/.thor if set" do
allow(ENV).to receive(:[]).with("APPDATA").and_return("/home/user/")
expect(Thor::Util.user_home).to eq("/home/user/")
end
end
describe "#thor_root_glob" do
before do
allow(ENV).to receive(:[])
Thor::Util.clear_user_home!
end
it "escapes globs in path" do
allow(ENV).to receive(:[]).with("HOME").and_return("/home/user{1}/")
expect(Dir).to receive(:[]).with('/home/user\\{1\\}/.thor/*').and_return([])
expect(Thor::Util.thor_root_glob).to eq([])
end
end
describe "#globs_for" do
it "escapes globs in path" do
expect(Thor::Util.globs_for("/home/apps{1}")).to eq([
'/home/apps\\{1\\}/Thorfile',
'/home/apps\\{1\\}/*.thor',
'/home/apps\\{1\\}/tasks/*.thor',
'/home/apps\\{1\\}/lib/tasks/**/*.thor'
])
end
end
describe "#escape_globs" do
it "escapes ? * { } [ ] glob characters" do
expect(Thor::Util.escape_globs("apps?")).to eq('apps\\?')
expect(Thor::Util.escape_globs("apps*")).to eq('apps\\*')
expect(Thor::Util.escape_globs("apps {1}")).to eq('apps \\{1\\}')
expect(Thor::Util.escape_globs("apps [1]")).to eq('apps \\[1\\]')
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/subcommand_spec.rb | spec/subcommand_spec.rb | require "helper"
describe Thor do
describe "#subcommand" do
it "maps a given subcommand to another Thor subclass" do
barn_help = capture(:stdout) { Scripts::MyDefaults.start(%w(barn)) }
expect(barn_help).to include("barn help [COMMAND] # Describe subcommands or one specific subcommand")
end
it "passes commands to subcommand classes" do
expect(capture(:stdout) { Scripts::MyDefaults.start(%w(barn open)) }.strip).to eq("Open sesame!")
end
it "passes arguments to subcommand classes" do
expect(capture(:stdout) { Scripts::MyDefaults.start(%w(barn open shotgun)) }.strip).to eq("That's going to leave a mark.")
end
it "ignores unknown options (the subcommand class will handle them)" do
expect(capture(:stdout) { Scripts::MyDefaults.start(%w(barn paint blue --coats 4)) }.strip).to eq("4 coats of blue paint")
end
it "passes parsed options to subcommands" do
output = capture(:stdout) { TestSubcommands::Parent.start(%w(sub print_opt --opt output)) }
expect(output).to eq("output")
end
it "accepts the help switch and calls the help command on the subcommand" do
output = capture(:stdout) { TestSubcommands::Parent.start(%w(sub print_opt --help)) }
sub_help = capture(:stdout) { TestSubcommands::Parent.start(%w(sub help print_opt)) }
expect(output).to eq(sub_help)
end
it "accepts the help short switch and calls the help command on the subcommand" do
output = capture(:stdout) { TestSubcommands::Parent.start(%w(sub print_opt -h)) }
sub_help = capture(:stdout) { TestSubcommands::Parent.start(%w(sub help print_opt)) }
expect(output).to eq(sub_help)
end
it "the help command on the subcommand and after it should result in the same output" do
output = capture(:stdout) { TestSubcommands::Parent.start(%w(sub help)) }
sub_help = capture(:stdout) { TestSubcommands::Parent.start(%w(help sub)) }
expect(output).to eq(sub_help)
end
end
context "subcommand with an arg" do
module SubcommandTest1
class Child1 < Thor
desc "foo NAME", "Fooo"
def foo(name)
puts "#{name} was given"
end
end
class Parent < Thor
desc "child1", "child1 description"
subcommand "child1", Child1
def self.exit_on_failure?
false
end
end
end
it "shows subcommand name and method name" do
sub_help = capture(:stderr) { SubcommandTest1::Parent.start(%w(child1 foo)) }
expect(sub_help).to eq ['ERROR: "thor child1 foo" was called with no arguments', 'Usage: "thor child1 foo NAME"', ""].join("\n")
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/command_spec.rb | spec/command_spec.rb | require "helper"
describe Thor::Command do
def command(options = {}, usage = "can_has")
options.each do |key, value|
options[key] = Thor::Option.parse(key, value)
end
@command ||= Thor::Command.new(:can_has, "I can has cheezburger", "I can has cheezburger\nLots and lots of it", nil, usage, options)
end
describe "#formatted_usage" do
it "includes namespace within usage" do
object = Struct.new(:namespace, :arguments).new("foo", [])
expect(command(bar: :required).formatted_usage(object)).to eq("foo:can_has --bar=BAR")
end
it "includes subcommand name within subcommand usage" do
object = Struct.new(:namespace, :arguments).new("main:foo", [])
expect(command(bar: :required).formatted_usage(object, false, true)).to eq("foo can_has --bar=BAR")
end
it "removes default from namespace" do
object = Struct.new(:namespace, :arguments).new("default:foo", [])
expect(command(bar: :required).formatted_usage(object)).to eq(":foo:can_has --bar=BAR")
end
it "injects arguments into usage" do
options = {required: true, type: :string}
object = Struct.new(:namespace, :arguments).new("foo", [Thor::Argument.new(:bar, options)])
expect(command(foo: :required).formatted_usage(object)).to eq("foo:can_has BAR --foo=FOO")
end
it "allows multiple usages" do
object = Struct.new(:namespace, :arguments).new("foo", [])
expect(command({bar: :required}, ["can_has FOO", "can_has BAR"]).formatted_usage(object, false)).to eq("can_has FOO --bar=BAR\ncan_has BAR --bar=BAR")
end
end
describe "#dynamic" do
it "creates a dynamic command with the given name" do
expect(Thor::DynamicCommand.new("command").name).to eq("command")
expect(Thor::DynamicCommand.new("command").description).to eq("A dynamically-generated command")
expect(Thor::DynamicCommand.new("command").usage).to eq("command")
expect(Thor::DynamicCommand.new("command").options).to eq({})
end
it "does not invoke an existing method" do
dub = double
expect(dub.class).to receive(:handle_no_command_error).with("to_s")
Thor::DynamicCommand.new("to_s").run(dub)
end
end
describe "#dup" do
it "dup options hash" do
command = Thor::Command.new("can_has", nil, nil, nil, nil, foo: true, bar: :required)
command.dup.options.delete(:foo)
expect(command.options[:foo]).to be
end
end
describe "#run" do
it "runs a command by calling a method in the given instance" do
dub = double
expect(dub).to receive(:can_has) { |*args| args }
expect(command.run(dub, [1, 2, 3])).to eq([1, 2, 3])
end
it "raises an error if the method to be invoked is private" do
klass = Class.new do
def self.handle_no_command_error(name)
name
end
def can_has
"fail"
end
private :can_has
end
expect(command.run(klass.new)).to eq("can_has")
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/nested_context_spec.rb | spec/nested_context_spec.rb | require "helper"
describe Thor::NestedContext do
subject(:context) { described_class.new }
describe "#enter" do
it "is never empty within the entered block" do
context.enter do
context.enter {}
expect(context).to be_entered
end
end
it "is empty when outside of all blocks" do
context.enter { context.enter {} }
expect(context).not_to be_entered
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/line_editor_spec.rb | spec/line_editor_spec.rb | require "helper"
require "readline"
describe Thor::LineEditor, "on a system with Readline support" do
before do
@original_readline = ::Readline
Object.send(:remove_const, :Readline)
::Readline = double("Readline")
end
after do
Object.send(:remove_const, :Readline)
::Readline = @original_readline
end
describe ".readline" do
it "uses the Readline line editor" do
editor = double("Readline")
expect(Thor::LineEditor::Readline).to receive(:new).with("Enter your name ", {default: "Brian"}).and_return(editor)
expect(editor).to receive(:readline).and_return("George")
expect(Thor::LineEditor.readline("Enter your name ", default: "Brian")).to eq("George")
end
end
end
describe Thor::LineEditor, "on a system without Readline support" do
before do
@original_readline = ::Readline
Object.send(:remove_const, :Readline)
end
after do
::Readline = @original_readline
end
describe ".readline" do
it "uses the Basic line editor" do
editor = double("Basic")
expect(Thor::LineEditor::Basic).to receive(:new).with("Enter your name ", {default: "Brian"}).and_return(editor)
expect(editor).to receive(:readline).and_return("George")
expect(Thor::LineEditor.readline("Enter your name ", default: "Brian")).to eq("George")
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/rake_compat_spec.rb | spec/rake_compat_spec.rb | require "helper"
require "thor/rake_compat"
require "rake/tasklib"
$main = self
class RakeTask < Rake::TaskLib
def initialize
define
end
def define
$main.instance_eval do
desc "Say it's cool"
task :cool do
puts "COOL"
end
namespace :hiper_mega do
task :super do
puts "HIPER MEGA SUPER"
end
end
end
end
end
class ThorTask < Thor
include Thor::RakeCompat
RakeTask.new
end
describe Thor::RakeCompat do
it "sets the rakefile application" do
expect(%w(rake_compat_spec.rb Thorfile)).to include(Rake.application.rakefile)
end
it "adds rake tasks to thor classes too" do
task = ThorTask.tasks["cool"]
expect(task).to be
end
it "uses rake tasks descriptions on thor" do
expect(ThorTask.tasks["cool"].description).to eq("Say it's cool")
end
it "gets usage from rake tasks name" do
expect(ThorTask.tasks["cool"].usage).to eq("cool")
end
it "uses non namespaced name as description if non is available" do
expect(ThorTask::HiperMega.tasks["super"].description).to eq("super")
end
it "converts namespaces to classes" do
expect(ThorTask.const_get(:HiperMega)).to eq(ThorTask::HiperMega)
end
it "does not add tasks from higher namespaces in lowers namespaces" do
expect(ThorTask.tasks["super"]).not_to be
end
it "invoking the thor task invokes the rake task" do
expect(capture(:stdout) do
ThorTask.start %w(cool)
end).to eq("COOL\n")
expect(capture(:stdout) do
ThorTask::HiperMega.start %w(super)
end).to eq("HIPER MEGA SUPER\n")
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/shell_spec.rb | spec/shell_spec.rb | require "helper"
describe Thor::Shell do
def shell
@shell ||= Thor::Base.shell.new
end
describe "#initialize" do
it "sets shell value" do
base = MyCounter.new [1, 2], {}, shell: shell
expect(base.shell).to eq(shell)
end
it "sets the base value on the shell if an accessor is available" do
base = MyCounter.new [1, 2], {}, shell: shell
expect(shell.base).to eq(base)
end
end
describe "#shell" do
it "returns the shell in use" do
expect(MyCounter.new([1, 2]).shell).to be_kind_of(Thor::Base.shell)
end
it "uses $THOR_SHELL" do
class Thor::Shell::TestShell < Thor::Shell::Basic; end
expect(Thor::Base.shell).to eq(shell.class)
ENV["THOR_SHELL"] = "TestShell"
Thor::Base.shell = nil
expect(Thor::Base.shell).to eq(Thor::Shell::TestShell)
ENV["THOR_SHELL"] = ""
Thor::Base.shell = shell.class
expect(Thor::Base.shell).to eq(shell.class)
end
end
describe "with_padding" do
it "uses padding for inside block outputs" do
base = MyCounter.new([1, 2])
base.with_padding do
expect(capture(:stdout) { base.say_status :padding, "cool" }.strip).to eq("padding cool")
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/base_spec.rb | spec/base_spec.rb | require "helper"
require "thor/base"
class Amazing
desc "hello", "say hello"
def hello
puts "Hello"
end
end
describe Thor::Base do
describe "#initialize" do
it "sets arguments array" do
base = MyCounter.new [1, 2]
expect(base.first).to eq(1)
expect(base.second).to eq(2)
end
it "sets arguments default values" do
base = MyCounter.new [1]
expect(base.second).to eq(2)
end
it "sets options default values" do
base = MyCounter.new [1, 2]
expect(base.options[:third]).to eq(3)
end
it "allows options to be given as symbols or strings" do
base = MyCounter.new [1, 2], third: 4
expect(base.options[:third]).to eq(4)
base = MyCounter.new [1, 2], "third" => 4
expect(base.options[:third]).to eq(4)
end
it "creates options with indifferent access" do
base = MyCounter.new [1, 2], third: 3
expect(base.options["third"]).to eq(3)
end
it "creates options with magic predicates" do
base = MyCounter.new [1, 2], third: 3
expect(base.options.third).to eq(3)
end
end
describe "#no_commands" do
it "avoids methods being added as commands" do
expect(MyScript.commands.keys).to include("animal")
expect(MyScript.commands.keys).not_to include("this_is_not_a_command")
expect(MyScript.commands.keys).not_to include("neither_is_this")
end
end
describe "#argument" do
it "sets a value as required and creates an accessor for it" do
expect(MyCounter.start(%w(1 2 --third 3))[0]).to eq(1)
expect(Scripts::MyScript.start(%w(zoo my_special_param --param=normal_param))).to eq("my_special_param")
end
it "does not set a value in the options hash" do
expect(BrokenCounter.start(%w(1 2 --third 3))[0]).to be nil
end
end
describe "#arguments" do
it "returns the arguments for the class" do
expect(MyCounter.arguments.size).to be(2)
end
end
describe "#class_exclusive_option_names" do
it "returns the exclusive option names for the class" do
expect(MyClassOptionScript.class_exclusive_option_names.size).to be(1)
expect(MyClassOptionScript.class_exclusive_option_names.first.size).to be(2)
end
end
describe "#class_at_least_one_option_names" do
it "returns the at least one of option names for the class" do
expect(MyClassOptionScript.class_at_least_one_option_names.size).to be(1)
expect(MyClassOptionScript.class_at_least_one_option_names.first.size).to be(2)
end
end
describe "#class_exclusive" do
it "raise error when exclusive options are given" do
begin
ENV["THOR_DEBUG"] = "1"
expect do
MyClassOptionScript.start %w[mix --one --two --three --five]
end.to raise_error(Thor::ExclusiveArgumentError, "Found exclusive options '--one', '--two'")
expect do
MyClassOptionScript.start %w[mix --one --three --five --six]
end.to raise_error(Thor::ExclusiveArgumentError, "Found exclusive options '--five', '--six'")
ensure
ENV["THOR_DEBUG"] = nil
end
end
end
describe "#class_at_least_one" do
it "raise error when at least one of required options are not given" do
begin
ENV["THOR_DEBUG"] = "1"
expect do
MyClassOptionScript.start %w[mix --five]
end.to raise_error(Thor::AtLeastOneRequiredArgumentError, "Not found at least one of required options '--three', '--four'")
expect do
MyClassOptionScript.start %w[mix --one --three]
end.to raise_error(Thor::AtLeastOneRequiredArgumentError, "Not found at least one of required options '--five', '--six', '--seven'")
ensure
ENV["THOR_DEBUG"] = nil
end
end
end
describe ":aliases" do
it "supports string aliases without a dash prefix" do
expect(MyCounter.start(%w(1 2 -z 3))[4]).to eq(3)
end
it "supports symbol aliases" do
expect(MyCounter.start(%w(1 2 -y 3))[5]).to eq(3)
expect(MyCounter.start(%w(1 2 -r 3))[5]).to eq(3)
end
end
describe "#class_option" do
it "sets options class wise" do
expect(MyCounter.start(%w(1 2 --third 3))[2]).to eq(3)
end
it "does not create an accessor for it" do
expect(BrokenCounter.start(%w(1 2 --third 3))[3]).to be false
end
end
describe "#class_options" do
it "sets default options overwriting superclass definitions" do
options = Scripts::MyScript.class_options
expect(options[:force]).not_to be_required
end
end
describe "#remove_argument" do
it "removes previously defined arguments from class" do
expect(ClearCounter.arguments).to be_empty
end
it "undefine accessors if required" do
expect(ClearCounter.new).not_to respond_to(:first)
expect(ClearCounter.new).not_to respond_to(:second)
end
end
describe "#remove_class_option" do
it "removes previous defined class option" do
expect(ClearCounter.class_options[:third]).to be nil
end
end
describe "#class_options_help" do
before do
@content = capture(:stdout) { MyCounter.help(Thor::Base.shell.new) }
end
it "shows option's description" do
expect(@content).to match(/# The third argument/)
end
it "shows usage with banner content" do
expect(@content).to match(/\[\-\-third=THREE\]/)
end
it "shows default values below descriptions" do
expect(@content).to match(/# Default: 3/)
end
it "prints arrays as copy pasteables" do
expect(@content).to match(/Default: "foo" "bar"/)
end
it "shows options in different groups" do
expect(@content).to match(/Options\:/)
expect(@content).to match(/Runtime options\:/)
expect(@content).to match(/\-p, \[\-\-pretend\]/)
end
it "use padding in options that do not have aliases" do
expect(@content).to match(/^ -t, \[--third/)
expect(@content).to match(/^ \[--fourth/)
expect(@content).to match(/^ -y, -r, \[--symbolic/)
end
it "allows extra options to be given" do
hash = {"Foo" => B.class_options.values}
content = capture(:stdout) { MyCounter.send(:class_options_help, Thor::Base.shell.new, hash) }
expect(content).to match(/Foo options\:/)
expect(content).to match(/--last-name=LAST_NAME/)
end
it "displays choices for enums" do
content = capture(:stdout) { Enum.help(Thor::Base.shell.new) }
expect(content).to match(/Possible values\: apple, banana/)
end
end
describe "#namespace" do
it "returns the default class namespace" do
expect(Scripts::MyScript.namespace).to eq("scripts:my_script")
end
it "sets a namespace to the class" do
expect(Scripts::MyDefaults.namespace).to eq("default")
end
end
describe "#group" do
it "sets a group" do
expect(MyScript.group).to eq("script")
end
it "inherits the group from parent" do
expect(MyChildScript.group).to eq("script")
end
it "defaults to standard if no group is given" do
expect(Amazing.group).to eq("standard")
end
end
describe "#subclasses" do
it "tracks its subclasses in an Array" do
expect(Thor::Base.subclasses).to include(MyScript)
expect(Thor::Base.subclasses).to include(MyChildScript)
expect(Thor::Base.subclasses).to include(Scripts::MyScript)
end
end
describe "#subclass_files" do
it "returns tracked subclasses, grouped by the files they come from" do
thorfile = File.join(File.dirname(__FILE__), "fixtures", "script.thor")
expect(Thor::Base.subclass_files[File.expand_path(thorfile)]).to eq([
MyScript, MyScript::AnotherScript, MyChildScript, Barn,
PackageNameScript, Scripts::MyScript, Scripts::MyDefaults,
Scripts::ChildDefault, Scripts::Arities, Apple, Pear, MyClassOptionScript, MyOptionScript
])
end
it "tracks a single subclass across multiple files" do
thorfile = File.join(File.dirname(__FILE__), "fixtures", "command.thor")
expect(Thor::Base.subclass_files[File.expand_path(thorfile)]).to include(Amazing)
expect(Thor::Base.subclass_files[File.expand_path(__FILE__)]).to include(Amazing)
end
end
describe "#commands" do
it "returns a list with all commands defined in this class" do
expect(MyChildScript.new).to respond_to("animal")
expect(MyChildScript.commands.keys).to include("animal")
end
it "raises an error if a command with reserved word is defined" do
expect do
klass = Class.new(Thor::Group)
klass.class_eval "def shell; end"
end.to raise_error(RuntimeError, /"shell" is a Thor reserved word and cannot be defined as command/)
end
end
describe "#all_commands" do
it "returns a list with all commands defined in this class plus superclasses" do
expect(MyChildScript.new).to respond_to("foo")
expect(MyChildScript.all_commands.keys).to include("foo")
end
end
describe "#remove_command" do
it "removes the command from its commands hash" do
expect(MyChildScript.all_commands.keys).not_to include("name_with_dashes")
expect(MyChildScript.commands.keys).not_to include("boom")
end
it "undefines the method if desired" do
expect(MyChildScript.new).not_to respond_to("boom")
end
end
describe "#from_superclass" do
it "does not send a method to the superclass if the superclass does not respond to it" do
expect(MyCounter.get_from_super).to eq(13)
end
end
describe "#start" do
it "raises an error instead of rescuing if THOR_DEBUG=1 is given" do
begin
ENV["THOR_DEBUG"] = "1"
expect do
MyScript.start %w(what --debug)
end.to raise_error(Thor::UndefinedCommandError, 'Could not find command "what" in "my_script" namespace.')
ensure
ENV["THOR_DEBUG"] = nil
end
end
it "raises an error instead of rescuing if :debug option is given" do
expect do
MyScript.start %w(what), debug: true
end.to raise_error(Thor::UndefinedCommandError, 'Could not find command "what" in "my_script" namespace.')
end
it "suggests commands that are similar if there is a typo" do
expected = "Could not find command \"paintz\" in \"barn\" namespace.\n".dup
expected << "Did you mean? \"paint\"\n" if Thor::Correctable
expect(capture(:stderr) { Barn.start(%w(paintz)) }).to eq(expected)
end
it "does not steal args" do
args = %w(foo bar --force true)
MyScript.start(args)
expect(args).to eq(%w(foo bar --force true))
end
it "checks unknown options" do
expect(capture(:stderr) do
MyScript.start(%w(foo bar --force true --unknown baz))
end.strip).to eq("Unknown switches \"--unknown\"")
end
it "checks unknown options except specified" do
expect(capture(:stderr) do
expect(MyScript.start(%w(with_optional NAME --omg --invalid))).to eq(["NAME", {}, %w(--omg --invalid)])
end.strip).to be_empty
end
end
describe "attr_*" do
it "does not add attr_reader as a command" do
expect(capture(:stderr) { MyScript.start(%w(another_attribute)) }).to match(/Could not find/)
end
it "does not add attr_writer as a command" do
expect(capture(:stderr) { MyScript.start(%w(another_attribute= foo)) }).to match(/Could not find/)
end
it "does not add attr_accessor as a command" do
expect(capture(:stderr) { MyScript.start(["some_attribute"]) }).to match(/Could not find/)
expect(capture(:stderr) { MyScript.start(["some_attribute=", "foo"]) }).to match(/Could not find/)
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/exit_condition_spec.rb | spec/exit_condition_spec.rb | require "helper"
require "thor/base"
describe "Exit conditions" do
it "exits 0, not bubble up EPIPE, if EPIPE is raised" do
epiped = false
command = Class.new(Thor) do
desc "my_action", "testing EPIPE"
define_method :my_action do
epiped = true
raise Errno::EPIPE
end
end
expect { command.start(["my_action"]) }.to raise_error(SystemExit)
expect(epiped).to eq(true)
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/helper.rb | spec/helper.rb | $TESTING = true
require "simplecov"
require "coveralls"
SimpleCov.formatters = [SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter]
SimpleCov.start do
add_filter "/spec"
minimum_coverage(90)
end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
require "thor"
require "thor/group"
require "stringio"
require "rdoc"
require "rspec"
require "diff/lcs" # You need diff/lcs installed to run specs (but not to run Thor).
require "webmock/rspec"
WebMock.disable_net_connect!(allow: "coveralls.io")
# Set shell to basic
ENV["THOR_COLUMNS"] = "10000"
$0 = "thor"
$thor_runner = true
ARGV.clear
Thor::Base.shell = Thor::Shell::Basic
# Load fixtures
load File.join(File.dirname(__FILE__), "fixtures", "enum.thor")
load File.join(File.dirname(__FILE__), "fixtures", "group.thor")
load File.join(File.dirname(__FILE__), "fixtures", "invoke.thor")
load File.join(File.dirname(__FILE__), "fixtures", "script.thor")
load File.join(File.dirname(__FILE__), "fixtures", "subcommand.thor")
load File.join(File.dirname(__FILE__), "fixtures", "command.thor")
RSpec.configure do |config|
config.before do
ARGV.replace []
end
config.expect_with :rspec do |c|
c.syntax = :expect
end
def capture(stream)
begin
stream = stream.to_s
eval "$#{stream} = StringIO.new"
yield
result = eval("$#{stream}").string
ensure
eval("$#{stream} = #{stream.upcase}")
end
result
end
def source_root
File.join(File.dirname(__FILE__), "fixtures")
end
def destination_root
File.join(File.dirname(__FILE__), "sandbox")
end
# This code was adapted from Ruby on Rails, available under MIT-LICENSE
# Copyright (c) 2004-2013 David Heinemeier Hansson
def silence_warnings
old_verbose = $VERBOSE
$VERBOSE = nil
yield
ensure
$VERBOSE = old_verbose
end
# true if running on windows, used for conditional spec skips
#
# @return [TrueClass/FalseClass]
def windows?
Gem.win_platform?
end
alias silence capture
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/tree_spec.rb | spec/tree_spec.rb | require "helper"
require "thor"
class TreeApp < Thor
desc "command1", "A top level command"
def command1
end
desc "command2", "Another top level command"
def command2
end
class SubApp < Thor
desc "subcommand1", "A subcommand"
def subcommand1
end
end
desc "sub", "Subcommands"
subcommand "sub", SubApp
end
RSpec.describe "Thor tree command" do
let(:shell) { Thor::Shell::Basic.new }
it "prints a tree of all commands" do
expect(capture(:stdout) { TreeApp.start(["tree"]) }).to match(/├─ command1/)
expect(capture(:stdout) { TreeApp.start(["tree"]) }).to match(/├─ command2/)
expect(capture(:stdout) { TreeApp.start(["tree"]) }).to match(/└─ sub/)
expect(capture(:stdout) { TreeApp.start(["tree"]) }).to match(/subcommand1/)
end
it "includes command descriptions" do
expect(capture(:stdout) { TreeApp.start(["tree"]) }).to match(/A top level command/)
expect(capture(:stdout) { TreeApp.start(["tree"]) }).to match(/Another top level command/)
expect(capture(:stdout) { TreeApp.start(["tree"]) }).to match(/A subcommand/)
end
it "doesn't show hidden commands" do
expect(capture(:stdout) { TreeApp.start(["tree"]) }).not_to match(/help/)
end
it "shows tree command in help" do
expect(capture(:stdout) { TreeApp.start(["help"]) }).to match(/tree.*Print a tree of all available commands/)
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/invocation_spec.rb | spec/invocation_spec.rb | require "helper"
require "thor/base"
describe Thor::Invocation do
describe "#invoke" do
it "invokes a command inside another command" do
expect(capture(:stdout) { A.new.invoke(:two) }).to eq("2\n3\n")
end
it "invokes a command just once" do
expect(capture(:stdout) { A.new.invoke(:one) }).to eq("1\n2\n3\n")
end
it "invokes a command just once even if they belongs to different classes" do
expect(capture(:stdout) { Defined.new.invoke(:one) }).to eq("1\n2\n3\n4\n5\n")
end
it "invokes a command with arguments" do
expect(A.new.invoke(:five, [5])).to be true
expect(A.new.invoke(:five, [7])).to be false
end
it "invokes the default command if none is given to a Thor class" do
content = capture(:stdout) { A.new.invoke("b") }
expect(content).to match(/Commands/)
expect(content).to match(/LAST_NAME/)
end
it "accepts a class as argument without a command to invoke" do
content = capture(:stdout) { A.new.invoke(B) }
expect(content).to match(/Commands/)
expect(content).to match(/LAST_NAME/)
end
it "accepts a class as argument with a command to invoke" do
base = A.new([], last_name: "Valim")
expect(base.invoke(B, :one, %w(Jose))).to eq("Valim, Jose")
end
it "allows customized options to be given" do
base = A.new([], last_name: "Wrong")
expect(base.invoke(B, :one, %w(Jose), last_name: "Valim")).to eq("Valim, Jose")
end
it "reparses options in the new class" do
expect(A.start(%w(invoker --last-name Valim))).to eq("Valim, Jose")
end
it "shares initialize options with invoked class" do
expect(A.new([], foo: :bar).invoke("b:two")).to eq("foo" => :bar)
end
it "uses default options from invoked class if no matching arguments are given" do
expect(A.new([]).invoke("b:four")).to eq("default")
end
it "overrides default options if options are passed to the invoker" do
expect(A.new([], defaulted_value: "not default").invoke("b:four")).to eq("not default")
end
it "returns the command chain" do
expect(I.new.invoke("two")).to eq([:two])
expect(J.start(%w(one two))).to eq([:one, :two])
end
it "dump configuration values to be used in the invoked class" do
base = A.new
expect(base.invoke("b:three").shell).to eq(base.shell)
end
it "allow extra configuration values to be given" do
base = A.new
shell = Thor::Base.shell.new
expect(base.invoke("b:three", [], {}, shell: shell).shell).to eq(shell)
end
it "invokes a Thor::Group and all of its commands" do
expect(capture(:stdout) { A.new.invoke(:c) }).to eq("1\n2\n3\n")
end
it "does not invoke a Thor::Group twice" do
base = A.new
silence(:stdout) { base.invoke(:c) }
expect(capture(:stdout) { base.invoke(:c) }).to be_empty
end
it "does not invoke any of Thor::Group commands twice" do
base = A.new
silence(:stdout) { base.invoke(:c) }
expect(capture(:stdout) { base.invoke("c:one") }).to be_empty
end
it "raises Thor::UndefinedCommandError if the command can't be found" do
expect do
A.new.invoke("foo:bar")
end.to raise_error(Thor::UndefinedCommandError)
end
it "raises Thor::UndefinedCommandError if the command can't be found even if all commands were already executed" do
base = C.new
silence(:stdout) { base.invoke_all }
expect do
base.invoke("foo:bar")
end.to raise_error(Thor::UndefinedCommandError)
end
it "raises an error if a non Thor class is given" do
expect do
A.new.invoke(Object)
end.to raise_error(RuntimeError, "Expected Thor class, got Object")
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/runner_spec.rb | spec/runner_spec.rb | require "helper"
require "thor/runner"
describe Thor::Runner do
def when_no_thorfiles_exist
old_dir = Dir.pwd
Dir.chdir ".."
delete = Thor::Base.subclasses.select { |e| e.namespace == "default" }
delete.each { |e| Thor::Base.subclasses.delete e }
yield
Thor::Base.subclasses.concat delete
Dir.chdir old_dir
end
describe "#help" do
it "shows information about Thor::Runner itself" do
expect(capture(:stdout) { Thor::Runner.start(%w(help)) }).to match(/List the available thor commands/)
end
it "shows information about a specific Thor::Runner command" do
content = capture(:stdout) { Thor::Runner.start(%w(help list)) }
expect(content).to match(/List the available thor commands/)
expect(content).not_to match(/help \[COMMAND\]/)
end
it "shows information about a specific Thor class" do
content = capture(:stdout) { Thor::Runner.start(%w(help my_script)) }
expect(content).to match(/zoo\s+# zoo around/m)
end
it "shows information about a specific command from a specific Thor class" do
content = capture(:stdout) { Thor::Runner.start(%w(help my_script:zoo)) }
expect(content).to match(/zoo around/)
expect(content).not_to match(/help \[COMMAND\]/)
end
it "shows information about a specific Thor group class" do
content = capture(:stdout) { Thor::Runner.start(%w(help my_counter)) }
expect(content).to match(/my_counter N/)
end
it "raises error if a class/command cannot be found" do
content = capture(:stderr) { Thor::Runner.start(%w(help unknown)) }
expect(content.strip).to eq('Could not find command "unknown" in "default" namespace.')
end
it "raises error if a class/command cannot be found for a setup without thorfiles" do
when_no_thorfiles_exist do
expect(Thor::Runner).to receive :exit
content = capture(:stderr) { Thor::Runner.start(%w(help unknown)) }
expect(content.strip).to eq('Could not find command "unknown".')
end
end
end
describe "#start" do
it "invokes a command from Thor::Runner" do
ARGV.replace %w(list)
expect(capture(:stdout) { Thor::Runner.start }).to match(/my_counter N/)
end
it "invokes a command from a specific Thor class" do
ARGV.replace %w(my_script:zoo)
expect(Thor::Runner.start).to be true
end
it "invokes the default command from a specific Thor class if none is specified" do
ARGV.replace %w(my_script)
expect(Thor::Runner.start).to eq("default command")
end
it "forwards arguments to the invoked command" do
ARGV.replace %w(my_script:animal horse)
expect(Thor::Runner.start).to eq(%w(horse))
end
it "invokes commands through shortcuts" do
ARGV.replace %w(my_script -T horse)
expect(Thor::Runner.start).to eq(%w(horse))
end
it "invokes a Thor::Group" do
ARGV.replace %w(my_counter 1 2 --third 3)
expect(Thor::Runner.start).to eq([1, 2, 3, nil, nil, nil])
end
it "raises an error if class/command can't be found" do
ARGV.replace %w(unknown)
content = capture(:stderr) { Thor::Runner.start }
expect(content.strip).to eq('Could not find command "unknown" in "default" namespace.')
end
it "raises an error if class/command can't be found in a setup without thorfiles" do
when_no_thorfiles_exist do
ARGV.replace %w(unknown)
expect(Thor::Runner).to receive :exit
content = capture(:stderr) { Thor::Runner.start }
expect(content.strip).to eq('Could not find command "unknown".')
end
end
it "does not swallow NoMethodErrors that occur inside the called method" do
ARGV.replace %w(my_script:call_unexistent_method)
expect { Thor::Runner.start }.to raise_error(NoMethodError)
end
it "does not swallow Thor::Group InvocationError" do
ARGV.replace %w(whiny_generator)
expect { Thor::Runner.start }.to raise_error(ArgumentError, /thor wrong_arity takes 1 argument, but it should not/)
end
it "does not swallow Thor InvocationError" do
ARGV.replace %w(my_script:animal)
content = capture(:stderr) { Thor::Runner.start }
expect(content.strip).to eq('ERROR: "thor animal" was called with no arguments
Usage: "thor my_script:animal TYPE"')
end
end
describe "commands" do
let(:location) { "#{File.dirname(__FILE__)}/fixtures/command.thor" }
before do
@original_yaml = {
"random" => {
location: location,
filename: "4a33b894ffce85d7b412fc1b36f88fe0",
namespaces: %w(amazing)
}
}
root_file = File.join(Thor::Util.thor_root, "thor.yml")
# Stub load and save to avoid thor.yaml from being overwritten
allow(YAML).to receive(:load_file).and_return(@original_yaml)
allow(File).to receive(:exist?).with(root_file).and_return(true)
allow(File).to receive(:open).with(root_file, "w")
end
describe "list" do
it "gives a list of the available commands" do
ARGV.replace %w(list)
content = capture(:stdout) { Thor::Runner.start }
expect(content).to match(/amazing:describe NAME\s+# say that someone is amazing/m)
end
it "gives a list of the available Thor::Group classes" do
ARGV.replace %w(list)
expect(capture(:stdout) { Thor::Runner.start }).to match(/my_counter N/)
end
it "can filter a list of the available commands by --group" do
ARGV.replace %w(list --group standard)
expect(capture(:stdout) { Thor::Runner.start }).to match(/amazing:describe NAME/)
ARGV.replace []
expect(capture(:stdout) { Thor::Runner.start }).not_to match(/my_script:animal TYPE/)
ARGV.replace %w(list --group script)
expect(capture(:stdout) { Thor::Runner.start }).to match(/my_script:animal TYPE/)
end
it "can skip all filters to show all commands using --all" do
ARGV.replace %w(list --all)
content = capture(:stdout) { Thor::Runner.start }
expect(content).to match(/amazing:describe NAME/)
expect(content).to match(/my_script:animal TYPE/)
end
it "doesn't list superclass commands in the subclass" do
ARGV.replace %w(list)
expect(capture(:stdout) { Thor::Runner.start }).not_to match(/amazing:help/)
end
it "presents commands in the default namespace with an empty namespace" do
ARGV.replace %w(list)
expect(capture(:stdout) { Thor::Runner.start }).to match(/^thor :cow\s+# prints 'moo'/m)
end
it "runs commands with an empty namespace from the default namespace" do
ARGV.replace %w(:command_conflict)
expect(capture(:stdout) { Thor::Runner.start }).to eq("command\n")
end
it "runs groups even when there is a command with the same name" do
ARGV.replace %w(command_conflict)
expect(capture(:stdout) { Thor::Runner.start }).to eq("group\n")
end
it "runs commands with no colon in the default namespace" do
ARGV.replace %w(cow)
expect(capture(:stdout) { Thor::Runner.start }).to eq("moo\n")
end
end
describe "uninstall" do
before do
path = File.join(Thor::Util.thor_root, @original_yaml["random"][:filename])
expect(FileUtils).to receive(:rm_rf).with(path)
end
it "uninstalls existing thor modules" do
silence(:stdout) { Thor::Runner.start(%w(uninstall random)) }
end
end
describe "installed" do
before do
expect(Dir).to receive(:[]).and_return([])
end
it "displays the modules installed in a pretty way" do
stdout = capture(:stdout) { Thor::Runner.start(%w(installed)) }
expect(stdout).to match(/random\s*amazing/)
expect(stdout).to match(/amazing:describe NAME\s+# say that someone is amazing/m)
end
end
describe "install/update" do
context "with local thor files" do
before do
allow(FileUtils).to receive(:mkdir_p)
allow(FileUtils).to receive(:touch)
allow(Thor::LineEditor).to receive(:readline).and_return("Y")
path = File.join(Thor::Util.thor_root, Digest::SHA256.hexdigest(location + "random"))
expect(File).to receive(:open).with(path, "w")
end
it "updates existing thor files" do
path = File.join(Thor::Util.thor_root, @original_yaml["random"][:filename])
if File.directory? path
expect(FileUtils).to receive(:rm_rf).with(path)
else
expect(File).to receive(:delete).with(path)
end
silence_warnings do
silence(:stdout) { Thor::Runner.start(%w(update random)) }
end
end
it "installs thor files" do
ARGV.replace %W(install #{location})
silence_warnings do
silence(:stdout) { Thor::Runner.start }
end
end
end
context "with remote thor files" do
let(:location) { "https://example.com/Thorfile" }
it "installs thor files" do
allow(Thor::LineEditor).to receive(:readline).and_return("Y", "random")
stub_request(:get, location).to_return(body: "class Foo < Thor; end")
path = File.join(Thor::Util.thor_root, Digest::SHA256.hexdigest(location + "random"))
expect(File).to receive(:open).with(path, "w")
expect { silence(:stdout) { Thor::Runner.start(%W(install #{location})) } }.not_to raise_error
end
it "shows proper errors" do
expect(Thor::Runner).to receive :exit
expect(URI).to receive(:open).with(location).and_raise(OpenURI::HTTPError.new("foo", StringIO.new))
content = capture(:stderr) { Thor::Runner.start(%W(install #{location})) }
expect(content).to include("Error opening URI '#{location}'")
end
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/line_editor/readline_spec.rb | spec/line_editor/readline_spec.rb | require "helper"
describe Thor::LineEditor::Readline do
before do
# Eagerly check Readline availability before mocking
Thor::LineEditor::Readline.available?
unless defined? ::Readline
::Readline = double("Readline")
allow(::Readline).to receive(:completion_append_character=).with(nil)
end
end
describe ".available?" do
it "returns true when ::Readline exists" do
allow(Object).to receive(:const_defined?).with(:Readline).and_return(true)
expect(described_class).to be_available
end
it "returns false when ::Readline does not exist" do
allow(Object).to receive(:const_defined?).with(:Readline).and_return(false)
expect(described_class).not_to be_available
end
end
describe "#readline" do
it "invokes the readline library" do
expect(::Readline).to receive(:readline).with("> ", true).and_return("foo")
expect(::Readline).to_not receive(:completion_proc=)
editor = Thor::LineEditor::Readline.new("> ", {})
expect(editor.readline).to eq("foo")
end
it "supports the add_to_history option" do
expect(::Readline).to receive(:readline).with("> ", false).and_return("foo")
expect(::Readline).to_not receive(:completion_proc=)
editor = Thor::LineEditor::Readline.new("> ", add_to_history: false)
expect(editor.readline).to eq("foo")
end
it "provides tab completion when given a limited_to option" do
expect(::Readline).to receive(:readline)
expect(::Readline).to receive(:completion_proc=) do |proc|
expect(proc.call("")).to eq %w(Apples Chicken Chocolate)
expect(proc.call("Ch")).to eq %w(Chicken Chocolate)
expect(proc.call("Chi")).to eq ["Chicken"]
end
editor = Thor::LineEditor::Readline.new("Best food: ", limited_to: %w(Apples Chicken Chocolate))
editor.readline
end
it "provides path tab completion when given the path option" do
expect(::Readline).to receive(:readline)
expect(::Readline).to receive(:completion_proc=) do |proc|
expect(proc.call("../line_ed").sort).to eq ["../line_editor/", "../line_editor_spec.rb"].sort
end
editor = Thor::LineEditor::Readline.new("Path to file: ", path: true)
Dir.chdir(File.dirname(__FILE__)) { editor.readline }
end
it "uses STDIN when asked not to echo input" do
expect($stdout).to receive(:print).with("Password: ")
noecho_stdin = double("noecho_stdin")
expect(noecho_stdin).to receive(:gets).and_return("secret")
expect($stdin).to receive(:noecho).and_yield(noecho_stdin)
editor = Thor::LineEditor::Readline.new("Password: ", echo: false)
expect(editor.readline).to eq("secret")
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/line_editor/basic_spec.rb | spec/line_editor/basic_spec.rb | require "helper"
describe Thor::LineEditor::Basic do
describe ".available?" do
it "returns true" do
expect(Thor::LineEditor::Basic).to be_available
end
end
describe "#readline" do
it "uses $stdin and $stdout to get input from the user" do
expect($stdout).to receive(:print).with("Enter your name ")
expect($stdin).to receive(:gets).and_return("George")
expect($stdin).not_to receive(:noecho)
editor = Thor::LineEditor::Basic.new("Enter your name ", {})
expect(editor.readline).to eq("George")
end
it "disables echo when asked to" do
expect($stdout).to receive(:print).with("Password: ")
noecho_stdin = double("noecho_stdin")
expect(noecho_stdin).to receive(:gets).and_return("secret")
expect($stdin).to receive(:noecho).and_yield(noecho_stdin)
editor = Thor::LineEditor::Basic.new("Password: ", echo: false)
expect(editor.readline).to eq("secret")
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/fixtures/application.rb | spec/fixtures/application.rb | class Application < Base
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/fixtures/application_helper.rb | spec/fixtures/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/fixtures/doc/block_helper.rb | spec/fixtures/doc/block_helper.rb | <% world do -%>
Hello
<% end -%>
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/fixtures/doc/config.rb | spec/fixtures/doc/config.rb | class <%= @klass %>; end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/actions/create_file_spec.rb | spec/actions/create_file_spec.rb | require "helper"
require "thor/actions"
describe Thor::Actions::CreateFile do
before do
@silence = false
::FileUtils.rm_rf(destination_root)
end
def create_file(destination = nil, config = {}, options = {}, contents = "CONFIGURATION")
@base = MyCounter.new([1, 2], options, destination_root: destination_root)
allow(@base).to receive(:file_name).and_return("rdoc")
@action = Thor::Actions::CreateFile.new(@base, destination, contents, {verbose: !@silence}.merge(config))
end
def invoke!
capture(:stdout) { @action.invoke! }
end
def revoke!
capture(:stdout) { @action.revoke! }
end
def silence!
@silence = true
end
describe "#invoke!" do
it "creates a file" do
create_file("doc/config.rb")
invoke!
expect(File.exist?(File.join(destination_root, "doc/config.rb"))).to be true
end
it "allows setting file permissions" do
create_file("config/private.key", perm: 0o600)
invoke!
stat = File.stat(File.join(destination_root, "config/private.key"))
expect(stat.mode.to_s(8)).to eq "100600"
end
it "does not create a file if pretending" do
create_file("doc/config.rb", {}, pretend: true)
invoke!
expect(File.exist?(File.join(destination_root, "doc/config.rb"))).to be false
end
it "shows created status to the user" do
create_file("doc/config.rb")
expect(invoke!).to eq(" create doc/config.rb\n")
end
it "does not show any information if log status is false" do
silence!
create_file("doc/config.rb")
expect(invoke!).to be_empty
end
it "returns the given destination" do
capture(:stdout) do
expect(create_file("doc/config.rb").invoke!).to eq("doc/config.rb")
end
end
it "converts encoded instructions" do
create_file("doc/%file_name%.rb.tt")
invoke!
expect(File.exist?(File.join(destination_root, "doc/rdoc.rb.tt"))).to be true
end
describe "when file exists" do
before do
create_file("doc/config.rb")
invoke!
end
describe "and is identical" do
it "shows identical status" do
create_file("doc/config.rb")
invoke!
expect(invoke!).to eq(" identical doc/config.rb\n")
end
end
describe "and is not identical" do
before do
File.open(File.join(destination_root, "doc/config.rb"), "w") { |f| f.write("FOO = 3") }
end
it "shows forced status to the user if force is given" do
expect(create_file("doc/config.rb", {}, force: true)).not_to be_identical
expect(invoke!).to eq(" force doc/config.rb\n")
end
it "shows skipped status to the user if skip is given" do
expect(create_file("doc/config.rb", {}, skip: true)).not_to be_identical
expect(invoke!).to eq(" skip doc/config.rb\n")
end
it "shows forced status to the user if force is configured" do
expect(create_file("doc/config.rb", force: true)).not_to be_identical
expect(invoke!).to eq(" force doc/config.rb\n")
end
it "shows skipped status to the user if skip is configured" do
expect(create_file("doc/config.rb", skip: true)).not_to be_identical
expect(invoke!).to eq(" skip doc/config.rb\n")
end
it "shows conflict status to the user" do
file = File.join(destination_root, "doc/config.rb")
expect(create_file("doc/config.rb")).not_to be_identical
expect(Thor::LineEditor).to receive(:readline).with("Overwrite #{file}? (enter \"h\" for help) [Ynaqdhm] ", anything).and_return("s")
content = invoke!
expect(content).to match(%r{conflict doc/config\.rb})
expect(content).to match(%r{skip doc/config\.rb})
end
it "creates the file if the file collision menu returns true" do
create_file("doc/config.rb")
expect(Thor::LineEditor).to receive(:readline).and_return("y")
expect(invoke!).to match(%r{force doc/config\.rb})
end
it "skips the file if the file collision menu returns false" do
create_file("doc/config.rb")
expect(Thor::LineEditor).to receive(:readline).and_return("n")
expect(invoke!).to match(%r{skip doc/config\.rb})
end
it "executes the block given to show file content" do
create_file("doc/config.rb")
expect(Thor::LineEditor).to receive(:readline).and_return("d", "n")
expect(@base.shell).to receive(:system).with("diff", "-u", /doc\/config\.rb/, /doc\/config\.rb/)
invoke!
end
it "executes the block given to run merge tool" do
create_file("doc/config.rb")
allow(@base.shell).to receive(:merge_tool).and_return("meld")
expect(Thor::LineEditor).to receive(:readline).and_return("m")
expect(@base.shell).to receive(:system).with("meld", /doc\/config\.rb/, /doc\/config\.rb/)
invoke!
end
end
end
context "when file exists and it causes a file clash" do
before do
create_file("doc/config")
invoke!
end
it "generates a file clash" do
create_file("doc/config/config.rb")
expect(invoke!).to eq(" file_clash doc/config/config.rb\n")
end
end
context "when directory exists and it causes a file clash" do
before do
create_file("doc/config/hello")
invoke!
end
it "generates a file clash" do
create_file("doc/config")
expect(invoke!) .to eq(" file_clash doc/config\n")
end
end
end
describe "#revoke!" do
it "removes the destination file" do
create_file("doc/config.rb")
invoke!
revoke!
expect(File.exist?(@action.destination)).to be false
end
it "does not raise an error if the file does not exist" do
create_file("doc/config.rb")
revoke!
expect(File.exist?(@action.destination)).to be false
end
end
describe "#exists?" do
it "returns true if the destination file exists" do
create_file("doc/config.rb")
expect(@action.exists?).to be false
invoke!
expect(@action.exists?).to be true
end
end
describe "#identical?" do
it "returns true if the destination file exists and is identical" do
create_file("doc/config.rb")
expect(@action.identical?).to be false
invoke!
expect(@action.identical?).to be true
end
it "returns true if the destination file exists and is identical and contains multi-byte UTF-8 codepoints" do
create_file("doc/config.rb", {}, {}, "€")
expect(@action.identical?).to be false
invoke!
expect(@action.identical?).to be true
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/actions/directory_spec.rb | spec/actions/directory_spec.rb | require "tmpdir"
require "helper"
require "thor/actions"
describe Thor::Actions::Directory do
before do
::FileUtils.rm_rf(destination_root)
allow(invoker).to receive(:file_name).and_return("rdoc")
end
def invoker
@invoker ||= WhinyGenerator.new([1, 2], {}, destination_root: destination_root)
end
def revoker
@revoker ||= WhinyGenerator.new([1, 2], {}, destination_root: destination_root, behavior: :revoke)
end
def invoke!(*args, &block)
capture(:stdout) { invoker.directory(*args, &block) }
end
def revoke!(*args, &block)
capture(:stdout) { revoker.directory(*args, &block) }
end
def exists_and_identical?(source_path, destination_path)
%w(config.rb README).each do |file|
source = File.join(source_root, source_path, file)
destination = File.join(destination_root, destination_path, file)
expect(File.exist?(destination)).to be true
expect(FileUtils.identical?(source, destination)).to be true
end
end
describe "#invoke!" do
it "raises an error if the source does not exist" do
expect do
invoke! "unknown"
end.to raise_error(Thor::Error, /Could not find "unknown" in any of your source paths/)
end
it "does not create a directory in pretend mode" do
invoke! "doc", "ghost", pretend: true
expect(File.exist?("ghost")).to be false
end
it "copies the whole directory recursively to the default destination" do
invoke! "doc"
exists_and_identical?("doc", "doc")
end
it "copies the whole directory recursively to the specified destination" do
invoke! "doc", "docs"
exists_and_identical?("doc", "docs")
end
it "copies only the first level files if recursive" do
invoke! ".", "commands", recursive: false
file = File.join(destination_root, "commands", "group.thor")
expect(File.exist?(file)).to be true
file = File.join(destination_root, "commands", "doc")
expect(File.exist?(file)).to be false
file = File.join(destination_root, "commands", "doc", "README")
expect(File.exist?(file)).to be false
end
it "ignores files within excluding/ directories when exclude_pattern is provided" do
invoke! "doc", "docs", exclude_pattern: %r{excluding/}
file = File.join(destination_root, "docs", "excluding", "rdoc.rb")
expect(File.exist?(file)).to be false
end
it "copies and evaluates files within excluding/ directory when no exclude_pattern is present" do
invoke! "doc", "docs"
file = File.join(destination_root, "docs", "excluding", "rdoc.rb")
expect(File.exist?(file)).to be true
expect(File.read(file)).to eq("BAR = BAR\n")
end
it "copies files from the source relative to the current path" do
invoker.inside "doc" do
invoke! "."
end
exists_and_identical?("doc", "doc")
end
it "copies and evaluates templates" do
invoke! "doc", "docs"
file = File.join(destination_root, "docs", "rdoc.rb")
expect(File.exist?(file)).to be true
expect(File.read(file)).to eq("FOO = FOO\n")
end
it "copies directories and preserves file mode" do
invoke! "preserve", "preserved", mode: :preserve
original = File.join(source_root, "preserve", "script.sh")
copy = File.join(destination_root, "preserved", "script.sh")
expect(File.stat(original).mode).to eq(File.stat(copy).mode)
end
it "copies directories" do
invoke! "doc", "docs"
file = File.join(destination_root, "docs", "components")
expect(File.exist?(file)).to be true
expect(File.directory?(file)).to be true
end
it "does not copy .empty_directory files" do
invoke! "doc", "docs"
file = File.join(destination_root, "docs", "components", ".empty_directory")
expect(File.exist?(file)).to be false
end
it "copies directories even if they are empty" do
invoke! "doc/components", "docs/components"
file = File.join(destination_root, "docs", "components")
expect(File.exist?(file)).to be true
end
it "does not copy empty directories twice" do
content = invoke!("doc/components", "docs/components")
expect(content).not_to match(/exist/)
end
it "logs status" do
content = invoke!("doc")
expect(content).to match(%r{create doc/README})
expect(content).to match(%r{create doc/config\.rb})
expect(content).to match(%r{create doc/rdoc\.rb})
expect(content).to match(%r{create doc/components})
end
it "yields a block" do
checked = false
invoke!("doc") do |content|
checked ||= !!(content =~ /FOO/)
end
expect(checked).to be true
end
it "works with glob characters in the path" do
content = invoke!("app{1}")
expect(content).to match(%r{create app\{1\}/README})
end
context "windows temp directories", if: windows? do
let(:spec_dir) { File.join(@temp_dir, "spec") }
before(:each) do
@temp_dir = Dir.mktmpdir("thor")
Dir.mkdir(spec_dir)
File.new(File.join(spec_dir, "spec_helper.rb"), "w").close
end
after(:each) { FileUtils.rm_rf(@temp_dir) }
it "works with windows temp dir" do
invoke! spec_dir, "specs"
file = File.join(destination_root, "specs")
expect(File.exist?(file)).to be true
expect(File.directory?(file)).to be true
end
end
end
describe "#revoke!" do
it "removes the destination file" do
invoke! "doc"
revoke! "doc"
expect(File.exist?(File.join(destination_root, "doc", "README"))).to be false
expect(File.exist?(File.join(destination_root, "doc", "config.rb"))).to be false
expect(File.exist?(File.join(destination_root, "doc", "components"))).to be false
end
it "works with glob characters in the path" do
invoke! "app{1}"
expect(File.exist?(File.join(destination_root, "app{1}", "README"))).to be true
revoke! "app{1}"
expect(File.exist?(File.join(destination_root, "app{1}", "README"))).to be false
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/actions/file_manipulation_spec.rb | spec/actions/file_manipulation_spec.rb | require "helper"
describe Thor::Actions do
def runner(options = {}, behavior = :invoke)
@runner ||= MyCounter.new([1], options, destination_root: destination_root, behavior: behavior)
end
def action(*args, &block)
capture(:stdout) { runner.send(*args, &block) }
end
def exists_and_identical?(source, destination)
destination = File.join(destination_root, destination)
expect(File.exist?(destination)).to be true
source = File.join(source_root, source)
expect(FileUtils).to be_identical(source, destination)
end
def file
File.join(destination_root, "foo")
end
before do
::FileUtils.rm_rf(destination_root)
end
describe "#chmod" do
it "executes the command given" do
expect(FileUtils).to receive(:chmod_R).with(0755, file)
action :chmod, "foo", 0755
end
it "does not execute the command if pretending" do
expect(FileUtils).not_to receive(:chmod_R)
runner(pretend: true)
action :chmod, "foo", 0755
end
it "logs status" do
expect(FileUtils).to receive(:chmod_R).with(0755, file)
expect(action(:chmod, "foo", 0755)).to eq(" chmod foo\n")
end
it "does not log status if required" do
expect(FileUtils).to receive(:chmod_R).with(0755, file)
expect(action(:chmod, "foo", 0755, verbose: false)).to be_empty
end
end
describe "#copy_file" do
it "copies file from source to default destination" do
action :copy_file, "command.thor"
exists_and_identical?("command.thor", "command.thor")
end
it "copies file from source to the specified destination" do
action :copy_file, "command.thor", "foo.thor"
exists_and_identical?("command.thor", "foo.thor")
end
it "copies file from the source relative to the current path" do
runner.inside("doc") do
action :copy_file, "README"
end
exists_and_identical?("doc/README", "doc/README")
end
it "copies file from source to default destination and preserves file mode" do
action :copy_file, "preserve/script.sh", mode: :preserve
original = File.join(source_root, "preserve/script.sh")
copy = File.join(destination_root, "preserve/script.sh")
expect(File.stat(original).mode).to eq(File.stat(copy).mode)
end
it "copies file from source to default destination and preserves file mode for templated filenames" do
expect(runner).to receive(:filename).and_return("app")
action :copy_file, "preserve/%filename%.sh", mode: :preserve
original = File.join(source_root, "preserve/%filename%.sh")
copy = File.join(destination_root, "preserve/app.sh")
expect(File.stat(original).mode).to eq(File.stat(copy).mode)
end
it "shows the diff when there is a collision and source has utf-8 characters" do
previous_internal = Encoding.default_internal
silence_warnings do
Encoding.default_internal = Encoding::UTF_8
end
destination = File.join(destination_root, "encoding_with_utf8.thor")
FileUtils.mkdir_p(destination_root)
File.write(destination, "blabla")
expect(Thor::LineEditor).to receive(:readline).and_return("d", "y")
expect(runner.shell).to receive(:system).with("diff", "-u", /encoding_with_utf8.thor/, /encoding_with_utf8.thor/)
action :copy_file, "encoding_with_utf8.thor"
exists_and_identical?("encoding_with_utf8.thor", "encoding_with_utf8.thor")
ensure
silence_warnings do
Encoding.default_internal = previous_internal
end
end
it "logs status" do
expect(action(:copy_file, "command.thor")).to eq(" create command.thor\n")
end
it "accepts a block to change output" do
action :copy_file, "command.thor" do |content|
"OMG" + content
end
expect(File.read(File.join(destination_root, "command.thor"))).to match(/^OMG/)
end
end
describe "#link_file", unless: windows? do
it "links file from source to default destination" do
action :link_file, "command.thor"
exists_and_identical?("command.thor", "command.thor")
end
it "links file from source to the specified destination" do
action :link_file, "command.thor", "foo.thor"
exists_and_identical?("command.thor", "foo.thor")
end
it "links file from the source relative to the current path" do
runner.inside("doc") do
action :link_file, "README"
end
exists_and_identical?("doc/README", "doc/README")
end
it "logs status" do
expect(action(:link_file, "command.thor")).to eq(" create command.thor\n")
end
end
describe "#get" do
it "copies file from source to the specified destination" do
action :get, "doc/README", "docs/README"
exists_and_identical?("doc/README", "docs/README")
end
it "uses just the source basename as destination if none is specified" do
action :get, "doc/README"
exists_and_identical?("doc/README", "README")
end
it "allows the destination to be set as a block result" do
action(:get, "doc/README") { "docs/README" }
exists_and_identical?("doc/README", "docs/README")
end
it "yields file content to a block" do
action :get, "doc/README" do |content|
expect(content).to eq("__start__\nREADME\n__end__\n")
end
end
it "logs status" do
expect(action(:get, "doc/README", "docs/README")).to eq(" create docs/README\n")
end
it "accepts http remote sources" do
body = "__start__\nHTTPFILE\n__end__\n"
stub_request(:get, "http://example.com/file.txt").to_return(body: body.dup)
action :get, "http://example.com/file.txt" do |content|
expect(a_request(:get, "http://example.com/file.txt")).to have_been_made
expect(content).to eq(body)
end
end
it "accepts https remote sources" do
body = "__start__\nHTTPSFILE\n__end__\n"
stub_request(:get, "https://example.com/file.txt").to_return(body: body.dup)
action :get, "https://example.com/file.txt" do |content|
expect(a_request(:get, "https://example.com/file.txt")).to have_been_made
expect(content).to eq(body)
end
end
it "accepts http headers" do
body = "__start__\nHTTPFILE\n__end__\n"
headers = {"Content-Type" => "application/json"}
stub_request(:get, "https://example.com/file.txt").with(headers: headers).to_return(body: body.dup)
action :get, "https://example.com/file.txt", {http_headers: headers} do |content|
expect(a_request(:get, "https://example.com/file.txt")).to have_been_made
expect(content).to eq(body)
end
end
end
describe "#template" do
it "allows using block helpers in the template" do
action :template, "doc/block_helper.rb"
file = File.join(destination_root, "doc/block_helper.rb")
expect(File.read(file)).to eq("Hello world!")
end
it "evaluates the template given as source" do
runner.instance_variable_set("@klass", "Config")
action :template, "doc/config.rb"
file = File.join(destination_root, "doc/config.rb")
expect(File.read(file)).to eq("class Config; end\n")
end
it "copies the template to the specified destination" do
runner.instance_variable_set("@klass", "Config")
action :template, "doc/config.rb", "doc/configuration.rb"
file = File.join(destination_root, "doc/configuration.rb")
expect(File.exist?(file)).to be true
end
it "converts encoded instructions" do
expect(runner).to receive(:file_name).and_return("rdoc")
action :template, "doc/%file_name%.rb.tt"
file = File.join(destination_root, "doc/rdoc.rb")
expect(File.exist?(file)).to be true
end
it "accepts filename without .tt for template method" do
expect(runner).to receive(:file_name).and_return("rdoc")
action :template, "doc/%file_name%.rb"
file = File.join(destination_root, "doc/rdoc.rb")
expect(File.exist?(file)).to be true
end
it "logs status" do
runner.instance_variable_set("@klass", "Config")
expect(capture(:stdout) { runner.template("doc/config.rb") }).to eq(" create doc/config.rb\n")
end
it "accepts a block to change output" do
runner.instance_variable_set("@klass", "Config")
action :template, "doc/config.rb" do |content|
"OMG" + content
end
expect(File.read(File.join(destination_root, "doc/config.rb"))).to match(/^OMG/)
end
it "accepts a context to use as the binding" do
begin
@klass = "FooBar"
action :template, "doc/config.rb", context: eval("binding")
expect(File.read(File.join(destination_root, "doc/config.rb"))).to eq("class FooBar; end\n")
ensure
remove_instance_variable(:@klass)
end
end
it "guesses the destination name when given only a source" do
action :template, "doc/config.yaml.tt"
file = File.join(destination_root, "doc/config.yaml")
expect(File.exist?(file)).to be true
end
it "has proper ERB stacktraces" do
error = nil
begin
action :template, "template/bad_config.yaml.tt"
rescue => e
error = e
end
expect(error).to be_a NameError
expect(error.backtrace.to_s).to include("bad_config.yaml.tt:2")
end
end
describe "when changing existent files" do
before do
::FileUtils.cp_r(source_root, destination_root)
end
def file
File.join(destination_root, "doc", "README")
end
describe "#remove_file" do
it "removes the file given" do
action :remove_file, "doc/README"
expect(File.exist?(file)).to be false
end
it "removes broken symlinks too" do
link_path = File.join(destination_root, "broken_symlink")
::FileUtils.ln_s("invalid_reference", link_path)
action :remove_file, "broken_symlink"
expect(File.symlink?(link_path) || File.exist?(link_path)).to be false
end
it "removes directories too" do
action :remove_dir, "doc"
expect(File.exist?(File.join(destination_root, "doc"))).to be false
end
it "does not remove if pretending" do
runner(pretend: true)
action :remove_file, "doc/README"
expect(File.exist?(file)).to be true
end
it "logs status" do
expect(action(:remove_file, "doc/README")).to eq(" remove doc/README\n")
end
it "does not log status if required" do
expect(action(:remove_file, "doc/README", verbose: false)).to be_empty
end
end
describe "#gsub_file!" do
context "with invoke behavior" do
it "replaces the content in the file" do
action :gsub_file!, "doc/README", "__start__", "START"
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
end
it "does not replace if pretending" do
runner(pretend: true)
action :gsub_file!, "doc/README", "__start__", "START"
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "accepts a block" do
action(:gsub_file!, "doc/README", "__start__") { |match| match.gsub("__", "").upcase }
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
end
it "logs status" do
expect(action(:gsub_file!, "doc/README", "__start__", "START")).to eq(" gsub doc/README\n")
end
it "does not log status if required" do
expect(action(:gsub_file!, file, "__", verbose: false) { |match| match * 2 }).to be_empty
end
it "cares if the file contents did not change" do
expect do
action :gsub_file!, "doc/README", "___start___", "START"
end.to raise_error(Thor::Error, "The content of #{destination_root}/doc/README did not change")
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
end
context "with revoke behavior" do
context "and no force option" do
it "does not replace the content in the file" do
runner({}, :revoke)
action :gsub_file!, "doc/README", "__start__", "START"
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "does not replace if pretending" do
runner({pretend: true}, :revoke)
action :gsub_file!, "doc/README", "__start__", "START"
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "does not replace the content in the file when given a block" do
runner({}, :revoke)
action(:gsub_file!, "doc/README", "__start__") { |match| match.gsub("__", "").upcase }
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "does not log status" do
runner({}, :revoke)
expect(action(:gsub_file!, "doc/README", "__start__", "START")).to be_empty
end
it "does not log status if required" do
runner({}, :revoke)
expect(action(:gsub_file!, file, "__", verbose: false) { |match| match * 2 }).to be_empty
end
end
context "and force option" do
it "replaces the content in the file" do
runner({}, :revoke)
action :gsub_file!, "doc/README", "__start__", "START", force: true
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
end
it "does not replace if pretending" do
runner({pretend: true}, :revoke)
action :gsub_file!, "doc/README", "__start__", "START", force: true
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "replaces the content in the file when given a block" do
runner({}, :revoke)
action(:gsub_file!, "doc/README", "__start__", force: true) { |match| match.gsub("__", "").upcase }
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
end
it "logs status" do
runner({}, :revoke)
expect(action(:gsub_file!, "doc/README", "__start__", "START", force: true)).to eq(" gsub doc/README\n")
end
it "does not log status if required" do
runner({}, :revoke)
expect(action(:gsub_file!, file, "__", verbose: false, force: true) { |match| match * 2 }).to be_empty
end
end
end
end
describe "#gsub_file" do
context "with invoke behavior" do
it "replaces the content in the file" do
action :gsub_file, "doc/README", "__start__", "START"
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
end
it "does not replace if pretending" do
runner(pretend: true)
action :gsub_file, "doc/README", "__start__", "START"
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "accepts a block" do
action(:gsub_file, "doc/README", "__start__") { |match| match.gsub("__", "").upcase }
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
end
it "logs status" do
expect(action(:gsub_file, "doc/README", "__start__", "START")).to eq(" gsub doc/README\n")
end
it "does not log status if required" do
expect(action(:gsub_file, file, "__", verbose: false) { |match| match * 2 }).to be_empty
end
it "does not care if the file contents did not change" do
action :gsub_file, "doc/README", "___start___", "START"
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
end
context "with revoke behavior" do
context "and no force option" do
it "does not replace the content in the file" do
runner({}, :revoke)
action :gsub_file, "doc/README", "__start__", "START"
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "does not replace if pretending" do
runner({pretend: true}, :revoke)
action :gsub_file, "doc/README", "__start__", "START"
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "does not replace the content in the file when given a block" do
runner({}, :revoke)
action(:gsub_file, "doc/README", "__start__") { |match| match.gsub("__", "").upcase }
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "does not log status" do
runner({}, :revoke)
expect(action(:gsub_file, "doc/README", "__start__", "START")).to be_empty
end
it "does not log status if required" do
runner({}, :revoke)
expect(action(:gsub_file, file, "__", verbose: false) { |match| match * 2 }).to be_empty
end
end
context "and force option" do
it "replaces the content in the file" do
runner({}, :revoke)
action :gsub_file, "doc/README", "__start__", "START", force: true
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
end
it "does not replace if pretending" do
runner({pretend: true}, :revoke)
action :gsub_file, "doc/README", "__start__", "START", force: true
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
it "replaces the content in the file when given a block" do
runner({}, :revoke)
action(:gsub_file, "doc/README", "__start__", force: true) { |match| match.gsub("__", "").upcase }
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
end
it "logs status" do
runner({}, :revoke)
expect(action(:gsub_file, "doc/README", "__start__", "START", force: true)).to eq(" gsub doc/README\n")
end
it "does not log status if required" do
runner({}, :revoke)
expect(action(:gsub_file, file, "__", verbose: false, force: true) { |match| match * 2 }).to be_empty
end
end
end
end
describe "#append_to_file" do
it "appends content to the file" do
action :append_to_file, "doc/README", "END\n"
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\nEND\n")
end
it "accepts a block" do
action(:append_to_file, "doc/README") { "END\n" }
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\nEND\n")
end
it "logs status" do
expect(action(:append_to_file, "doc/README", "END")).to eq(" append doc/README\n")
end
end
describe "#prepend_to_file" do
it "prepends content to the file" do
action :prepend_to_file, "doc/README", "START\n"
expect(File.binread(file)).to eq("START\n__start__\nREADME\n__end__\n")
end
it "accepts a block" do
action(:prepend_to_file, "doc/README") { "START\n" }
expect(File.binread(file)).to eq("START\n__start__\nREADME\n__end__\n")
end
it "logs status" do
expect(action(:prepend_to_file, "doc/README", "START")).to eq(" prepend doc/README\n")
end
end
describe "#inject_into_class" do
def file
File.join(destination_root, "application.rb")
end
it "appends content to a class" do
action :inject_into_class, "application.rb", "Application", " filter_parameters :password\n"
expect(File.binread(file)).to eq("class Application < Base\n filter_parameters :password\nend\n")
end
it "accepts a block" do
action(:inject_into_class, "application.rb", "Application") { " filter_parameters :password\n" }
expect(File.binread(file)).to eq("class Application < Base\n filter_parameters :password\nend\n")
end
it "logs status" do
expect(action(:inject_into_class, "application.rb", "Application", " filter_parameters :password\n")).to eq(" insert application.rb\n")
end
it "does not append if class name does not match" do
action :inject_into_class, "application.rb", "App", " filter_parameters :password\n"
expect(File.binread(file)).to eq("class Application < Base\nend\n")
end
end
describe "#inject_into_module" do
def file
File.join(destination_root, "application_helper.rb")
end
it "appends content to a module" do
action :inject_into_module, "application_helper.rb", "ApplicationHelper", " def help; 'help'; end\n"
expect(File.binread(file)).to eq("module ApplicationHelper\n def help; 'help'; end\nend\n")
end
it "accepts a block" do
action(:inject_into_module, "application_helper.rb", "ApplicationHelper") { " def help; 'help'; end\n" }
expect(File.binread(file)).to eq("module ApplicationHelper\n def help; 'help'; end\nend\n")
end
it "logs status" do
expect(action(:inject_into_module, "application_helper.rb", "ApplicationHelper", " def help; 'help'; end\n")).to eq(" insert application_helper.rb\n")
end
it "does not append if module name does not match" do
action :inject_into_module, "application_helper.rb", "App", " def help; 'help'; end\n"
expect(File.binread(file)).to eq("module ApplicationHelper\nend\n")
end
end
end
describe "when adjusting comments" do
before do
::FileUtils.cp_r(source_root, destination_root)
end
def file
File.join(destination_root, "doc", "COMMENTER")
end
unmodified_comments_file = /__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\norange\n purple\n ind#igo\n # ind#igo\n # spaces_between\n__end__/
describe "#uncomment_lines" do
it "uncomments all matching lines in the file" do
action :uncomment_lines, "doc/COMMENTER", "green"
expect(File.binread(file)).to match(/__start__\n greenblue\n#\n# yellowblue\n#yellowred\n greenred\norange\n purple\n ind#igo\n # ind#igo\n # spaces_between\n__end__/)
action :uncomment_lines, "doc/COMMENTER", "red"
expect(File.binread(file)).to match(/__start__\n greenblue\n#\n# yellowblue\nyellowred\n greenred\norange\n purple\n ind#igo\n # ind#igo\n # spaces_between\n__end__/)
end
it "correctly uncomments lines with hashes in them" do
action :uncomment_lines, "doc/COMMENTER", "ind#igo"
expect(File.binread(file)).to match(/__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\norange\n purple\n ind#igo\n ind#igo\n # spaces_between\n__end__/)
end
it "will leave the space which existed before the comment hash in tact" do
action :uncomment_lines, "doc/COMMENTER", "ind#igo"
action :uncomment_lines, "doc/COMMENTER", "spaces_between"
expect(File.binread(file)).to match(/__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\norange\n purple\n ind#igo\n ind#igo\n spaces_between\n__end__/)
end
it "does not modify already uncommented lines in the file" do
action :uncomment_lines, "doc/COMMENTER", "orange"
action :uncomment_lines, "doc/COMMENTER", "purple"
expect(File.binread(file)).to match(unmodified_comments_file)
end
it "does not uncomment the wrong line when uncommenting lines preceded by blank commented line" do
action :uncomment_lines, "doc/COMMENTER", "yellow"
expect(File.binread(file)).to match(/__start__\n # greenblue\n#\nyellowblue\nyellowred\n #greenred\norange\n purple\n ind#igo\n # ind#igo\n # spaces_between\n__end__/)
end
end
describe "#comment_lines" do
it "comments lines which are not commented" do
action :comment_lines, "doc/COMMENTER", "orange"
expect(File.binread(file)).to match(/__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\n# orange\n purple\n ind#igo\n # ind#igo\n # spaces_between\n__end__/)
action :comment_lines, "doc/COMMENTER", "purple"
expect(File.binread(file)).to match(/__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\n# orange\n # purple\n ind#igo\n # ind#igo\n # spaces_between\n__end__/)
end
it "correctly comments lines with hashes in them" do
action :comment_lines, "doc/COMMENTER", "ind#igo"
expect(File.binread(file)).to match(/__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\norange\n purple\n # ind#igo\n # ind#igo\n # spaces_between\n__end__/)
end
it "does not modify already commented lines" do
action :comment_lines, "doc/COMMENTER", "green"
expect(File.binread(file)).to match(unmodified_comments_file)
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/actions/create_link_spec.rb | spec/actions/create_link_spec.rb | require "helper"
require "thor/actions"
require "tempfile"
describe Thor::Actions::CreateLink, unless: windows? do
before do
@hardlink_to = File.join(Dir.tmpdir, "linkdest.rb")
::FileUtils.rm_rf(destination_root)
::FileUtils.rm_rf(@hardlink_to)
end
let(:config) { {} }
let(:options) { {} }
let(:base) do
base = MyCounter.new([1, 2], options, destination_root: destination_root)
allow(base).to receive(:file_name).and_return("rdoc")
base
end
let(:tempfile) { Tempfile.new("config.rb") }
let(:source) { tempfile.path }
let(:destination) { "doc/config.rb" }
let(:action) do
Thor::Actions::CreateLink.new(base, destination, source, config)
end
def invoke!
capture(:stdout) { action.invoke! }
end
def revoke!
capture(:stdout) { action.revoke! }
end
describe "#invoke!" do
context "specifying :symbolic => true" do
let(:config) { {symbolic: true} }
it "creates a symbolic link" do
invoke!
destination_path = File.join(destination_root, "doc/config.rb")
expect(File.exist?(destination_path)).to be true
expect(File.symlink?(destination_path)).to be true
end
end
context "specifying :symbolic => false" do
let(:config) { {symbolic: false} }
let(:destination) { @hardlink_to }
it "creates a hard link" do
invoke!
destination_path = @hardlink_to
expect(File.exist?(destination_path)).to be true
expect(File.symlink?(destination_path)).to be false
end
end
it "creates a symbolic link by default" do
invoke!
destination_path = File.join(destination_root, "doc/config.rb")
expect(File.exist?(destination_path)).to be true
expect(File.symlink?(destination_path)).to be true
end
context "specifying :pretend => true" do
let(:options) { {pretend: true} }
it "does not create a link" do
invoke!
expect(File.exist?(File.join(destination_root, "doc/config.rb"))).to be false
end
end
it "shows created status to the user" do
expect(invoke!).to eq(" create doc/config.rb\n")
end
context "specifying :verbose => false" do
let(:config) { {verbose: false} }
it "does not show any information" do
expect(invoke!).to be_empty
end
end
end
describe "#identical?" do
it "returns true if the destination link exists and is identical" do
expect(action.identical?).to be false
invoke!
expect(action.identical?).to be true
end
context "with source path relative to destination" do
let(:source) do
destination_path = File.dirname(File.join(destination_root, destination))
Pathname.new(super()).relative_path_from(Pathname.new(destination_path)).to_s
end
it "returns true if the destination link exists and is identical" do
expect(action.identical?).to be false
invoke!
expect(action.identical?).to be true
end
end
end
describe "#revoke!" do
it "removes the symbolic link of non-existent destination" do
invoke!
File.delete(tempfile.path)
revoke!
expect(File.symlink?(action.destination)).to be false
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/actions/empty_directory_spec.rb | spec/actions/empty_directory_spec.rb | require "helper"
require "thor/actions"
describe Thor::Actions::EmptyDirectory do
before do
::FileUtils.rm_rf(destination_root)
end
def empty_directory(destination, options = {})
@action = Thor::Actions::EmptyDirectory.new(base, destination)
end
def invoke!
capture(:stdout) { @action.invoke! }
end
def revoke!
capture(:stdout) { @action.revoke! }
end
def base
@base ||= MyCounter.new([1, 2], {}, destination_root: destination_root)
end
describe "#destination" do
it "returns the full destination with the destination_root" do
expect(empty_directory("doc").destination).to eq(File.join(destination_root, "doc"))
end
it "takes relative root into account" do
base.inside("doc") do
expect(empty_directory("contents").destination).to eq(File.join(destination_root, "doc", "contents"))
end
end
end
describe "#relative_destination" do
it "returns the relative destination to the original destination root" do
base.inside("doc") do
expect(empty_directory("contents").relative_destination).to eq("doc/contents")
end
end
end
describe "#given_destination" do
it "returns the destination supplied by the user" do
base.inside("doc") do
expect(empty_directory("contents").given_destination).to eq("contents")
end
end
end
describe "#invoke!" do
it "copies the file to the specified destination" do
empty_directory("doc")
invoke!
expect(File.exist?(File.join(destination_root, "doc"))).to be true
end
it "shows created status to the user" do
empty_directory("doc")
expect(invoke!).to eq(" create doc\n")
end
it "does not create a directory if pretending" do
base.inside("foo", pretend: true) do
empty_directory("ghost")
end
expect(File.exist?(File.join(base.destination_root, "ghost"))).to be false
end
describe "when directory exists" do
it "shows exist status" do
empty_directory("doc")
invoke!
expect(invoke!).to eq(" exist doc\n")
end
end
end
describe "#revoke!" do
it "removes the destination file" do
empty_directory("doc")
invoke!
revoke!
expect(File.exist?(@action.destination)).to be false
end
end
describe "#exists?" do
it "returns true if the destination file exists" do
empty_directory("doc")
expect(@action.exists?).to be false
invoke!
expect(@action.exists?).to be true
end
end
context "protected methods" do
describe "#convert_encoded_instructions" do
before do
empty_directory("test_dir")
allow(@action.base).to receive(:file_name).and_return("expected")
end
it "accepts and executes a 'legal' %\w+% encoded instruction" do
expect(@action.send(:convert_encoded_instructions, "%file_name%.txt")).to eq("expected.txt")
end
it "accepts and executes a private %\w+% encoded instruction" do
@action.base.extend Module.new {
def private_file_name
"expected"
end
private :private_file_name
}
expect(@action.send(:convert_encoded_instructions, "%private_file_name%.txt")).to eq("expected.txt")
end
it "ignores an 'illegal' %\w+% encoded instruction" do
expect(@action.send(:convert_encoded_instructions, "%some_name%.txt")).to eq("%some_name%.txt")
end
it "ignores incorrectly encoded instruction" do
expect(@action.send(:convert_encoded_instructions, "%some.name%.txt")).to eq("%some.name%.txt")
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/actions/inject_into_file_spec.rb | spec/actions/inject_into_file_spec.rb | # encoding: utf-8
require "helper"
require "thor/actions"
describe Thor::Actions::InjectIntoFile do
before do
::FileUtils.rm_rf(destination_root)
::FileUtils.cp_r(source_root, destination_root)
end
def invoker(options = {})
@invoker ||= MyCounter.new([1, 2], options, destination_root: destination_root)
end
def revoker
@revoker ||= MyCounter.new([1, 2], {}, destination_root: destination_root, behavior: :revoke)
end
def invoke!(*args, &block)
capture(:stdout) { invoker.insert_into_file(*args, &block) }
end
def invoke_with_a_bang!(*args, &block)
capture(:stdout) { invoker.insert_into_file!(*args, &block) }
end
def revoke!(*args, &block)
capture(:stdout) { revoker.insert_into_file(*args, &block) }
end
def file
File.join(destination_root, "doc/README")
end
describe "#invoke!" do
it "changes the file adding content after the flag" do
invoke! "doc/README", "\nmore content", after: "__start__"
expect(File.read(file)).to eq("__start__\nmore content\nREADME\n__end__\n")
end
it "changes the file adding content before the flag" do
invoke! "doc/README", "more content\n", before: "__end__"
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "appends content to the file if before and after arguments not provided" do
invoke!("doc/README", "more content\n")
expect(File.read(file)).to eq("__start__\nREADME\n__end__\nmore content\n")
end
it "does not change the file if replacement present in the file" do
invoke!("doc/README", "more specific content\n")
expect(invoke!("doc/README", "more specific content\n")).to(
eq(" unchanged doc/README\n")
)
end
it "does not change the file and logs the warning if flag not found in the file" do
expect(invoke!("doc/README", "more content\n", after: "whatever")).to(
eq("#{Thor::Actions::WARNINGS[:unchanged_no_flag]} doc/README\n")
)
end
it "accepts data as a block" do
invoke! "doc/README", before: "__end__" do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "logs status" do
expect(invoke!("doc/README", "\nmore content", after: "__start__")).to eq(" insert doc/README\n")
end
it "logs status if pretending" do
invoker(pretend: true)
expect(invoke!("doc/README", "\nmore content", after: "__start__")).to eq(" insert doc/README\n")
end
it "does not change the file if pretending" do
invoker pretend: true
invoke! "doc/README", "\nmore content", after: "__start__"
expect(File.read(file)).to eq("__start__\nREADME\n__end__\n")
end
it "does not change the file if already includes content" do
invoke! "doc/README", before: "__end__" do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
invoke! "doc/README", before: "__end__" do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "does not change the file if already includes content using before with capture" do
invoke! "doc/README", before: /(__end__)/ do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
invoke! "doc/README", before: /(__end__)/ do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "does not change the file if already includes content using after with capture" do
invoke! "doc/README", after: /(README\n)/ do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
invoke! "doc/README", after: /(README\n)/ do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "does not attempt to change the file if it doesn't exist - instead raises Thor::Error" do
expect do
invoke! "idontexist", before: "something" do
"any content"
end
end.to raise_error(Thor::Error, /does not appear to exist/)
expect(File.exist?("idontexist")).to be_falsey
end
it "does not attempt to change the file if it doesn't exist and pretending" do
expect do
invoker pretend: true
invoke! "idontexist", before: "something" do
"any content"
end
end.not_to raise_error
expect(File.exist?("idontexist")).to be_falsey
end
it "does change the file if already includes content and :force is true" do
invoke! "doc/README", before: "__end__" do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
invoke! "doc/README", before: "__end__", force: true do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\nmore content\n__end__\n")
end
it "can insert chinese" do
encoding_original = Encoding.default_external
begin
silence_warnings do
Encoding.default_external = Encoding.find("UTF-8")
end
invoke! "doc/README.zh", "\n中文", after: "__start__"
expect(File.read(File.join(destination_root, "doc/README.zh"))).to eq("__start__\n中文\n说明\n__end__\n")
ensure
silence_warnings do
Encoding.default_external = encoding_original
end
end
end
context "with a bang" do
it "changes the file adding content after the flag" do
invoke_with_a_bang! "doc/README", "\nmore content", after: "__start__"
expect(File.read(file)).to eq("__start__\nmore content\nREADME\n__end__\n")
end
it "changes the file adding content before the flag" do
invoke_with_a_bang! "doc/README", "more content\n", before: "__end__"
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "appends content to the file if before and after arguments not provided" do
invoke_with_a_bang!("doc/README", "more content\n")
expect(File.read(file)).to eq("__start__\nREADME\n__end__\nmore content\n")
end
it "does not change the file and raises an error if replacement present in the file" do
invoke_with_a_bang!("doc/README", "more specific content\n")
expect do
invoke_with_a_bang!("doc/README", "more specific content\n")
end.to raise_error(Thor::Error, "The content of #{destination_root}/doc/README did not change")
end
it "does not change the file and raises an error if flag not found in the file" do
expect do
invoke_with_a_bang!("doc/README", "more content\n", after: "whatever")
end.to raise_error(Thor::Error, "The content of #{destination_root}/doc/README did not change")
end
it "accepts data as a block" do
invoke_with_a_bang! "doc/README", before: "__end__" do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "logs status" do
expect(invoke_with_a_bang!("doc/README", "\nmore content", after: "__start__")).to eq(" insert doc/README\n")
end
it "logs status if pretending" do
invoker(pretend: true)
expect(invoke_with_a_bang!("doc/README", "\nmore content", after: "__start__")).to eq(" insert doc/README\n")
end
it "does not change the file if pretending" do
invoker pretend: true
invoke_with_a_bang! "doc/README", "\nmore content", after: "__start__"
expect(File.read(file)).to eq("__start__\nREADME\n__end__\n")
end
it "does not change the file and raises an error if already includes content" do
invoke_with_a_bang! "doc/README", before: "__end__" do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
expect do
invoke_with_a_bang! "doc/README", before: "__end__" do
"more content\n"
end
end.to raise_error(Thor::Error, "The content of #{destination_root}/doc/README did not change")
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "does not change the file and raises an error if already includes content using before with capture" do
invoke_with_a_bang! "doc/README", before: /(__end__)/ do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
expect do
invoke_with_a_bang! "doc/README", before: /(__end__)/ do
"more content\n"
end
end.to raise_error(Thor::Error, "The content of #{destination_root}/doc/README did not change")
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "does not change the file and raises an error if already includes content using after with capture" do
invoke_with_a_bang! "doc/README", after: /(README\n)/ do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
expect do
invoke_with_a_bang! "doc/README", after: /(README\n)/ do
"more content\n"
end
end.to raise_error(Thor::Error, "The content of #{destination_root}/doc/README did not change")
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end
it "does not attempt to change the file if it doesn't exist - instead raises Thor::Error" do
expect do
invoke_with_a_bang! "idontexist", before: "something" do
"any content"
end
end.to raise_error(Thor::Error, /does not appear to exist/)
expect(File.exist?("idontexist")).to be_falsey
end
it "does not attempt to change the file if it doesn't exist and pretending" do
expect do
invoker pretend: true
invoke_with_a_bang! "idontexist", before: "something" do
"any content"
end
end.not_to raise_error
expect(File.exist?("idontexist")).to be_falsey
end
it "does change the file if already includes content and :force is true" do
invoke_with_a_bang! "doc/README", before: "__end__" do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
invoke_with_a_bang! "doc/README", before: "__end__", force: true do
"more content\n"
end
expect(File.read(file)).to eq("__start__\nREADME\nmore content\nmore content\n__end__\n")
end
it "can insert chinese" do
encoding_original = Encoding.default_external
begin
silence_warnings do
Encoding.default_external = Encoding.find("UTF-8")
end
invoke_with_a_bang! "doc/README.zh", "\n中文", after: "__start__"
expect(File.read(File.join(destination_root, "doc/README.zh"))).to eq("__start__\n中文\n说明\n__end__\n")
ensure
silence_warnings do
Encoding.default_external = encoding_original
end
end
end
it "does not mutate the provided config" do
config = {after: "__start__"}
invoke_with_a_bang! "doc/README", "\nmore content", config
expect(File.read(file)).to eq("__start__\nmore content\nREADME\n__end__\n")
expect(config).to eq({after: "__start__"})
end
end
end
describe "#revoke!" do
it "subtracts the destination file after injection" do
invoke! "doc/README", "\nmore content", after: "__start__"
revoke! "doc/README", "\nmore content", after: "__start__"
expect(File.read(file)).to eq("__start__\nREADME\n__end__\n")
end
it "subtracts the destination file before injection" do
invoke! "doc/README", "more content\n", before: "__start__"
revoke! "doc/README", "more content\n", before: "__start__"
expect(File.read(file)).to eq("__start__\nREADME\n__end__\n")
end
it "subtracts even with double after injection" do
invoke! "doc/README", "\nmore content", after: "__start__"
invoke! "doc/README", "\nanother stuff", after: "__start__"
revoke! "doc/README", "\nmore content", after: "__start__"
expect(File.read(file)).to eq("__start__\nanother stuff\nREADME\n__end__\n")
end
it "subtracts even with double before injection" do
invoke! "doc/README", "more content\n", before: "__start__"
invoke! "doc/README", "another stuff\n", before: "__start__"
revoke! "doc/README", "more content\n", before: "__start__"
expect(File.read(file)).to eq("another stuff\n__start__\nREADME\n__end__\n")
end
it "subtracts when prepending" do
invoke! "doc/README", "more content\n", after: /\A/
invoke! "doc/README", "another stuff\n", after: /\A/
revoke! "doc/README", "more content\n", after: /\A/
expect(File.read(file)).to eq("another stuff\n__start__\nREADME\n__end__\n")
end
it "subtracts when appending" do
invoke! "doc/README", "more content\n", before: /\z/
invoke! "doc/README", "another stuff\n", before: /\z/
revoke! "doc/README", "more content\n", before: /\z/
expect(File.read(file)).to eq("__start__\nREADME\n__end__\nanother stuff\n")
end
it "shows progress information to the user" do
invoke!("doc/README", "\nmore content", after: "__start__")
expect(revoke!("doc/README", "\nmore content", after: "__start__")).to eq(" subtract doc/README\n")
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/core_ext/hash_with_indifferent_access_spec.rb | spec/core_ext/hash_with_indifferent_access_spec.rb | require "helper"
require "thor/core_ext/hash_with_indifferent_access"
describe Thor::CoreExt::HashWithIndifferentAccess do
before do
@hash = Thor::CoreExt::HashWithIndifferentAccess.new :foo => "bar", "baz" => "bee", :force => true
end
it "has values accessible by either strings or symbols" do
expect(@hash["foo"]).to eq("bar")
expect(@hash[:foo]).to eq("bar")
expect(@hash.values_at(:foo, :baz)).to eq(%w(bar bee))
expect(@hash.delete(:foo)).to eq("bar")
end
it "supports except" do
unexcepted_hash = @hash.dup
@hash.except("foo")
expect(@hash).to eq(unexcepted_hash)
expect(@hash.except("foo")).to eq("baz" => "bee", "force" => true)
expect(@hash.except("foo", "baz")).to eq("force" => true)
expect(@hash.except(:foo)).to eq("baz" => "bee", "force" => true)
expect(@hash.except(:foo, :baz)).to eq("force" => true)
end
it "supports fetch" do
expect(@hash.fetch("foo")).to eq("bar")
expect(@hash.fetch("foo", nil)).to eq("bar")
expect(@hash.fetch(:foo)).to eq("bar")
expect(@hash.fetch(:foo, nil)).to eq("bar")
expect(@hash.fetch("baz")).to eq("bee")
expect(@hash.fetch("baz", nil)).to eq("bee")
expect(@hash.fetch(:baz)).to eq("bee")
expect(@hash.fetch(:baz, nil)).to eq("bee")
expect { @hash.fetch(:missing) }.to raise_error(IndexError)
expect(@hash.fetch(:missing, :found)).to eq(:found)
end
it "supports slice" do
expect(@hash.slice("foo")).to eq({"foo" => "bar"})
expect(@hash.slice(:foo)).to eq({"foo" => "bar"})
expect(@hash.slice("baz")).to eq({"baz" => "bee"})
expect(@hash.slice(:baz)).to eq({"baz" => "bee"})
expect(@hash.slice("foo", "baz")).to eq({"foo" => "bar", "baz" => "bee"})
expect(@hash.slice(:foo, :baz)).to eq({"foo" => "bar", "baz" => "bee"})
expect(@hash.slice("missing")).to eq({})
expect(@hash.slice(:missing)).to eq({})
end
it "has key checkable by either strings or symbols" do
expect(@hash.key?("foo")).to be true
expect(@hash.key?(:foo)).to be true
expect(@hash.key?("nothing")).to be false
expect(@hash.key?(:nothing)).to be false
end
it "handles magic boolean predicates" do
expect(@hash.force?).to be true
expect(@hash.foo?).to be true
expect(@hash.nothing?).to be false
end
it "handles magic comparisons" do
expect(@hash.foo?("bar")).to be true
expect(@hash.foo?("bee")).to be false
end
it "maps methods to keys" do
expect(@hash.foo).to eq(@hash["foo"])
end
it "merges keys independent if they are symbols or strings" do
@hash["force"] = false
@hash[:baz] = "boom"
expect(@hash[:force]).to eq(false)
expect(@hash["baz"]).to eq("boom")
end
it "creates a new hash by merging keys independent if they are symbols or strings" do
other = @hash.merge("force" => false, :baz => "boom")
expect(other[:force]).to eq(false)
expect(other["baz"]).to eq("boom")
end
it "converts to a traditional hash" do
expect(@hash.to_hash.class).to eq(Hash)
expect(@hash).to eq("foo" => "bar", "baz" => "bee", "force" => true)
end
it "handles reverse_merge" do
other = {:foo => "qux", "boo" => "bae"}
new_hash = @hash.reverse_merge(other)
expect(@hash.object_id).not_to eq(new_hash.object_id)
expect(new_hash[:foo]).to eq("bar")
expect(new_hash[:boo]).to eq("bae")
end
it "handles reverse_merge!" do
other = {:foo => "qux", "boo" => "bae"}
new_hash = @hash.reverse_merge!(other)
expect(@hash.object_id).to eq(new_hash.object_id)
expect(new_hash[:foo]).to eq("bar")
expect(new_hash[:boo]).to eq("bae")
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/shell/html_spec.rb | spec/shell/html_spec.rb | require "helper"
describe Thor::Shell::HTML do
def shell
@shell ||= Thor::Shell::HTML.new
end
describe "#say" do
it "sets the color if specified" do
out = capture(:stdout) { shell.say "Wow! Now we have colors!", :green }
expect(out.chomp).to eq('<span style="color: green;">Wow! Now we have colors!</span>')
end
it "sets bold if specified" do
out = capture(:stdout) { shell.say "Wow! Now we have colors *and* bold!", [:green, :bold] }
expect(out.chomp).to eq('<span style="color: green; font-weight: bold;">Wow! Now we have colors *and* bold!</span>')
end
it "does not use a new line even with colors" do
out = capture(:stdout) { shell.say "Wow! Now we have colors! ", :green }
expect(out.chomp).to eq('<span style="color: green;">Wow! Now we have colors! </span>')
end
end
describe "#say_status" do
it "uses color to say status" do
expect($stdout).to receive(:print).with("<span style=\"color: red; font-weight: bold;\"> conflict</span> README\n")
shell.say_status :conflict, "README", :red
end
end
describe "#set_color" do
it "escapes HTML content when using the default colors" do
expect(shell.set_color("<htmlcontent>", :blue)).to eq "<span style=\"color: blue;\"><htmlcontent></span>"
end
it "escapes HTML content when not using the default colors" do
expect(shell.set_color("<htmlcontent>", [:nocolor])).to eq "<span style=\";\"><htmlcontent></span>"
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/shell/color_spec.rb | spec/shell/color_spec.rb | require "helper"
describe Thor::Shell::Color do
def shell
@shell ||= Thor::Shell::Color.new
end
before do
allow($stdout).to receive(:tty?).and_return(true)
allow(ENV).to receive(:[]).and_return(nil)
allow(ENV).to receive(:[]).with("TERM").and_return("ansi")
allow_any_instance_of(StringIO).to receive(:tty?).and_return(true)
end
describe "#ask" do
it "sets the color if specified and tty?" do
expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? \e[0m", anything).and_return("yes")
shell.ask "Is this green?", :green
expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? [Yes, No, Maybe] \e[0m", anything).and_return("Yes")
shell.ask "Is this green?", :green, limited_to: %w(Yes No Maybe)
end
it "does not set the color if specified and NO_COLOR is set to a non-empty value" do
allow(ENV).to receive(:[]).with("NO_COLOR").and_return("non-empty value")
expect(Thor::LineEditor).to receive(:readline).with("Is this green? ", anything).and_return("yes")
shell.ask "Is this green?", :green
expect(Thor::LineEditor).to receive(:readline).with("Is this green? [Yes, No, Maybe] ", anything).and_return("Yes")
shell.ask "Is this green?", :green, limited_to: %w(Yes No Maybe)
end
it "sets the color when NO_COLOR is ignored because the environment variable is nil" do
allow(ENV).to receive(:[]).with("NO_COLOR").and_return(nil)
expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? \e[0m", anything).and_return("yes")
shell.ask "Is this green?", :green
expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? [Yes, No, Maybe] \e[0m", anything).and_return("Yes")
shell.ask "Is this green?", :green, limited_to: %w(Yes No Maybe)
end
it "sets the color when NO_COLOR is ignored because the environment variable is an empty-string" do
allow(ENV).to receive(:[]).with("NO_COLOR").and_return("")
expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? \e[0m", anything).and_return("yes")
shell.ask "Is this green?", :green
expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? [Yes, No, Maybe] \e[0m", anything).and_return("Yes")
shell.ask "Is this green?", :green, limited_to: %w(Yes No Maybe)
end
it "handles an Array of colors" do
expect(Thor::LineEditor).to receive(:readline).with("\e[32m\e[47m\e[1mIs this green on white? \e[0m", anything).and_return("yes")
shell.ask "Is this green on white?", [:green, :on_white, :bold]
end
it "supports the legacy color syntax" do
expect(Thor::LineEditor).to receive(:readline).with("\e[1m\e[34mIs this legacy blue? \e[0m", anything).and_return("yes")
shell.ask "Is this legacy blue?", [:blue, true]
end
end
describe "#say" do
it "set the color if specified and tty?" do
out = capture(:stdout) do
shell.say "Wow! Now we have colors!", :green
end
expect(out.chomp).to eq("\e[32mWow! Now we have colors!\e[0m")
end
it "does not set the color if output is not a tty" do
out = capture(:stdout) do
expect($stdout).to receive(:tty?).and_return(false)
shell.say "Wow! Now we have colors!", :green
end
expect(out.chomp).to eq("Wow! Now we have colors!")
end
it "does not set the color if NO_COLOR is set to any value that is not an empty string" do
allow(ENV).to receive(:[]).with("NO_COLOR").and_return("non-empty string value")
out = capture(:stdout) do
shell.say "NO_COLOR is enforced! We should not have colors!", :green
end
expect(out.chomp).to eq("NO_COLOR is enforced! We should not have colors!")
end
it "colors are still used and NO_COLOR is ignored if the environment variable is nil" do
allow(ENV).to receive(:[]).with("NO_COLOR").and_return(nil)
out = capture(:stdout) do
shell.say "NO_COLOR is ignored! We have colors!", :green
end
expect(out.chomp).to eq("\e[32mNO_COLOR is ignored! We have colors!\e[0m")
end
it "colors are still used and NO_COLOR is ignored if the environment variable is an empty-string" do
allow(ENV).to receive(:[]).with("NO_COLOR").and_return("")
out = capture(:stdout) do
shell.say "NO_COLOR is ignored! We have colors!", :green
end
expect(out.chomp).to eq("\e[32mNO_COLOR is ignored! We have colors!\e[0m")
end
it "does not use a new line even with colors" do
out = capture(:stdout) do
shell.say "Wow! Now we have colors! ", :green
end
expect(out.chomp).to eq("\e[32mWow! Now we have colors! \e[0m")
end
it "handles an Array of colors" do
out = capture(:stdout) do
shell.say "Wow! Now we have colors *and* background colors", [:green, :on_red, :bold]
end
expect(out.chomp).to eq("\e[32m\e[41m\e[1mWow! Now we have colors *and* background colors\e[0m")
end
it "supports the legacy color syntax" do
out = capture(:stdout) do
shell.say "Wow! This still works?", [:blue, true]
end
expect(out.chomp).to eq("\e[1m\e[34mWow! This still works?\e[0m")
end
end
describe "#say_status" do
it "uses color to say status" do
out = capture(:stdout) do
shell.say_status :conflict, "README", :red
end
expect(out.chomp).to eq("\e[1m\e[31m conflict\e[0m README")
end
end
describe "#set_color" do
it "colors a string with a foreground color" do
red = shell.set_color "hi!", :red
expect(red).to eq("\e[31mhi!\e[0m")
end
it "colors a string with a background color" do
on_red = shell.set_color "hi!", :white, :on_red
expect(on_red).to eq("\e[37m\e[41mhi!\e[0m")
end
it "colors a string with a bold color" do
bold = shell.set_color "hi!", :white, true
expect(bold).to eq("\e[1m\e[37mhi!\e[0m")
bold = shell.set_color "hi!", :white, :bold
expect(bold).to eq("\e[37m\e[1mhi!\e[0m")
bold = shell.set_color "hi!", :white, :on_red, :bold
expect(bold).to eq("\e[37m\e[41m\e[1mhi!\e[0m")
end
it "does nothing when there are no colors" do
colorless = shell.set_color "hi!", nil
expect(colorless).to eq("hi!")
colorless = shell.set_color "hi!"
expect(colorless).to eq("hi!")
end
it "does nothing when stdout is not a tty" do
allow($stdout).to receive(:tty?).and_return(false)
colorless = shell.set_color "hi!", :white
expect(colorless).to eq("hi!")
end
it "does nothing when the TERM environment variable is set to 'dumb'" do
allow(ENV).to receive(:[]).with("TERM").and_return("dumb")
colorless = shell.set_color "hi!", :white
expect(colorless).to eq("hi!")
end
it "does nothing when the NO_COLOR environment variable is set to a non-empty string" do
allow(ENV).to receive(:[]).with("NO_COLOR").and_return("non-empty value")
allow($stdout).to receive(:tty?).and_return(true)
colorless = shell.set_color "hi!", :white
expect(colorless).to eq("hi!")
end
it "sets color when the NO_COLOR environment variable is ignored for being nil" do
allow(ENV).to receive(:[]).with("NO_COLOR").and_return(nil)
allow($stdout).to receive(:tty?).and_return(true)
red = shell.set_color "hi!", :red
expect(red).to eq("\e[31mhi!\e[0m")
on_red = shell.set_color "hi!", :white, :on_red
expect(on_red).to eq("\e[37m\e[41mhi!\e[0m")
end
it "sets color when the NO_COLOR environment variable is ignored for being an empty string" do
allow(ENV).to receive(:[]).with("NO_COLOR").and_return("")
allow($stdout).to receive(:tty?).and_return(true)
red = shell.set_color "hi!", :red
expect(red).to eq("\e[31mhi!\e[0m")
on_red = shell.set_color "hi!", :white, :on_red
expect(on_red).to eq("\e[37m\e[41mhi!\e[0m")
end
end
describe "#file_collision" do
describe "when a block is given" do
it "invokes the diff command" do
allow($stdout).to receive(:print)
allow($stdout).to receive(:tty?).and_return(true)
expect(Thor::LineEditor).to receive(:readline).and_return("d", "n")
output = capture(:stdout) { shell.file_collision("spec/fixtures/doc/README") { "README\nEND\n" } }
expect(output).to match(/\e\[31m\- __start__\e\[0m/)
expect(output).to match(/^ README/)
expect(output).to match(/\e\[32m\+ END\e\[0m/)
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/shell/basic_spec.rb | spec/shell/basic_spec.rb | # coding: utf-8
require "helper"
describe Thor::Shell::Basic do
def shell
@shell ||= Thor::Shell::Basic.new
end
describe "#padding" do
it "cannot be set to below zero" do
shell.padding = 10
expect(shell.padding).to eq(10)
shell.padding = -1
expect(shell.padding).to eq(0)
end
end
describe "#indent" do
it "sets the padding temporarily" do
shell.indent { expect(shell.padding).to eq(1) }
expect(shell.padding).to eq(0)
end
it "derives padding from original value" do
shell.padding = 6
shell.indent { expect(shell.padding).to eq(7) }
end
it "accepts custom indentation amounts" do
shell.indent(6) do
expect(shell.padding).to eq(6)
end
end
it "increases the padding when nested" do
shell.indent do
expect(shell.padding).to eq(1)
shell.indent do
expect(shell.padding).to eq(2)
end
end
expect(shell.padding).to eq(0)
end
end
describe "#ask" do
it "prints a message to the user and gets the response" do
expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", {}).and_return("Sure")
expect(shell.ask("Should I overwrite it?")).to eq("Sure")
end
it "prints a message to the user prefixed with the current padding" do
expect(Thor::LineEditor).to receive(:readline).with(" Enter your name: ", {}).and_return("George")
shell.padding = 2
shell.ask("Enter your name:")
end
it "prints a message and returns nil if EOF is given as input" do
expect(Thor::LineEditor).to receive(:readline).with(" ", {}).and_return(nil)
expect(shell.ask("")).to eq(nil)
end
it "prints a message to the user and does not echo stdin if the echo option is set to false" do
expect($stdout).to receive(:print).with("What's your password? ")
expect($stdin).to receive(:noecho).and_return("mysecretpass")
expect(shell.ask("What's your password?", echo: false)).to eq("mysecretpass")
end
it "prints a message to the user with the available options, expects case-sensitive matching, and determines the correctness of the answer" do
flavors = %w(strawberry chocolate vanilla)
expect(Thor::LineEditor).to receive(:readline).with("What's your favorite Neopolitan flavor? [strawberry, chocolate, vanilla] ", {limited_to: flavors}).and_return("chocolate")
expect(shell.ask("What's your favorite Neopolitan flavor?", limited_to: flavors)).to eq("chocolate")
end
it "prints a message to the user with the available options, expects case-sensitive matching, and reasks the question after an incorrect response" do
flavors = %w(strawberry chocolate vanilla)
expect($stdout).to receive(:print).with("Your response must be one of: [strawberry, chocolate, vanilla]. Please try again.\n")
expect(Thor::LineEditor).to receive(:readline).with("What's your favorite Neopolitan flavor? [strawberry, chocolate, vanilla] ", {limited_to: flavors}).and_return("moose tracks", "chocolate")
expect(shell.ask("What's your favorite Neopolitan flavor?", limited_to: flavors)).to eq("chocolate")
end
it "prints a message to the user with the available options, expects case-sensitive matching, and reasks the question after a case-insensitive match" do
flavors = %w(strawberry chocolate vanilla)
expect($stdout).to receive(:print).with("Your response must be one of: [strawberry, chocolate, vanilla]. Please try again.\n")
expect(Thor::LineEditor).to receive(:readline).with("What's your favorite Neopolitan flavor? [strawberry, chocolate, vanilla] ", {limited_to: flavors}).and_return("cHoCoLaTe", "chocolate")
expect(shell.ask("What's your favorite Neopolitan flavor?", limited_to: flavors)).to eq("chocolate")
end
it "prints a message to the user with the available options, expects case-insensitive matching, and determines the correctness of the answer" do
flavors = %w(strawberry chocolate vanilla)
expect(Thor::LineEditor).to receive(:readline).with("What's your favorite Neopolitan flavor? [strawberry, chocolate, vanilla] ", {limited_to: flavors, case_insensitive: true}).and_return("CHOCOLATE")
expect(shell.ask("What's your favorite Neopolitan flavor?", limited_to: flavors, case_insensitive: true)).to eq("chocolate")
end
it "prints a message to the user with the available options, expects case-insensitive matching, and reasks the question after an incorrect response" do
flavors = %w(strawberry chocolate vanilla)
expect($stdout).to receive(:print).with("Your response must be one of: [strawberry, chocolate, vanilla]. Please try again.\n")
expect(Thor::LineEditor).to receive(:readline).with("What's your favorite Neopolitan flavor? [strawberry, chocolate, vanilla] ", {limited_to: flavors, case_insensitive: true}).and_return("moose tracks", "chocolate")
expect(shell.ask("What's your favorite Neopolitan flavor?", limited_to: flavors, case_insensitive: true)).to eq("chocolate")
end
it "prints a message to the user containing a default and sets the default if only enter is pressed" do
expect(Thor::LineEditor).to receive(:readline).with("What's your favorite Neopolitan flavor? (vanilla) ", {default: "vanilla"}).and_return("")
expect(shell.ask("What's your favorite Neopolitan flavor?", default: "vanilla")).to eq("vanilla")
end
it "prints a message to the user with the available options and reasks the question after an incorrect response and then returns the default" do
flavors = %w(strawberry chocolate vanilla)
expect($stdout).to receive(:print).with("Your response must be one of: [strawberry, chocolate, vanilla]. Please try again.\n")
expect(Thor::LineEditor).to receive(:readline).with("What's your favorite Neopolitan flavor? [strawberry, chocolate, vanilla] (vanilla) ", {default: "vanilla", limited_to: flavors}).and_return("moose tracks", "")
expect(shell.ask("What's your favorite Neopolitan flavor?", default: "vanilla", limited_to: flavors)).to eq("vanilla")
end
end
describe "#yes?" do
it "asks the user and returns true if the user replies yes" do
expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", {add_to_history: false}).and_return("y")
expect(shell.yes?("Should I overwrite it?")).to be true
end
it "asks the user and returns false if the user replies no" do
expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", {add_to_history: false}).and_return("n")
expect(shell.yes?("Should I overwrite it?")).not_to be true
end
it "asks the user and returns false if the user replies with an answer other than yes or no" do
expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", {add_to_history: false}).and_return("foobar")
expect(shell.yes?("Should I overwrite it?")).to be false
end
end
describe "#no?" do
it "asks the user and returns true if the user replies no" do
expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", {add_to_history: false}).and_return("n")
expect(shell.no?("Should I overwrite it?")).to be true
end
it "asks the user and returns false if the user replies yes" do
expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", {add_to_history: false}).and_return("Yes")
expect(shell.no?("Should I overwrite it?")).to be false
end
it "asks the user and returns false if the user replies with an answer other than yes or no" do
expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", {add_to_history: false}).and_return("foobar")
expect(shell.no?("Should I overwrite it?")).to be false
end
end
describe "#say" do
it "prints a message to the user" do
expect($stdout).to receive(:print).with("Running...\n")
shell.say("Running...")
end
it "prints a message to the user without new line if it ends with a whitespace" do
expect($stdout).to receive(:print).with("Running... ")
shell.say("Running... ")
end
it "does not use a new line with whitespace+newline embedded" do
expect($stdout).to receive(:print).with("It's \nRunning...\n")
shell.say("It's \nRunning...")
end
it "prints a message to the user without new line" do
expect($stdout).to receive(:print).with("Running...")
shell.say("Running...", nil, false)
end
it "coerces everything to a string before printing" do
expect($stdout).to receive(:print).with("this_is_not_a_string\n")
shell.say(:this_is_not_a_string, nil, true)
end
it "does not print a message if muted" do
expect($stdout).not_to receive(:print)
shell.mute do
shell.say("Running...")
end
end
it "does not print a message if base is set to quiet" do
shell.base = MyCounter.new [1, 2]
expect(shell.base).to receive(:options).and_return(quiet: true)
expect($stdout).not_to receive(:print)
shell.say("Running...")
end
end
describe "#say_error" do
it "prints a message to the user" do
expect($stderr).to receive(:print).with("Running...\n")
shell.say_error("Running...")
end
it "prints a message to the user without new line if it ends with a whitespace" do
expect($stderr).to receive(:print).with("Running... ")
shell.say_error("Running... ")
end
it "does not use a new line with whitespace+newline embedded" do
expect($stderr).to receive(:print).with("It's \nRunning...\n")
shell.say_error("It's \nRunning...")
end
it "prints a message to the user without new line" do
expect($stderr).to receive(:print).with("Running...")
shell.say_error("Running...", nil, false)
end
it "coerces everything to a string before printing" do
expect($stderr).to receive(:print).with("this_is_not_a_string\n")
shell.say_error(:this_is_not_a_string, nil, true)
end
it "does not print a message if muted" do
expect($stderr).not_to receive(:print)
shell.mute do
shell.say_error("Running...")
end
end
it "does not print a message if base is set to quiet" do
shell.base = MyCounter.new [1, 2]
expect(shell.base).to receive(:options).and_return(quiet: true)
expect($stderr).not_to receive(:print)
shell.say_error("Running...")
end
end
describe "#print_wrapped" do
let(:message) do
"Creates a back-up of the given folder by compressing it in a .tar.gz\n"\
"file and then uploading it to the configured Amazon S3 Bucket.\n\n"\
"It does not verify the integrity of the generated back-up."
end
before do
allow(ENV).to receive(:[]).with("THOR_COLUMNS").and_return(80)
end
context "without indentation" do
subject(:wrap_text) { described_class.new.print_wrapped(message) }
let(:expected_output) do
"Creates a back-up of the given folder by compressing it in a .tar.gz file and\n"\
"then uploading it to the configured Amazon S3 Bucket.\n\n"\
"It does not verify the integrity of the generated back-up.\n"
end
it "properly wraps the text around the 80th column" do
expect { wrap_text }.to output(expected_output).to_stdout
end
end
context "with indentation" do
subject(:wrap_text) { described_class.new.print_wrapped(message, indent: 4) }
let(:expected_output) do
" Creates a back-up of the given folder by compressing it in a .tar.gz file\n"\
" and then uploading it to the configured Amazon S3 Bucket.\n\n"\
" It does not verify the integrity of the generated back-up.\n"
end
it "properly wraps the text around the 80th column" do
expect { wrap_text }.to output(expected_output).to_stdout
end
end
end
describe "#say_status" do
it "prints a message to the user with status" do
expect($stdout).to receive(:print).with(" create ~/.thor/command.thor\n")
shell.say_status(:create, "~/.thor/command.thor")
end
it "always uses new line" do
expect($stdout).to receive(:print).with(" create \n")
shell.say_status(:create, "")
end
it "indents a multiline message" do
status = :foobar
lines = ["first line", "second line", " third line", " fourth line"]
expect($stdout).to receive(:print) do |string|
formatted_status = string[/^\s*#{status}\s*/]
margin = " " * formatted_status.length
expect(string).to eq(formatted_status + lines.join("\n#{margin}") + "\n")
end
shell.say_status(status, lines.join("\n") + "\n")
end
it "does not print a message if base is muted" do
expect(shell).to receive(:mute?).and_return(true)
expect($stdout).not_to receive(:print)
shell.mute do
shell.say_status(:created, "~/.thor/command.thor")
end
end
it "does not print a message if base is set to quiet" do
base = MyCounter.new [1, 2]
expect(base).to receive(:options).and_return(quiet: true)
expect($stdout).not_to receive(:print)
shell.base = base
shell.say_status(:created, "~/.thor/command.thor")
end
it "does not print a message if log status is set to false" do
expect($stdout).not_to receive(:print)
shell.say_status(:created, "~/.thor/command.thor", false)
end
it "uses padding to set message's left margin" do
shell.padding = 2
expect($stdout).to receive(:print).with(" create ~/.thor/command.thor\n")
shell.say_status(:create, "~/.thor/command.thor")
end
end
describe "#print_in_columns" do
before do
@array = [1_234_567_890]
@array += ("a".."e").to_a
end
it "prints in columns" do
content = capture(:stdout) { shell.print_in_columns(@array) }
expect(content.rstrip).to eq("1234567890 a b c d e")
end
end
describe "#print_table" do
before do
@table = []
@table << ["abc", "#123", "first three"]
@table << ["", "#0", "empty"]
@table << ["xyz", "#786", "last three"]
end
it "prints a table" do
content = capture(:stdout) { shell.print_table(@table) }
expect(content).to eq(<<-TABLE)
abc #123 first three
#0 empty
xyz #786 last three
TABLE
end
it "prints a table with indentation" do
content = capture(:stdout) { shell.print_table(@table, indent: 2) }
expect(content).to eq(<<-TABLE)
abc #123 first three
#0 empty
xyz #786 last three
TABLE
end
it "uses maximum terminal width" do
@table << ["def", "#456", "Lançam foo bar"]
@table << ["ghi", "#789", "بالله عليكم"]
content = capture(:stdout) { shell.print_table(@table, indent: 2, truncate: 20) }
expect(content).to eq(<<-TABLE)
abc #123 firs...
#0 empty
xyz #786 last...
def #456 Lanç...
ghi #789 بالل...
TABLE
end
it "honors the colwidth option" do
content = capture(:stdout) { shell.print_table(@table, colwidth: 10) }
expect(content).to eq(<<-TABLE)
abc #123 first three
#0 empty
xyz #786 last three
TABLE
end
it "prints tables with implicit columns" do
2.times { @table.first.pop }
content = capture(:stdout) { shell.print_table(@table) }
expect(content).to eq(<<-TABLE)
abc#{" "}
#0 empty
xyz #786 last three
TABLE
end
it "prints a table with small numbers and right-aligns them" do
table = [
["Name", "Number", "Color"], # rubocop: disable Style/WordArray
["Erik", 1, "green"]
]
content = capture(:stdout) { shell.print_table(table) }
expect(content).to eq(<<-TABLE)
Name Number Color
Erik 1 green
TABLE
end
it "doesn't output extra spaces for right-aligned columns in the last column" do
table = [
["Name", "Number"], # rubocop: disable Style/WordArray
["Erik", 1]
]
content = capture(:stdout) { shell.print_table(table) }
expect(content).to eq(<<-TABLE)
Name Number
Erik 1
TABLE
end
it "prints a table with big numbers" do
table = [
["Name", "Number", "Color"], # rubocop: disable Style/WordArray
["Erik", 1_234_567_890_123, "green"]
]
content = capture(:stdout) { shell.print_table(table) }
expect(content).to eq(<<-TABLE)
Name Number Color
Erik 1234567890123 green
TABLE
end
it "prints a table with borders" do
content = capture(:stdout) { shell.print_table(@table, borders: true) }
expect(content).to eq(<<-TABLE)
+-----+------+-------------+
| abc | #123 | first three |
| | #0 | empty |
| xyz | #786 | last three |
+-----+------+-------------+
TABLE
end
it "prints a table with borders and separators" do
@table.insert(1, :separator)
content = capture(:stdout) { shell.print_table(@table, borders: true) }
expect(content).to eq(<<-TABLE)
+-----+------+-------------+
| abc | #123 | first three |
+-----+------+-------------+
| | #0 | empty |
| xyz | #786 | last three |
+-----+------+-------------+
TABLE
end
it "prints a table with borders and small numbers and right-aligns them" do
table = [
["Name", "Number", "Color"], # rubocop: disable Style/WordArray
["Erik", 1, "green"]
]
content = capture(:stdout) { shell.print_table(table, borders: true) }
expect(content).to eq(<<-TABLE)
+------+--------+-------+
| Name | Number | Color |
| Erik | 1 | green |
+------+--------+-------+
TABLE
end
it "prints a table with borders and indentation" do
table = [
["Name", "Number", "Color"], # rubocop: disable Style/WordArray
["Erik", 1, "green"]
]
content = capture(:stdout) { shell.print_table(table, borders: true, indent: 2) }
expect(content).to eq(<<-TABLE)
+------+--------+-------+
| Name | Number | Color |
| Erik | 1 | green |
+------+--------+-------+
TABLE
end
end
describe "#file_collision" do
it "shows a menu with options" do
expect(Thor::LineEditor).to receive(:readline).with('Overwrite foo? (enter "h" for help) [Ynaqh] ', {add_to_history: false}).and_return("n")
shell.file_collision("foo")
end
it "outputs a new line and returns true if stdin is closed" do
expect($stdout).to receive(:print).with("\n")
expect(Thor::LineEditor).to receive(:readline).and_return(nil)
expect(shell.file_collision("foo")).to be true
end
it "returns true if the user chooses default option" do
expect(Thor::LineEditor).to receive(:readline).and_return("")
expect(shell.file_collision("foo")).to be true
end
it "returns false if the user chooses no" do
expect(Thor::LineEditor).to receive(:readline).and_return("n")
expect(shell.file_collision("foo")).to be false
end
it "returns true if the user chooses yes" do
expect(Thor::LineEditor).to receive(:readline).and_return("y")
expect(shell.file_collision("foo")).to be true
end
it "shows help usage if the user chooses help" do
expect(Thor::LineEditor).to receive(:readline).and_return("h", "n")
help = capture(:stdout) { shell.file_collision("foo") }
expect(help).to match(/h \- help, show this help/)
end
it "quits if the user chooses quit" do
expect($stdout).to receive(:print).with("Aborting...\n")
expect(Thor::LineEditor).to receive(:readline).and_return("q")
expect do
shell.file_collision("foo")
end.to raise_error(SystemExit)
end
it "always returns true if the user chooses always" do
expect(Thor::LineEditor).to receive(:readline).with('Overwrite foo? (enter "h" for help) [Ynaqh] ', {add_to_history: false}).and_return("a")
expect(shell.file_collision("foo")).to be true
expect($stdout).not_to receive(:print)
expect(shell.file_collision("foo")).to be true
end
describe "when a block is given" do
it "displays diff and merge options to the user" do
expect(Thor::LineEditor).to receive(:readline).with('Overwrite foo? (enter "h" for help) [Ynaqdhm] ', {add_to_history: false}).and_return("s")
shell.file_collision("foo") {}
end
it "invokes the diff command" do
expect(Thor::LineEditor).to receive(:readline).and_return("d")
expect(Thor::LineEditor).to receive(:readline).and_return("n")
expect(shell).to receive(:system).with("diff", "-u", "foo", /foo/)
capture(:stdout) { shell.file_collision("foo") {} }
end
it "invokes the merge tool" do
allow(shell).to receive(:merge_tool).and_return("meld")
expect(Thor::LineEditor).to receive(:readline).and_return("m")
expect(shell).to receive(:system).with("meld", /foo/, "foo")
capture(:stdout) { shell.file_collision("foo") {} }
end
it "invokes the merge tool that specified at ENV['THOR_MERGE']" do
allow(ENV).to receive(:[]).with("THOR_MERGE").and_return("meld")
expect(Thor::LineEditor).to receive(:readline).and_return("m")
expect(shell).to receive(:system).with("meld", /foo/, "foo")
capture(:stdout) { shell.file_collision("foo") {} }
end
it "invokes the merge tool with arguments when THOR_MERGE contains them" do
allow(ENV).to receive(:[]).with("THOR_MERGE").and_return("nvim -d")
expect(Thor::LineEditor).to receive(:readline).and_return("m")
expect(shell).to receive(:system).with("nvim", "-d", /foo/, "foo")
capture(:stdout) { shell.file_collision("foo") {} }
end
it "invokes the merge tool with arguments when there is no THOR_MERGE" do
expect(Thor::LineEditor).to receive(:readline).and_return("m")
expect(shell).to receive(:system).with("git", "difftool", "--no-index", /foo/, "foo")
capture(:stdout) { shell.file_collision("foo") {} }
end
it "show warning if user chooses merge but merge tool is not specified" do
allow(shell).to receive(:merge_tool).and_return("")
expect(Thor::LineEditor).to receive(:readline).and_return("m")
expect(Thor::LineEditor).to receive(:readline).and_return("n")
help = capture(:stdout) { shell.file_collision("foo") {} }
expect(help).to match(/Please specify merge tool to `THOR_MERGE` env/)
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/parser/option_spec.rb | spec/parser/option_spec.rb | require "helper"
require "thor/parser"
describe Thor::Option do
def parse(key, value)
Thor::Option.parse(key, value)
end
def option(name, options = {})
@option ||= Thor::Option.new(name, options)
end
describe "#parse" do
describe "with value as a symbol" do
describe "and symbol is a valid type" do
it "has type equals to the symbol" do
expect(parse(:foo, :string).type).to eq(:string)
expect(parse(:foo, :numeric).type).to eq(:numeric)
end
it "has no default value" do
expect(parse(:foo, :string).default).to be nil
expect(parse(:foo, :numeric).default).to be nil
end
end
describe "equals to :required" do
it "has type equals to :string" do
expect(parse(:foo, :required).type).to eq(:string)
end
it "has no default value" do
expect(parse(:foo, :required).default).to be nil
end
end
describe "and symbol is not a reserved key" do
it "has type equal to :string" do
expect(parse(:foo, :bar).type).to eq(:string)
end
it "has no default value" do
expect(parse(:foo, :bar).default).to be nil
end
end
end
describe "with value as hash" do
it "has default type :hash" do
expect(parse(:foo, a: :b).type).to eq(:hash)
end
it "has default value equal to the hash" do
expect(parse(:foo, a: :b).default).to eq(a: :b)
end
end
describe "with value as array" do
it "has default type :array" do
expect(parse(:foo, [:a, :b]).type).to eq(:array)
end
it "has default value equal to the array" do
expect(parse(:foo, [:a, :b]).default).to eq([:a, :b])
end
end
describe "with value as string" do
it "has default type :string" do
expect(parse(:foo, "bar").type).to eq(:string)
end
it "has default value equal to the string" do
expect(parse(:foo, "bar").default).to eq("bar")
end
end
describe "with value as numeric" do
it "has default type :numeric" do
expect(parse(:foo, 2.0).type).to eq(:numeric)
end
it "has default value equal to the numeric" do
expect(parse(:foo, 2.0).default).to eq(2.0)
end
end
describe "with value as boolean" do
it "has default type :boolean" do
expect(parse(:foo, true).type).to eq(:boolean)
expect(parse(:foo, false).type).to eq(:boolean)
end
it "has default value equal to the boolean" do
expect(parse(:foo, true).default).to eq(true)
expect(parse(:foo, false).default).to eq(false)
end
end
describe "with key as a symbol" do
it "sets the name equal to the key" do
expect(parse(:foo, true).name).to eq("foo")
end
end
describe "with key as an array" do
it "sets the first items in the array to the name" do
expect(parse([:foo, :b, "--bar"], true).name).to eq("foo")
end
it "sets all other items as normalized aliases" do
expect(parse([:foo, :b, "--bar"], true).aliases).to eq(["-b", "--bar"])
end
end
end
it "returns the switch name" do
expect(option("foo").switch_name).to eq("--foo")
expect(option("--foo").switch_name).to eq("--foo")
end
it "returns the human name" do
expect(option("foo").human_name).to eq("foo")
expect(option("--foo").human_name).to eq("foo")
end
it "converts underscores to dashes" do
expect(option("foo_bar").switch_name).to eq("--foo-bar")
end
it "can be required and have default values" do
option = option("foo", required: true, type: :string, default: "bar")
expect(option.default).to eq("bar")
expect(option).to be_required
end
it "raises an error if default is inconsistent with type and check_default_type is true" do
expect do
option("foo_bar", type: :numeric, default: "baz", check_default_type: true)
end.to raise_error(ArgumentError, 'Expected numeric default value for \'--foo-bar\'; got "baz" (string)')
end
it "raises an error if repeatable and default is inconsistent with type and check_default_type is true" do
expect do
option("foo_bar", type: :numeric, repeatable: true, default: "baz", check_default_type: true)
end.to raise_error(ArgumentError, 'Expected array default value for \'--foo-bar\'; got "baz" (string)')
end
it "raises an error type hash is repeatable and default is inconsistent with type and check_default_type is true" do
expect do
option("foo_bar", type: :hash, repeatable: true, default: "baz", check_default_type: true)
end.to raise_error(ArgumentError, 'Expected hash default value for \'--foo-bar\'; got "baz" (string)')
end
it "does not raises an error if type hash is repeatable and default is consistent with type and check_default_type is true" do
expect do
option("foo_bar", type: :hash, repeatable: true, default: {}, check_default_type: true)
end.not_to raise_error
end
it "does not raises an error if repeatable and default is consistent with type and check_default_type is true" do
expect do
option("foo_bar", type: :numeric, repeatable: true, default: [1], check_default_type: true)
end.not_to raise_error
end
it "does not raises an error if default is an symbol and type string and check_default_type is true" do
expect do
option("foo", type: :string, default: :bar, check_default_type: true)
end.not_to raise_error
end
it "does not raises an error if default is inconsistent with type and check_default_type is false" do
expect do
option("foo_bar", type: :numeric, default: "baz", check_default_type: false)
end.not_to raise_error
end
it "boolean options cannot be required" do
expect do
option("foo", required: true, type: :boolean)
end.to raise_error(ArgumentError, "An option cannot be boolean and required.")
end
it "does not raises an error if default is a boolean and it is required" do
expect do
option("foo", required: true, default: true)
end.not_to raise_error
end
it "allows type predicates" do
expect(parse(:foo, :string)).to be_string
expect(parse(:foo, :boolean)).to be_boolean
expect(parse(:foo, :numeric)).to be_numeric
end
it "raises an error on method missing" do
expect do
parse(:foo, :string).unknown?
end.to raise_error(NoMethodError)
end
describe "#usage" do
it "returns usage for string types" do
expect(parse(:foo, :string).usage).to eq("[--foo=FOO]")
end
it "returns usage for numeric types" do
expect(parse(:foo, :numeric).usage).to eq("[--foo=N]")
end
it "returns usage for array types" do
expect(parse(:foo, :array).usage).to eq("[--foo=one two three]")
end
it "returns usage for hash types" do
expect(parse(:foo, :hash).usage).to eq("[--foo=key:value]")
end
it "returns usage for boolean types" do
expect(parse(:foo, :boolean).usage).to eq("[--foo], [--no-foo], [--skip-foo]")
end
it "does not use padding when no aliases are given" do
expect(parse(:foo, :boolean).usage).to eq("[--foo], [--no-foo], [--skip-foo]")
end
it "documents a negative option when boolean" do
expect(parse(:foo, :boolean).usage).to include("[--no-foo]")
end
it "does not document a negative option for a negative boolean" do
expect(parse(:'no-foo', :boolean).usage).not_to include("[--no-no-foo]")
expect(parse(:'no-foo', :boolean).usage).not_to include("[--skip-no-foo]")
expect(parse(:'skip-foo', :boolean).usage).not_to include("[--no-skip-foo]")
expect(parse(:'skip-foo', :boolean).usage).not_to include("[--skip-skip-foo]")
end
it "does not document a negative option for an underscored negative boolean" do
expect(parse(:no_foo, :boolean).usage).not_to include("[--no-no-foo]")
end
it "documents a negative option for a positive boolean starting with 'no'" do
expect(parse(:'nougat', :boolean).usage).to include("[--no-nougat]")
end
it "uses banner when supplied" do
expect(option(:foo, required: false, type: :string, banner: "BAR").usage).to eq("[--foo=BAR]")
end
it "checks when banner is an empty string" do
expect(option(:foo, required: false, type: :string, banner: "").usage).to eq("[--foo]")
end
describe "with required values" do
it "does not show the usage between brackets" do
expect(parse(:foo, :required).usage).to eq("--foo=FOO")
end
end
describe "with aliases" do
it "does not show the usage between brackets" do
expect(parse([:foo, "-f", "-b"], :required).usage).to eq("-f, -b, --foo=FOO")
end
it "does not negate the aliases" do
expect(parse([:foo, "-f", "-b"], :boolean).usage).to eq("-f, -b, [--foo], [--no-foo], [--skip-foo]")
end
it "normalizes the aliases" do
expect(parse([:foo, :f, "-b"], :required).usage).to eq("-f, -b, --foo=FOO")
end
end
end
describe "#print_default" do
it "prints boolean with true default value" do
expect(option(:foo, {
required: false,
type: :boolean,
default: true
}).print_default).to eq(true)
end
it "prints boolean with false default value" do
expect(option(:foo, {
required: false,
type: :boolean,
default: false
}).print_default).to eq(false)
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/parser/argument_spec.rb | spec/parser/argument_spec.rb | require "helper"
require "thor/parser"
describe Thor::Argument do
def argument(name, options = {})
@argument ||= Thor::Argument.new(name, options)
end
describe "errors" do
it "raises an error if name is not supplied" do
expect do
argument(nil)
end.to raise_error(ArgumentError, "Argument name can't be nil.")
end
it "raises an error if type is unknown" do
expect do
argument(:command, type: :unknown)
end.to raise_error(ArgumentError, "Type :unknown is not valid for arguments.")
end
it "raises an error if argument is required and has default values" do
expect do
argument(:command, type: :string, default: "bar", required: true)
end.to raise_error(ArgumentError, "An argument cannot be required and have default value.")
end
it "raises an error if enum isn't enumerable" do
expect do
argument(:command, type: :string, enum: "bar")
end.to raise_error(ArgumentError, "An argument cannot have an enum other than an enumerable.")
end
end
describe "#usage" do
it "returns usage for string types" do
expect(argument(:foo, type: :string).usage).to eq("FOO")
end
it "returns usage for numeric types" do
expect(argument(:foo, type: :numeric).usage).to eq("N")
end
it "returns usage for array types" do
expect(argument(:foo, type: :array).usage).to eq("one two three")
end
it "returns usage for hash types" do
expect(argument(:foo, type: :hash).usage).to eq("key:value")
end
end
describe "#print_default" do
it "prints arrays in a copy pasteable way" do
expect(argument(:foo, {
required: false,
type: :array,
default: ["one","two"]
}).print_default).to eq('"one" "two"')
end
it "prints arrays with a single string default as before" do
expect(argument(:foo, {
required: false,
type: :array,
default: "foobar"
}).print_default).to eq("foobar")
end
it "prints none arrays as default" do
expect(argument(:foo, {
required: false,
type: :numeric,
default: 13,
}).print_default).to eq(13)
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/parser/arguments_spec.rb | spec/parser/arguments_spec.rb | require "helper"
require "thor/parser"
describe Thor::Arguments do
def create(opts = {})
arguments = opts.map do |type, default|
options = {required: default.nil?, type: type, default: default}
Thor::Argument.new(type.to_s, options)
end
arguments.sort! { |a, b| b.name <=> a.name }
@opt = Thor::Arguments.new(arguments)
end
def parse(*args)
@opt.parse(args)
end
describe "#parse" do
it "parses arguments in the given order" do
create string: nil, numeric: nil
expect(parse("name", "13")["string"]).to eq("name")
expect(parse("name", "13")["numeric"]).to eq(13)
expect(parse("name", "+13")["numeric"]).to eq(13)
expect(parse("name", "+13.3")["numeric"]).to eq(13.3)
expect(parse("name", "-13")["numeric"]).to eq(-13)
expect(parse("name", "-13.3")["numeric"]).to eq(-13.3)
end
it "accepts hashes" do
create string: nil, hash: nil
expect(parse("product", "title:string", "age:integer")["string"]).to eq("product")
expect(parse("product", "title:string", "age:integer")["hash"]).to eq("title" => "string", "age" => "integer")
expect(parse("product", "url:http://www.amazon.com/gp/product/123")["hash"]).to eq("url" => "http://www.amazon.com/gp/product/123")
end
it "accepts arrays" do
create string: nil, array: nil
expect(parse("product", "title", "age")["string"]).to eq("product")
expect(parse("product", "title", "age")["array"]).to eq(%w(title age))
end
it "accepts - as an array argument" do
create array: nil
expect(parse("-")["array"]).to eq(%w(-))
expect(parse("-", "title", "-")["array"]).to eq(%w(- title -))
end
describe "with no inputs" do
it "and no arguments returns an empty hash" do
create
expect(parse).to eq({})
end
it "and required arguments raises an error" do
create string: nil, numeric: nil
expect { parse }.to raise_error(Thor::RequiredArgumentMissingError, "No value provided for required arguments 'string', 'numeric'")
end
it "and default arguments returns default values" do
create string: "name", numeric: 13
expect(parse).to eq("string" => "name", "numeric" => 13)
end
end
it "returns the input if it's already parsed" do
create string: nil, hash: nil, array: nil, numeric: nil
expect(parse("", 0, {}, [])).to eq("string" => "", "numeric" => 0, "hash" => {}, "array" => [])
end
it "returns the default value if none is provided" do
create string: "foo", numeric: 3.0
expect(parse("bar")).to eq("string" => "bar", "numeric" => 3.0)
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/spec/parser/options_spec.rb | spec/parser/options_spec.rb | require "helper"
require "thor/parser"
describe Thor::Options do
def create(opts, defaults = {}, stop_on_unknown = false, exclusives = [], at_least_ones = [])
relation = {
exclusive_option_names: exclusives,
at_least_one_option_names: at_least_ones
}
opts.each do |key, value|
opts[key] = Thor::Option.parse(key, value) unless value.is_a?(Thor::Option)
end
@opt = Thor::Options.new(opts, defaults, stop_on_unknown, false, relation)
end
def parse(*args)
@opt.parse(args.flatten)
end
def check_unknown!
@opt.check_unknown!
end
def remaining
@opt.remaining
end
describe "#to_switches" do
it "turns true values into a flag" do
expect(Thor::Options.to_switches(color: true)).to eq("--color")
end
it "ignores nil" do
expect(Thor::Options.to_switches(color: nil)).to eq("")
end
it "ignores false" do
expect(Thor::Options.to_switches(color: false)).to eq("")
end
it "avoids extra spaces" do
expect(Thor::Options.to_switches(color: false, foo: nil)).to eq("")
end
it "writes --name value for anything else" do
expect(Thor::Options.to_switches(format: "specdoc")).to eq('--format "specdoc"')
end
it "joins several values" do
switches = Thor::Options.to_switches(color: true, foo: "bar").split(" ").sort
expect(switches).to eq(%w("bar" --color --foo))
end
it "accepts arrays" do
expect(Thor::Options.to_switches(count: [1, 2, 3])).to eq("--count 1 2 3")
end
it "accepts hashes" do
expect(Thor::Options.to_switches(count: {a: :b})).to eq("--count a:b")
end
it "accepts underscored options" do
expect(Thor::Options.to_switches(under_score_option: "foo bar")).to eq('--under_score_option "foo bar"')
end
end
describe "#parse" do
it "allows multiple aliases for a given switch" do
create %w(--foo --bar --baz) => :string
expect(parse("--foo", "12")["foo"]).to eq("12")
expect(parse("--bar", "12")["foo"]).to eq("12")
expect(parse("--baz", "12")["foo"]).to eq("12")
end
it "allows custom short names" do
create "-f" => :string
expect(parse("-f", "12")).to eq("f" => "12")
end
it "allows custom short-name aliases" do
create %w(--bar -f) => :string
expect(parse("-f", "12")).to eq("bar" => "12")
end
it "accepts conjoined short switches" do
create %w(--foo -f) => true, %w(--bar -b) => true, %w(--app -a) => true
opts = parse("-fba")
expect(opts["foo"]).to be true
expect(opts["bar"]).to be true
expect(opts["app"]).to be true
end
it "accepts conjoined short switches with input" do
create %w(--foo -f) => true, %w(--bar -b) => true, %w(--app -a) => :required
opts = parse "-fba", "12"
expect(opts["foo"]).to be true
expect(opts["bar"]).to be true
expect(opts["app"]).to eq("12")
end
it "returns the default value if none is provided" do
create foo: "baz", bar: :required
expect(parse("--bar", "boom")["foo"]).to eq("baz")
end
it "returns the default value from defaults hash to required arguments" do
create Hash[bar: :required], Hash[bar: "baz"]
expect(parse["bar"]).to eq("baz")
end
it "gives higher priority to defaults given in the hash" do
create Hash[bar: true], Hash[bar: false]
expect(parse["bar"]).to eq(false)
end
it "raises an error for unknown switches" do
create foo: "baz", bar: :required
parse("--bar", "baz", "--baz", "unknown")
expected = "Unknown switches \"--baz\"".dup
expected << "\nDid you mean? \"--bar\"" if Thor::Correctable
expect { check_unknown! }.to raise_error(Thor::UnknownArgumentError) do |error|
expect(error.to_s).to eq(expected)
end
end
it "skips leading non-switches" do
create(foo: "baz")
expect(parse("asdf", "--foo", "bar")).to eq("foo" => "bar")
end
it "correctly recognizes things that look kind of like options, but aren't, as not options" do
create(foo: "baz")
expect(parse("--asdf---asdf", "baz", "--foo", "--asdf---dsf--asdf")).to eq("foo" => "--asdf---dsf--asdf")
check_unknown!
end
it "accepts underscores in commandline args hash for boolean" do
create foo_bar: :boolean
expect(parse("--foo_bar")["foo_bar"]).to eq(true)
expect(parse("--no_foo_bar")["foo_bar"]).to eq(false)
end
it "accepts underscores in commandline args hash for strings" do
create foo_bar: :string, baz_foo: :string
expect(parse("--foo_bar", "baz")["foo_bar"]).to eq("baz")
expect(parse("--baz_foo", "foo bar")["baz_foo"]).to eq("foo bar")
end
it "interprets everything after -- as args instead of options" do
create(foo: :string, bar: :required)
expect(parse(%w(--bar abc moo -- --foo def -a))).to eq("bar" => "abc")
expect(remaining).to eq(%w(moo --foo def -a))
end
it "ignores -- when looking for single option values" do
create(foo: :string, bar: :required)
expect(parse(%w(--bar -- --foo def -a))).to eq("bar" => "--foo")
expect(remaining).to eq(%w(def -a))
end
it "ignores -- when looking for array option values" do
create(foo: :array)
expect(parse(%w(--foo a b -- c d -e))).to eq("foo" => %w(a b c d -e))
expect(remaining).to eq([])
end
it "ignores -- when looking for hash option values" do
create(foo: :hash)
expect(parse(%w(--foo a:b -- c:d -e))).to eq("foo" => {"a" => "b", "c" => "d"})
expect(remaining).to eq(%w(-e))
end
it "ignores trailing --" do
create(foo: :string)
expect(parse(%w(--foo --))).to eq("foo" => nil)
expect(remaining).to eq([])
end
describe "with no input" do
it "and no switches returns an empty hash" do
create({})
expect(parse).to eq({})
end
it "and several switches returns an empty hash" do
create "--foo" => :boolean, "--bar" => :string
expect(parse).to eq({})
end
it "and a required switch raises an error" do
create "--foo" => :required
expect { parse }.to raise_error(Thor::RequiredArgumentMissingError, "No value provided for required options '--foo'")
end
end
describe "with one required and one optional switch" do
before do
create "--foo" => :required, "--bar" => :boolean
end
it "raises an error if the required switch has no argument" do
expect { parse("--foo") }.to raise_error(Thor::MalformattedArgumentError)
end
it "raises an error if the required switch isn't given" do
expect { parse("--bar") }.to raise_error(Thor::RequiredArgumentMissingError)
end
it "raises an error if the required switch is set to nil" do
expect { parse("--no-foo") }.to raise_error(Thor::RequiredArgumentMissingError)
end
it "does not raises an error if the required option has a default value" do
options = {required: true, type: :string, default: "baz"}
create foo: Thor::Option.new("foo", options), bar: :boolean
expect { parse("--bar") }.not_to raise_error
end
end
context "when stop_on_unknown is true" do
before do
create({foo: :string, verbose: :boolean}, {}, true)
end
it "stops parsing on first non-option" do
expect(parse(%w(foo --verbose))).to eq({})
expect(remaining).to eq(%w(foo --verbose))
end
it "stops parsing on unknown option" do
expect(parse(%w(--bar --verbose))).to eq({})
expect(remaining).to eq(%w(--bar --verbose))
end
it "retains -- after it has stopped parsing" do
expect(parse(%w(--bar -- whatever))).to eq({})
expect(remaining).to eq(%w(--bar -- whatever))
end
it "still accepts options that are given before non-options" do
expect(parse(%w(--verbose foo))).to eq("verbose" => true)
expect(remaining).to eq(%w(foo))
end
it "still accepts options that require a value" do
expect(parse(%w(--foo bar baz))).to eq("foo" => "bar")
expect(remaining).to eq(%w(baz))
end
it "still interprets everything after -- as args instead of options" do
expect(parse(%w(-- --verbose))).to eq({})
expect(remaining).to eq(%w(--verbose))
end
end
context "when exclusives is given" do
before do
create({foo: :boolean, bar: :boolean, baz: :boolean, qux: :boolean}, {}, false,
[["foo", "bar"], ["baz","qux"]])
end
it "raises an error if exclusive argumets are given" do
expect{parse(%w[--foo --bar])}.to raise_error(Thor::ExclusiveArgumentError, "Found exclusive options '--foo', '--bar'")
end
it "does not raise an error if exclusive argumets are not given" do
expect{parse(%w[--foo --baz])}.not_to raise_error
end
end
context "when at_least_ones is given" do
before do
create({foo: :string, bar: :boolean, baz: :boolean, qux: :boolean}, {}, false,
[], [["foo", "bar"], ["baz","qux"]])
end
it "raises an error if at least one of required argumet is not given" do
expect{parse(%w[--baz])}.to raise_error(Thor::AtLeastOneRequiredArgumentError, "Not found at least one of required options '--foo', '--bar'")
end
it "does not raise an error if at least one of required argument is given" do
expect{parse(%w[--foo --baz])}.not_to raise_error
end
end
context "when exclusives is given" do
before do
create({foo: :boolean, bar: :boolean, baz: :boolean, qux: :boolean}, {}, false,
[["foo", "bar"], ["baz","qux"]])
end
it "raises an error if exclusive argumets are given" do
expect{parse(%w[--foo --bar])}.to raise_error(Thor::ExclusiveArgumentError, "Found exclusive options '--foo', '--bar'")
end
it "does not raise an error if exclusive argumets are not given" do
expect{parse(%w[--foo --baz])}.not_to raise_error
end
end
context "when at_least_ones is given" do
before do
create({foo: :string, bar: :boolean, baz: :boolean, qux: :boolean}, {}, false,
[], [["foo", "bar"], ["baz","qux"]])
end
it "raises an error if at least one of required argumet is not given" do
expect{parse(%w[--baz])}.to raise_error(Thor::AtLeastOneRequiredArgumentError, "Not found at least one of required options '--foo', '--bar'")
end
it "does not raise an error if at least one of required argument is given" do
expect{parse(%w[--foo --baz])}.not_to raise_error
end
end
describe "with :string type" do
before do
create %w(--foo -f) => :required
end
it "accepts a switch <value> assignment" do
expect(parse("--foo", "12")["foo"]).to eq("12")
end
it "accepts a switch=<value> assignment" do
expect(parse("-f=12")["foo"]).to eq("12")
expect(parse("--foo=12")["foo"]).to eq("12")
expect(parse("--foo=bar=baz")["foo"]).to eq("bar=baz")
expect(parse("--foo=-bar")["foo"]).to eq("-bar")
expect(parse("--foo=-bar -baz")["foo"]).to eq("-bar -baz")
end
it "must accept underscores switch=value assignment" do
create foo_bar: :required
expect(parse("--foo_bar=http://example.com/under_score/")["foo_bar"]).to eq("http://example.com/under_score/")
end
it "accepts a --no-switch format" do
create "--foo" => "bar"
expect(parse("--no-foo")["foo"]).to be nil
end
it "does not consume an argument for --no-switch format" do
create "--cheese" => :string
expect(parse("burger", "--no-cheese", "fries")["cheese"]).to be nil
end
it "accepts a --switch format on non required types" do
create "--foo" => :string
expect(parse("--foo")["foo"]).to eq("foo")
end
it "accepts a --switch format on non required types with default values" do
create "--baz" => :string, "--foo" => "bar"
expect(parse("--baz", "bang", "--foo")["foo"]).to eq("bar")
end
it "overwrites earlier values with later values" do
expect(parse("--foo=bar", "--foo", "12")["foo"]).to eq("12")
expect(parse("--foo", "12", "--foo", "13")["foo"]).to eq("13")
end
it "raises error when value isn't in enum" do
enum = %w(apple banana)
create fruit: Thor::Option.new("fruit", type: :string, enum: enum)
expect { parse("--fruit", "orange") }.to raise_error(Thor::MalformattedArgumentError,
"Expected '--fruit' to be one of #{enum.join(', ')}; got orange")
end
it "does not erroneously mutate defaults" do
create foo: Thor::Option.new("foo", type: :string, repeatable: true, required: false, default: [])
expect(parse("--foo=bar", "--foo", "12")["foo"]).to eq(["bar", "12"])
expect(@opt.instance_variable_get(:@switches)["--foo"].default).to eq([])
end
end
describe "with :boolean type" do
before do
create "--foo" => false
end
it "accepts --opt assignment" do
expect(parse("--foo")["foo"]).to eq(true)
expect(parse("--foo", "--bar")["foo"]).to eq(true)
end
it "uses the default value if no switch is given" do
expect(parse("")["foo"]).to eq(false)
end
it "accepts --opt=value assignment" do
expect(parse("--foo=true")["foo"]).to eq(true)
expect(parse("--foo=false")["foo"]).to eq(false)
end
it "accepts --[no-]opt variant, setting false for value" do
expect(parse("--no-foo")["foo"]).to eq(false)
end
it "accepts --[skip-]opt variant, setting false for value" do
expect(parse("--skip-foo")["foo"]).to eq(false)
end
it "accepts --[skip-]opt variant, setting false for value, even if there's a trailing non-switch" do
expect(parse("--skip-foo", "asdf")["foo"]).to eq(false)
end
it "will prefer 'no-opt' variant over inverting 'opt' if explicitly set" do
create "--no-foo" => true
expect(parse("--no-foo")["no-foo"]).to eq(true)
end
it "will prefer 'skip-opt' variant over inverting 'opt' if explicitly set" do
create "--skip-foo" => true
expect(parse("--skip-foo")["skip-foo"]).to eq(true)
end
it "will prefer 'skip-opt' variant over inverting 'opt' if explicitly set, even if there's a trailing non-switch" do
create "--skip-foo" => true
expect(parse("--skip-foo", "asdf")["skip-foo"]).to eq(true)
end
it "will prefer 'skip-opt' variant over inverting 'opt' if explicitly set, and given a value" do
create "--skip-foo" => true
expect(parse("--skip-foo=f")["skip-foo"]).to eq(false)
expect(parse("--skip-foo=false")["skip-foo"]).to eq(false)
expect(parse("--skip-foo=t")["skip-foo"]).to eq(true)
expect(parse("--skip-foo=true")["skip-foo"]).to eq(true)
end
it "accepts inputs in the human name format" do
create foo_bar: :boolean
expect(parse("--foo-bar")["foo_bar"]).to eq(true)
expect(parse("--no-foo-bar")["foo_bar"]).to eq(false)
expect(parse("--skip-foo-bar")["foo_bar"]).to eq(false)
end
it "doesn't eat the next part of the param" do
expect(parse("--foo", "bar")).to eq("foo" => true)
expect(@opt.remaining).to eq(%w(bar))
end
it "doesn't eat the next part of the param with 'no-opt' variant" do
expect(parse("--no-foo", "bar")).to eq("foo" => false)
expect(@opt.remaining).to eq(%w(bar))
end
it "doesn't eat the next part of the param with 'skip-opt' variant" do
expect(parse("--skip-foo", "bar")).to eq("foo" => false)
expect(@opt.remaining).to eq(%w(bar))
end
it "allows multiple values if repeatable is specified" do
create verbose: Thor::Option.new("verbose", type: :boolean, aliases: "-v", repeatable: true)
expect(parse("-v", "-v", "-v")["verbose"].count).to eq(3)
end
end
describe "with :hash type" do
before do
create "--attributes" => :hash
end
it "accepts a switch=<value> assignment" do
expect(parse("--attributes=name:string", "age:integer")["attributes"]).to eq("name" => "string", "age" => "integer")
expect(parse("--attributes=-name:string", "age:integer", "--gender:string")["attributes"]).to eq("-name" => "string", "age" => "integer")
end
it "accepts a switch <value> assignment" do
expect(parse("--attributes", "name:string", "age:integer")["attributes"]).to eq("name" => "string", "age" => "integer")
end
it "must not mix values with other switches" do
expect(parse("--attributes", "name:string", "age:integer", "--baz", "cool")["attributes"]).to eq("name" => "string", "age" => "integer")
end
it "must not allow the same hash key to be specified multiple times" do
expect { parse("--attributes", "name:string", "name:integer") }.to raise_error(Thor::MalformattedArgumentError, "You can't specify 'name' more than once in option '--attributes'; got name:string and name:integer")
end
it "allows multiple values if repeatable is specified" do
create attributes: Thor::Option.new("attributes", type: :hash, repeatable: true)
expect(parse("--attributes", "name:one", "foo:1", "--attributes", "name:two", "bar:2")["attributes"]).to eq({"name"=>"two", "foo"=>"1", "bar" => "2"})
end
end
describe "with :array type" do
before do
create "--attributes" => :array
end
it "accepts a switch=<value> assignment" do
expect(parse("--attributes=a", "b", "c")["attributes"]).to eq(%w(a b c))
expect(parse("--attributes=-a", "b", "-c")["attributes"]).to eq(%w(-a b))
end
it "accepts a switch <value> assignment" do
expect(parse("--attributes", "a", "b", "c")["attributes"]).to eq(%w(a b c))
end
it "must not mix values with other switches" do
expect(parse("--attributes", "a", "b", "c", "--baz", "cool")["attributes"]).to eq(%w(a b c))
end
it "allows multiple values if repeatable is specified" do
create attributes: Thor::Option.new("attributes", type: :array, repeatable: true)
expect(parse("--attributes", "1", "2", "--attributes", "3", "4")["attributes"]).to eq([["1", "2"], ["3", "4"]])
end
it "raises error when value isn't in enum" do
enum = %w(apple banana)
create fruit: Thor::Option.new("fruits", type: :array, enum: enum)
expect { parse("--fruits=", "apple", "banana", "strawberry") }.to raise_error(Thor::MalformattedArgumentError,
"Expected all values of '--fruits' to be one of #{enum.join(', ')}; got strawberry")
end
end
describe "with :numeric type" do
before do
create "n" => :numeric, "m" => 5
end
it "accepts a -nXY assignment" do
expect(parse("-n12")["n"]).to eq(12)
end
it "converts values to numeric types" do
expect(parse("-n", "3", "-m", ".5")).to eq("n" => 3, "m" => 0.5)
end
it "raises error when value isn't numeric" do
expect { parse("-n", "foo") }.to raise_error(Thor::MalformattedArgumentError,
"Expected numeric value for '-n'; got \"foo\"")
end
it "raises error when value isn't in Array enum" do
enum = [1, 2]
create limit: Thor::Option.new("limit", type: :numeric, enum: enum)
expect { parse("--limit", "3") }.to raise_error(Thor::MalformattedArgumentError,
"Expected '--limit' to be one of 1, 2; got 3")
end
it "raises error when value isn't in Range enum" do
enum = 1..2
create limit: Thor::Option.new("limit", type: :numeric, enum: enum)
expect { parse("--limit", "3") }.to raise_error(Thor::MalformattedArgumentError,
"Expected '--limit' to be one of 1..2; got 3")
end
it "allows multiple values if repeatable is specified" do
create run: Thor::Option.new("run", type: :numeric, repeatable: true)
expect(parse("--run", "1", "--run", "2")["run"]).to eq([1, 2])
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor.rb | lib/thor.rb | require_relative "thor/base"
class Thor
$thor_runner ||= false
class << self
# Allows for custom "Command" package naming.
#
# === Parameters
# name<String>
# options<Hash>
#
def package_name(name, _ = {})
@package_name = name.nil? || name == "" ? nil : name
end
# Sets the default command when thor is executed without an explicit command to be called.
#
# ==== Parameters
# meth<Symbol>:: name of the default command
#
def default_command(meth = nil)
if meth
@default_command = meth == :none ? "help" : meth.to_s
else
@default_command ||= from_superclass(:default_command, "help")
end
end
alias_method :default_task, :default_command
# Registers another Thor subclass as a command.
#
# ==== Parameters
# klass<Class>:: Thor subclass to register
# command<String>:: Subcommand name to use
# usage<String>:: Short usage for the subcommand
# description<String>:: Description for the subcommand
def register(klass, subcommand_name, usage, description, options = {})
if klass <= Thor::Group
desc usage, description, options
define_method(subcommand_name) { |*args| invoke(klass, args) }
else
desc usage, description, options
subcommand subcommand_name, klass
end
end
# Defines the usage and the description of the next command.
#
# ==== Parameters
# usage<String>
# description<String>
# options<String>
#
def desc(usage, description, options = {})
if options[:for]
command = find_and_refresh_command(options[:for])
command.usage = usage if usage
command.description = description if description
else
@usage = usage
@desc = description
@hide = options[:hide] || false
end
end
# Defines the long description of the next command.
#
# Long description is by default indented, line-wrapped and repeated whitespace merged.
# In order to print long description verbatim, with indentation and spacing exactly
# as found in the code, use the +wrap+ option
#
# long_desc 'your very long description', wrap: false
#
# ==== Parameters
# long description<String>
# options<Hash>
#
def long_desc(long_description, options = {})
if options[:for]
command = find_and_refresh_command(options[:for])
command.long_description = long_description if long_description
else
@long_desc = long_description
@long_desc_wrap = options[:wrap] != false
end
end
# Maps an input to a command. If you define:
#
# map "-T" => "list"
#
# Running:
#
# thor -T
#
# Will invoke the list command.
#
# ==== Parameters
# Hash[String|Array => Symbol]:: Maps the string or the strings in the array to the given command.
#
def map(mappings = nil, **kw)
@map ||= from_superclass(:map, {})
if mappings && !kw.empty?
mappings = kw.merge!(mappings)
else
mappings ||= kw
end
if mappings
mappings.each do |key, value|
if key.respond_to?(:each)
key.each { |subkey| @map[subkey] = value }
else
@map[key] = value
end
end
end
@map
end
# Declares the options for the next command to be declared.
#
# ==== Parameters
# Hash[Symbol => Object]:: The hash key is the name of the option and the value
# is the type of the option. Can be :string, :array, :hash, :boolean, :numeric
# or :required (string). If you give a value, the type of the value is used.
#
def method_options(options = nil)
@method_options ||= {}
build_options(options, @method_options) if options
@method_options
end
alias_method :options, :method_options
# Adds an option to the set of method options. If :for is given as option,
# it allows you to change the options from a previous defined command.
#
# def previous_command
# # magic
# end
#
# method_option :foo, :for => :previous_command
#
# def next_command
# # magic
# end
#
# ==== Parameters
# name<Symbol>:: The name of the argument.
# options<Hash>:: Described below.
#
# ==== Options
# :desc - Description for the argument.
# :required - If the argument is required or not.
# :default - Default value for this argument. It cannot be required and have default values.
# :aliases - Aliases for this option.
# :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean.
# :banner - String to show on usage notes.
# :hide - If you want to hide this option from the help.
#
def method_option(name, options = {})
unless [ Symbol, String ].any? { |klass| name.is_a?(klass) }
raise ArgumentError, "Expected a Symbol or String, got #{name.inspect}"
end
scope = if options[:for]
find_and_refresh_command(options[:for]).options
else
method_options
end
build_option(name, options, scope)
end
alias_method :option, :method_option
# Adds and declares option group for exclusive options in the
# block and arguments. You can declare options as the outside of the block.
#
# If :for is given as option, it allows you to change the options from
# a previous defined command.
#
# ==== Parameters
# Array[Thor::Option.name]
# options<Hash>:: :for is applied for previous defined command.
#
# ==== Examples
#
# exclusive do
# option :one
# option :two
# end
#
# Or
#
# option :one
# option :two
# exclusive :one, :two
#
# If you give "--one" and "--two" at the same time ExclusiveArgumentsError
# will be raised.
#
def method_exclusive(*args, &block)
register_options_relation_for(:method_options,
:method_exclusive_option_names, *args, &block)
end
alias_method :exclusive, :method_exclusive
# Adds and declares option group for required at least one of options in the
# block of arguments. You can declare options as the outside of the block.
#
# If :for is given as option, it allows you to change the options from
# a previous defined command.
#
# ==== Parameters
# Array[Thor::Option.name]
# options<Hash>:: :for is applied for previous defined command.
#
# ==== Examples
#
# at_least_one do
# option :one
# option :two
# end
#
# Or
#
# option :one
# option :two
# at_least_one :one, :two
#
# If you do not give "--one" and "--two" AtLeastOneRequiredArgumentError
# will be raised.
#
# You can use at_least_one and exclusive at the same time.
#
# exclusive do
# at_least_one do
# option :one
# option :two
# end
# end
#
# Then it is required either only one of "--one" or "--two".
#
def method_at_least_one(*args, &block)
register_options_relation_for(:method_options,
:method_at_least_one_option_names, *args, &block)
end
alias_method :at_least_one, :method_at_least_one
# Prints help information for the given command.
#
# ==== Parameters
# shell<Thor::Shell>
# command_name<String>
#
def command_help(shell, command_name)
meth = normalize_command_name(command_name)
command = all_commands[meth]
handle_no_command_error(meth) unless command
shell.say "Usage:"
shell.say " #{banner(command).split("\n").join("\n ")}"
shell.say
class_options_help(shell, nil => command.options.values)
print_exclusive_options(shell, command)
print_at_least_one_required_options(shell, command)
if command.long_description
shell.say "Description:"
if command.wrap_long_description
shell.print_wrapped(command.long_description, indent: 2)
else
shell.say command.long_description
end
else
shell.say command.description
end
end
alias_method :task_help, :command_help
# Prints help information for this class.
#
# ==== Parameters
# shell<Thor::Shell>
#
def help(shell, subcommand = false)
list = printable_commands(true, subcommand)
Thor::Util.thor_classes_in(self).each do |klass|
list += klass.printable_commands(false)
end
sort_commands!(list)
if defined?(@package_name) && @package_name
shell.say "#{@package_name} commands:"
else
shell.say "Commands:"
end
shell.print_table(list, indent: 2, truncate: true)
shell.say
class_options_help(shell)
print_exclusive_options(shell)
print_at_least_one_required_options(shell)
end
# Returns commands ready to be printed.
def printable_commands(all = true, subcommand = false)
(all ? all_commands : commands).map do |_, command|
next if command.hidden?
item = []
item << banner(command, false, subcommand)
item << (command.description ? "# #{command.description.gsub(/\s+/m, ' ')}" : "")
item
end.compact
end
alias_method :printable_tasks, :printable_commands
def subcommands
@subcommands ||= from_superclass(:subcommands, [])
end
alias_method :subtasks, :subcommands
def subcommand_classes
@subcommand_classes ||= {}
end
def subcommand(subcommand, subcommand_class)
subcommands << subcommand.to_s
subcommand_class.subcommand_help subcommand
subcommand_classes[subcommand.to_s] = subcommand_class
define_method(subcommand) do |*args|
args, opts = Thor::Arguments.split(args)
invoke_args = [args, opts, {invoked_via_subcommand: true, class_options: options}]
invoke_args.unshift "help" if opts.delete("--help") || opts.delete("-h")
invoke subcommand_class, *invoke_args
end
subcommand_class.commands.each do |_meth, command|
command.ancestor_name = subcommand
end
end
alias_method :subtask, :subcommand
# Extend check unknown options to accept a hash of conditions.
#
# === Parameters
# options<Hash>: A hash containing :only and/or :except keys
def check_unknown_options!(options = {})
@check_unknown_options ||= {}
options.each do |key, value|
if value
@check_unknown_options[key] = Array(value)
else
@check_unknown_options.delete(key)
end
end
@check_unknown_options
end
# Overwrite check_unknown_options? to take subcommands and options into account.
def check_unknown_options?(config) #:nodoc:
options = check_unknown_options
return false unless options
command = config[:current_command]
return true unless command
name = command.name
if subcommands.include?(name)
false
elsif options[:except]
!options[:except].include?(name.to_sym)
elsif options[:only]
options[:only].include?(name.to_sym)
else
true
end
end
# Stop parsing of options as soon as an unknown option or a regular
# argument is encountered. All remaining arguments are passed to the command.
# This is useful if you have a command that can receive arbitrary additional
# options, and where those additional options should not be handled by
# Thor.
#
# ==== Example
#
# To better understand how this is useful, let's consider a command that calls
# an external command. A user may want to pass arbitrary options and
# arguments to that command. The command itself also accepts some options,
# which should be handled by Thor.
#
# class_option "verbose", :type => :boolean
# stop_on_unknown_option! :exec
# check_unknown_options! :except => :exec
#
# desc "exec", "Run a shell command"
# def exec(*args)
# puts "diagnostic output" if options[:verbose]
# Kernel.exec(*args)
# end
#
# Here +exec+ can be called with +--verbose+ to get diagnostic output,
# e.g.:
#
# $ thor exec --verbose echo foo
# diagnostic output
# foo
#
# But if +--verbose+ is given after +echo+, it is passed to +echo+ instead:
#
# $ thor exec echo --verbose foo
# --verbose foo
#
# ==== Parameters
# Symbol ...:: A list of commands that should be affected.
def stop_on_unknown_option!(*command_names)
@stop_on_unknown_option = stop_on_unknown_option | command_names
end
def stop_on_unknown_option?(command) #:nodoc:
command && stop_on_unknown_option.include?(command.name.to_sym)
end
# Disable the check for required options for the given commands.
# This is useful if you have a command that does not need the required options
# to work, like help.
#
# ==== Parameters
# Symbol ...:: A list of commands that should be affected.
def disable_required_check!(*command_names)
@disable_required_check = disable_required_check | command_names
end
def disable_required_check?(command) #:nodoc:
command && disable_required_check.include?(command.name.to_sym)
end
# Checks if a specified command exists.
#
# ==== Parameters
# command_name<String>:: The name of the command to check for existence.
#
# ==== Returns
# Boolean:: +true+ if the command exists, +false+ otherwise.
def command_exists?(command_name) #:nodoc:
commands.keys.include?(normalize_command_name(command_name))
end
protected
# Returns this class exclusive options array set.
#
# ==== Returns
# Array[Array[Thor::Option.name]]
#
def method_exclusive_option_names #:nodoc:
@method_exclusive_option_names ||= []
end
# Returns this class at least one of required options array set.
#
# ==== Returns
# Array[Array[Thor::Option.name]]
#
def method_at_least_one_option_names #:nodoc:
@method_at_least_one_option_names ||= []
end
def stop_on_unknown_option #:nodoc:
@stop_on_unknown_option ||= []
end
# help command has the required check disabled by default.
def disable_required_check #:nodoc:
@disable_required_check ||= [:help]
end
def print_exclusive_options(shell, command = nil) # :nodoc:
opts = []
opts = command.method_exclusive_option_names unless command.nil?
opts += class_exclusive_option_names
unless opts.empty?
shell.say "Exclusive Options:"
shell.print_table(opts.map{ |ex| ex.map{ |e| "--#{e}"}}, indent: 2 )
shell.say
end
end
def print_at_least_one_required_options(shell, command = nil) # :nodoc:
opts = []
opts = command.method_at_least_one_option_names unless command.nil?
opts += class_at_least_one_option_names
unless opts.empty?
shell.say "Required At Least One:"
shell.print_table(opts.map{ |ex| ex.map{ |e| "--#{e}"}}, indent: 2 )
shell.say
end
end
# The method responsible for dispatching given the args.
def dispatch(meth, given_args, given_opts, config) #:nodoc:
meth ||= retrieve_command_name(given_args)
command = all_commands[normalize_command_name(meth)]
if !command && config[:invoked_via_subcommand]
# We're a subcommand and our first argument didn't match any of our
# commands. So we put it back and call our default command.
given_args.unshift(meth)
command = all_commands[normalize_command_name(default_command)]
end
if command
args, opts = Thor::Options.split(given_args)
if stop_on_unknown_option?(command) && !args.empty?
# given_args starts with a non-option, so we treat everything as
# ordinary arguments
args.concat opts
opts.clear
end
else
args = given_args
opts = nil
command = dynamic_command_class.new(meth)
end
opts = given_opts || opts || []
config[:current_command] = command
config[:command_options] = command.options
instance = new(args, opts, config)
yield instance if block_given?
args = instance.args
trailing = args[Range.new(arguments.size, -1)]
instance.invoke_command(command, trailing || [])
end
# The banner for this class. You can customize it if you are invoking the
# thor class by another ways which is not the Thor::Runner. It receives
# the command that is going to be invoked and a boolean which indicates if
# the namespace should be displayed as arguments.
#
def banner(command, namespace = nil, subcommand = false)
command.formatted_usage(self, $thor_runner, subcommand).split("\n").map do |formatted_usage|
"#{basename} #{formatted_usage}"
end.join("\n")
end
def baseclass #:nodoc:
Thor
end
def dynamic_command_class #:nodoc:
Thor::DynamicCommand
end
def create_command(meth) #:nodoc:
@usage ||= nil
@desc ||= nil
@long_desc ||= nil
@long_desc_wrap ||= nil
@hide ||= nil
if @usage && @desc
base_class = @hide ? Thor::HiddenCommand : Thor::Command
relations = {exclusive_option_names: method_exclusive_option_names,
at_least_one_option_names: method_at_least_one_option_names}
commands[meth] = base_class.new(meth, @desc, @long_desc, @long_desc_wrap, @usage, method_options, relations)
@usage, @desc, @long_desc, @long_desc_wrap, @method_options, @hide = nil
@method_exclusive_option_names, @method_at_least_one_option_names = nil
true
elsif all_commands[meth] || meth == "method_missing"
true
else
puts "[WARNING] Attempted to create command #{meth.inspect} without usage or description. " \
"Call desc if you want this method to be available as command or declare it inside a " \
"no_commands{} block. Invoked from #{caller[1].inspect}."
false
end
end
alias_method :create_task, :create_command
def initialize_added #:nodoc:
class_options.merge!(method_options)
@method_options = nil
end
# Retrieve the command name from given args.
def retrieve_command_name(args) #:nodoc:
meth = args.first.to_s unless args.empty?
args.shift if meth && (map[meth] || meth !~ /^\-/)
end
alias_method :retrieve_task_name, :retrieve_command_name
# receives a (possibly nil) command name and returns a name that is in
# the commands hash. In addition to normalizing aliases, this logic
# will determine if a shortened command is an unambiguous substring of
# a command or alias.
#
# +normalize_command_name+ also converts names like +animal-prison+
# into +animal_prison+.
def normalize_command_name(meth) #:nodoc:
return default_command.to_s.tr("-", "_") unless meth
possibilities = find_command_possibilities(meth)
raise AmbiguousTaskError, "Ambiguous command #{meth} matches [#{possibilities.join(', ')}]" if possibilities.size > 1
if possibilities.empty?
meth ||= default_command
elsif map[meth]
meth = map[meth]
else
meth = possibilities.first
end
meth.to_s.tr("-", "_") # treat foo-bar as foo_bar
end
alias_method :normalize_task_name, :normalize_command_name
# this is the logic that takes the command name passed in by the user
# and determines whether it is an unambiguous substrings of a command or
# alias name.
def find_command_possibilities(meth)
len = meth.to_s.length
possibilities = all_commands.reject {|k, v| v.is_a?(HiddenCommand) }.merge(map).keys.select { |n| meth == n[0, len] }.sort
unique_possibilities = possibilities.map { |k| map[k] || k }.uniq
if possibilities.include?(meth)
[meth]
elsif unique_possibilities.size == 1
unique_possibilities
else
possibilities
end
end
alias_method :find_task_possibilities, :find_command_possibilities
def subcommand_help(cmd)
desc "help [COMMAND]", "Describe subcommands or one specific subcommand"
class_eval "
def help(command = nil, subcommand = true); super; end
"
end
alias_method :subtask_help, :subcommand_help
# Sort the commands, lexicographically by default.
#
# Can be overridden in the subclass to change the display order of the
# commands.
def sort_commands!(list)
list.sort! { |a, b| a[0] <=> b[0] }
end
end
include Thor::Base
map HELP_MAPPINGS => :help
desc "help [COMMAND]", "Describe available commands or one specific command"
def help(command = nil, subcommand = false)
if command
if self.class.subcommands.include? command
self.class.subcommand_classes[command].help(shell, true)
else
self.class.command_help(shell, command)
end
else
self.class.help(shell, subcommand)
end
end
map TREE_MAPPINGS => :tree
desc "tree", "Print a tree of all available commands"
def tree
build_command_tree(self.class, "")
end
private
def build_command_tree(klass, indent)
# Print current class name if it's not the root Thor class
unless klass == Thor
say "#{indent}#{klass.namespace || 'default'}", :blue
indent = "#{indent} "
end
# Print all commands for this class
visible_commands = klass.commands.reject { |_, cmd| cmd.hidden? || cmd.name == "help" }
commands_count = visible_commands.count
visible_commands.sort.each_with_index do |(command_name, command), i|
description = command.description.split("\n").first || ""
icon = i == (commands_count - 1) ? "└─" : "├─"
say "#{indent}#{icon} ", nil, false
say command_name, :green, false
say " (#{description})" unless description.empty?
end
# Print all subcommands (from registered Thor subclasses)
klass.subcommand_classes.each do |_, subclass|
build_command_tree(subclass, indent)
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/command.rb | lib/thor/command.rb | class Thor
class Command < Struct.new(:name, :description, :long_description, :wrap_long_description, :usage, :options, :options_relation, :ancestor_name)
FILE_REGEXP = /^#{Regexp.escape(File.dirname(__FILE__))}/
def initialize(name, description, long_description, wrap_long_description, usage, options = nil, options_relation = nil)
super(name.to_s, description, long_description, wrap_long_description, usage, options || {}, options_relation || {})
end
def initialize_copy(other) #:nodoc:
super(other)
self.options = other.options.dup if other.options
self.options_relation = other.options_relation.dup if other.options_relation
end
def hidden?
false
end
# By default, a command invokes a method in the thor class. You can change this
# implementation to create custom commands.
def run(instance, args = [])
arity = nil
if private_method?(instance)
instance.class.handle_no_command_error(name)
elsif public_method?(instance)
arity = instance.method(name).arity
instance.__send__(name, *args)
elsif local_method?(instance, :method_missing)
instance.__send__(:method_missing, name.to_sym, *args)
else
instance.class.handle_no_command_error(name)
end
rescue ArgumentError => e
handle_argument_error?(instance, e, caller) ? instance.class.handle_argument_error(self, e, args, arity) : (raise e)
rescue NoMethodError => e
handle_no_method_error?(instance, e, caller) ? instance.class.handle_no_command_error(name) : (raise e)
end
# Returns the formatted usage by injecting given required arguments
# and required options into the given usage.
def formatted_usage(klass, namespace = true, subcommand = false)
if ancestor_name
formatted = "#{ancestor_name} ".dup # add space
elsif namespace
namespace = klass.namespace
formatted = "#{namespace.gsub(/^(default)/, '')}:".dup
end
formatted ||= "#{klass.namespace.split(':').last} ".dup if subcommand
formatted ||= "".dup
Array(usage).map do |specific_usage|
formatted_specific_usage = formatted
formatted_specific_usage += required_arguments_for(klass, specific_usage)
# Add required options
formatted_specific_usage += " #{required_options}"
# Strip and go!
formatted_specific_usage.strip
end.join("\n")
end
def method_exclusive_option_names #:nodoc:
self.options_relation[:exclusive_option_names] || []
end
def method_at_least_one_option_names #:nodoc:
self.options_relation[:at_least_one_option_names] || []
end
protected
# Add usage with required arguments
def required_arguments_for(klass, usage)
if klass && !klass.arguments.empty?
usage.to_s.gsub(/^#{name}/) do |match|
match << " " << klass.arguments.map(&:usage).compact.join(" ")
end
else
usage.to_s
end
end
def not_debugging?(instance)
!(instance.class.respond_to?(:debugging) && instance.class.debugging)
end
def required_options
@required_options ||= options.map { |_, o| o.usage if o.required? }.compact.sort.join(" ")
end
# Given a target, checks if this class name is a public method.
def public_method?(instance) #:nodoc:
!(instance.public_methods & [name.to_s, name.to_sym]).empty?
end
def private_method?(instance)
!(instance.private_methods & [name.to_s, name.to_sym]).empty?
end
def local_method?(instance, name)
methods = instance.public_methods(false) + instance.private_methods(false) + instance.protected_methods(false)
!(methods & [name.to_s, name.to_sym]).empty?
end
def sans_backtrace(backtrace, caller) #:nodoc:
saned = backtrace.reject { |frame| frame =~ FILE_REGEXP || (frame =~ /\.java:/ && RUBY_PLATFORM =~ /java/) || (frame =~ %r{^kernel/} && RUBY_ENGINE =~ /rbx/) }
saned - caller
end
def handle_argument_error?(instance, error, caller)
not_debugging?(instance) && (error.message =~ /wrong number of arguments/ || error.message =~ /given \d*, expected \d*/) && begin
saned = sans_backtrace(error.backtrace, caller)
saned.empty? || saned.size == 1
end
end
def handle_no_method_error?(instance, error, caller)
not_debugging?(instance) &&
error.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/
end
end
Task = Command
# A command that is hidden in help messages but still invocable.
class HiddenCommand < Command
def hidden?
true
end
end
HiddenTask = HiddenCommand
# A dynamic command that handles method missing scenarios.
class DynamicCommand < Command
def initialize(name, options = nil)
super(name.to_s, "A dynamically-generated command", name.to_s, nil, name.to_s, options)
end
def run(instance, args = [])
if (instance.methods & [name.to_s, name.to_sym]).empty?
super
else
instance.class.handle_no_command_error(name)
end
end
end
DynamicTask = DynamicCommand
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/actions.rb | lib/thor/actions.rb | require_relative "actions/create_file"
require_relative "actions/create_link"
require_relative "actions/directory"
require_relative "actions/empty_directory"
require_relative "actions/file_manipulation"
require_relative "actions/inject_into_file"
class Thor
module Actions
attr_accessor :behavior
def self.included(base) #:nodoc:
super(base)
base.extend ClassMethods
end
module ClassMethods
# Hold source paths for one Thor instance. source_paths_for_search is the
# method responsible to gather source_paths from this current class,
# inherited paths and the source root.
#
def source_paths
@_source_paths ||= []
end
# Stores and return the source root for this class
def source_root(path = nil)
@_source_root = path if path
@_source_root ||= nil
end
# Returns the source paths in the following order:
#
# 1) This class source paths
# 2) Source root
# 3) Parents source paths
#
def source_paths_for_search
paths = []
paths += source_paths
paths << source_root if source_root
paths += from_superclass(:source_paths, [])
paths
end
# Add runtime options that help actions execution.
#
def add_runtime_options!
class_option :force, type: :boolean, aliases: "-f", group: :runtime,
desc: "Overwrite files that already exist"
class_option :pretend, type: :boolean, aliases: "-p", group: :runtime,
desc: "Run but do not make any changes"
class_option :quiet, type: :boolean, aliases: "-q", group: :runtime,
desc: "Suppress status output"
class_option :skip, type: :boolean, aliases: "-s", group: :runtime,
desc: "Skip files that already exist"
end
end
# Extends initializer to add more configuration options.
#
# ==== Configuration
# behavior<Symbol>:: The actions default behavior. Can be :invoke or :revoke.
# It also accepts :force, :skip and :pretend to set the behavior
# and the respective option.
#
# destination_root<String>:: The root directory needed for some actions.
#
def initialize(args = [], options = {}, config = {})
self.behavior = case config[:behavior].to_s
when "force", "skip"
_cleanup_options_and_set(options, config[:behavior])
:invoke
when "revoke"
:revoke
else
:invoke
end
super
self.destination_root = config[:destination_root]
end
# Wraps an action object and call it accordingly to the thor class behavior.
#
def action(instance) #:nodoc:
if behavior == :revoke
instance.revoke!
else
instance.invoke!
end
end
# Returns the root for this thor class (also aliased as destination root).
#
def destination_root
@destination_stack.last
end
# Sets the root for this thor class. Relatives path are added to the
# directory where the script was invoked and expanded.
#
def destination_root=(root)
@destination_stack ||= []
@destination_stack[0] = File.expand_path(root || "")
end
# Returns the given path relative to the absolute root (ie, root where
# the script started).
#
def relative_to_original_destination_root(path, remove_dot = true)
root = @destination_stack[0]
if path.start_with?(root) && [File::SEPARATOR, File::ALT_SEPARATOR, nil, ""].include?(path[root.size..root.size])
path = path.dup
path[0...root.size] = "."
remove_dot ? (path[2..-1] || "") : path
else
path
end
end
# Holds source paths in instance so they can be manipulated.
#
def source_paths
@source_paths ||= self.class.source_paths_for_search
end
# Receives a file or directory and search for it in the source paths.
#
def find_in_source_paths(file)
possible_files = [file, file + TEMPLATE_EXTNAME]
relative_root = relative_to_original_destination_root(destination_root, false)
source_paths.each do |source|
possible_files.each do |f|
source_file = File.expand_path(f, File.join(source, relative_root))
return source_file if File.exist?(source_file)
end
end
message = "Could not find #{file.inspect} in any of your source paths. ".dup
unless self.class.source_root
message << "Please invoke #{self.class.name}.source_root(PATH) with the PATH containing your templates. "
end
message << if source_paths.empty?
"Currently you have no source paths."
else
"Your current source paths are: \n#{source_paths.join("\n")}"
end
raise Error, message
end
# Do something in the root or on a provided subfolder. If a relative path
# is given it's referenced from the current root. The full path is yielded
# to the block you provide. The path is set back to the previous path when
# the method exits.
#
# Returns the value yielded by the block.
#
# ==== Parameters
# dir<String>:: the directory to move to.
# config<Hash>:: give :verbose => true to log and use padding.
#
def inside(dir = "", config = {}, &block)
verbose = config.fetch(:verbose, false)
pretend = options[:pretend]
say_status :inside, dir, verbose
shell.padding += 1 if verbose
@destination_stack.push File.expand_path(dir, destination_root)
# If the directory doesn't exist and we're not pretending
if !File.exist?(destination_root) && !pretend
require "fileutils"
FileUtils.mkdir_p(destination_root)
end
result = nil
if pretend
# In pretend mode, just yield down to the block
result = block.arity == 1 ? yield(destination_root) : yield
else
require "fileutils"
FileUtils.cd(destination_root) { result = block.arity == 1 ? yield(destination_root) : yield }
end
@destination_stack.pop
shell.padding -= 1 if verbose
result
end
# Goes to the root and execute the given block.
#
def in_root
inside(@destination_stack.first) { yield }
end
# Loads an external file and execute it in the instance binding.
#
# ==== Parameters
# path<String>:: The path to the file to execute. Can be a web address or
# a relative path from the source root.
#
# ==== Examples
#
# apply "http://gist.github.com/103208"
#
# apply "recipes/jquery.rb"
#
def apply(path, config = {})
verbose = config.fetch(:verbose, true)
is_uri = path =~ %r{^https?\://}
path = find_in_source_paths(path) unless is_uri
say_status :apply, path, verbose
shell.padding += 1 if verbose
contents = if is_uri
require "open-uri"
URI.open(path, "Accept" => "application/x-thor-template", &:read)
else
File.open(path, &:read)
end
instance_eval(contents, path)
shell.padding -= 1 if verbose
end
# Executes a command returning the contents of the command.
#
# ==== Parameters
# command<String>:: the command to be executed.
# config<Hash>:: give :verbose => false to not log the status, :capture => true to hide to output. Specify :with
# to append an executable to command execution.
#
# ==== Example
#
# inside('vendor') do
# run('ln -s ~/edge rails')
# end
#
def run(command, config = {})
return unless behavior == :invoke
destination = relative_to_original_destination_root(destination_root, false)
desc = "#{command} from #{destination.inspect}"
if config[:with]
desc = "#{File.basename(config[:with].to_s)} #{desc}"
command = "#{config[:with]} #{command}"
end
say_status :run, desc, config.fetch(:verbose, true)
return if options[:pretend]
env_splat = [config[:env]] if config[:env]
if config[:capture]
require "open3"
result, status = Open3.capture2e(*env_splat, command.to_s)
success = status.success?
else
result = system(*env_splat, command.to_s)
success = result
end
abort if !success && config.fetch(:abort_on_failure, self.class.exit_on_failure?)
result
end
# Executes a ruby script (taking into account WIN32 platform quirks).
#
# ==== Parameters
# command<String>:: the command to be executed.
# config<Hash>:: give :verbose => false to not log the status.
#
def run_ruby_script(command, config = {})
return unless behavior == :invoke
run command, config.merge(with: Thor::Util.ruby_command)
end
# Run a thor command. A hash of options can be given and it's converted to
# switches.
#
# ==== Parameters
# command<String>:: the command to be invoked
# args<Array>:: arguments to the command
# config<Hash>:: give :verbose => false to not log the status, :capture => true to hide to output.
# Other options are given as parameter to Thor.
#
#
# ==== Examples
#
# thor :install, "http://gist.github.com/103208"
# #=> thor install http://gist.github.com/103208
#
# thor :list, :all => true, :substring => 'rails'
# #=> thor list --all --substring=rails
#
def thor(command, *args)
config = args.last.is_a?(Hash) ? args.pop : {}
verbose = config.key?(:verbose) ? config.delete(:verbose) : true
pretend = config.key?(:pretend) ? config.delete(:pretend) : false
capture = config.key?(:capture) ? config.delete(:capture) : false
args.unshift(command)
args.push Thor::Options.to_switches(config)
command = args.join(" ").strip
run command, with: :thor, verbose: verbose, pretend: pretend, capture: capture
end
protected
# Allow current root to be shared between invocations.
#
def _shared_configuration #:nodoc:
super.merge!(destination_root: destination_root)
end
def _cleanup_options_and_set(options, key) #:nodoc:
case options
when Array
%w(--force -f --skip -s).each { |i| options.delete(i) }
options << "--#{key}"
when Hash
[:force, :skip, "force", "skip"].each { |i| options.delete(i) }
options.merge!(key => true)
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/line_editor.rb | lib/thor/line_editor.rb | require_relative "line_editor/basic"
require_relative "line_editor/readline"
class Thor
module LineEditor
def self.readline(prompt, options = {})
best_available.new(prompt, options).readline
end
def self.best_available
[
Thor::LineEditor::Readline,
Thor::LineEditor::Basic
].detect(&:available?)
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/version.rb | lib/thor/version.rb | class Thor
VERSION = "1.4.0"
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.