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 |
|---|---|---|---|---|---|---|---|---|
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/one_cookie_no_spaces_servlet.rb | lib/mechanize/test_case/one_cookie_no_spaces_servlet.rb | # frozen_string_literal: true
class OneCookieNoSpacesServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
cookie = WEBrick::Cookie.new("foo", "bar")
cookie.path = "/"
cookie.expires = Time.now + 86400
res.cookies << cookie.to_s.gsub(/; /, ';')
res['Content-Type'] = "text/html"
res.body = "<html><body>hello</body></html>"
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/form_servlet.rb | lib/mechanize/test_case/form_servlet.rb | # frozen_string_literal: true
class FormServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
res.content_type = 'text/html'
query = []
req.query.each_key { |k|
key = WEBrick::HTTPUtils.unescape k
req.query[k].each_data { |data|
value = WEBrick::HTTPUtils.unescape data
query << "<li><a href=\"#\">#{key}:#{value}</a>"
}
}
res.body = <<-BODY
<!DOCTYPE html>
<title>GET results</title>
<ul>
#{query.join "\n"}
</ul>
<div id=\"query\">#{req.query}</div>
BODY
end
def do_POST(req, res)
res.content_type = 'text/html'
query = []
req.query.each_key { |k|
key = WEBrick::HTTPUtils.unescape k
req.query[k].each_data { |data|
value = WEBrick::HTTPUtils.unescape data
query << "<li><a href=\"#\">#{key}:#{value}</a>"
}
}
res.body = <<-BODY
<!DOCTYPE html>
<title>POST results</title>
<ul>
#{query.join "\n"}
</ul>
<div id=\"query\">#{req.body}</div>
BODY
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/server.rb | lib/mechanize/test_case/server.rb | # frozen_string_literal: true
require 'webrick'
require 'mechanize/test_case/servlets'
server = WEBrick::HTTPServer.new :Port => 8000
server.mount_proc '/' do |req, res|
res.content_type = 'text/html'
servlets = MECHANIZE_TEST_CASE_SERVLETS.map do |path, servlet|
"<dt>#{servlet}<dd><a href=\"#{path}\">#{path}</a>"
end.join "\n"
res.body = <<-BODY
<!DOCTYPE html>
<title>Mechanize Test Case Servlets</title>
<p>This server allows you to test various mechanize behavior against other
HTTP clients. Some endpoints may require headers be set to have a reasonable
function, or may respond diffently to POST vs GET requests. Please see the
servlet implementation and mechanize tests for further details.
<p>Here are the servlet endpoints available:
<dl>
#{servlets}
</dl>
BODY
end
MECHANIZE_TEST_CASE_SERVLETS.each do |path, servlet|
server.mount path, servlet
end
trap 'INT' do server.shutdown end
trap 'TERM' do server.shutdown end
server.start
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/redirect_servlet.rb | lib/mechanize/test_case/redirect_servlet.rb | # frozen_string_literal: true
class RedirectServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
res['Content-Type'] = req.query['ct'] || 'text/html'
res.status = req.query['code'] ? req.query['code'].to_i : '302'
res['Location'] = req['X-Location'] || '/verb'
end
alias :do_POST :do_GET
alias :do_HEAD :do_GET
alias :do_PUT :do_GET
alias :do_DELETE :do_GET
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/basic_auth_servlet.rb | lib/mechanize/test_case/basic_auth_servlet.rb | # frozen_string_literal: true
class BasicAuthServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req,res)
htpd = nil
Tempfile.open 'dot.htpasswd' do |io|
htpd = WEBrick::HTTPAuth::Htpasswd.new(io.path)
htpd.set_passwd('Blah', 'user', 'pass')
end
authenticator = WEBrick::HTTPAuth::BasicAuth.new({
:UserDB => htpd,
:Realm => 'Blah',
:Logger => Logger.new(nil)
})
begin
authenticator.authenticate(req,res)
res.body = 'You are authenticated'
rescue WEBrick::HTTPStatus::Unauthorized
res.status = 401
end
end
alias :do_POST :do_GET
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/bad_chunking_servlet.rb | lib/mechanize/test_case/bad_chunking_servlet.rb | # frozen_string_literal: true
class BadChunkingServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET req, res
res.keep_alive = false if res.respond_to? :keep_alive=
res['Transfer-Encoding'] = 'chunked'
res.body = <<-BODY
a\r
0123456789\r
0\r
BODY
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/refresh_without_url.rb | lib/mechanize/test_case/refresh_without_url.rb | # frozen_string_literal: true
class RefreshWithoutUrl < WEBrick::HTTPServlet::AbstractServlet
@@count = 0
def do_GET(req, res)
address = "#{req.host}:#{req.port}"
res['Content-Type'] = "text/html"
@@count += 1
if @@count > 1
res['Refresh'] = "0; url=http://#{address}/";
else
res['Refresh'] = "0";
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/digest_auth_servlet.rb | lib/mechanize/test_case/digest_auth_servlet.rb | # frozen_string_literal: true
require 'logger'
class DigestAuthServlet < WEBrick::HTTPServlet::AbstractServlet
htpd = nil
Tempfile.open 'digest.htpasswd' do |io|
htpd = WEBrick::HTTPAuth::Htdigest.new(io.path)
htpd.set_passwd('Blah', 'user', 'pass')
end
@@authenticator = WEBrick::HTTPAuth::DigestAuth.new({
:UserDB => htpd,
:Realm => 'Blah',
:Algorithm => 'MD5',
:Logger => Logger.new(nil)
})
def do_GET req, res
def req.request_time; Time.now; end
def req.request_uri; '/digest_auth'; end
def req.request_method; 'GET'; end
begin
@@authenticator.authenticate req, res
res.body = 'You are authenticated'
rescue WEBrick::HTTPStatus::Unauthorized
res.status = 401
end
end
alias :do_POST :do_GET
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/verb_servlet.rb | lib/mechanize/test_case/verb_servlet.rb | # frozen_string_literal: true
class VerbServlet < WEBrick::HTTPServlet::AbstractServlet
%w[HEAD GET POST PUT DELETE].each do |verb|
define_method "do_#{verb}" do |req, res|
res.header['X-Request-Method'] = verb
res.body = verb
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/quoted_value_cookie_servlet.rb | lib/mechanize/test_case/quoted_value_cookie_servlet.rb | # frozen_string_literal: true
class QuotedValueCookieServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
cookie = WEBrick::Cookie.new("quoted", "\"value\"")
cookie.path = "/"
cookie.expires = Time.now + 86400
res.cookies << cookie
res['Content-Type'] = "text/html"
res.body = "<html><body>hello</body></html>"
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/page/meta_refresh.rb | lib/mechanize/page/meta_refresh.rb | # frozen_string_literal: true
##
# This class encapsulates a meta element with a refresh http-equiv. Mechanize
# treats meta refresh elements just like 'a' tags. MetaRefresh objects will
# contain links, but most likely will have no text.
class Mechanize::Page::MetaRefresh < Mechanize::Page::Link
##
# Time to wait before next refresh
attr_reader :delay
##
# This MetaRefresh links did not contain a url= in the content attribute and
# links to itself.
attr_reader :link_self
##
# Matches the content attribute of a meta refresh element. After the match:
#
# $1:: delay
# $3:: url
CONTENT_REGEXP = /^\s*(\d+\.?\d*)\s*(?:;(?:\s*url\s*=\s*(['"]?)(\S*)\2)?\s*)?$/i
##
# Regexp of unsafe URI characters that excludes % for Issue #177
UNSAFE = /[^\-_.!~*'()a-zA-Z\d;\/?:@&%=+$,\[\]]/
##
# Parses the delay and url from the content attribute of a meta
# refresh element.
#
# Returns an array of [delay, url, link_self], where the first two
# are strings containing the respective parts of the refresh value,
# and link_self is a boolean value that indicates whether the url
# part is missing or empty. If base_uri, the URI of the current
# page is given, the value of url becomes an absolute URI.
def self.parse content, base_uri = nil
m = CONTENT_REGEXP.match(content) or return
delay, url = m[1], m[3]
url &&= url.empty? ? nil : Mechanize::Util.uri_escape(url, UNSAFE)
link_self = url.nil?
if base_uri
url = url ? base_uri + url : base_uri
end
return delay, url, link_self
end
def self.from_node node, page, uri = nil
http_equiv = node['http-equiv'] and
/\ARefresh\z/i =~ http_equiv or return
delay, uri, link_self = parse node['content'], uri
return unless delay
new node, page, delay, uri, link_self
end
def initialize node, page, delay, href, link_self = false
super node, page.mech, page
@delay = delay.include?(?.) ? delay.to_f : delay.to_i
@href = href
@link_self = link_self
end
def noreferrer?
true
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/page/frame.rb | lib/mechanize/page/frame.rb | # frozen_string_literal: true
# A Frame object wraps a frame HTML element. Frame objects can be treated
# just like Link objects. They contain #src, the #link they refer to and a
# #name, the name of the frame they refer to. #src and #name are aliased to
# #href and #text respectively so that a Frame object can be treated just like
# a Link.
class Mechanize::Page::Frame < Mechanize::Page::Link
alias :src :href
attr_reader :text
alias :name :text
attr_reader :node
def initialize(node, mech, referer)
super(node, mech, referer)
@node = node
@text = node['name']
@href = node['src']
@content = nil
end
def content
@content ||= @mech.get @href, [], page
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/page/link.rb | lib/mechanize/page/link.rb | # frozen_string_literal: true
##
# This class encapsulates links. It contains the text and the URI for
# 'a' tags parsed out of an HTML page. If the link contains an image,
# the alt text will be used for that image.
#
# For example, the text for the following links with both be 'Hello World':
#
# <a href="http://example">Hello World</a>
# <a href="http://example"><img src="test.jpg" alt="Hello World"></a>
require 'addressable/uri'
class Mechanize::Page::Link
attr_reader :node
attr_reader :href
attr_reader :attributes
attr_reader :page
alias :referer :page
def initialize(node, mech, page)
@node = node
@attributes = node
@href = node['href']
@mech = mech
@page = page
@text = nil
@uri = nil
end
# Click on this link
def click
@mech.click self
end
# This method is a shorthand to get link's DOM id.
# Common usage:
# page.link_with(:dom_id => "links_exact_id")
def dom_id
node['id']
end
# This method is a shorthand to get a link's DOM class
# Common usage:
# page.link_with(:dom_class => "links_exact_class")
def dom_class
node['class']
end
def pretty_print(q) # :nodoc:
q.object_group(self) {
q.breakable; q.pp text
q.breakable; q.pp href
}
end
alias inspect pretty_inspect # :nodoc:
# A list of words in the rel attribute, all lower-cased.
def rel
@rel ||= (val = attributes['rel']) ? val.downcase.split(' ') : []
end
# Test if the rel attribute includes +kind+.
def rel? kind
rel.include? kind
end
# Test if this link should not be traced.
def noreferrer?
rel?('noreferrer')
end
# The text content of this link
def text
return @text if @text
@text = @node.inner_text
# If there is no text, try to find an image and use it's alt text
if (@text.nil? or @text.empty?) and imgs = @node.search('img') then
@text = imgs.map do |e|
e['alt']
end.join
end
@text
end
alias :to_s :text
# A URI for the #href for this link. The link is first parsed as a raw
# link. If that fails parsing an escaped link is attepmted.
def uri
@uri ||= if @href then
begin
URI.parse @href
rescue URI::InvalidURIError
begin
URI.parse(Addressable::URI.escape(@href))
rescue Addressable::URI::InvalidURIError
raise URI::InvalidURIError
end
end
end
end
# A fully resolved URI for the #href for this link.
def resolved_uri
@mech.resolve uri
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/page/base.rb | lib/mechanize/page/base.rb | # frozen_string_literal: true
##
# A base element on an HTML page. Mechanize treats base tags just like 'a'
# tags. Base objects will contain links, but most likely will have no text.
class Mechanize::Page::Base < Mechanize::Page::Link
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/page/image.rb | lib/mechanize/page/image.rb | # frozen_string_literal: true
##
# An image element on an HTML page
class Mechanize::Page::Image
attr_reader :node
attr_accessor :page
attr_accessor :mech
##
# Creates a new Mechanize::Page::Image from an image +node+ and source
# +page+.
def initialize node, page
@node = node
@page = page
@mech = page.mech
end
##
# The alt attribute of the image
def alt
node['alt']
end
##
# The caption of the image. In order of preference, the #title, #alt, or
# empty string "".
def caption
title || alt || ''
end
alias :text :caption
##
# The class attribute of the image
def dom_class
node['class']
end
##
# The id attribute of the image
def dom_id
node['id']
end
##
# The suffix of the #url. The dot is a part of suffix, not a delimiter.
#
# p image.url # => "http://example/test.jpg"
# p image.extname # => ".jpg"
#
# Returns an empty string if #url has no suffix:
#
# p image.url # => "http://example/sampleimage"
# p image.extname # => ""
def extname
return nil unless src
File.extname url.path
end
##
# Downloads the image.
#
# agent.page.image_with(:src => /logo/).fetch.save
#
# The referer is:
#
# #page("parent") ::
# all images on http html, relative #src images on https html
# (no referer) ::
# absolute #src images on https html
# user specified ::
# img.fetch(nil, my_referer_uri_or_page)
def fetch parameters = [], referer = nil, headers = {}
mech.get src, parameters, referer || image_referer, headers
end
##
# The height attribute of the image
def height
node['height']
end
def image_referer # :nodoc:
http_page = page.uri && page.uri.scheme == 'http'
https_page = page.uri && page.uri.scheme == 'https'
case
when http_page then page
when https_page && relative? then page
else
Mechanize::File.new(nil, { 'content-type' => 'text/plain' }, '', 200)
end
end
##
# MIME type guessed from the image url suffix
#
# p image.extname # => ".jpg"
# p image.mime_type # => "image/jpeg"
# page.images_with(:mime_type => /gif|jpeg|png/).each do ...
#
# Returns nil if url has no (well-known) suffix:
#
# p image.url # => "http://example/sampleimage"
# p image.mime_type # => nil
def mime_type
suffix_without_dot = extname ? extname.sub(/\A\./){''}.downcase : nil
Mechanize::Util::DefaultMimeTypes[suffix_without_dot]
end
def pretty_print(q) # :nodoc:
q.object_group(self) {
q.breakable; q.pp url
q.breakable; q.pp caption
}
end
alias inspect pretty_inspect # :nodoc:
def relative? # :nodoc:
%r{^https?://} !~ src
end
##
# The src attribute of the image
def src
node['src']
end
##
# The title attribute of the image
def title
node['title']
end
##
# The URL string of this image
def to_s
url.to_s
end
##
# URI for this image
def url
if relative? then
if page.bases[0] then
page.bases[0].href + src.to_s
else
page.uri + Mechanize::Util.uri_escape(src.to_s)
end
else
URI Mechanize::Util.uri_escape(src)
end
end
alias uri url
##
# The width attribute of the image
def width
node['width']
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/page/label.rb | lib/mechanize/page/label.rb | # frozen_string_literal: true
##
# A form label on an HTML page
class Mechanize::Page::Label
attr_reader :node
attr_reader :text
attr_reader :page
alias :to_s :text
def initialize(node, page)
@node = node
@text = node.inner_text
@page = page
end
def for
(id = @node['for']) && page.search("##{id}") || nil
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/textarea.rb | lib/mechanize/form/textarea.rb | # frozen_string_literal: true
class Mechanize::Form::Textarea < Mechanize::Form::Field
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/submit.rb | lib/mechanize/form/submit.rb | # frozen_string_literal: true
class Mechanize::Form::Submit < Mechanize::Form::Button
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/text.rb | lib/mechanize/form/text.rb | # frozen_string_literal: true
class Mechanize::Form::Text < Mechanize::Form::Field
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/hidden.rb | lib/mechanize/form/hidden.rb | # frozen_string_literal: true
class Mechanize::Form::Hidden < Mechanize::Form::Field
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/image_button.rb | lib/mechanize/form/image_button.rb | # frozen_string_literal: true
##
# This class represents an image button in a form. Use the x and y methods to
# set the x and y positions for where the mouse "clicked".
class Mechanize::Form::ImageButton < Mechanize::Form::Button
attr_accessor :x, :y
def initialize *args
@x = nil
@y = nil
super
end
def query_value
[["#{@name}.x", (@x || 0).to_s],
["#{@name}.y", (@y || 0).to_s]]
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/check_box.rb | lib/mechanize/form/check_box.rb | # frozen_string_literal: true
##
# This class represents a check box found in a Form. To activate the CheckBox
# in the Form, set the checked method to true.
class Mechanize::Form::CheckBox < Mechanize::Form::RadioButton
def query_value
[[@name, @value || "on"]]
end
def inspect # :nodoc:
"[%s:0x%x type: %s name: %s value: %s]" % [
self.class.name.sub(/Mechanize::Form::/, '').downcase,
object_id, type, name, checked
]
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/field.rb | lib/mechanize/form/field.rb | # frozen_string_literal: true
##
# This class represents a field in a form. It handles the following input
# tags found in a form:
#
# * text
# * password
# * hidden
# * int
# * textarea
# * keygen
#
# To set the value of a field, just use the value method:
#
# field.value = "foo"
class Mechanize::Form::Field
extend Forwardable
attr_accessor :name, :value, :node, :type
# This fields value before it's sent through Util.html_unescape.
attr_reader :raw_value
# index is used to maintain order for fields with Hash nodes
attr_accessor :index
def initialize node, value = node['value']
@node = node
@name = Mechanize::Util.html_unescape(node['name'])
@raw_value = value
@value = if value.is_a? String
Mechanize::Util.html_unescape(value)
else
value
end
@type = node['type']
end
def query_value
[[@name, @value || '']]
end
def <=> other
return 0 if self == other
# If both are hashes, sort by index
if Hash === node && Hash === other.node && index
return index <=> other.index
end
# Otherwise put Hash based fields at the end
return 1 if Hash === node
return -1 if Hash === other.node
# Finally let nokogiri determine sort order
node <=> other.node
end
# This method is a shortcut to get field's DOM id.
# Common usage: form.field_with(:dom_id => "foo")
def dom_id
node['id']
end
# This method is a shortcut to get field's DOM class.
# Common usage: form.field_with(:dom_class => "foo")
def dom_class
node['class']
end
##
# :method: search
#
# Shorthand for +node.search+.
#
# See Nokogiri::XML::Node#search for details.
##
# :method: css
#
# Shorthand for +node.css+.
#
# See also Nokogiri::XML::Node#css for details.
##
# :method: xpath
#
# Shorthand for +node.xpath+.
#
# See also Nokogiri::XML::Node#xpath for details.
##
# :method: at
#
# Shorthand for +node.at+.
#
# See also Nokogiri::XML::Node#at for details.
##
# :method: at_css
#
# Shorthand for +node.at_css+.
#
# See also Nokogiri::XML::Node#at_css for details.
##
# :method: at_xpath
#
# Shorthand for +node.at_xpath+.
#
# See also Nokogiri::XML::Node#at_xpath for details.
def_delegators :node, :search, :css, :xpath, :at, :at_css, :at_xpath
def inspect # :nodoc:
"[%s:0x%x type: %s name: %s value: %s]" % [
self.class.name.sub(/Mechanize::Form::/, '').downcase,
object_id, type, name, value
]
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/radio_button.rb | lib/mechanize/form/radio_button.rb | # frozen_string_literal: true
##
# This class represents a radio button found in a Form. To activate the
# RadioButton in the Form, set the checked method to true.
class Mechanize::Form::RadioButton < Mechanize::Form::Field
attr_accessor :checked
attr_reader :form
def initialize node, form
@checked = !!node['checked']
@form = form
super(node)
end
def == other # :nodoc:
self.class === other and
other.form == @form and
other.name == @name and
other.value == @value
end
alias eql? == # :nodoc:
def check
uncheck_peers
@checked = true
end
alias checked? checked
def uncheck
@checked = false
end
def click
checked ? uncheck : check
end
def hash # :nodoc:
@form.hash ^ @name.hash ^ @value.hash
end
def label
(id = self['id']) && @form.page.labels_hash[id] || nil
end
def text
label.text rescue nil
end
def [](key)
@node[key]
end
def pretty_print_instance_variables # :nodoc:
[:@checked, :@name, :@value]
end
private
def uncheck_peers
@form.radiobuttons_with(:name => name).each do |b|
next if b.value == value
b.uncheck
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/keygen.rb | lib/mechanize/form/keygen.rb | # frozen_string_literal: true
##
# This class represents a keygen (public / private key generator) found in a
# Form. The field will automatically generate a key pair and compute its own
# value to match the challenge. Call key to access the public/private key
# pair.
class Mechanize::Form::Keygen < Mechanize::Form::Field
# The challenge for this <keygen>.
attr_reader :challenge
# The key associated with this <keygen> tag.
attr_reader :key
def initialize(node, value = nil)
super
@challenge = node['challenge']
@spki = OpenSSL::Netscape::SPKI.new
@spki.challenge = @challenge
@key = nil
generate_key if value.nil? || value.empty?
end
# Generates a key pair and sets the field's value.
def generate_key(key_size = 2048)
# Spec at http://dev.w3.org/html5/spec/Overview.html#the-keygen-element
@key = OpenSSL::PKey::RSA.new key_size
@spki.public_key = @key.public_key
@spki.sign @key, OpenSSL::Digest::MD5.new
self.value = @spki.to_pem
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/button.rb | lib/mechanize/form/button.rb | # frozen_string_literal: true
##
# A Submit button in a Form
class Mechanize::Form::Button < Mechanize::Form::Field
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/select_list.rb | lib/mechanize/form/select_list.rb | # frozen_string_literal: true
# This class represents a select list or drop down box in a Form. Set the
# value for the list by calling SelectList#value=. SelectList contains a list
# of Option that were found. After finding the correct option, set the select
# lists value to the option value:
#
# selectlist.value = selectlist.options.first.value
#
# Options can also be selected by "clicking" or selecting them. See Option
class Mechanize::Form::SelectList < Mechanize::Form::MultiSelectList
def initialize node
super
if selected_options.length > 1
selected_options.reverse[1..selected_options.length].each do |o|
o.unselect
end
end
end
def value
value = super
if value.length > 0
value.last
elsif @options.length > 0
@options.first.value
else
nil
end
end
def value=(new_value)
if new_value != new_value.to_s and new_value.respond_to? :first
super([new_value.first])
else
super([new_value.to_s])
end
end
def query_value
value ? [[name, value]] : nil
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/option.rb | lib/mechanize/form/option.rb | # frozen_string_literal: true
##
# This class contains an option found within SelectList. A SelectList can
# have many Option classes associated with it. An option can be selected by
# calling Option#tick, or Option#click.
#
# To select the first option in a list:
#
# select_list.first.tick
class Mechanize::Form::Option
attr_reader :value, :selected, :text, :select_list, :node
alias :to_s :value
alias :selected? :selected
def initialize(node, select_list)
@node = node
@text = node.inner_text
@value = Mechanize::Util.html_unescape(node['value'] || node.inner_text)
@selected = node.has_attribute? 'selected'
@select_list = select_list # The select list this option belongs to
end
# Select this option
def select
unselect_peers
@selected = true
end
# Unselect this option
def unselect
@selected = false
end
alias :tick :select
alias :untick :unselect
# Toggle the selection value of this option
def click
unselect_peers
@selected = !@selected
end
private
def unselect_peers
return unless Mechanize::Form::SelectList === @select_list
@select_list.select_none
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/multi_select_list.rb | lib/mechanize/form/multi_select_list.rb | # frozen_string_literal: true
##
# This class represents a select list where multiple values can be selected.
# MultiSelectList#value= accepts an array, and those values are used as
# values for the select list. For example, to select multiple values,
# simply do this:
#
# list.value = ['one', 'two']
#
# Single values are still supported, so these two are the same:
#
# list.value = ['one']
# list.value = 'one'
class Mechanize::Form::MultiSelectList < Mechanize::Form::Field
extend Mechanize::ElementMatcher
attr_accessor :options
def initialize node
value = []
@options = node.search('option').map { |n|
Mechanize::Form::Option.new(n, self)
}
super node, value
end
##
# :method: option_with
#
# Find one option on this select list with +criteria+
#
# Example:
#
# select_list.option_with(:value => '1').value = 'foo'
##
# :method: option_with!(criteria)
#
# Same as +option_with+ but raises an ElementNotFoundError if no button
# matches +criteria+
##
# :method: options_with
#
# Find all options on this select list with +criteria+
#
# Example:
#
# select_list.options_with(:value => /1|2/).each do |field|
# field.value = '20'
# end
elements_with :option
def query_value
value ? value.map { |v| [name, v] } : ''
end
# Select no options
def select_none
@value = []
options.each(&:untick)
end
# Select all options
def select_all
@value = []
options.each(&:tick)
end
# Get a list of all selected options
def selected_options
@options.find_all(&:selected?)
end
def value=(values)
select_none
[values].flatten.each do |value|
option = options.find { |o| o.value == value }
if option.nil?
@value.push(value)
else
option.select
end
end
end
def value
@value + selected_options.map(&:value)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/file_upload.rb | lib/mechanize/form/file_upload.rb | # frozen_string_literal: true
# This class represents a file upload field found in a form. To use this
# class, set FileUpload#file_data= to the data of the file you want to upload
# and FileUpload#mime_type= to the appropriate mime type of the file.
#
# See the example in EXAMPLES
class Mechanize::Form::FileUpload < Mechanize::Form::Field
attr_accessor :file_name # File name
attr_accessor :mime_type # Mime Type (Optional)
alias :file_data :value
alias :file_data= :value=
def initialize node, file_name
@file_name = Mechanize::Util.html_unescape(file_name)
@file_data = nil
@node = node
super(node, @file_data)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form/reset.rb | lib/mechanize/form/reset.rb | # frozen_string_literal: true
class Mechanize::Form::Reset < Mechanize::Form::Button
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/http/agent.rb | lib/mechanize/http/agent.rb | # frozen_string_literal: true
require 'tempfile'
require 'net/ntlm'
require 'webrobots'
##
# An HTTP (and local disk access) user agent. This class is an implementation
# detail and is subject to change at any time.
class Mechanize::HTTP::Agent
CREDENTIAL_HEADERS = ['Authorization']
COOKIE_HEADERS = ['Cookie']
POST_HEADERS = ['Content-Length', 'Content-MD5', 'Content-Type']
# :section: Headers
# Disables If-Modified-Since conditional requests (enabled by default)
attr_accessor :conditional_requests
# Is gzip compression of requests enabled?
attr_accessor :gzip_enabled
# A hash of request headers to be used for every request
attr_accessor :request_headers
# The User-Agent header to send
attr_reader :user_agent
# :section: History
# history of requests made
attr_accessor :history
# :section: Hooks
# A list of hooks to call after retrieving a response. Hooks are called with
# the agent and the response returned.
attr_reader :post_connect_hooks
# A list of hooks to call before making a request. Hooks are called with
# the agent and the request to be performed.
attr_reader :pre_connect_hooks
# A list of hooks to call to handle the content-encoding of a request.
attr_reader :content_encoding_hooks
# :section: HTTP Authentication
attr_reader :auth_store # :nodoc:
attr_reader :authenticate_methods # :nodoc:
attr_reader :digest_challenges # :nodoc:
# :section: Redirection
# Follow HTML meta refresh and HTTP Refresh. If set to +:anywhere+ meta
# refresh tags outside of the head element will be followed.
attr_accessor :follow_meta_refresh
# Follow an HTML meta refresh that has no "url=" in the content attribute.
#
# Defaults to false to prevent infinite refresh loops.
attr_accessor :follow_meta_refresh_self
# Controls how this agent deals with redirects. The following values are
# allowed:
#
# :all, true:: All 3xx redirects are followed (default)
# :permanent:: Only 301 Moved Permanently redirects are followed
# false:: No redirects are followed
attr_accessor :redirect_ok
# Maximum number of redirects to follow
attr_accessor :redirection_limit
# :section: Allowed error codes
# List of error codes (in String or Integer) to handle without
# raising Mechanize::ResponseCodeError, defaulted to an empty array.
# Note that 2xx, 3xx and 401 status codes will be handled without
# checking this list.
attr_accessor :allowed_error_codes
# :section: Robots
# When true, this agent will consult the site's robots.txt for each access.
attr_reader :robots
# Mutex used when fetching robots.txt
attr_reader :robots_mutex
# :section: SSL
# OpenSSL key password
attr_accessor :pass
# :section: Timeouts
# Set to false to disable HTTP/1.1 keep-alive requests
attr_accessor :keep_alive
# Length of time to wait until a connection is opened in seconds
attr_accessor :open_timeout
# Length of time to attempt to read data from the server
attr_accessor :read_timeout
# Length of time to attempt to write data to the server
attr_accessor :write_timeout
# :section:
# The cookies for this agent
attr_accessor :cookie_jar
# Responses larger than this will be written to a Tempfile instead of stored
# in memory. Setting this to nil disables creation of Tempfiles.
attr_accessor :max_file_buffer
# :section: Utility
# The context parses responses into pages
attr_accessor :context
attr_reader :http # :nodoc:
# When set to true mechanize will ignore an EOF during chunked transfer
# encoding so long as at least one byte was received. Be careful when
# enabling this as it may cause data loss.
attr_accessor :ignore_bad_chunking
# Handlers for various URI schemes
attr_accessor :scheme_handlers
# :section:
# Creates a new Mechanize HTTP user agent. The user agent is an
# implementation detail of mechanize and its API may change at any time.
# The connection_name can be used to segregate SSL connections.
# Agents with different names will not share the same persistent connection.
def initialize(connection_name = 'mechanize')
@allowed_error_codes = []
@conditional_requests = true
@context = nil
@content_encoding_hooks = []
@cookie_jar = Mechanize::CookieJar.new
@follow_meta_refresh = false
@follow_meta_refresh_self = false
@gzip_enabled = true
@history = Mechanize::History.new
@ignore_bad_chunking = false
@keep_alive = true
@max_file_buffer = 100_000 # 5MB for response bodies
@open_timeout = nil
@post_connect_hooks = []
@pre_connect_hooks = []
@read_timeout = nil
@redirect_ok = true
@redirection_limit = 20
@request_headers = {}
@robots = false
@robots_mutex = Mutex.new
@user_agent = nil
@webrobots = nil
@write_timeout = nil
# HTTP Authentication
@auth_store = Mechanize::HTTP::AuthStore.new
@authenticate_parser = Mechanize::HTTP::WWWAuthenticateParser.new
@authenticate_methods = Hash.new do |methods, uri|
methods[uri] = Hash.new do |realms, auth_scheme|
realms[auth_scheme] = []
end
end
@digest_auth = Net::HTTP::DigestAuth.new
@digest_challenges = {}
# SSL
@pass = nil
@scheme_handlers = Hash.new { |h, scheme|
h[scheme] = lambda { |link, page|
raise Mechanize::UnsupportedSchemeError.new(scheme, link)
}
}
@scheme_handlers['http'] = lambda { |link, page| link }
@scheme_handlers['https'] = @scheme_handlers['http']
@scheme_handlers['relative'] = @scheme_handlers['http']
@scheme_handlers['file'] = @scheme_handlers['http']
@http =
if defined?(Net::HTTP::Persistent::DEFAULT_POOL_SIZE)
Net::HTTP::Persistent.new(name: connection_name)
else
# net-http-persistent < 3.0
Net::HTTP::Persistent.new(connection_name)
end
@http.idle_timeout = 5
@http.keep_alive = 300
end
##
# Adds credentials +user+, +pass+ for +uri+. If +realm+ is set the
# credentials are used only for that realm. If +realm+ is not set the
# credentials become the default for any realm on that URI.
#
# +domain+ and +realm+ are exclusive as NTLM does not follow RFC 2617. If
# +domain+ is given it is only used for NTLM authentication.
def add_auth uri, user, password, realm = nil, domain = nil
@auth_store.add_auth uri, user, password, realm, domain
end
##
# USE OF add_default_auth IS NOT RECOMMENDED AS IT MAY EXPOSE PASSWORDS TO
# THIRD PARTIES
#
# Adds credentials +user+, +pass+ as the default authentication credentials.
# If no other credentials are available these will be returned from
# credentials_for.
#
# If +domain+ is given it is only used for NTLM authentication.
def add_default_auth user, password, domain = nil # :nodoc:
@auth_store.add_default_auth user, password, domain
end
##
# Retrieves +uri+ and parses it into a page or other object according to
# PluggableParser. If the URI is an HTTP or HTTPS scheme URI the given HTTP
# +method+ is used to retrieve it, along with the HTTP +headers+, request
# +params+ and HTTP +referer+.
#
# The final URI to access is built with +uri+ and +params+, the
# latter of which is formatted into a string using
# Mechanize::Util.build_query_string, which see.
#
# +redirects+ tracks the number of redirects experienced when retrieving the
# page. If it is over the redirection_limit an error will be raised.
def fetch uri, method = :get, headers = {}, params = [],
referer = current_page, redirects = 0
referer_uri = referer ? referer.uri : nil
uri = resolve uri, referer
uri, params = resolve_parameters uri, method, params
request = http_request uri, method, params
connection = connection_for uri
request_auth request, uri
disable_keep_alive request
enable_gzip request
request_language_charset request
request_cookies request, uri
request_host request, uri
request_referer request, uri, referer_uri
request_user_agent request
request_add_headers request, headers
pre_connect request
# Consult robots.txt
if robots && uri.is_a?(URI::HTTP)
robots_allowed?(uri) or raise Mechanize::RobotsDisallowedError.new(uri)
end
# Add If-Modified-Since if page is in history
if page = visited_page(uri) and last_modified = page.response['Last-Modified']
request['If-Modified-Since'] = last_modified
end if @conditional_requests
# Specify timeouts if supplied and our connection supports them
if @open_timeout && connection.respond_to?(:open_timeout=)
connection.open_timeout = @open_timeout
end
if @read_timeout && connection.respond_to?(:read_timeout=)
connection.read_timeout = @read_timeout
end
if @write_timeout && connection.respond_to?(:write_timeout=)
connection.write_timeout = @write_timeout
end
request_log request
response_body_io = nil
# Send the request
begin
response = connection.request(uri, request) { |res|
response_log res
response_body_io = response_read res, request, uri
res
}
rescue Mechanize::ChunkedTerminationError => e
raise unless @ignore_bad_chunking
response = e.response
response_body_io = e.body_io
end
hook_content_encoding response, uri, response_body_io
response_body_io = response_content_encoding response, response_body_io if
request.response_body_permitted?
post_connect uri, response, response_body_io
page = response_parse response, response_body_io, uri
response_cookies response, uri, page
meta = response_follow_meta_refresh response, uri, page, redirects
return meta if meta
if robots && page.is_a?(Mechanize::Page)
page.parser.noindex? and raise Mechanize::RobotsDisallowedError.new(uri)
end
case response
when Net::HTTPSuccess
page
when Mechanize::FileResponse
page
when Net::HTTPNotModified
log.debug("Got cached page") if log
visited_page(uri) || page
when Net::HTTPRedirection
response_redirect response, method, page, redirects, headers, referer
when Net::HTTPUnauthorized
response_authenticate(response, page, uri, request, headers, params,
referer)
else
if @allowed_error_codes.any? {|code| code.to_s == page.code} then
page
else
raise Mechanize::ResponseCodeError.new(page, 'unhandled response')
end
end
end
# URI for a proxy connection
def proxy_uri
@http.proxy_uri
end
# Retry non-idempotent requests?
def retry_change_requests
@http.retry_change_requests
end
# Retry non-idempotent requests
def retry_change_requests= retri
@http.retry_change_requests = retri
end
# :section: Headers
def user_agent= user_agent
@webrobots = nil if user_agent != @user_agent
@user_agent = user_agent
end
# :section: History
# Equivalent to the browser back button. Returns the most recent page
# visited.
def back
@history.pop
end
##
# Returns the latest page loaded by the agent
def current_page
@history.last
end
# Returns the maximum size for the history stack.
def max_history
@history.max_size
end
# Set the maximum size for the history stack.
def max_history=(length)
@history.max_size = length
end
# Returns a visited page for the url passed in, otherwise nil
def visited_page url
@history.visited_page resolve url
end
# :section: Hooks
def hook_content_encoding response, uri, response_body_io
@content_encoding_hooks.each do |hook|
hook.call self, uri, response, response_body_io
end
end
##
# Invokes hooks added to post_connect_hooks after a +response+ is returned
# and the response +body+ is handled.
#
# Yields the +context+, the +uri+ for the request, the +response+ and the
# response +body+.
def post_connect uri, response, body_io # :yields: agent, uri, response, body
@post_connect_hooks.each do |hook|
begin
hook.call self, uri, response, body_io.read
ensure
body_io.rewind
end
end
end
##
# Invokes hooks added to pre_connect_hooks before a +request+ is made.
# Yields the +agent+ and the +request+ that will be performed to each hook.
def pre_connect request # :yields: agent, request
@pre_connect_hooks.each do |hook|
hook.call self, request
end
end
# :section: Request
def connection_for uri
case uri.scheme.downcase
when 'http', 'https' then
return @http
when 'file' then
return Mechanize::FileConnection.new
end
end
# Closes all open connections for this agent.
def shutdown
http.shutdown
end
##
# Decodes a gzip-encoded +body_io+. If it cannot be decoded, inflate is
# tried followed by raising an error.
def content_encoding_gunzip body_io
log.debug('gzip response') if log
zio = Zlib::GzipReader.new body_io
out_io = auto_io 'mechanize-gunzip', 16384, zio
zio.finish
return out_io
rescue Zlib::Error => gz_error
log.warn "unable to gunzip response: #{gz_error} (#{gz_error.class})" if
log
body_io.rewind
body_io.read 10
begin
log.warn "trying raw inflate on response" if log
return inflate body_io, -Zlib::MAX_WBITS
rescue Zlib::Error => e
log.error "unable to inflate response: #{e} (#{e.class})" if log
raise
end
ensure
# do not close a second time if we failed the first time
zio.close if zio and !(zio.closed? or gz_error)
body_io.close unless body_io.closed?
end
##
# Decodes a deflate-encoded +body_io+. If it cannot be decoded, raw inflate
# is tried followed by raising an error.
def content_encoding_inflate body_io
log.debug('deflate body') if log
return inflate body_io
rescue Zlib::Error
log.error('unable to inflate response, trying raw deflate') if log
body_io.rewind
begin
return inflate body_io, -Zlib::MAX_WBITS
rescue Zlib::Error => e
log.error("unable to inflate response: #{e}") if log
raise
end
ensure
body_io.close
end
##
# Decodes a Brotli-encoded +body_io+
#
# (Experimental, CRuby only) Although Mechanize will never request a Brotli-encoded response via
# `accept-encoding`, buggy servers may return brotli-encoded responses anyway. Let's try to handle
# that case if the Brotli gem is loaded.
#
# If you need to handle Brotli-encoded responses, install the 'brotli' gem and require it in your
# application. If the `Brotli` constant is defined, Mechanize will attempt to use it to inflate
# the response.
#
def content_encoding_brotli(body_io)
log.debug('deflate brotli body') if log
unless defined?(::Brotli)
raise Mechanize::Error, "cannot deflate brotli-encoded response. Please install and require the 'brotli' gem."
end
begin
return StringIO.new(Brotli.inflate(body_io.read))
rescue Brotli::Error
log.error("unable to brotli-inflate response") if log
raise Mechanize::Error, "error inflating brotli-encoded response."
end
ensure
body_io.close
end
##
# Decodes a Zstd-encoded +body_io+
#
# (Experimental, CRuby only) Although Mechanize will never request a zstd-encoded response via
# `accept-encoding`, buggy servers may return zstd-encoded responses, or you might need to
# inform the zstd keyword on your Accept-Encoding headers. Let's try to handle those cases if
# the Zstd gem is loaded.
#
# If you need to handle Zstd-encoded responses, install the 'zstd-ruby' gem and require it in your
# application. If the `Zstd` constant is defined, Mechanize will attempt to use it to inflate
# the response.
#
def content_encoding_zstd(body_io)
log.debug('deflate zstd body') if log
unless defined?(::Zstd)
raise Mechanize::Error, "cannot deflate zstd-encoded response. Please install and require the 'zstd-ruby' gem."
end
begin
return StringIO.new(Zstd.decompress(body_io.read))
rescue StandardError
log.error("unable to zstd#decompress response") if log
raise Mechanize::Error, "error decompressing zstd-encoded response."
end
ensure
body_io.close
end
def disable_keep_alive request
request['connection'] = 'close' unless @keep_alive
end
def enable_gzip request
request['accept-encoding'] = if @gzip_enabled
'gzip,deflate,identity'
else
'identity'
end
end
def http_request uri, method, params = nil
case uri.scheme.downcase
when 'http', 'https' then
klass = Net::HTTP.const_get(method.to_s.capitalize)
request ||= klass.new(uri.request_uri)
request.body = params.first if params
request
when 'file' then
Mechanize::FileRequest.new uri
end
end
def request_add_headers request, headers = {}
@request_headers.each do |k,v|
request[k] = v
end
headers.each do |field, value|
case field
when :etag then request["ETag"] = value
when :if_modified_since then request["If-Modified-Since"] = value
when Symbol then
raise ArgumentError, "unknown header symbol #{field}"
else
request[field] = value
end
end
end
def request_auth request, uri
base_uri = uri + '/'
base_uri.user &&= nil
base_uri.password &&= nil
schemes = @authenticate_methods[base_uri]
if realm = schemes[:digest].find { |r| r.uri == base_uri } then
request_auth_digest request, uri, realm, base_uri, false
elsif realm = schemes[:iis_digest].find { |r| r.uri == base_uri } then
request_auth_digest request, uri, realm, base_uri, true
elsif realm = schemes[:basic].find { |r| r.uri == base_uri } then
user, password, = @auth_store.credentials_for uri, realm.realm
request.basic_auth user, password
end
end
def request_auth_digest request, uri, realm, base_uri, iis
challenge = @digest_challenges[realm]
uri.user, uri.password, = @auth_store.credentials_for uri, realm.realm
auth = @digest_auth.auth_header uri, challenge.to_s, request.method, iis
request['Authorization'] = auth
end
def request_cookies request, uri
return if @cookie_jar.empty? uri
cookies = @cookie_jar.cookies uri
return if cookies.empty?
request.add_field 'Cookie', cookies.join('; ')
end
def request_host request, uri
port = [80, 443].include?(uri.port.to_i) ? nil : uri.port
host = uri.host
request['Host'] = [host, port].compact.join ':'
end
def request_language_charset request
request['accept-language'] = 'en-us,en;q=0.5'
end
# Log specified headers for the request
def request_log request
return unless log
log.info("#{request.class}: #{request.path}")
request.each_header do |k, v|
log.debug("request-header: #{k} => #{v}")
end
end
# Sets a Referer header. Fragment part is removed as demanded by
# RFC 2616 14.36, and user information part is removed just like
# major browsers do.
def request_referer request, uri, referer
return unless referer
return if 'https'.casecmp(referer.scheme) == 0 and
'https'.casecmp(uri.scheme) != 0
if referer.fragment || referer.user || referer.password
referer = referer.dup
referer.fragment = referer.user = referer.password = nil
end
request['Referer'] = referer
end
def request_user_agent request
request['User-Agent'] = @user_agent if @user_agent
end
def resolve(uri, referer = current_page)
referer_uri = referer && referer.uri
if uri.is_a?(URI)
uri = uri.dup
elsif uri.nil?
if referer_uri
return referer_uri
end
raise ArgumentError, "absolute URL needed (not nil)"
else
url = uri.to_s.strip
if url.empty?
if referer_uri
return referer_uri.dup.tap { |u| u.fragment = nil }
end
raise ArgumentError, "absolute URL needed (not #{uri.inspect})"
end
url.gsub!(/[^#{0.chr}-#{126.chr}]/o) { |match|
Mechanize::Util.uri_escape(match)
}
escaped_url = Mechanize::Util.html_unescape(
url.split(/((?:%[0-9A-Fa-f]{2})+|#)/).each_slice(2).map { |x, y|
"#{WEBrick::HTTPUtils.escape(x)}#{y}"
}.join('')
)
begin
uri = URI.parse(escaped_url)
rescue
uri = URI.parse(WEBrick::HTTPUtils.escape(escaped_url))
end
end
uri.host = referer_uri.host if referer_uri && URI::HTTP === uri && uri.host.nil?
scheme = uri.relative? ? 'relative' : uri.scheme.downcase
uri = @scheme_handlers[scheme].call(uri, referer)
if uri.relative?
raise ArgumentError, "absolute URL needed (not #{uri})" unless
referer_uri
if referer.respond_to?(:bases) && referer.parser &&
(lbase = referer.bases.last) && lbase.uri && lbase.uri.absolute?
base = lbase
else
base = nil
end
base = referer_uri + (base ? base.uri : referer_uri)
# Workaround for URI's bug in that it squashes consecutive
# slashes. See #304.
if uri.path.match(%r{\A(.*?/)(?!/\.\.?(?!/))(/.*)\z}i)
uri = URI((base + $1).to_s + $2)
else
uri = base + uri
end
# Strip initial "/.." bits from the path
uri.path.sub!(/^(\/\.\.)+(?=\/)/, '')
end
unless ['http', 'https', 'file'].include?(uri.scheme.downcase)
raise ArgumentError, "unsupported scheme: #{uri.scheme}"
end
case uri.path
when nil
raise ArgumentError, "hierarchical URL needed (not #{uri})"
when ''.freeze
uri.path = '/'
end
uri
end
def secure_resolve!(uri, referer = current_page)
new_uri = resolve(uri, referer)
if (referer_uri = referer && referer.uri) &&
referer_uri.scheme != 'file'.freeze &&
new_uri.scheme == 'file'.freeze
raise Mechanize::Error, "insecure redirect to a file URI"
end
new_uri
end
def resolve_parameters uri, method, parameters
case method
when :head, :get, :delete, :trace then
if parameters and parameters.length > 0
uri.query ||= ''
uri.query << '&' if uri.query.length > 0
uri.query << Mechanize::Util.build_query_string(parameters)
end
return uri, nil
end
return uri, parameters
end
# :section: Response
def get_meta_refresh response, uri, page
return nil unless @follow_meta_refresh
if page.respond_to?(:meta_refresh) and
(redirect = page.meta_refresh.first) then
[redirect.delay, redirect.href] unless
not @follow_meta_refresh_self and redirect.link_self
elsif refresh = response['refresh']
delay, href, link_self = Mechanize::Page::MetaRefresh.parse refresh, uri
raise Mechanize::Error, 'Invalid refresh http header' unless delay
[delay.to_f, href] unless
not @follow_meta_refresh_self and link_self
end
end
def response_authenticate(response, page, uri, request, headers, params,
referer)
www_authenticate = response['www-authenticate']
unless www_authenticate = response['www-authenticate'] then
message = 'WWW-Authenticate header missing in response'
raise Mechanize::UnauthorizedError.new(page, nil, message)
end
challenges = @authenticate_parser.parse www_authenticate
unless @auth_store.credentials? uri, challenges then
message = "no credentials found, provide some with #add_auth"
raise Mechanize::UnauthorizedError.new(page, challenges, message)
end
if challenge = challenges.find { |c| c.scheme =~ /^Digest$/i } then
realm = challenge.realm uri
auth_scheme = if response['server'] =~ /Microsoft-IIS/ then
:iis_digest
else
:digest
end
existing_realms = @authenticate_methods[realm.uri][auth_scheme]
if existing_realms.include? realm
message = 'Digest authentication failed'
raise Mechanize::UnauthorizedError.new(page, challenges, message)
end
existing_realms << realm
@digest_challenges[realm] = challenge
elsif challenge = challenges.find { |c| c.scheme == 'NTLM' } then
existing_realms = @authenticate_methods[uri + '/'][:ntlm]
if existing_realms.include?(realm) and not challenge.params then
message = 'NTLM authentication failed'
raise Mechanize::UnauthorizedError.new(page, challenges, message)
end
existing_realms << realm
if challenge.params then
type_2 = Net::NTLM::Message.decode64 challenge.params
user, password, domain = @auth_store.credentials_for uri, nil
type_3 = type_2.response({ :user => user, :password => password,
:domain => domain },
{ :ntlmv2 => true }).encode64
headers['Authorization'] = "NTLM #{type_3}"
else
type_1 = Net::NTLM::Message::Type1.new.encode64
headers['Authorization'] = "NTLM #{type_1}"
end
elsif challenge = challenges.find { |c| c.scheme == 'Basic' } then
realm = challenge.realm uri
existing_realms = @authenticate_methods[realm.uri][:basic]
if existing_realms.include? realm then
message = 'Basic authentication failed'
raise Mechanize::UnauthorizedError.new(page, challenges, message)
end
existing_realms << realm
else
message = 'unsupported authentication scheme'
raise Mechanize::UnauthorizedError.new(page, challenges, message)
end
fetch uri, request.method.downcase.to_sym, headers, params, referer
end
def response_content_encoding response, body_io
length = response.content_length ||
case body_io
when Tempfile, IO then
body_io.stat.size
else
body_io.length
end
return body_io if length.zero?
out_io = case response['Content-Encoding']
when nil, 'none', '7bit', 'identity', "" then
body_io
when 'deflate' then
content_encoding_inflate body_io
when 'gzip', 'x-gzip' then
content_encoding_gunzip body_io
when 'br' then
content_encoding_brotli body_io
when 'zstd' then
content_encoding_zstd body_io
else
raise Mechanize::Error,
"unsupported content-encoding: #{response['Content-Encoding']}"
end
out_io.flush
out_io.rewind
out_io
rescue Zlib::Error => e
message = String.new("error handling content-encoding #{response['Content-Encoding']}:")
message << " #{e.message} (#{e.class})"
raise Mechanize::Error, message
ensure
begin
if Tempfile === body_io and
(StringIO === out_io or (out_io and out_io.path != body_io.path)) then
body_io.close!
end
rescue IOError
# HACK ruby 1.8 raises IOError when closing the stream
end
end
def response_cookies response, uri, page
if Mechanize::Page === page and page.body =~ /Set-Cookie/n
page.search('//head/meta[@http-equiv="Set-Cookie"]').each do |meta|
save_cookies(uri, meta['content'])
end
end
header_cookies = response.get_fields 'Set-Cookie'
return unless header_cookies
header_cookies.each do |set_cookie|
save_cookies(uri, set_cookie)
end
end
def save_cookies(uri, set_cookie)
return [] if set_cookie.nil?
if log = log() # reduce method calls
@cookie_jar.parse(set_cookie, uri, :logger => log) { |c|
log.debug("saved cookie: #{c}")
true
}
else
@cookie_jar.parse(set_cookie, uri)
end
end
def response_follow_meta_refresh response, uri, page, redirects
delay, new_url = get_meta_refresh(response, uri, page)
return nil unless delay
new_url = new_url ? secure_resolve!(new_url, page) : uri
raise Mechanize::RedirectLimitReachedError.new(page, redirects) if
redirects + 1 > @redirection_limit
sleep delay
@history.push(page, page.uri)
fetch new_url, :get, {}, [],
Mechanize::Page.new, redirects + 1
end
def response_log response
return unless log
log.info("status: #{response.class} #{response.http_version} " \
"#{response.code} #{response.message}")
response.each_header do |k, v|
log.debug("response-header: #{k} => #{v}")
end
end
def response_parse response, body_io, uri
@context.parse uri, response, body_io
end
def response_read response, request, uri
content_length = response.content_length
if use_tempfile? content_length then
body_io = make_tempfile 'mechanize-raw'
else
body_io = StringIO.new.set_encoding(Encoding::BINARY)
end
total = 0
begin
response.read_body { |part|
total += part.length
if StringIO === body_io and use_tempfile? total then
new_io = make_tempfile 'mechanize-raw'
new_io.write body_io.string
body_io = new_io
end
body_io.write(part)
log.debug("Read #{part.length} bytes (#{total} total)") if log
}
rescue EOFError => e
# terminating CRLF might be missing, let the user check the document
raise unless response.chunked? and total.nonzero?
body_io.rewind
raise Mechanize::ChunkedTerminationError.new(e, response, body_io, uri,
@context)
rescue Net::HTTP::Persistent::Error, Errno::ECONNRESET => e
body_io.rewind
raise Mechanize::ResponseReadError.new(e, response, body_io, uri,
@context)
end
body_io.flush
body_io.rewind
raise Mechanize::ResponseCodeError.new(response, uri) if
Net::HTTPUnknownResponse === response
content_length = response.content_length
unless Net::HTTP::Head === request or Net::HTTPRedirection === response then
if content_length and content_length != body_io.length
err = EOFError.new("Content-Length (#{content_length}) does not " \
"match response body length (#{body_io.length})")
raise Mechanize::ResponseReadError.new(err, response, body_io, uri,
@context)
end
end
body_io
end
def response_redirect(response, method, page, redirects, headers,
referer = current_page)
case @redirect_ok
when true, :all
# shortcut
when false, nil
return page
when :permanent
return page unless Net::HTTPMovedPermanently === response
end
log.info("follow redirect to: #{response['Location']}") if log
raise Mechanize::RedirectLimitReachedError.new(page, redirects) if
redirects + 1 > @redirection_limit
redirect_method = method == :head ? :head : :get
new_uri = secure_resolve!(response['Location'].to_s, page)
@history.push(page, page.uri)
# Make sure we are not copying over the POST headers from the original request
POST_HEADERS.each do |key|
headers.delete_if { |h| h.casecmp?(key) }
end
# Make sure we clear credential headers if being redirected to another site
if new_uri.host == page.uri.host
if new_uri.port != page.uri.port
# https://datatracker.ietf.org/doc/html/rfc6265#section-8.5
# cookies are OK to be shared across ports on the same host
CREDENTIAL_HEADERS.each { |ch| headers.delete_if { |h| h.casecmp?(ch) } }
end
else
(COOKIE_HEADERS + CREDENTIAL_HEADERS).each { |ch| headers.delete_if { |h| h.casecmp?(ch) } }
end
fetch new_uri, redirect_method, headers, [], referer, redirects + 1
end
# :section: Robots
RobotsKey = :__mechanize_get_robots__
def get_robots(uri) # :nodoc:
robots_mutex.synchronize do
Thread.current[RobotsKey] = true
begin
fetch(uri).body
rescue Mechanize::ResponseCodeError => e
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | true |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/http/auth_store.rb | lib/mechanize/http/auth_store.rb | # frozen_string_literal: true
##
# A credential store for HTTP authentication.
#
# uri = URI 'http://example'
#
# store = Mechanize::HTTP::AuthStore.new
# store.add_auth uri, 'user1', 'pass'
# store.add_auth uri, 'user2', 'pass', 'realm'
#
# user, pass = store.credentials_for uri, 'realm' #=> 'user2', 'pass'
# user, pass = store.credentials_for uri, 'other' #=> 'user1', 'pass'
#
# store.remove_auth uri # removes all credentials
class Mechanize::HTTP::AuthStore
attr_reader :auth_accounts # :nodoc:
attr_reader :default_auth # :nodoc:
##
# Creates a new AuthStore
def initialize
@auth_accounts = Hash.new do |h, uri|
h[uri] = {}
end
@default_auth = nil
end
##
# Adds credentials +user+, +pass+ for the server at +uri+. If +realm+ is
# set the credentials are used only for that realm. If +realm+ is not set
# the credentials become the default for any realm on that URI.
#
# +domain+ and +realm+ are exclusive as NTLM does not follow RFC
# 2617. If +domain+ is given it is only used for NTLM authentication.
def add_auth uri, user, pass, realm = nil, domain = nil
uri = URI uri unless URI === uri
raise ArgumentError,
'NTLM domain given with realm which NTLM does not use' if
realm and domain
uri += '/'
auth_accounts[uri][realm] = [user, pass, domain]
self
end
##
# USE OF add_default_auth IS NOT RECOMMENDED AS IT MAY EXPOSE PASSWORDS TO
# THIRD PARTIES
#
# Adds credentials +user+, +pass+ as the default authentication credentials.
# If no other credentials are available these will be returned from
# credentials_for.
#
# If +domain+ is given it is only used for NTLM authentication.
def add_default_auth user, pass, domain = nil
warn <<-WARN
You have supplied default authentication credentials that apply to ANY SERVER.
Your username and password can be retrieved by ANY SERVER using Basic
authentication.
THIS EXPOSES YOUR USERNAME AND PASSWORD TO DISCLOSURE WITHOUT YOUR KNOWLEDGE.
Use add_auth to set authentication credentials that will only be delivered
only to a particular server you specify.
WARN
@default_auth = [user, pass, domain]
end
##
# Returns true if credentials exist for the +challenges+ from the server at
# +uri+.
def credentials? uri, challenges
challenges.any? do |challenge|
credentials_for uri, challenge.realm_name
end
end
##
# Retrieves credentials for +realm+ on the server at +uri+.
def credentials_for uri, realm
uri = URI uri unless URI === uri
uri += '/'
uri.user = nil
uri.password = nil
realms = @auth_accounts[uri]
realms[realm] || realms[nil] || @default_auth
end
##
# Removes credentials for +realm+ on the server at +uri+. If +realm+ is not
# set all credentials for the server at +uri+ are removed.
def remove_auth uri, realm = nil
uri = URI uri unless URI === uri
uri += '/'
if realm then
auth_accounts[uri].delete realm
else
auth_accounts.delete uri
end
self
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/http/auth_realm.rb | lib/mechanize/http/auth_realm.rb | # frozen_string_literal: true
class Mechanize::HTTP::AuthRealm
attr_reader :scheme
attr_reader :uri
attr_reader :realm
def initialize scheme, uri, realm
@scheme = scheme
@uri = uri
@realm = realm if realm
end
def == other
self.class === other and
@scheme == other.scheme and
@uri == other.uri and
@realm == other.realm
end
alias eql? ==
def hash # :nodoc:
[@scheme, @uri, @realm].hash
end
def inspect # :nodoc:
"#<AuthRealm %s %p \"%s\">" % [@scheme, @uri, @realm]
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/http/www_authenticate_parser.rb | lib/mechanize/http/www_authenticate_parser.rb | # frozen_string_literal: true
require 'strscan'
##
# Parses the WWW-Authenticate HTTP header into separate challenges.
class Mechanize::HTTP::WWWAuthenticateParser
attr_accessor :scanner # :nodoc:
##
# Creates a new header parser for WWW-Authenticate headers
def initialize
@scanner = nil
end
##
# Parsers the header. Returns an Array of challenges as strings
def parse www_authenticate
challenges = []
@scanner = StringScanner.new www_authenticate
while true do
break if @scanner.eos?
start = @scanner.pos
challenge = Mechanize::HTTP::AuthChallenge.new
scheme = auth_scheme
if scheme == 'Negotiate'
scan_comma_spaces
end
break unless scheme
challenge.scheme = scheme
space = spaces
if scheme == 'NTLM' then
if space then
challenge.params = @scanner.scan(/.*/)
end
challenge.raw = www_authenticate[start, @scanner.pos]
challenges << challenge
next
else
scheme.capitalize!
end
next unless space
params = {}
while true do
pos = @scanner.pos
name, value = auth_param
name.downcase! if name =~ /^realm$/i
unless name then
challenge.params = params
challenges << challenge
if @scanner.eos? then
challenge.raw = www_authenticate[start, @scanner.pos]
break
end
@scanner.pos = pos # rewind
challenge.raw = www_authenticate[start, @scanner.pos].sub(/(,+)? *$/, '')
challenge = nil # a token should be next, new challenge
break
else
params[name] = value
end
spaces
@scanner.scan(/(, *)+/)
end
end
challenges
end
##
# 1*SP
#
# Parses spaces
def spaces
@scanner.scan(/ +/)
end
##
# scans a comma followed by spaces
# needed for Negotiation, NTLM
#
def scan_comma_spaces
@scanner.scan(/, +/)
end
##
# token = 1*<any CHAR except CTLs or separators>
#
# Parses a token
def token
@scanner.scan(/[^\000-\037\177()<>@,;:\\"\/\[\]?={} ]+/)
end
##
# auth-scheme = token
#
# Parses an auth scheme (a token)
alias auth_scheme token
##
# auth-param = token "=" ( token | quoted-string )
#
# Parses an auth parameter
def auth_param
return nil unless name = token
return nil unless @scanner.scan(/ *= */)
value = if @scanner.peek(1) == '"' then
quoted_string
else
token
end
return nil unless value
return name, value
end
##
# quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
# qdtext = <any TEXT except <">>
# quoted-pair = "\" CHAR
#
# For TEXT, the rules of RFC 2047 are ignored.
def quoted_string
return nil unless @scanner.scan(/"/)
text = String.new
while true do
chunk = @scanner.scan(/[\r\n \t\x21\x23-\x7e\u0080-\u00ff]+/) # not " which is \x22
if chunk then
text << chunk
text << @scanner.get_byte if
chunk.end_with? '\\' and '"' == @scanner.peek(1)
else
if '"' == @scanner.peek(1) then
@scanner.get_byte
break
else
return nil
end
end
end
text
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/http/auth_challenge.rb | lib/mechanize/http/auth_challenge.rb | # frozen_string_literal: true
class Mechanize::HTTP
AuthChallenge = Struct.new :scheme, :params, :raw
##
# A parsed WWW-Authenticate header
class AuthChallenge
##
# :attr_accessor: scheme
#
# The authentication scheme
##
# :attr_accessor: params
#
# The authentication parameters
##
# :method: initialize
#
# :call-seq:
# initialize(scheme = nil, params = nil)
#
# Creates a new AuthChallenge header with the given scheme and parameters
##
# Retrieves +param+ from the params list
def [] param
params[param]
end
##
# Constructs an AuthRealm for this challenge
def realm uri
case scheme
when 'Basic' then
raise ArgumentError, "provide uri for Basic authentication" unless uri
Mechanize::HTTP::AuthRealm.new scheme, uri + '/', self['realm']
when 'Digest' then
Mechanize::HTTP::AuthRealm.new scheme, uri + '/', self['realm']
else
raise Mechanize::Error, "unknown HTTP authentication scheme #{scheme}"
end
end
##
# The name of the realm for this challenge
def realm_name
params['realm'] if Hash === params # NTLM has a string for params
end
##
# The raw authentication challenge
alias to_s raw
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/http/content_disposition_parser.rb | lib/mechanize/http/content_disposition_parser.rb | # frozen_string_literal: true
# coding: BINARY
require 'strscan'
require 'time'
class Mechanize::HTTP
ContentDisposition = Struct.new :type, :filename, :creation_date,
:modification_date, :read_date, :size, :parameters
end
##
# Parser Content-Disposition headers that loosely follows RFC 2183.
#
# Beyond RFC 2183, this parser allows:
#
# * Missing disposition-type
# * Multiple semicolons
# * Whitespace around semicolons
# * Dates in ISO 8601 format
class Mechanize::HTTP::ContentDispositionParser
attr_accessor :scanner # :nodoc:
@parser = nil
##
# Parses the disposition type and params in the +content_disposition+
# string. The "Content-Disposition:" must be removed.
def self.parse content_disposition
@parser ||= self.new
@parser.parse content_disposition
end
##
# Creates a new parser Content-Disposition headers
def initialize
@scanner = nil
end
##
# Parses the +content_disposition+ header. If +header+ is set to true the
# "Content-Disposition:" portion will be parsed
def parse content_disposition, header = false
return nil if content_disposition.empty?
@scanner = StringScanner.new content_disposition
if header then
return nil unless @scanner.scan(/Content-Disposition/i)
return nil unless @scanner.scan(/:/)
spaces
end
type = rfc_2045_token
@scanner.scan(/;+/)
if @scanner.peek(1) == '=' then
@scanner.pos = 0
type = nil
end
disposition = Mechanize::HTTP::ContentDisposition.new type
spaces
return nil unless parameters = parse_parameters
disposition.filename = parameters.delete 'filename'
disposition.creation_date = parameters.delete 'creation-date'
disposition.modification_date = parameters.delete 'modification-date'
disposition.read_date = parameters.delete 'read-date'
disposition.size = parameters.delete 'size'
disposition.parameters = parameters
disposition
end
##
# Extracts disposition-param and returns a Hash.
def parse_parameters
parameters = {}
while true do
return nil unless param = rfc_2045_token
param.downcase!
return nil unless @scanner.scan(/=/)
value = case param
when /^filename$/ then
rfc_2045_value
when /^(creation|modification|read)-date$/ then
date = rfc_2045_quoted_string
begin
Time.rfc822 date
rescue ArgumentError
begin
Time.iso8601 date
rescue ArgumentError
nil
end
end
when /^size$/ then
rfc_2045_value.to_i(10)
else
rfc_2045_value
end
return nil unless value
parameters[param] = value
spaces
break if @scanner.eos? or not @scanner.scan(/;+/)
spaces
end
parameters
end
##
# quoted-string = <"> *(qtext/quoted-pair) <">
# qtext = <any CHAR excepting <">, "\" & CR,
# and including linear-white-space
# quoted-pair = "\" CHAR
#
# Parses an RFC 2045 quoted-string
def rfc_2045_quoted_string
return nil unless @scanner.scan(/"/)
text = String.new
while true do
chunk = @scanner.scan(/[\000-\014\016-\041\043-\133\135-\177]+/) # not \r "
if chunk then
text << chunk
if @scanner.peek(1) == '\\' then
@scanner.get_byte
return nil if @scanner.eos?
text << @scanner.get_byte
elsif @scanner.scan(/\r\n[\t ]+/) then
text << " "
end
else
if '\\"' == @scanner.peek(2) then
@scanner.skip(/\\/)
text << @scanner.get_byte
elsif '"' == @scanner.peek(1) then
@scanner.get_byte
break
else
return nil
end
end
end
text
end
##
# token := 1*<any (US-ASCII) CHAR except SPACE, CTLs, or tspecials>
#
# Parses an RFC 2045 token
def rfc_2045_token
@scanner.scan(/[^\000-\037\177()<>@,;:\\"\/\[\]?= ]+/)
end
##
# value := token / quoted-string
#
# Parses an RFC 2045 value
def rfc_2045_value
if @scanner.peek(1) == '"' then
rfc_2045_quoted_string
else
rfc_2045_token
end
end
##
# 1*SP
#
# Parses spaces
def spaces
@scanner.scan(/ +/)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/test/jbuilder_test.rb | test/jbuilder_test.rb | require 'test_helper'
require 'active_support/inflector'
require 'jbuilder'
def jbuild(*args, &block)
Jbuilder.new(*args, &block).attributes!
end
Comment = Struct.new(:content, :id)
class NonEnumerable
def initialize(collection)
@collection = collection
end
delegate :map, :count, to: :@collection
end
class VeryBasicWrapper < BasicObject
def initialize(thing)
@thing = thing
end
def method_missing(name, *args, &block)
@thing.send name, *args, &block
end
end
# This is not Struct, because structs are Enumerable
class Person
attr_reader :name, :age
def initialize(name, age)
@name, @age = name, age
end
end
class RelationMock
include Enumerable
def each(&block)
[Person.new('Bob', 30), Person.new('Frank', 50)].each(&block)
end
def empty?
false
end
end
class JbuilderTest < ActiveSupport::TestCase
teardown do
Jbuilder.send :class_variable_set, '@@key_formatter', nil
end
test 'single key' do
result = jbuild do |json|
json.content 'hello'
end
assert_equal 'hello', result['content']
end
test 'single key with false value' do
result = jbuild do |json|
json.content false
end
assert_equal false, result['content']
end
test 'single key with nil value' do
result = jbuild do |json|
json.content nil
end
assert result.has_key?('content')
assert_nil result['content']
end
test 'multiple keys' do
result = jbuild do |json|
json.title 'hello'
json.content 'world'
end
assert_equal 'hello', result['title']
assert_equal 'world', result['content']
end
test 'extracting from object' do
person = Struct.new(:name, :age).new('David', 32)
result = jbuild do |json|
json.extract! person, :name, :age
end
assert_equal 'David', result['name']
assert_equal 32, result['age']
end
test 'extracting from object using call style' do
person = Struct.new(:name, :age).new('David', 32)
result = jbuild do |json|
json.(person, :name, :age)
end
assert_equal 'David', result['name']
assert_equal 32, result['age']
end
test 'extracting from hash' do
person = {:name => 'Jim', :age => 34}
result = jbuild do |json|
json.extract! person, :name, :age
end
assert_equal 'Jim', result['name']
assert_equal 34, result['age']
end
test 'nesting single child with block' do
result = jbuild do |json|
json.author do
json.name 'David'
json.age 32
end
end
assert_equal 'David', result['author']['name']
assert_equal 32, result['author']['age']
end
test 'empty block handling' do
result = jbuild do |json|
json.foo 'bar'
json.author do
end
end
assert_equal 'bar', result['foo']
assert !result.key?('author')
end
test 'blocks are additive' do
result = jbuild do |json|
json.author do
json.name 'David'
end
json.author do
json.age 32
end
end
assert_equal 'David', result['author']['name']
assert_equal 32, result['author']['age']
end
test 'nested blocks are additive' do
result = jbuild do |json|
json.author do
json.name do
json.first 'David'
end
end
json.author do
json.name do
json.last 'Heinemeier Hansson'
end
end
end
assert_equal 'David', result['author']['name']['first']
assert_equal 'Heinemeier Hansson', result['author']['name']['last']
end
test 'support merge! method' do
result = jbuild do |json|
json.merge! 'foo' => 'bar'
end
assert_equal 'bar', result['foo']
end
test 'support merge! method in a block' do
result = jbuild do |json|
json.author do
json.merge! 'name' => 'Pavel'
end
end
assert_equal 'Pavel', result['author']['name']
end
test 'support merge! method with Jbuilder instance' do
obj = jbuild do |json|
json.foo 'bar'
end
result = jbuild do |json|
json.merge! obj
end
assert_equal 'bar', result['foo']
end
test 'blocks are additive via extract syntax' do
person = Person.new('Pavel', 27)
result = jbuild do |json|
json.author person, :age
json.author person, :name
end
assert_equal 'Pavel', result['author']['name']
assert_equal 27, result['author']['age']
end
test 'arrays are additive' do
result = jbuild do |json|
json.array! %w[foo]
json.array! %w[bar]
end
assert_equal %w[foo bar], result
end
test 'nesting multiple children with block' do
result = jbuild do |json|
json.comments do
json.child! { json.content 'hello' }
json.child! { json.content 'world' }
end
end
assert_equal 'hello', result['comments'].first['content']
assert_equal 'world', result['comments'].second['content']
end
test 'nesting single child with inline extract' do
person = Person.new('David', 32)
result = jbuild do |json|
json.author person, :name, :age
end
assert_equal 'David', result['author']['name']
assert_equal 32, result['author']['age']
end
test 'nesting multiple children from array' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
result = jbuild do |json|
json.comments comments, :content
end
assert_equal ['content'], result['comments'].first.keys
assert_equal 'hello', result['comments'].first['content']
assert_equal 'world', result['comments'].second['content']
end
test 'nesting multiple children from array when child array is empty' do
comments = []
result = jbuild do |json|
json.name 'Parent'
json.comments comments, :content
end
assert_equal 'Parent', result['name']
assert_equal [], result['comments']
end
test 'nesting multiple children from array with inline loop' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
result = jbuild do |json|
json.comments comments do |comment|
json.content comment.content
end
end
assert_equal ['content'], result['comments'].first.keys
assert_equal 'hello', result['comments'].first['content']
assert_equal 'world', result['comments'].second['content']
end
test 'handles nil-collections as empty arrays' do
result = jbuild do |json|
json.comments nil do |comment|
json.content comment.content
end
end
assert_equal [], result['comments']
end
test 'nesting multiple children from a non-Enumerable that responds to #map' do
comments = NonEnumerable.new([ Comment.new('hello', 1), Comment.new('world', 2) ])
result = jbuild do |json|
json.comments comments, :content
end
assert_equal ['content'], result['comments'].first.keys
assert_equal 'hello', result['comments'].first['content']
assert_equal 'world', result['comments'].second['content']
end
test 'nesting multiple children from a non-Enumerable that responds to #map with inline loop' do
comments = NonEnumerable.new([ Comment.new('hello', 1), Comment.new('world', 2) ])
result = jbuild do |json|
json.comments comments do |comment|
json.content comment.content
end
end
assert_equal ['content'], result['comments'].first.keys
assert_equal 'hello', result['comments'].first['content']
assert_equal 'world', result['comments'].second['content']
end
test 'array! casts array-like objects to array before merging' do
wrapped_array = VeryBasicWrapper.new(%w[foo bar])
result = jbuild do |json|
json.array! wrapped_array
end
assert_equal %w[foo bar], result
end
test 'nesting multiple children from array with inline loop on root' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
result = jbuild do |json|
json.call(comments) do |comment|
json.content comment.content
end
end
assert_equal 'hello', result.first['content']
assert_equal 'world', result.second['content']
end
test 'array nested inside nested hash' do
result = jbuild do |json|
json.author do
json.name 'David'
json.age 32
json.comments do
json.child! { json.content 'hello' }
json.child! { json.content 'world' }
end
end
end
assert_equal 'hello', result['author']['comments'].first['content']
assert_equal 'world', result['author']['comments'].second['content']
end
test 'array nested inside array' do
result = jbuild do |json|
json.comments do
json.child! do
json.authors do
json.child! do
json.name 'david'
end
end
end
end
end
assert_equal 'david', result['comments'].first['authors'].first['name']
end
test 'directly set an array nested in another array' do
data = [ { :department => 'QA', :not_in_json => 'hello', :names => ['John', 'David'] } ]
result = jbuild do |json|
json.array! data do |object|
json.department object[:department]
json.names do
json.array! object[:names]
end
end
end
assert_equal 'David', result[0]['names'].last
assert !result[0].key?('not_in_json')
end
test 'nested jbuilder objects' do
to_nest = Jbuilder.new{ |json| json.nested_value 'Nested Test' }
result = jbuild do |json|
json.value 'Test'
json.nested to_nest
end
expected = {'value' => 'Test', 'nested' => {'nested_value' => 'Nested Test'}}
assert_equal expected, result
end
test 'nested jbuilder object via set!' do
to_nest = Jbuilder.new{ |json| json.nested_value 'Nested Test' }
result = jbuild do |json|
json.value 'Test'
json.set! :nested, to_nest
end
expected = {'value' => 'Test', 'nested' => {'nested_value' => 'Nested Test'}}
assert_equal expected, result
end
test 'top-level array' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
result = jbuild do |json|
json.array! comments do |comment|
json.content comment.content
end
end
assert_equal 'hello', result.first['content']
assert_equal 'world', result.second['content']
end
test 'it allows using next in array block to skip value' do
comments = [ Comment.new('hello', 1), Comment.new('skip', 2), Comment.new('world', 3) ]
result = jbuild do |json|
json.array! comments do |comment|
next if comment.id == 2
json.content comment.content
end
end
assert_equal 2, result.length
assert_equal 'hello', result.first['content']
assert_equal 'world', result.second['content']
end
test 'extract attributes directly from array' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
result = jbuild do |json|
json.array! comments, :content, :id
end
assert_equal 'hello', result.first['content']
assert_equal 1, result.first['id']
assert_equal 'world', result.second['content']
assert_equal 2, result.second['id']
end
test 'empty top-level array' do
comments = []
result = jbuild do |json|
json.array! comments do |comment|
json.content comment.content
end
end
assert_equal [], result
end
test 'dynamically set a key/value' do
result = jbuild do |json|
json.set! :each, 'stuff'
end
assert_equal 'stuff', result['each']
end
test 'dynamically set a key/nested child with block' do
result = jbuild do |json|
json.set! :author do
json.name 'David'
json.age 32
end
end
assert_equal 'David', result['author']['name']
assert_equal 32, result['author']['age']
end
test 'dynamically sets a collection' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
result = jbuild do |json|
json.set! :comments, comments, :content
end
assert_equal ['content'], result['comments'].first.keys
assert_equal 'hello', result['comments'].first['content']
assert_equal 'world', result['comments'].second['content']
end
test 'query like object' do
result = jbuild do |json|
json.relations RelationMock.new, :name, :age
end
assert_equal 2, result['relations'].length
assert_equal 'Bob', result['relations'][0]['name']
assert_equal 50, result['relations'][1]['age']
end
test 'initialize via options hash' do
jbuilder = Jbuilder.new(key_formatter: 1, ignore_nil: 2)
assert_equal 1, jbuilder.instance_eval{ @key_formatter }
assert_equal 2, jbuilder.instance_eval{ @ignore_nil }
end
test 'key_format! with parameter' do
result = jbuild do |json|
json.key_format! camelize: [:lower]
json.camel_style 'for JS'
end
assert_equal ['camelStyle'], result.keys
end
test 'key_format! with parameter not as an array' do
result = jbuild do |json|
json.key_format! :camelize => :lower
json.camel_style 'for JS'
end
assert_equal ['camelStyle'], result.keys
end
test 'key_format! propagates to child elements' do
result = jbuild do |json|
json.key_format! :upcase
json.level1 'one'
json.level2 do
json.value 'two'
end
end
assert_equal 'one', result['LEVEL1']
assert_equal 'two', result['LEVEL2']['VALUE']
end
test 'key_format! resets after child element' do
result = jbuild do |json|
json.level2 do
json.key_format! :upcase
json.value 'two'
end
json.level1 'one'
end
assert_equal 'two', result['level2']['VALUE']
assert_equal 'one', result['level1']
end
test 'key_format! can be changed in child elements' do
result = jbuild do |json|
json.key_format! camelize: :lower
json.level_one do
json.key_format! :upcase
json.value 'two'
end
end
assert_equal ['levelOne'], result.keys
assert_equal ['VALUE'], result['levelOne'].keys
end
test 'key_format! can be changed in array!' do
result = jbuild do |json|
json.key_format! camelize: :lower
json.level_one do
json.array! [{value: 'two'}] do |object|
json.key_format! :upcase
json.value object[:value]
end
end
end
assert_equal ['levelOne'], result.keys
assert_equal ['VALUE'], result['levelOne'][0].keys
end
test 'key_format! with no parameter' do
result = jbuild do |json|
json.key_format! :upcase
json.lower 'Value'
end
assert_equal ['LOWER'], result.keys
end
test 'key_format! with multiple steps' do
result = jbuild do |json|
json.key_format! :upcase, :pluralize
json.pill 'foo'
end
assert_equal ['PILLs'], result.keys
end
test 'key_format! with lambda/proc' do
result = jbuild do |json|
json.key_format! ->(key){ key + ' and friends' }
json.oats 'foo'
end
assert_equal ['oats and friends'], result.keys
end
test 'key_format! is not applied deeply by default' do
names = { first_name: 'camel', last_name: 'case' }
result = jbuild do |json|
json.key_format! camelize: :lower
json.set! :all_names, names
end
assert_equal %i[first_name last_name], result['allNames'].keys
end
test 'applying key_format! deeply can be enabled per scope' do
names = { first_name: 'camel', last_name: 'case' }
result = jbuild do |json|
json.key_format! camelize: :lower
json.scope do
json.deep_format_keys!
json.set! :all_names, names
end
json.set! :all_names, names
end
assert_equal %w[firstName lastName], result['scope']['allNames'].keys
assert_equal %i[first_name last_name], result['allNames'].keys
end
test 'applying key_format! deeply can be disabled per scope' do
names = { first_name: 'camel', last_name: 'case' }
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.set! :all_names, names
json.scope do
json.deep_format_keys! false
json.set! :all_names, names
end
end
assert_equal %w[firstName lastName], result['allNames'].keys
assert_equal %i[first_name last_name], result['scope']['allNames'].keys
end
test 'applying key_format! deeply can be enabled globally' do
names = { first_name: 'camel', last_name: 'case' }
Jbuilder.deep_format_keys true
result = jbuild do |json|
json.key_format! camelize: :lower
json.set! :all_names, names
end
assert_equal %w[firstName lastName], result['allNames'].keys
Jbuilder.send(:class_variable_set, '@@deep_format_keys', false)
end
test 'deep key_format! with merge!' do
hash = { camel_style: 'for JS' }
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.merge! hash
end
assert_equal ['camelStyle'], result.keys
end
test 'deep key_format! with merge! deep' do
hash = { camel_style: { sub_attr: 'for JS' } }
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.merge! hash
end
assert_equal ['subAttr'], result['camelStyle'].keys
end
test 'deep key_format! with set! array of hashes' do
names = [{ first_name: 'camel', last_name: 'case' }]
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.set! :names, names
end
assert_equal %w[firstName lastName], result['names'][0].keys
end
test 'deep key_format! with set! extracting hash from object' do
comment = Struct.new(:author).new({ first_name: 'camel', last_name: 'case' })
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.set! :comment, comment, :author
end
assert_equal %w[firstName lastName], result['comment']['author'].keys
end
test 'deep key_format! with array! of hashes' do
names = [{ first_name: 'camel', last_name: 'case' }]
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.array! names
end
assert_equal %w[firstName lastName], result[0].keys
end
test 'deep key_format! with merge! array of hashes' do
names = [{ first_name: 'camel', last_name: 'case' }]
new_names = [{ first_name: 'snake', last_name: 'case' }]
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.array! names
json.merge! new_names
end
assert_equal %w[firstName lastName], result[1].keys
end
test 'deep key_format! is applied to hash extracted from object' do
comment = Struct.new(:author).new({ first_name: 'camel', last_name: 'case' })
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.extract! comment, :author
end
assert_equal %w[firstName lastName], result['author'].keys
end
test 'deep key_format! is applied to hash extracted from hash' do
comment = {author: { first_name: 'camel', last_name: 'case' }}
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.extract! comment, :author
end
assert_equal %w[firstName lastName], result['author'].keys
end
test 'deep key_format! is applied to hash extracted directly from array' do
comments = [Struct.new(:author).new({ first_name: 'camel', last_name: 'case' })]
result = jbuild do |json|
json.key_format! camelize: :lower
json.deep_format_keys!
json.array! comments, :author
end
assert_equal %w[firstName lastName], result[0]['author'].keys
end
test 'default key_format!' do
Jbuilder.key_format camelize: :lower
result = jbuild{ |json| json.camel_style 'for JS' }
assert_equal ['camelStyle'], result.keys
end
test 'use default key formatter when configured' do
Jbuilder.key_format
jbuild{ |json| json.key 'value' }
formatter = Jbuilder.send(:class_variable_get, '@@key_formatter')
cache = formatter.instance_variable_get('@cache')
assert_includes cache, :key
end
test 'ignore_nil! without a parameter' do
result = jbuild do |json|
json.ignore_nil!
json.test nil
end
assert_empty result.keys
end
test 'ignore_nil! with parameter' do
result = jbuild do |json|
json.ignore_nil! true
json.name 'Bob'
json.dne nil
end
assert_equal ['name'], result.keys
result = jbuild do |json|
json.ignore_nil! false
json.name 'Bob'
json.dne nil
end
assert_equal ['name', 'dne'], result.keys
end
test 'default ignore_nil!' do
Jbuilder.ignore_nil
result = jbuild do |json|
json.name 'Bob'
json.dne nil
end
assert_equal ['name'], result.keys
Jbuilder.send(:class_variable_set, '@@ignore_nil', false)
end
test 'nil!' do
result = jbuild do |json|
json.key 'value'
json.nil!
end
assert_nil result
end
test 'null!' do
result = jbuild do |json|
json.key 'value'
json.null!
end
assert_nil result
end
test 'null! in a block' do
result = jbuild do |json|
json.author do
json.name 'David'
end
json.author do
json.null!
end
end
assert result.key?('author')
assert_nil result['author']
end
test 'empty attributes respond to empty?' do
attributes = Jbuilder.new.attributes!
assert attributes.empty?
assert attributes.blank?
assert !attributes.present?
end
test 'throws ArrayError when trying to add a key to an array' do
assert_raise Jbuilder::ArrayError do
jbuild do |json|
json.array! %w[foo bar]
json.fizz "buzz"
end
end
end
test 'throws NullError when trying to add properties to null' do
assert_raise Jbuilder::NullError do
jbuild do |json|
json.null!
json.foo 'bar'
end
end
end
test 'throws NullError when trying to add properties to null using block syntax' do
assert_raise Jbuilder::NullError do
jbuild do |json|
json.author do
json.null!
end
json.author do
json.name "Pavel"
end
end
end
end
test "throws MergeError when trying to merge array with non-empty hash" do
assert_raise Jbuilder::MergeError do
jbuild do |json|
json.name "Daniel"
json.merge! []
end
end
end
test "throws MergeError when trying to merge hash with array" do
assert_raise Jbuilder::MergeError do
jbuild do |json|
json.array!
json.merge!({})
end
end
end
test "throws MergeError when trying to merge invalid objects" do
assert_raise Jbuilder::MergeError do
jbuild do |json|
json.name "Daniel"
json.merge! "Nope"
end
end
end
test "respects JSON encoding customizations" do
# Active Support overrides Time#as_json for custom formatting.
# Ensure we call #to_json on the final attributes instead of JSON.dump.
result = JSON.load(Jbuilder.encode { |json| json.time Time.parse("2018-05-13 11:51:00.485 -0400") })
assert_equal "2018-05-13T11:51:00.485-04:00", result["time"]
end
test "encode forwards options to new" do
Jbuilder.encode(key_formatter: 1, ignore_nil: 2) do |json|
assert_equal 1, json.instance_eval{ @key_formatter }
assert_equal 2, json.instance_eval{ @ignore_nil }
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/test/jbuilder_generator_test.rb | test/jbuilder_generator_test.rb | require 'test_helper'
require 'rails/generators/test_case'
require 'generators/rails/jbuilder_generator'
class JbuilderGeneratorTest < Rails::Generators::TestCase
tests Rails::Generators::JbuilderGenerator
arguments %w(Post title body:text password:digest)
destination File.expand_path('../tmp', __FILE__)
setup :prepare_destination
test 'views are generated' do
run_generator
%w(index show).each do |view|
assert_file "app/views/posts/#{view}.json.jbuilder"
end
assert_file "app/views/posts/_post.json.jbuilder"
end
test 'index content' do
run_generator
assert_file 'app/views/posts/index.json.jbuilder' do |content|
assert_match %r{json\.array! @posts, partial: "posts/post", as: :post}, content
end
assert_file 'app/views/posts/show.json.jbuilder' do |content|
assert_match %r{json\.partial! "posts/post", post: @post}, content
end
assert_file 'app/views/posts/_post.json.jbuilder' do |content|
assert_match %r{json\.extract! post, :id, :title, :body}, content
assert_match %r{:created_at, :updated_at}, content
assert_match %r{json\.url post_url\(post, format: :json\)}, content
end
end
test 'timestamps are not generated in partial with --no-timestamps' do
run_generator %w(Post title body:text --no-timestamps)
assert_file 'app/views/posts/_post.json.jbuilder' do |content|
assert_match %r{json\.extract! post, :id, :title, :body$}, content
assert_no_match %r{:created_at, :updated_at}, content
end
end
test 'namespaced views are generated correctly for index' do
run_generator %w(Admin::Post --model-name=Post)
assert_file 'app/views/admin/posts/index.json.jbuilder' do |content|
assert_match %r{json\.array! @posts, partial: "admin/posts/post", as: :post}, content
end
assert_file 'app/views/admin/posts/show.json.jbuilder' do |content|
assert_match %r{json\.partial! "admin/posts/post", post: @post}, content
end
end
test 'handles virtual attributes' do
run_generator %w(Message content:rich_text video:attachment photos:attachments)
assert_file 'app/views/messages/_message.json.jbuilder' do |content|
assert_match %r{json\.content message\.content\.to_s}, content
assert_match %r{json\.video url_for\(message\.video\)}, content
assert_match %r{json\.photos do\n json\.array!\(message\.photos\) do \|photo\|\n json\.id photo\.id\n json\.url url_for\(photo\)\n end\nend}, content
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/test/jbuilder_dependency_tracker_test.rb | test/jbuilder_dependency_tracker_test.rb | require 'test_helper'
require 'jbuilder/jbuilder_dependency_tracker'
class FakeTemplate
attr_reader :source, :handler
def initialize(source, handler = :jbuilder)
@source, @handler = source, handler
end
end
class JbuilderDependencyTrackerTest < ActiveSupport::TestCase
def make_tracker(name, source)
template = FakeTemplate.new(source)
Jbuilder::DependencyTracker.new(name, template)
end
def track_dependencies(source)
make_tracker('jbuilder_template', source).dependencies
end
test 'detects dependency via direct partial! call' do
dependencies = track_dependencies <<-RUBY
json.partial! 'path/to/partial', foo: bar
json.partial! 'path/to/another/partial', :fizz => buzz
RUBY
assert_equal %w[path/to/partial path/to/another/partial], dependencies
end
test 'detects dependency via direct partial! call with parens' do
dependencies = track_dependencies <<-RUBY
json.partial!("path/to/partial")
RUBY
assert_equal %w[path/to/partial], dependencies
end
test 'detects partial with options (1.9 style)' do
dependencies = track_dependencies <<-RUBY
json.partial! hello: 'world', partial: 'path/to/partial', foo: :bar
RUBY
assert_equal %w[path/to/partial], dependencies
end
test 'detects partial with options (1.8 style)' do
dependencies = track_dependencies <<-RUBY
json.partial! :hello => 'world', :partial => 'path/to/partial', :foo => :bar
RUBY
assert_equal %w[path/to/partial], dependencies
end
test 'detects partial in indirect collection calls' do
dependencies = track_dependencies <<-RUBY
json.comments @post.comments, partial: 'comments/comment', as: :comment
RUBY
assert_equal %w[comments/comment], dependencies
end
test 'detects explicit dependency' do
dependencies = track_dependencies <<-RUBY
# Template Dependency: path/to/partial
json.foo 'bar'
RUBY
assert_equal %w[path/to/partial], dependencies
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/test/test_helper.rb | test/test_helper.rb | require "bundler/setup"
require "rails"
require "jbuilder"
require "active_support/core_ext/array/access"
require "active_support/cache/memory_store"
require "active_support/json"
require "active_model"
require 'action_controller/railtie'
require 'action_view/railtie'
require "active_support/testing/autorun"
require "mocha/minitest"
ActiveSupport.test_order = :random
ENV["RAILS_ENV"] ||= "test"
class << Rails
redefine_method :cache do
@cache ||= ActiveSupport::Cache::MemoryStore.new
end
end
Jbuilder::CollectionRenderer.collection_cache = Rails.cache
class Post < Struct.new(:id, :body, :author_name)
def cache_key
"post-#{id}"
end
end
class Racer < Struct.new(:id, :name)
extend ActiveModel::Naming
include ActiveModel::Conversion
end
# Instantiate an Application in order to trigger the initializers
Class.new(Rails::Application) do
config.secret_key_base = 'secret'
config.eager_load = false
end.initialize!
# Touch AV::Base in order to trigger :action_view on_load hook before running the tests
ActionView::Base.inspect
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/test/scaffold_api_controller_generator_test.rb | test/scaffold_api_controller_generator_test.rb | require 'test_helper'
require 'rails/generators/test_case'
require 'generators/rails/scaffold_controller_generator'
class ScaffoldApiControllerGeneratorTest < Rails::Generators::TestCase
tests Rails::Generators::ScaffoldControllerGenerator
arguments %w(Post title body:text images:attachments --api --skip-routes)
destination File.expand_path('../tmp', __FILE__)
setup :prepare_destination
test 'controller content' do
run_generator
assert_file 'app/controllers/posts_controller.rb' do |content|
assert_instance_method :index, content do |m|
assert_match %r{@posts = Post\.all}, m
end
assert_instance_method :show, content do |m|
assert m.blank?
end
assert_instance_method :create, content do |m|
assert_match %r{@post = Post\.new\(post_params\)}, m
assert_match %r{@post\.save}, m
assert_match %r{render :show, status: :created, location: @post}, m
assert_match %r{render json: @post\.errors, status: :unprocessable_entity}, m
end
assert_instance_method :update, content do |m|
assert_match %r{render :show, status: :ok, location: @post}, m
assert_match %r{render json: @post.errors, status: :unprocessable_entity}, m
end
assert_instance_method :destroy, content do |m|
assert_match %r{@post\.destroy}, m
end
assert_match %r{def set_post}, content
if Rails::VERSION::MAJOR >= 8
assert_match %r{params\.expect\(:id\)}, content
else
assert_match %r{params\[:id\]}, content
end
assert_match %r{def post_params}, content
if Rails::VERSION::MAJOR >= 8
assert_match %r{params\.expect\(post: \[ :title, :body, images: \[\] \]\)}, content
else
assert_match %r{params\.require\(:post\)\.permit\(:title, :body, images: \[\]\)}, content
end
end
end
test "don't use require and permit if there are no attributes" do
run_generator %w(Post --api --skip-routes)
assert_file 'app/controllers/posts_controller.rb' do |content|
assert_match %r{def post_params}, content
assert_match %r{params\.fetch\(:post, \{\}\)}, content
end
end
test 'handles virtual attributes' do
run_generator %w(Message content:rich_text video:attachment photos:attachments --skip-routes)
assert_file 'app/controllers/messages_controller.rb' do |content|
if Rails::VERSION::MAJOR >= 8
assert_match %r{params\.expect\(message: \[ :content, :video, photos: \[\] \]\)}, content
else
assert_match %r{params\.require\(:message\)\.permit\(:content, :video, photos: \[\]\)}, content
end
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/test/scaffold_controller_generator_test.rb | test/scaffold_controller_generator_test.rb | require 'test_helper'
require 'rails/generators/test_case'
require 'generators/rails/scaffold_controller_generator'
class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
tests Rails::Generators::ScaffoldControllerGenerator
arguments %w(Post title body:text images:attachments --skip-routes)
destination File.expand_path('../tmp', __FILE__)
setup :prepare_destination
test 'controller content' do
run_generator
assert_file 'app/controllers/posts_controller.rb' do |content|
assert_instance_method :index, content do |m|
assert_match %r{@posts = Post\.all}, m
end
assert_instance_method :show, content do |m|
assert m.blank?
end
assert_instance_method :new, content do |m|
assert_match %r{@post = Post\.new}, m
end
assert_instance_method :edit, content do |m|
assert m.blank?
end
assert_instance_method :create, content do |m|
assert_match %r{@post = Post\.new\(post_params\)}, m
assert_match %r{@post\.save}, m
assert_match %r{format\.html \{ redirect_to @post, notice: "Post was successfully created\." \}}, m
assert_match %r{format\.json \{ render :show, status: :created, location: @post \}}, m
assert_match %r{format\.html \{ render :new, status: :unprocessable_entity \}}, m
assert_match %r{format\.json \{ render json: @post\.errors, status: :unprocessable_entity \}}, m
end
assert_instance_method :update, content do |m|
assert_match %r{format\.html \{ redirect_to @post, notice: "Post was successfully updated\.", status: :see_other \}}, m
assert_match %r{format\.json \{ render :show, status: :ok, location: @post \}}, m
assert_match %r{format\.html \{ render :edit, status: :unprocessable_entity \}}, m
assert_match %r{format\.json \{ render json: @post.errors, status: :unprocessable_entity \}}, m
end
assert_instance_method :destroy, content do |m|
assert_match %r{@post\.destroy}, m
assert_match %r{format\.html \{ redirect_to posts_path, notice: "Post was successfully destroyed\.", status: :see_other \}}, m
assert_match %r{format\.json \{ head :no_content \}}, m
end
assert_match %r{def set_post}, content
if Rails::VERSION::MAJOR >= 8
assert_match %r{params\.expect\(:id\)}, content
else
assert_match %r{params\[:id\]}, content
end
assert_match %r{def post_params}, content
if Rails::VERSION::MAJOR >= 8
assert_match %r{params\.expect\(post: \[ :title, :body, images: \[\] \]\)}, content
else
assert_match %r{params\.require\(:post\)\.permit\(:title, :body, images: \[\]\)}, content
end
end
end
test 'controller with namespace' do
run_generator %w(Admin::Post --model-name=Post --skip-routes)
assert_file 'app/controllers/admin/posts_controller.rb' do |content|
assert_instance_method :create, content do |m|
assert_match %r{format\.html \{ redirect_to \[:admin, @post\], notice: "Post was successfully created\." \}}, m
end
assert_instance_method :update, content do |m|
assert_match %r{format\.html \{ redirect_to \[:admin, @post\], notice: "Post was successfully updated\.", status: :see_other \}}, m
end
assert_instance_method :destroy, content do |m|
assert_match %r{format\.html \{ redirect_to admin_posts_path, notice: "Post was successfully destroyed\.", status: :see_other \}}, m
end
end
end
test "don't use require and permit if there are no attributes" do
run_generator %w(Post --skip-routes)
assert_file 'app/controllers/posts_controller.rb' do |content|
assert_match %r{def post_params}, content
assert_match %r{params\.fetch\(:post, \{\}\)}, content
end
end
test 'handles virtual attributes' do
run_generator %w(Message content:rich_text video:attachment photos:attachments --skip-routes)
assert_file 'app/controllers/messages_controller.rb' do |content|
if Rails::VERSION::MAJOR >= 8
assert_match %r{params\.expect\(message: \[ :content, :video, photos: \[\] \]\)}, content
else
assert_match %r{params\.require\(:message\)\.permit\(:content, :video, photos: \[\]\)}, content
end
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/test/jbuilder_template_test.rb | test/jbuilder_template_test.rb | require "test_helper"
require "action_view/testing/resolvers"
class JbuilderTemplateTest < ActiveSupport::TestCase
POST_PARTIAL = <<-JBUILDER
json.extract! post, :id, :body
json.author do
first_name, last_name = post.author_name.split(nil, 2)
json.first_name first_name
json.last_name last_name
end
JBUILDER
COLLECTION_PARTIAL = <<-JBUILDER
json.extract! collection, :id, :name
JBUILDER
RACER_PARTIAL = <<-JBUILDER
json.extract! racer, :id, :name
JBUILDER
PARTIALS = {
"_partial.json.jbuilder" => "json.content content",
"_post.json.jbuilder" => POST_PARTIAL,
"racers/_racer.json.jbuilder" => RACER_PARTIAL,
"_collection.json.jbuilder" => COLLECTION_PARTIAL,
# Ensure we find only Jbuilder partials from within Jbuilder templates.
"_post.html.erb" => "Hello world!"
}
AUTHORS = [ "David Heinemeier Hansson", "Pavel Pravosud" ].cycle
POSTS = (1..10).collect { |i| Post.new(i, "Post ##{i}", AUTHORS.next) }
setup { Rails.cache.clear }
test "basic template" do
result = render('json.content "hello"')
assert_equal "hello", result["content"]
end
test "partial by name with top-level locals" do
result = render('json.partial! "partial", content: "hello"')
assert_equal "hello", result["content"]
end
test "partial by name with nested locals" do
result = render('json.partial! "partial", locals: { content: "hello" }')
assert_equal "hello", result["content"]
end
test "partial by name with hash value omission (punning) as last statement [3.1+]" do
major, minor, _ = RUBY_VERSION.split(".").map(&:to_i)
return unless (major == 3 && minor >= 1) || major > 3
result = render(<<-JBUILDER)
content = "hello"
json.partial! "partial", content:
JBUILDER
assert_equal "hello", result["content"]
end
test "partial by options containing nested locals" do
result = render('json.partial! partial: "partial", locals: { content: "hello" }')
assert_equal "hello", result["content"]
end
test "partial by options containing top-level locals" do
result = render('json.partial! partial: "partial", content: "hello"')
assert_equal "hello", result["content"]
end
test "partial for Active Model" do
result = render('json.partial! @racer', racer: Racer.new(123, "Chris Harris"))
assert_equal 123, result["id"]
assert_equal "Chris Harris", result["name"]
end
test "partial collection by name with symbol local" do
result = render('json.partial! "post", collection: @posts, as: :post', posts: POSTS)
assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end
test "partial collection by name with caching" do
result = render('json.partial! "post", collection: @posts, cached: true, as: :post', posts: POSTS)
assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end
test "partial collection by name with string local" do
result = render('json.partial! "post", collection: @posts, as: "post"', posts: POSTS)
assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end
test "partial collection by options" do
result = render('json.partial! partial: "post", collection: @posts, as: :post', posts: POSTS)
assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end
test "nil partial collection by name" do
Jbuilder::CollectionRenderer.expects(:new).never
assert_equal [], render('json.partial! "post", collection: @posts, as: :post', posts: nil)
end
test "nil partial collection by options" do
Jbuilder::CollectionRenderer.expects(:new).never
assert_equal [], render('json.partial! partial: "post", collection: @posts, as: :post', posts: nil)
end
test "array of partials" do
result = render('json.array! @posts, partial: "post", as: :post', posts: POSTS)
assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end
test "empty array of partials from empty collection" do
Jbuilder::CollectionRenderer.expects(:new).never
assert_equal [], render('json.array! @posts, partial: "post", as: :post', posts: [])
end
test "empty array of partials from nil collection" do
Jbuilder::CollectionRenderer.expects(:new).never
assert_equal [], render('json.array! @posts, partial: "post", as: :post', posts: nil)
end
test "array of partials under key" do
result = render('json.posts @posts, partial: "post", as: :post', posts: POSTS)
assert_equal 10, result["posts"].count
assert_equal "Post #5", result["posts"][4]["body"]
assert_equal "Heinemeier Hansson", result["posts"][2]["author"]["last_name"]
assert_equal "Pavel", result["posts"][5]["author"]["first_name"]
end
test "empty array of partials under key from nil collection" do
Jbuilder::CollectionRenderer.expects(:new).never
result = render('json.posts @posts, partial: "post", as: :post', posts: nil)
assert_equal [], result["posts"]
end
test "empty array of partials under key from an empy collection" do
Jbuilder::CollectionRenderer.expects(:new).never
result = render('json.posts @posts, partial: "post", as: :post', posts: [])
assert_equal [], result["posts"]
end
test "object fragment caching" do
render(<<-JBUILDER)
json.cache! "cache-key" do
json.name "Hit"
end
JBUILDER
hit = render('json.cache! "cache-key" do; end')
assert_equal "Hit", hit["name"]
end
test "conditional object fragment caching" do
render(<<-JBUILDER)
json.cache_if! true, "cache-key" do
json.a "Hit"
end
json.cache_if! false, "cache-key" do
json.b "Hit"
end
JBUILDER
result = render(<<-JBUILDER)
json.cache_if! true, "cache-key" do
json.a "Miss"
end
json.cache_if! false, "cache-key" do
json.b "Miss"
end
JBUILDER
assert_equal "Hit", result["a"]
assert_equal "Miss", result["b"]
end
test "object fragment caching with expiry" do
travel_to Time.iso8601("2018-05-12T11:29:00-04:00")
render <<-JBUILDER
json.cache! "cache-key", expires_in: 1.minute do
json.name "Hit"
end
JBUILDER
travel 30.seconds
result = render(<<-JBUILDER)
json.cache! "cache-key", expires_in: 1.minute do
json.name "Miss"
end
JBUILDER
assert_equal "Hit", result["name"]
travel 31.seconds
result = render(<<-JBUILDER)
json.cache! "cache-key", expires_in: 1.minute do
json.name "Miss"
end
JBUILDER
assert_equal "Miss", result["name"]
end
test "object root caching" do
render <<-JBUILDER
json.cache_root! "cache-key" do
json.name "Hit"
end
JBUILDER
assert_equal JSON.dump(name: "Hit"), Rails.cache.read("jbuilder/root/cache-key")
result = render(<<-JBUILDER)
json.cache_root! "cache-key" do
json.name "Miss"
end
JBUILDER
assert_equal "Hit", result["name"]
end
test "array fragment caching" do
render <<-JBUILDER
json.cache! "cache-key" do
json.array! %w[ a b c ]
end
JBUILDER
assert_equal %w[ a b c ], render('json.cache! "cache-key" do; end')
end
test "array root caching" do
render <<-JBUILDER
json.cache_root! "cache-key" do
json.array! %w[ a b c ]
end
JBUILDER
assert_equal JSON.dump(%w[ a b c ]), Rails.cache.read("jbuilder/root/cache-key")
assert_equal %w[ a b c ], render(<<-JBUILDER)
json.cache_root! "cache-key" do
json.array! %w[ d e f ]
end
JBUILDER
end
test "failing to cache root after JSON structures have been defined" do
assert_raises ActionView::Template::Error, "cache_root! can't be used after JSON structures have been defined" do
render <<-JBUILDER
json.name "Kaboom"
json.cache_root! "cache-key" do
json.name "Miss"
end
JBUILDER
end
end
test "empty fragment caching" do
render 'json.cache! "nothing" do; end'
result = nil
assert_nothing_raised do
result = render(<<-JBUILDER)
json.foo "bar"
json.cache! "nothing" do; end
JBUILDER
end
assert_equal "bar", result["foo"]
end
test "cache instrumentation" do
payloads = {}
ActiveSupport::Notifications.subscribe("read_fragment.action_controller") { |*args| payloads[:read] = args.last }
ActiveSupport::Notifications.subscribe("write_fragment.action_controller") { |*args| payloads[:write] = args.last }
render <<-JBUILDER
json.cache! "cache-key" do
json.name "Cache"
end
JBUILDER
assert_equal "jbuilder/cache-key", payloads[:read][:key]
assert_equal "jbuilder/cache-key", payloads[:write][:key]
end
test "camelized keys" do
result = render(<<-JBUILDER)
json.key_format! camelize: [:lower]
json.first_name "David"
JBUILDER
assert_equal "David", result["firstName"]
end
test "returns an empty array for an empty collection" do
Jbuilder::CollectionRenderer.expects(:new).never
result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: [])
# Do not use #assert_empty as it is important to ensure that the type of the JSON result is an array.
assert_equal [], result
end
test "works with an enumerable object" do
enumerable_class = Class.new do
include Enumerable
def each(&block)
[].each(&block)
end
end
result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: enumerable_class.new)
# Do not use #assert_empty as it is important to ensure that the type of the JSON result is an array.
assert_equal [], result
end
test "supports the cached: true option" do
result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: POSTS)
assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
expected = {
"id" => 1,
"body" => "Post #1",
"author" => {
"first_name" => "David",
"last_name" => "Heinemeier Hansson"
}
}
assert_equal expected, Rails.cache.read("post-1")
result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: POSTS)
assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end
test "supports the cached: ->() {} option" do
result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)
assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
expected = {
"id" => 1,
"body" => "Post #1",
"author" => {
"first_name" => "David",
"last_name" => "Heinemeier Hansson"
}
}
assert_equal expected, Rails.cache.read("post-1/foo")
result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)
assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end
test "raises an error on a render call with the :layout option" do
error = assert_raises NotImplementedError do
render('json.array! @posts, partial: "post", as: :post, layout: "layout"', posts: POSTS)
end
assert_equal "The `:layout' option is not supported in collection rendering.", error.message
end
test "raises an error on a render call with the :spacer_template option" do
error = assert_raises NotImplementedError do
render('json.array! @posts, partial: "post", as: :post, spacer_template: "template"', posts: POSTS)
end
assert_equal "The `:spacer_template' option is not supported in collection rendering.", error.message
end
private
def render(*args)
JSON.load render_without_parsing(*args)
end
def render_without_parsing(source, assigns = {})
view = build_view(fixtures: PARTIALS.merge("source.json.jbuilder" => source), assigns: assigns)
view.render(template: "source")
end
def build_view(options = {})
resolver = ActionView::FixtureResolver.new(options.fetch(:fixtures))
lookup_context = ActionView::LookupContext.new([ resolver ], {}, [""])
controller = ActionView::TestCase::TestController.new
view = ActionView::Base.with_empty_template_cache.new(lookup_context, options.fetch(:assigns, {}), controller)
def view.view_cache_dependencies; []; end
def view.combined_fragment_cache_key(key) [ key ] end
def view.cache_fragment_name(key, *) key end
def view.fragment_name_with_digest(key) key end
view
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder.rb | lib/jbuilder.rb | # frozen_string_literal: true
require 'active_support'
require 'jbuilder/jbuilder'
require 'jbuilder/blank'
require 'jbuilder/key_formatter'
require 'jbuilder/errors'
require 'json'
require 'active_support/core_ext/hash/deep_merge'
class Jbuilder
@@key_formatter = nil
@@ignore_nil = false
@@deep_format_keys = false
def initialize(
key_formatter: @@key_formatter,
ignore_nil: @@ignore_nil,
deep_format_keys: @@deep_format_keys,
&block
)
@attributes = {}
@key_formatter = key_formatter
@ignore_nil = ignore_nil
@deep_format_keys = deep_format_keys
yield self if block
end
# Yields a builder and automatically turns the result into a JSON string
def self.encode(...)
new(...).target!
end
BLANK = Blank.new
def set!(key, value = BLANK, *args, &block)
result = if ::Kernel.block_given?
if !_blank?(value)
# json.comments @post.comments { |comment| ... }
# { "comments": [ { ... }, { ... } ] }
_scope{ array! value, &block }
else
# json.comments { ... }
# { "comments": ... }
_merge_block(key){ yield self }
end
elsif args.empty?
if ::Jbuilder === value
# json.age 32
# json.person another_jbuilder
# { "age": 32, "person": { ... }
_format_keys(value.attributes!)
else
# json.age 32
# { "age": 32 }
_format_keys(value)
end
elsif _is_collection?(value)
# json.comments @post.comments, :content, :created_at
# { "comments": [ { "content": "hello", "created_at": "..." }, { "content": "world", "created_at": "..." } ] }
_scope{ array! value, *args }
else
# json.author @post.creator, :name, :email_address
# { "author": { "name": "David", "email_address": "david@loudthinking.com" } }
_merge_block(key){ _extract value, args }
end
_set_value key, result
end
# Specifies formatting to be applied to the key. Passing in a name of a function
# will cause that function to be called on the key. So :upcase will upper case
# the key. You can also pass in lambdas for more complex transformations.
#
# Example:
#
# json.key_format! :upcase
# json.author do
# json.name "David"
# json.age 32
# end
#
# { "AUTHOR": { "NAME": "David", "AGE": 32 } }
#
# You can pass parameters to the method using a hash pair.
#
# json.key_format! camelize: :lower
# json.first_name "David"
#
# { "firstName": "David" }
#
# Lambdas can also be used.
#
# json.key_format! ->(key){ "_" + key }
# json.first_name "David"
#
# { "_first_name": "David" }
#
def key_format!(...)
@key_formatter = KeyFormatter.new(...)
end
# Same as the instance method key_format! except sets the default.
def self.key_format(...)
@@key_formatter = KeyFormatter.new(...)
end
# If you want to skip adding nil values to your JSON hash. This is useful
# for JSON clients that don't deal well with nil values, and would prefer
# not to receive keys which have null values.
#
# Example:
# json.ignore_nil! false
# json.id User.new.id
#
# { "id": null }
#
# json.ignore_nil!
# json.id User.new.id
#
# {}
#
def ignore_nil!(value = true)
@ignore_nil = value
end
# Same as instance method ignore_nil! except sets the default.
def self.ignore_nil(value = true)
@@ignore_nil = value
end
# Deeply apply key format to nested hashes and arrays passed to
# methods like set!, merge! or array!.
#
# Example:
#
# json.key_format! camelize: :lower
# json.settings({some_value: "abc"})
#
# { "settings": { "some_value": "abc" }}
#
# json.key_format! camelize: :lower
# json.deep_format_keys!
# json.settings({some_value: "abc"})
#
# { "settings": { "someValue": "abc" }}
#
def deep_format_keys!(value = true)
@deep_format_keys = value
end
# Same as instance method deep_format_keys! except sets the default.
def self.deep_format_keys(value = true)
@@deep_format_keys = value
end
# Turns the current element into an array and yields a builder to add a hash.
#
# Example:
#
# json.comments do
# json.child! { json.content "hello" }
# json.child! { json.content "world" }
# end
#
# { "comments": [ { "content": "hello" }, { "content": "world" } ]}
#
# More commonly, you'd use the combined iterator, though:
#
# json.comments(@post.comments) do |comment|
# json.content comment.formatted_content
# end
def child!
@attributes = [] unless ::Array === @attributes
@attributes << _scope{ yield self }
end
# Turns the current element into an array and iterates over the passed collection, adding each iteration as
# an element of the resulting array.
#
# Example:
#
# json.array!(@people) do |person|
# json.name person.name
# json.age calculate_age(person.birthday)
# end
#
# [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ]
#
# You can use the call syntax instead of an explicit extract! call:
#
# json.(@people) { |person| ... }
#
# It's generally only needed to use this method for top-level arrays. If you have named arrays, you can do:
#
# json.people(@people) do |person|
# json.name person.name
# json.age calculate_age(person.birthday)
# end
#
# { "people": [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ] }
#
# If you omit the block then you can set the top level array directly:
#
# json.array! [1, 2, 3]
#
# [1,2,3]
def array!(collection = [], *attributes, &block)
array = if collection.nil?
[]
elsif ::Kernel.block_given?
_map_collection(collection, &block)
elsif attributes.any?
_map_collection(collection) { |element| _extract element, attributes }
else
_format_keys(collection.to_a)
end
@attributes = _merge_values(@attributes, array)
end
# Extracts the mentioned attributes or hash elements from the passed object and turns them into attributes of the JSON.
#
# Example:
#
# @person = Struct.new(:name, :age).new('David', 32)
#
# or you can utilize a Hash
#
# @person = { name: 'David', age: 32 }
#
# json.extract! @person, :name, :age
#
# { "name": David", "age": 32 }, { "name": Jamie", "age": 31 }
#
# You can also use the call syntax instead of an explicit extract! call:
#
# json.(@person, :name, :age)
def extract!(object, *attributes)
_extract object, attributes
end
def call(object, *attributes, &block)
if ::Kernel.block_given?
array! object, &block
else
_extract object, attributes
end
end
# Returns the nil JSON.
def nil!
@attributes = nil
end
alias_method :null!, :nil!
# Returns the attributes of the current builder.
def attributes!
@attributes
end
# Merges hash, array, or Jbuilder instance into current builder.
def merge!(object)
hash_or_array = ::Jbuilder === object ? object.attributes! : object
@attributes = _merge_values(@attributes, _format_keys(hash_or_array))
end
# Encodes the current builder as JSON.
def target!
@attributes.to_json
end
private
alias_method :method_missing, :set!
def _extract(object, attributes)
if ::Hash === object
_extract_hash_values(object, attributes)
else
_extract_method_values(object, attributes)
end
end
def _extract_hash_values(object, attributes)
attributes.each{ |key| _set_value key, _format_keys(object.fetch(key)) }
end
def _extract_method_values(object, attributes)
attributes.each{ |key| _set_value key, _format_keys(object.public_send(key)) }
end
def _merge_block(key)
current_value = _blank? ? BLANK : @attributes.fetch(_key(key), BLANK)
::Kernel.raise NullError.build(key) if current_value.nil?
new_value = _scope{ yield self }
_merge_values(current_value, new_value)
end
def _merge_values(current_value, updates)
if _blank?(updates)
current_value
elsif _blank?(current_value) || updates.nil? || current_value.empty? && ::Array === updates
updates
elsif ::Array === current_value && ::Array === updates
current_value + updates
elsif ::Hash === current_value && ::Hash === updates
current_value.deep_merge(updates)
else
::Kernel.raise MergeError.build(current_value, updates)
end
end
def _key(key)
if @key_formatter
@key_formatter.format(key)
elsif key.is_a?(::Symbol)
key.name
else
key.to_s
end
end
def _format_keys(hash_or_array)
return hash_or_array unless @deep_format_keys
if ::Array === hash_or_array
hash_or_array.map { |value| _format_keys(value) }
elsif ::Hash === hash_or_array
::Hash[hash_or_array.collect { |k, v| [_key(k), _format_keys(v)] }]
else
hash_or_array
end
end
def _set_value(key, value)
::Kernel.raise NullError.build(key) if @attributes.nil?
::Kernel.raise ArrayError.build(key) if ::Array === @attributes
return if @ignore_nil && value.nil? or _blank?(value)
@attributes = {} if _blank?
@attributes[_key(key)] = value
end
def _map_collection(collection)
collection.map do |element|
_scope{ yield element }
end - [BLANK]
end
def _scope
parent_attributes, parent_formatter, parent_deep_format_keys = @attributes, @key_formatter, @deep_format_keys
@attributes = BLANK
yield
@attributes
ensure
@attributes, @key_formatter, @deep_format_keys = parent_attributes, parent_formatter, parent_deep_format_keys
end
def _is_collection?(object)
object.respond_to?(:map) && object.respond_to?(:count) && !(::Struct === object)
end
def _blank?(value=@attributes)
BLANK == value
end
end
require 'jbuilder/railtie' if defined?(Rails)
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/generators/rails/jbuilder_generator.rb | lib/generators/rails/jbuilder_generator.rb | # frozen_string_literal: true
require 'rails/generators/named_base'
require 'rails/generators/resource_helpers'
module Rails
module Generators
class JbuilderGenerator < NamedBase # :nodoc:
include Rails::Generators::ResourceHelpers
source_root File.expand_path('../templates', __FILE__)
argument :attributes, type: :array, default: [], banner: 'field:type field:type'
class_option :timestamps, type: :boolean, default: true
def create_root_folder
path = File.join('app/views', controller_file_path)
empty_directory path unless File.directory?(path)
end
def copy_view_files
%w(index show).each do |view|
filename = filename_with_extensions(view)
template filename, File.join('app/views', controller_file_path, filename)
end
template filename_with_extensions('partial'), File.join('app/views', controller_file_path, filename_with_extensions("_#{singular_table_name}"))
end
protected
def attributes_names
[:id] + super
end
def filename_with_extensions(name)
[name, :json, :jbuilder] * '.'
end
def full_attributes_list
if options[:timestamps]
attributes_list(attributes_names + %w(created_at updated_at))
else
attributes_list(attributes_names)
end
end
def attributes_list(attributes = attributes_names)
if self.attributes.any? {|attr| attr.name == 'password' && attr.type == :digest}
attributes = attributes.reject {|name| %w(password password_confirmation).include? name}
end
attributes.map { |a| ":#{a}"} * ', '
end
def virtual_attributes
attributes.select {|name| name.respond_to?(:virtual?) && name.virtual? }
end
def partial_path_name
[controller_file_path, singular_table_name].join("/")
end
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/generators/rails/scaffold_controller_generator.rb | lib/generators/rails/scaffold_controller_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'
module Rails
module Generators
class ScaffoldControllerGenerator
source_paths << File.expand_path('../templates', __FILE__)
hook_for :jbuilder, type: :boolean, default: true
private
def permitted_params
attributes_names.map { |name| ":#{name}" }.join(', ')
end unless private_method_defined? :permitted_params
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/generators/rails/templates/api_controller.rb | lib/generators/rails/templates/api_controller.rb | <% if namespaced? -%>
require_dependency "<%= namespaced_path %>/application_controller"
<% end -%>
<% module_namespacing do -%>
class <%= controller_class_name %>Controller < ApplicationController
before_action :set_<%= singular_table_name %>, only: %i[ show update destroy ]
# GET <%= route_url %>
# GET <%= route_url %>.json
def index
@<%= plural_table_name %> = <%= orm_class.all(class_name) %>
end
# GET <%= route_url %>/1
# GET <%= route_url %>/1.json
def show
end
# POST <%= route_url %>
# POST <%= route_url %>.json
def create
@<%= singular_table_name %> = <%= orm_class.build(class_name, "#{singular_table_name}_params") %>
if @<%= orm_instance.save %>
render :show, status: :created, location: <%= "@#{singular_table_name}" %>
else
render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity
end
end
# PATCH/PUT <%= route_url %>/1
# PATCH/PUT <%= route_url %>/1.json
def update
if @<%= orm_instance.update("#{singular_table_name}_params") %>
render :show, status: :ok, location: <%= "@#{singular_table_name}" %>
else
render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity
end
end
# DELETE <%= route_url %>/1
# DELETE <%= route_url %>/1.json
def destroy
@<%= orm_instance.destroy %>
end
private
# Use callbacks to share common setup or constraints between actions.
def set_<%= singular_table_name %>
<%- if Rails::VERSION::MAJOR >= 8 -%>
@<%= singular_table_name %> = <%= orm_class.find(class_name, "params.expect(:id)") %>
<%- else -%>
@<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
<%- end -%>
end
# Only allow a list of trusted parameters through.
def <%= "#{singular_table_name}_params" %>
<%- if attributes_names.empty? -%>
params.fetch(<%= ":#{singular_table_name}" %>, {})
<%- elsif Rails::VERSION::MAJOR >= 8 -%>
params.expect(<%= singular_table_name %>: [ <%= permitted_params %> ])
<%- else -%>
params.require(<%= ":#{singular_table_name}" %>).permit(<%= permitted_params %>)
<%- end -%>
end
end
<% end -%>
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/generators/rails/templates/controller.rb | lib/generators/rails/templates/controller.rb | <% if namespaced? -%>
require_dependency "<%= namespaced_path %>/application_controller"
<% end -%>
<% module_namespacing do -%>
class <%= controller_class_name %>Controller < ApplicationController
before_action :set_<%= singular_table_name %>, only: %i[ show edit update destroy ]
# GET <%= route_url %> or <%= route_url %>.json
def index
@<%= plural_table_name %> = <%= orm_class.all(class_name) %>
end
# GET <%= route_url %>/1 or <%= route_url %>/1.json
def show
end
# GET <%= route_url %>/new
def new
@<%= singular_table_name %> = <%= orm_class.build(class_name) %>
end
# GET <%= route_url %>/1/edit
def edit
end
# POST <%= route_url %> or <%= route_url %>.json
def create
@<%= singular_table_name %> = <%= orm_class.build(class_name, "#{singular_table_name}_params") %>
respond_to do |format|
if @<%= orm_instance.save %>
format.html { redirect_to <%= redirect_resource_name %>, notice: <%= %("#{human_name} was successfully created.") %> }
format.json { render :show, status: :created, location: <%= "@#{singular_table_name}" %> }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity }
end
end
end
# PATCH/PUT <%= route_url %>/1 or <%= route_url %>/1.json
def update
respond_to do |format|
if @<%= orm_instance.update("#{singular_table_name}_params") %>
format.html { redirect_to <%= redirect_resource_name %>, notice: <%= %("#{human_name} was successfully updated.") %>, status: :see_other }
format.json { render :show, status: :ok, location: <%= "@#{singular_table_name}" %> }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity }
end
end
end
# DELETE <%= route_url %>/1 or <%= route_url %>/1.json
def destroy
@<%= orm_instance.destroy %>
respond_to do |format|
format.html { redirect_to <%= index_helper %>_path, notice: <%= %("#{human_name} was successfully destroyed.") %>, status: :see_other }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_<%= singular_table_name %>
<%- if Rails::VERSION::MAJOR >= 8 -%>
@<%= singular_table_name %> = <%= orm_class.find(class_name, "params.expect(:id)") %>
<%- else -%>
@<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
<%- end -%>
end
# Only allow a list of trusted parameters through.
def <%= "#{singular_table_name}_params" %>
<%- if attributes_names.empty? -%>
params.fetch(<%= ":#{singular_table_name}" %>, {})
<%- elsif Rails::VERSION::MAJOR >= 8 -%>
params.expect(<%= singular_table_name %>: [ <%= permitted_params %> ])
<%- else -%>
params.require(<%= ":#{singular_table_name}" %>).permit(<%= permitted_params %>)
<%- end -%>
end
end
<% end -%>
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder/version.rb | lib/jbuilder/version.rb | # frozen_string_literal: true
class Jbuilder < BasicObject
VERSION = "2.14.1"
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder/jbuilder.rb | lib/jbuilder/jbuilder.rb | # frozen_string_literal: true
require 'jbuilder/version'
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder/errors.rb | lib/jbuilder/errors.rb | # frozen_string_literal: true
require 'jbuilder/version'
class Jbuilder
class NullError < ::NoMethodError
def self.build(key)
message = "Failed to add #{key.to_s.inspect} property to null object"
new(message)
end
end
class ArrayError < ::StandardError
def self.build(key)
message = "Failed to add #{key.to_s.inspect} property to an array"
new(message)
end
end
class MergeError < ::StandardError
def self.build(current_value, updates)
message = "Can't merge #{updates.inspect} into #{current_value.inspect}"
new(message)
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder/key_formatter.rb | lib/jbuilder/key_formatter.rb | # frozen_string_literal: true
require 'jbuilder/jbuilder'
class Jbuilder
class KeyFormatter
def initialize(*formats, **formats_with_options)
@mutex = Mutex.new
@formats = formats
@formats_with_options = formats_with_options
@cache = {}
end
def format(key)
@mutex.synchronize do
@cache[key] ||= begin
value = key.is_a?(Symbol) ? key.name : key.to_s
@formats.each do |func|
value = func.is_a?(Proc) ? func.call(value) : value.send(func)
end
@formats_with_options.each do |func, params|
value = func.is_a?(Proc) ? func.call(value, *params) : value.send(func, *params)
end
value
end
end
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder/blank.rb | lib/jbuilder/blank.rb | # frozen_string_literal: true
class Jbuilder
class Blank
def ==(other)
super || Blank === other
end
def empty?
true
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder/jbuilder_dependency_tracker.rb | lib/jbuilder/jbuilder_dependency_tracker.rb | # frozen_string_literal: true
class Jbuilder::DependencyTracker
EXPLICIT_DEPENDENCY = /# Template Dependency: (\S+)/
# Matches:
# json.partial! "messages/message"
# json.partial!('messages/message')
#
DIRECT_RENDERS = /
\w+\.partial! # json.partial!
\(?\s* # optional parenthesis
(['"])([^'"]+)\1 # quoted value
/x
# Matches:
# json.partial! partial: "comments/comment"
# json.comments @post.comments, partial: "comments/comment", as: :comment
# json.array! @posts, partial: "posts/post", as: :post
# = render partial: "account"
#
INDIRECT_RENDERS = /
(?::partial\s*=>|partial:) # partial: or :partial =>
\s* # optional whitespace
(['"])([^'"]+)\1 # quoted value
/x
def self.call(name, template, view_paths = nil)
new(name, template, view_paths).dependencies
end
def initialize(name, template, view_paths = nil)
@name, @template, @view_paths = name, template, view_paths
end
def dependencies
direct_dependencies + indirect_dependencies + explicit_dependencies
end
private
attr_reader :name, :template
def direct_dependencies
source.scan(DIRECT_RENDERS).map(&:second)
end
def indirect_dependencies
source.scan(INDIRECT_RENDERS).map(&:second)
end
def explicit_dependencies
dependencies = source.scan(EXPLICIT_DEPENDENCY).flatten.uniq
wildcards, explicits = dependencies.partition { |dependency| dependency.end_with?("/*") }
(explicits + resolve_directories(wildcards)).uniq
end
def resolve_directories(wildcard_dependencies)
return [] unless @view_paths
return [] if wildcard_dependencies.empty?
# Remove trailing "/*"
prefixes = wildcard_dependencies.map { |query| query[0..-3] }
@view_paths.flat_map(&:all_template_paths).uniq.filter_map { |path|
path.to_s if prefixes.include?(path.prefix)
}.sort
end
def source
template.source
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder/railtie.rb | lib/jbuilder/railtie.rb | # frozen_string_literal: true
require 'rails'
require 'jbuilder/jbuilder_template'
class Jbuilder
class Railtie < ::Rails::Railtie
initializer :jbuilder do
ActiveSupport.on_load :action_view do
ActionView::Template.register_template_handler :jbuilder, JbuilderHandler
require 'jbuilder/jbuilder_dependency_tracker'
end
module ::ActionController
module ApiRendering
include ActionView::Rendering
end
end
ActiveSupport.on_load :action_controller_api do
include ActionController::Helpers
include ActionController::ImplicitRender
helper_method :combined_fragment_cache_key
helper_method :view_cache_dependencies
end
end
generators do |app|
Rails::Generators.configure! app.config.generators
Rails::Generators.hidden_namespaces.uniq!
require 'generators/rails/scaffold_controller_generator'
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder/jbuilder_template.rb | lib/jbuilder/jbuilder_template.rb | # frozen_string_literal: true
require 'jbuilder/jbuilder'
require 'jbuilder/collection_renderer'
require 'action_dispatch/http/mime_type'
require 'active_support/cache'
class JbuilderTemplate < Jbuilder
class << self
attr_accessor :template_lookup_options
end
self.template_lookup_options = { handlers: [:jbuilder] }
def initialize(context, options = nil)
@context = context
@cached_root = nil
options.nil? ? super() : super(**options)
end
# Generates JSON using the template specified with the `:partial` option. For example, the code below will render
# the file `views/comments/_comments.json.jbuilder`, and set a local variable comments with all this message's
# comments, which can be used inside the partial.
#
# Example:
#
# json.partial! 'comments/comments', comments: @message.comments
#
# There are multiple ways to generate a collection of elements as JSON, as ilustrated below:
#
# Example:
#
# json.array! @posts, partial: 'posts/post', as: :post
#
# # or:
# json.partial! 'posts/post', collection: @posts, as: :post
#
# # or:
# json.partial! partial: 'posts/post', collection: @posts, as: :post
#
# # or:
# json.comments @post.comments, partial: 'comments/comment', as: :comment
#
# Aside from that, the `:cached` options is available on Rails >= 6.0. This will cache the rendered results
# effectively using the multi fetch feature.
#
# Example:
#
# json.array! @posts, partial: "posts/post", as: :post, cached: true
#
# json.comments @post.comments, partial: "comments/comment", as: :comment, cached: true
#
def partial!(*args)
if args.one? && _is_active_model?(args.first)
_render_active_model_partial args.first
else
options = args.extract_options!.dup
options[:partial] = args.first if args.present?
_render_partial_with_options options
end
end
# Caches the json constructed within the block passed. Has the same signature as the `cache` helper
# method in `ActionView::Helpers::CacheHelper` and so can be used in the same way.
#
# Example:
#
# json.cache! ['v1', @person], expires_in: 10.minutes do
# json.extract! @person, :name, :age
# end
def cache!(key=nil, options={})
if @context.controller.perform_caching
value = _cache_fragment_for(key, options) do
_scope { yield self }
end
merge! value
else
yield
end
end
# Caches the json structure at the root using a string rather than the hash structure. This is considerably
# faster, but the drawback is that it only works, as the name hints, at the root. So you cannot
# use this approach to cache deeper inside the hierarchy, like in partials or such. Continue to use #cache! there.
#
# Example:
#
# json.cache_root! @person do
# json.extract! @person, :name, :age
# end
#
# # json.extra 'This will not work either, the root must be exclusive'
def cache_root!(key=nil, options={})
if @context.controller.perform_caching
::Kernel.raise "cache_root! can't be used after JSON structures have been defined" if @attributes.present?
@cached_root = _cache_fragment_for([ :root, key ], options) { yield; target! }
else
yield
end
end
# Conditionally caches the json depending in the condition given as first parameter. Has the same
# signature as the `cache` helper method in `ActionView::Helpers::CacheHelper` and so can be used in
# the same way.
#
# Example:
#
# json.cache_if! !admin?, @person, expires_in: 10.minutes do
# json.extract! @person, :name, :age
# end
def cache_if!(condition, *args, &block)
condition ? cache!(*args, &block) : yield
end
def target!
@cached_root || super
end
def array!(collection = [], *args)
options = args.first
if args.one? && _partial_options?(options)
options = options.dup
options[:collection] = collection
_render_partial_with_options options
else
super
end
end
def set!(name, object = BLANK, *args)
options = args.first
if args.one? && _partial_options?(options)
_set_inline_partial name, object, options.dup
else
super
end
end
private
alias_method :method_missing, :set!
def _render_partial_with_options(options)
options[:locals] ||= options.except(:partial, :as, :collection, :cached)
options[:handlers] ||= ::JbuilderTemplate.template_lookup_options[:handlers]
as = options[:as]
if as && options.key?(:collection)
collection = options.delete(:collection) || []
partial = options.delete(:partial)
options[:locals][:json] = self
collection = EnumerableCompat.new(collection) if collection.respond_to?(:count) && !collection.respond_to?(:size)
if options.has_key?(:layout)
::Kernel.raise ::NotImplementedError, "The `:layout' option is not supported in collection rendering."
end
if options.has_key?(:spacer_template)
::Kernel.raise ::NotImplementedError, "The `:spacer_template' option is not supported in collection rendering."
end
if collection.present?
results = CollectionRenderer
.new(@context.lookup_context, options) { |&block| _scope(&block) }
.render_collection_with_partial(collection, partial, @context, nil)
array! if results.respond_to?(:body) && results.body.nil?
else
array!
end
else
_render_partial options
end
end
def _render_partial(options)
options[:locals][:json] = self
@context.render options
end
def _cache_fragment_for(key, options, &block)
key = _cache_key(key, options)
_read_fragment_cache(key, options) || _write_fragment_cache(key, options, &block)
end
def _read_fragment_cache(key, options = nil)
@context.controller.instrument_fragment_cache :read_fragment, key do
::Rails.cache.read(key, options)
end
end
def _write_fragment_cache(key, options = nil)
@context.controller.instrument_fragment_cache :write_fragment, key do
yield.tap do |value|
::Rails.cache.write(key, value, options)
end
end
end
def _cache_key(key, options)
name_options = options.slice(:skip_digest, :virtual_path)
key = _fragment_name_with_digest(key, name_options)
if @context.respond_to?(:combined_fragment_cache_key)
key = @context.combined_fragment_cache_key(key)
else
key = url_for(key).split('://', 2).last if ::Hash === key
end
::ActiveSupport::Cache.expand_cache_key(key, :jbuilder)
end
def _fragment_name_with_digest(key, options)
if @context.respond_to?(:cache_fragment_name)
@context.cache_fragment_name(key, **options)
else
key
end
end
def _partial_options?(options)
::Hash === options && options.key?(:as) && options.key?(:partial)
end
def _is_active_model?(object)
object.class.respond_to?(:model_name) && object.respond_to?(:to_partial_path)
end
def _set_inline_partial(name, object, options)
value = if object.nil?
[]
elsif _is_collection?(object)
_scope do
options[:collection] = object
_render_partial_with_options options
end
else
_scope do
options[:locals] = { options[:as] => object }
_render_partial_with_options options
end
end
_set_value name, value
end
def _render_active_model_partial(object)
@context.render object, json: self
end
end
class JbuilderHandler
cattr_accessor :default_format
self.default_format = :json
def self.call(template, source = nil)
source ||= template.source
# this juggling is required to keep line numbers right in the error
%{__already_defined = defined?(json); json||=JbuilderTemplate.new(self); #{source};
json.target! unless (__already_defined && __already_defined != "method")}
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
rails/jbuilder | https://github.com/rails/jbuilder/blob/38339adaa9d44ba89c0dde2a795338a886941e6f/lib/jbuilder/collection_renderer.rb | lib/jbuilder/collection_renderer.rb | # frozen_string_literal: true
require 'delegate'
require 'action_view'
require 'action_view/renderer/collection_renderer'
class Jbuilder
class CollectionRenderer < ::ActionView::CollectionRenderer # :nodoc:
class ScopedIterator < ::SimpleDelegator # :nodoc:
include Enumerable
def initialize(obj, scope)
super(obj)
@scope = scope
end
def each_with_info
return enum_for(:each_with_info) unless block_given?
__getobj__.each_with_info do |object, info|
@scope.call { yield(object, info) }
end
end
end
private_constant :ScopedIterator
def initialize(lookup_context, options, &scope)
super(lookup_context, options)
@scope = scope
end
private
def build_rendered_template(content, template, layout = nil)
super(content || json.attributes!, template)
end
def build_rendered_collection(templates, _spacer)
json.merge!(templates.map(&:body))
end
def json
@options[:locals].fetch(:json)
end
def collection_with_template(view, template, layout, collection)
super(view, template, layout, ScopedIterator.new(collection, @scope))
end
end
class EnumerableCompat < ::SimpleDelegator
# Rails 6.1 requires this.
def size(*args, &block)
__getobj__.count(*args, &block)
end
end
end
| ruby | MIT | 38339adaa9d44ba89c0dde2a795338a886941e6f | 2026-01-04T15:46:22.398194Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/gemfiles/rails_7.2.rb | gemfiles/rails_7.2.rb | # frozen_string_literal: true
source "https://rubygems.org"
gemspec path: ".."
gem "activerecord", "~> 7.2.0"
gem "activesupport", "~> 7.2.0"
gem "mysql2", "~> 0.5.6"
gem "pg", "~> 1.5.8"
gem "sqlite3", "~> 2.0.0"
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/gemfiles/rails_8.0.rb | gemfiles/rails_8.0.rb | # frozen_string_literal: true
source "https://rubygems.org"
gemspec path: ".."
gem "activerecord", "~> 8.0.0"
gem "activesupport", "~> 8.0.0"
gem "mysql2", "~> 0.5.6"
gem "pg", "~> 1.5.8"
gem "sqlite3", "~> 2.1.0"
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/gemfiles/rails_8.1.rb | gemfiles/rails_8.1.rb | # frozen_string_literal: true
source "https://rubygems.org"
gemspec path: ".."
gem "activerecord", "~> 8.1.0"
gem "activesupport", "~> 8.1.0"
gem "mysql2", "~> 0.5.6"
gem "pg", "~> 1.5.8"
gem "sqlite3", "~> 2.1.0"
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/random_test.rb | test/random_test.rb | # frozen_string_literal: true
require "test_helper"
class RandomTest < ActiveSupport::TestCase
def test_that_hex_tokens_are_unique
tokens = Array.new(100) { Authlogic::Random.hex_token }
assert_equal tokens.size, tokens.uniq.size
end
def test_that_friendly_tokens_are_unique
tokens = Array.new(100) { Authlogic::Random.friendly_token }
assert_equal tokens.size, tokens.uniq.size
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/adapter_test.rb | test/adapter_test.rb | # frozen_string_literal: true
require "test_helper"
require "authlogic/controller_adapters/rails_adapter"
module Authlogic
module ControllerAdapters
class AbstractAdapterTest < ActiveSupport::TestCase
def test_controller
controller = Class.new(MockController) do
def controller.an_arbitrary_method
"bar"
end
end.new
adapter = Authlogic::ControllerAdapters::AbstractAdapter.new(controller)
assert_equal controller, adapter.controller
assert controller.params.equal?(adapter.params)
assert adapter.respond_to?(:an_arbitrary_method)
assert_equal "bar", adapter.an_arbitrary_method
end
end
class RailsAdapterTest < ActiveSupport::TestCase
def test_api_controller
controller = MockAPIController.new
adapter = Authlogic::ControllerAdapters::RailsAdapter.new(controller)
assert_equal controller, adapter.controller
assert_nil adapter.cookies
end
end
class RailsRequestAdapterTest < ActiveSupport::TestCase
def test_adapter_with_string_cookie
controller = MockController.new
controller.cookies["foo"] = "bar"
adapter = Authlogic::TestCase::RailsRequestAdapter.new(controller)
assert adapter.cookies
end
def test_adapter_with_hash_cookie
controller = MockController.new
controller.cookies["foo"] = {
value: "bar",
expires: nil
}
adapter = Authlogic::TestCase::RailsRequestAdapter.new(controller)
assert adapter.cookies
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/test_helper.rb | test/test_helper.rb | # frozen_string_literal: true
require "coveralls"
require "simplecov"
require "simplecov-console"
Coveralls.wear!
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new(
[
SimpleCov::Formatter::Console,
# Want a nice code coverage website? Uncomment this next line!
SimpleCov::Formatter::HTMLFormatter
]
)
SimpleCov.start { add_filter "/test/" }
require "byebug"
require "rubygems"
require "minitest/autorun"
require "active_record"
require "active_record/fixtures"
require "timecop"
require "i18n"
require "minitest/reporters"
Minitest::Reporters.use!(Minitest::Reporters::SpecReporter.new)
I18n.load_path << File.dirname(__FILE__) + "/i18n/lol.yml"
case ENV["DB"]
when "mysql"
ActiveRecord::Base.establish_connection(
adapter: "mysql2",
database: ENV.fetch("AUTHLOGIC_DB_NAME", "authlogic"),
host: ENV.fetch("AUTHLOGIC_DB_HOST", nil),
port: ENV.fetch("AUTHLOGIC_DB_PORT", nil),
username: ENV.fetch("AUTHLOGIC_DB_USER", "root")
)
when "postgres"
ActiveRecord::Base.establish_connection(
adapter: "postgresql",
database: ENV.fetch("AUTHLOGIC_DB_NAME", "authlogic"),
host: ENV.fetch("AUTHLOGIC_DB_HOST", nil),
password: ENV.fetch("AUTHLOGIC_DB_PASSWORD", nil),
port: ENV.fetch("AUTHLOGIC_DB_PORT", nil),
username: ENV.fetch("AUTHLOGIC_DB_USER", nil)
)
else
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
end
logger = Logger.new(STDOUT)
logger.level = Logger::FATAL
ActiveRecord::Base.logger = logger
if ActiveSupport.respond_to?(:test_order)
ActiveSupport.test_order = :sorted
end
ActiveRecord.default_timezone = :local
ActiveRecord::Schema.define(version: 1) do
create_table :companies do |t|
t.datetime :created_at, limit: 6
t.datetime :updated_at, limit: 6
t.string :name
t.boolean :active
end
create_table :projects do |t|
t.datetime :created_at, limit: 6
t.datetime :updated_at, limit: 6
t.string :name
end
create_table :projects_users, id: false do |t|
t.integer :project_id
t.integer :user_id
end
create_table :users do |t|
t.datetime :created_at, limit: 6
t.datetime :updated_at, limit: 6
t.integer :lock_version, default: 0
t.integer :company_id
t.string :login
t.string :crypted_password
t.string :password_salt
t.string :persistence_token
t.string :single_access_token
t.string :perishable_token
t.string :email
t.string :first_name
t.string :last_name
t.integer :login_count, default: 0, null: false
t.integer :failed_login_count, default: 0, null: false
t.datetime :last_request_at, limit: 6
t.datetime :current_login_at, limit: 6
t.datetime :last_login_at, limit: 6
t.string :current_login_ip
t.string :last_login_ip
t.boolean :active, default: true
t.boolean :approved, default: true
t.boolean :confirmed, default: true
end
create_table :employees do |t|
t.datetime :created_at, limit: 6
t.datetime :updated_at, limit: 6
t.integer :company_id
t.string :email
t.string :crypted_password
t.string :password_salt
t.string :persistence_token
t.string :first_name
t.string :last_name
t.integer :login_count, default: 0, null: false
t.datetime :last_request_at, limit: 6
t.datetime :current_login_at, limit: 6
t.datetime :last_login_at, limit: 6
t.string :current_login_ip
t.string :last_login_ip
end
create_table :affiliates do |t|
t.datetime :created_at, limit: 6
t.datetime :updated_at, limit: 6
t.integer :company_id
t.string :username
t.string :pw_hash
t.string :pw_salt
t.string :persistence_token
end
create_table :ldapers do |t|
t.datetime :created_at, limit: 6
t.datetime :updated_at, limit: 6
t.string :ldap_login
t.string :persistence_token
end
create_table :admins do |t|
t.datetime :created_at, limit: 6
t.datetime :updated_at, limit: 6
t.string :login
t.string :crypted_password
t.string :password_salt
t.string :persistence_token
t.string :perishable_token
t.string :email
t.string :role
end
end
require "English"
$LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
require "authlogic"
require "authlogic/test_case"
# Configure SCrypt to be as fast as possible. This is desirable for a test
# suite, and would be the opposite of desirable for production.
Authlogic::CryptoProviders::SCrypt.max_time = 0.001 # 1ms
Authlogic::CryptoProviders::SCrypt.max_mem = 1024 * 1024 # 1MB, the minimum SCrypt allows
require "libs/project"
require "libs/affiliate"
require "libs/employee"
require "libs/employee_session"
require "libs/ldaper"
require "libs/user"
require "libs/user_session"
require "libs/company"
require "libs/admin"
module ActiveSupport
class TestCase
include ActiveRecord::TestFixtures
self.fixture_paths = [File.dirname(__FILE__) + "/fixtures"]
self.use_transactional_tests = false
self.use_instantiated_fixtures = false
self.pre_loaded_fixtures = false
fixtures :all
setup :activate_authlogic
setup :config_setup
teardown :config_teardown
teardown { Timecop.return } # for tests that need to freeze the time
private
# Many of the tests change Authlogic config for the test models. Some tests
# were not resetting the config after tests, which didn't surface as broken
# tests until Rails 4.1 was added for testing. This ensures that all the
# models start tests with their original config.
def config_setup
[
Project,
Affiliate,
Employee,
EmployeeSession,
Ldaper,
User,
UserSession,
Company,
Admin
].each do |model|
unless model.respond_to?(:original_acts_as_authentic_config)
model.class_attribute :original_acts_as_authentic_config
end
model.original_acts_as_authentic_config = model.acts_as_authentic_config
end
end
def config_teardown
[
Project,
Affiliate,
Employee,
EmployeeSession,
Ldaper,
User,
UserSession,
Company,
Admin
].each do |model|
model.acts_as_authentic_config = model.original_acts_as_authentic_config
end
end
def env_session_options
controller.request.env.fetch(
::Authlogic::ControllerAdapters::AbstractAdapter::ENV_SESSION_OPTIONS,
{}
).with_indifferent_access
end
def password_for(user)
case user
when users(:ben)
"benrocks"
when users(:zack)
"zackrocks"
when users(:aaron)
"aaronrocks"
end
end
def http_basic_auth_for(user = nil)
unless user.blank?
controller.http_user = user.login
controller.http_password = password_for(user)
end
yield
controller.http_user = controller.http_password = controller.realm = nil
end
def set_cookie_for(user)
controller.cookies["user_credentials"] = {
value: "#{user.persistence_token}::#{user.id}",
expires: nil
}
end
def unset_cookie
controller.cookies["user_credentials"] = nil
end
def set_params_for(user)
controller.params["user_credentials"] = user.single_access_token
end
def unset_params
controller.params["user_credentials"] = nil
end
def set_request_content_type(type)
controller.request_content_type = type
end
def unset_request_content_type
controller.request_content_type = nil
end
def session_credentials_prefix(scope_record)
if scope_record.nil?
""
else
format(
"%s_%d_",
scope_record.class.model_name.name.underscore,
scope_record.id
)
end
end
# Sets the session variables that `record` (eg. a `User`) would have after
# logging in.
def set_session_for(record)
record_class_name = record.class.model_name.name.underscore
controller.session["#{record_class_name}_credentials"] = record.persistence_token
controller.session["#{record_class_name}_credentials_id"] = record.id
end
def unset_session
controller.session["user_credentials"] = controller.session["user_credentials_id"] = nil
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/config_test.rb | test/config_test.rb | # frozen_string_literal: true
require "test_helper"
class ConfigTest < ActiveSupport::TestCase
def setup
@klass = Class.new {
extend Authlogic::Config
def self.foobar(value = nil)
rw_config(:foobar_field, value, "default_foobar")
end
}
@subklass = Class.new(@klass)
end
def test_config
assert_equal({}, @klass.acts_as_authentic_config)
end
def test_rw_config_read_with_default
assert "default_foobar", @klass.foobar
end
def test_rw_config_write
assert_equal "my_foobar", @klass.foobar("my_foobar")
assert_equal "my_foobar", @klass.foobar
assert_equal "my_new_foobar", @klass.foobar("my_new_foobar")
assert_equal "my_new_foobar", @klass.foobar
end
def test_subclass_rw_config_write
assert_equal "subklass_foobar", @subklass.foobar("subklass_foobar")
assert_equal "default_foobar", @klass.foobar
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/i18n_test.rb | test/i18n_test.rb | # frozen_string_literal: true
require "test_helper"
class I18nTest < ActiveSupport::TestCase
def test_uses_authlogic_as_scope_by_default
assert_equal :authlogic, Authlogic::I18n.scope
end
def test_can_set_scope
assert_nothing_raised { Authlogic::I18n.scope = %i[a b] }
assert_equal %i[a b], Authlogic::I18n.scope
Authlogic::I18n.scope = :authlogic
end
def test_uses_built_in_translator_by_default
assert_equal Authlogic::I18n::Translator, Authlogic::I18n.translator.class
end
def test_can_set_custom_translator
old_translator = Authlogic::I18n.translator
assert_nothing_raised do
Authlogic::I18n.translator = Class.new do
def translate(key, _options = {})
"Translated: #{key}"
end
end.new
end
assert_equal "Translated: x", Authlogic::I18n.translate(:x)
Authlogic::I18n.translator = old_translator
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/session_test.rb | test/session_test/session_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module SessionTest
class ConfigTest < ActiveSupport::TestCase
def test_session_key
UserSession.session_key = "my_session_key"
assert_equal "my_session_key", UserSession.session_key
UserSession.session_key "user_credentials"
assert_equal "user_credentials", UserSession.session_key
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_persist_persist_by_session
ben = users(:ben)
set_session_for(ben)
assert session = UserSession.find
assert_equal ben, session.record
assert_equal ben.persistence_token, controller.session["user_credentials"]
refute_includes env_session_options, :renew
end
# A SQL injection attack to steal the persistence_token.
# TODO: Explain how `:select` is used, and sanitized.
def test_persist_persist_by_session_with_sql_injection_attack
ben = users(:ben)
controller.session["user_credentials"] = "neo"
controller.session["user_credentials_id"] = {
select: " *,'neo' AS persistence_token FROM users WHERE id = #{ben.id} limit 1 -- "
}
@user_session = UserSession.find
assert @user_session.blank?
end
def test_persist_persist_by_session_with_sql_injection_attack_2
controller.session["user_credentials"] = { select: "ABRA CADABRA" }
controller.session["user_credentials_id"] = nil
assert_nothing_raised do
@user_session = UserSession.find
end
assert @user_session.blank?
end
def test_persist_persist_by_session_with_token_only
ben = users(:ben)
set_session_for(ben)
controller.session["user_credentials_id"] = nil
session = UserSession.find
assert_equal ben, session.record
assert_equal ben.persistence_token, controller.session["user_credentials"]
refute_includes env_session_options, :renew
end
def test_after_save_update_session
ben = users(:ben)
session = UserSession.new(ben)
assert controller.session["user_credentials"].blank?
assert session.save
assert_equal ben.persistence_token, controller.session["user_credentials"]
assert_equal env_session_options[:renew], true
end
def test_after_destroy_update_session
ben = users(:ben)
set_session_for(ben)
assert_equal ben.persistence_token, controller.session["user_credentials"]
assert session = UserSession.find
assert session.destroy
assert controller.session["user_credentials"].blank?
refute_includes env_session_options, :renew
end
def test_after_persisting_update_session
ben = users(:ben)
set_cookie_for(ben)
assert controller.session["user_credentials"].blank?
assert UserSession.find
assert_equal ben.persistence_token, controller.session["user_credentials"]
refute_includes env_session_options, :renew
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/klass_test.rb | test/session_test/klass_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module KlassTest
class ConfigTest < ActiveSupport::TestCase
def test_authenticate_with
UserSession.authenticate_with = Employee
assert_equal "Employee", UserSession.klass_name
assert_equal Employee, UserSession.klass
UserSession.authenticate_with User
assert_equal "User", UserSession.klass_name
assert_equal User, UserSession.klass
end
def test_klass
assert_equal User, UserSession.klass
end
def test_klass_name
assert_equal "User", UserSession.klass_name
end
def test_klass_name_uses_custom_name
assert_equal "User", UserSession.klass_name
assert_equal "BackOfficeUser", BackOfficeUserSession.klass_name
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_record_method
ben = users(:ben)
set_session_for(ben)
session = UserSession.find
assert_equal ben, session.record
assert_equal ben, session.user
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/unauthorized_record_test.rb | test/session_test/unauthorized_record_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
class UnauthorizedRecordTest < ActiveSupport::TestCase
def test_credentials
ben = users(:ben)
session = UserSession.new
session.credentials = [ben]
assert_equal ben, session.unauthorized_record
assert_equal({ unauthorized_record: "<protected>" }, session.credentials)
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/cookies_test.rb | test/session_test/cookies_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module CookiesTest
class ConfigTest < ActiveSupport::TestCase
def test_cookie_key
UserSession.cookie_key = "my_cookie_key"
assert_equal "my_cookie_key", UserSession.cookie_key
UserSession.cookie_key "user_credentials"
assert_equal "user_credentials", UserSession.cookie_key
end
def test_default_cookie_key
assert_equal "user_credentials", UserSession.cookie_key
assert_equal "back_office_user_credentials", BackOfficeUserSession.cookie_key
end
def test_remember_me
UserSession.remember_me = true
assert_equal true, UserSession.remember_me
session = UserSession.new
assert_equal true, session.remember_me
UserSession.remember_me false
assert_equal false, UserSession.remember_me
session = UserSession.new
assert_equal false, session.remember_me
end
def test_remember_me_for
UserSession.remember_me_for = 3.years
assert_equal 3.years, UserSession.remember_me_for
session = UserSession.new
session.remember_me = true
assert_equal 3.years, session.remember_me_for
UserSession.remember_me_for 3.months
assert_equal 3.months, UserSession.remember_me_for
session = UserSession.new
session.remember_me = true
assert_equal 3.months, session.remember_me_for
end
def test_secure
assert_equal true, UserSession.secure
session = UserSession.new
assert_equal true, session.secure
UserSession.secure false
assert_equal false, UserSession.secure
session = UserSession.new
assert_equal false, session.secure
end
def test_httponly
assert_equal true, UserSession.httponly
session = UserSession.new
assert_equal true, session.httponly
UserSession.httponly false
assert_equal false, UserSession.httponly
session = UserSession.new
assert_equal false, session.httponly
end
def test_same_site
assert_nil UserSession.same_site
assert_nil UserSession.new.same_site
UserSession.same_site "Strict"
assert_equal "Strict", UserSession.same_site
session = UserSession.new
assert_equal "Strict", session.same_site
session.same_site = "Lax"
assert_equal "Lax", session.same_site
session.same_site = "None"
assert_equal "None", session.same_site
assert_raise(ArgumentError) { UserSession.same_site "foo" }
assert_raise(ArgumentError) { UserSession.new.same_site "foo" }
end
def test_sign_cookie
UserSession.sign_cookie = true
assert_equal true, UserSession.sign_cookie
session = UserSession.new
assert_equal true, session.sign_cookie
UserSession.sign_cookie false
assert_equal false, UserSession.sign_cookie
session = UserSession.new
assert_equal false, session.sign_cookie
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_credentials
session = UserSession.new
session.credentials = { remember_me: true }
assert_equal({}, session.credentials)
end
def test_credentials_assignment
session = UserSession.new
session.credentials = { remember_me: true }
assert_equal true, session.remember_me
end
def test_remember_me
session = UserSession.new
assert_equal false, session.remember_me
refute session.remember_me?
session.remember_me = false
assert_equal false, session.remember_me
refute session.remember_me?
session.remember_me = true
assert_equal true, session.remember_me
assert session.remember_me?
session.remember_me = nil
assert_nil session.remember_me
refute session.remember_me?
session.remember_me = "1"
assert_equal "1", session.remember_me
assert session.remember_me?
session.remember_me = "true"
assert_equal "true", session.remember_me
assert session.remember_me?
end
def test_remember_me_until
session = UserSession.new
assert_nil session.remember_me_until
session.remember_me = true
assert 3.months.from_now <= session.remember_me_until
end
def test_persist_persist_by_cookie
ben = users(:ben)
refute UserSession.find
set_cookie_for(ben)
assert session = UserSession.find
assert_equal ben, session.record
end
def test_persist_persist_by_cookie_with_blank_persistence_token
ben = users(:ben)
ben.update_column(:persistence_token, "")
refute UserSession.find
set_cookie_for(ben)
refute UserSession.find
end
def test_remember_me_expired
ben = users(:ben)
session = UserSession.new(ben)
session.remember_me = true
assert session.save
refute session.remember_me_expired?
session = UserSession.new(ben)
session.remember_me = false
assert session.save
refute session.remember_me_expired?
end
def test_after_save_save_cookie
ben = users(:ben)
session = UserSession.new(ben)
assert session.save
assert_equal(
"#{ben.persistence_token}::#{ben.id}",
controller.cookies["user_credentials"]
)
end
def test_after_save_save_cookie_encrypted
ben = users(:ben)
assert_nil controller.cookies["user_credentials"]
payload = "#{ben.persistence_token}::#{ben.id}"
session = UserSession.new(ben)
session.encrypt_cookie = true
assert session.save
assert_equal payload, controller.cookies.encrypted["user_credentials"]
assert_equal(
Authlogic::TestCase::MockEncryptedCookieJar.encrypt(payload),
controller.cookies.encrypted.parent_jar["user_credentials"]
)
end
def test_after_save_save_cookie_signed
ben = users(:ben)
assert_nil controller.cookies["user_credentials"]
payload = "#{ben.persistence_token}::#{ben.id}"
session = UserSession.new(ben)
session.sign_cookie = true
assert session.save
assert_equal payload, controller.cookies.signed["user_credentials"]
assert_equal(
"#{payload}--#{Digest::SHA1.hexdigest payload}",
controller.cookies.signed.parent_jar["user_credentials"]
)
end
def test_after_save_save_cookie_with_remember_me
Timecop.freeze do
ben = users(:ben)
session = UserSession.new(ben)
session.remember_me = true
assert session.save
assert_equal(
"#{ben.persistence_token}::#{ben.id}::#{session.remember_me_until.iso8601}",
controller.cookies["user_credentials"]
)
end
end
def test_after_save_save_cookie_with_same_site
session = UserSession.new(users(:ben))
session.same_site = "Strict"
assert session.save
assert_equal(
"Strict",
controller.cookies.set_cookies["user_credentials"][:same_site]
)
end
def test_after_destroy_destroy_cookie
ben = users(:ben)
set_cookie_for(ben)
session = UserSession.find
assert controller.cookies["user_credentials"]
assert session.destroy
refute controller.cookies["user_credentials"]
end
def test_string_cookie
payload = "bar"
controller.cookies["foo"] = payload
assert_equal(payload, controller.cookies["foo"])
end
def test_string_cookie_signed
payload = "bar"
session = UserSession.new
session.sign_cookie = true
controller.cookies["foo"] = payload
assert_equal(payload, controller.cookies.signed["foo"])
end
def test_string_cookie_encrypted
payload = "bar"
session = UserSession.new
session.encrypt_cookie = true
controller.cookies["foo"] = payload
assert_equal(payload, controller.cookies.encrypted["foo"])
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/http_auth_test.rb | test/session_test/http_auth_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
class HttpAuthTest < ActiveSupport::TestCase
class ConfigTest < ActiveSupport::TestCase
def test_allow_http_basic_auth
UserSession.allow_http_basic_auth = false
assert_equal false, UserSession.allow_http_basic_auth
UserSession.allow_http_basic_auth true
assert_equal true, UserSession.allow_http_basic_auth
end
def test_request_http_basic_auth
UserSession.request_http_basic_auth = true
assert_equal true, UserSession.request_http_basic_auth
UserSession.request_http_basic_auth = false
assert_equal false, UserSession.request_http_basic_auth
end
def test_http_basic_auth_realm
assert_equal "Application", UserSession.http_basic_auth_realm
UserSession.http_basic_auth_realm = "TestRealm"
assert_equal "TestRealm", UserSession.http_basic_auth_realm
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_persist_persist_by_http_auth
UserSession.allow_http_basic_auth = true
aaron = users(:aaron)
http_basic_auth_for do
refute UserSession.find
end
http_basic_auth_for(aaron) do
assert session = UserSession.find
assert_equal aaron, session.record
assert_equal aaron.login, session.login
assert_equal "aaronrocks", session.send(:protected_password)
refute controller.http_auth_requested?
end
unset_session
UserSession.request_http_basic_auth = true
UserSession.http_basic_auth_realm = "PersistTestRealm"
http_basic_auth_for(aaron) do
assert session = UserSession.find
assert_equal aaron, session.record
assert_equal aaron.login, session.login
assert_equal "aaronrocks", session.send(:protected_password)
assert_equal "PersistTestRealm", controller.realm
assert controller.http_auth_requested?
end
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/foundation_test.rb | test/session_test/foundation_test.rb | # frozen_string_literal: true
require "test_helper"
# We forbid the use of AC::Parameters, and we have a test to that effect, but we
# do not want a development dependency on `actionpack`, so we define it here.
module ActionController
class Parameters; end
end
module SessionTest
class FoundationTest < ActiveSupport::TestCase
def test_credentials_raise_if_not_a_hash
session = UserSession.new
e = assert_raises(TypeError) {
session.credentials = ActionController::Parameters.new
}
assert_equal(
::Authlogic::Session::Base::E_AC_PARAMETERS,
e.message
)
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/id_test.rb | test/session_test/id_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
class IdTest < ActiveSupport::TestCase
def test_credentials
session = UserSession.new
session.credentials = [:my_id]
assert_equal :my_id, session.id
end
def test_id
session = UserSession.new
session.id = :my_id
assert_equal :my_id, session.id
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/magic_states_test.rb | test/session_test/magic_states_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module SessionTest
class ConfigTest < ActiveSupport::TestCase
def test_disable_magic_states_config
UserSession.disable_magic_states = true
assert_equal true, UserSession.disable_magic_states
UserSession.disable_magic_states false
assert_equal false, UserSession.disable_magic_states
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_disabling_magic_states
UserSession.disable_magic_states = true
ben = users(:ben)
ben.update_attribute(:active, false)
refute UserSession.create(ben).new_session?
UserSession.disable_magic_states = false
end
def test_validate_validate_magic_states_active
session = UserSession.new
ben = users(:ben)
session.unauthorized_record = ben
assert session.valid?
ben.update_attribute(:active, false)
refute session.valid?
refute session.errors[:base].empty?
end
def test_validate_validate_magic_states_approved
session = UserSession.new
ben = users(:ben)
session.unauthorized_record = ben
assert session.valid?
ben.update_attribute(:approved, false)
refute session.valid?
refute session.errors[:base].empty?
end
def test_validate_validate_magic_states_confirmed
session = UserSession.new
ben = users(:ben)
session.unauthorized_record = ben
assert session.valid?
ben.update_attribute(:confirmed, false)
refute session.valid?
refute session.errors[:base].empty?
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/brute_force_protection_test.rb | test/session_test/brute_force_protection_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module BruteForceProtectionTest
class ConfigTest < ActiveSupport::TestCase
def test_consecutive_failed_logins_limit
UserSession.consecutive_failed_logins_limit = 10
assert_equal 10, UserSession.consecutive_failed_logins_limit
UserSession.consecutive_failed_logins_limit 50
assert_equal 50, UserSession.consecutive_failed_logins_limit
end
def test_failed_login_ban_for
UserSession.failed_login_ban_for = 10
assert_equal 10, UserSession.failed_login_ban_for
UserSession.failed_login_ban_for 2.hours
assert_equal 2.hours.to_i, UserSession.failed_login_ban_for
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_under_limit
ben = users(:ben)
ben.failed_login_count = UserSession.consecutive_failed_logins_limit - 1
assert ben.save
session = UserSession.create(login: ben.login, password: "benrocks")
refute session.new_session?
end
def test_exceeded_limit
ben = users(:ben)
ben.failed_login_count = UserSession.consecutive_failed_logins_limit
assert ben.save
session = UserSession.create(login: ben.login, password: "benrocks")
assert session.new_session?
assert UserSession.create(ben).new_session?
ben.reload
ben.updated_at = (UserSession.failed_login_ban_for + 2.hours.to_i).seconds.ago
refute UserSession.create(ben).new_session?
end
def test_exceeding_failed_logins_limit
UserSession.consecutive_failed_logins_limit = 2
ben = users(:ben)
2.times do |i|
session = UserSession.new(login: ben.login, password: "badpassword1")
refute session.save
refute session.errors[:password].empty?
assert_equal i + 1, ben.reload.failed_login_count
end
session = UserSession.new(login: ben.login, password: "badpassword2")
refute session.save
assert session.errors[:password].empty?
assert_equal 3, ben.reload.failed_login_count
UserSession.consecutive_failed_logins_limit = 50
end
def test_exceeded_ban_for
UserSession.consecutive_failed_logins_limit = 2
UserSession.generalize_credentials_error_messages true
ben = users(:ben)
2.times do |i|
session = UserSession.new(login: ben.login, password: "badpassword1")
refute session.save
assert session.invalid_password?
assert_equal i + 1, ben.reload.failed_login_count
end
ActiveRecord::Base.connection.execute(
"update users set updated_at = '#{1.day.ago.to_formatted_s(:db)}'
where login = '#{ben.login}'"
)
session = UserSession.new(login: ben.login, password: "benrocks")
assert session.save
assert_equal 0, ben.reload.failed_login_count
UserSession.consecutive_failed_logins_limit = 50
UserSession.generalize_credentials_error_messages false
end
def test_exceeded_ban_and_failed_doesnt_ban_again
UserSession.consecutive_failed_logins_limit = 2
ben = users(:ben)
2.times do |i|
session = UserSession.new(login: ben.login, password: "badpassword1")
refute session.save
refute session.errors[:password].empty?
assert_equal i + 1, ben.reload.failed_login_count
end
ActiveRecord::Base.connection.execute(
"update users set updated_at = '#{1.day.ago.to_formatted_s(:db)}'
where login = '#{ben.login}'"
)
session = UserSession.new(login: ben.login, password: "badpassword1")
refute session.save
assert_equal 1, ben.reload.failed_login_count
UserSession.consecutive_failed_logins_limit = 50
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/magic_columns_test.rb | test/session_test/magic_columns_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module MagicColumnsTest
class ConfigTest < ActiveSupport::TestCase
def test_last_request_at_threshold_config
UserSession.last_request_at_threshold = 2.minutes
assert_equal 2.minutes, UserSession.last_request_at_threshold
UserSession.last_request_at_threshold 0
assert_equal 0, UserSession.last_request_at_threshold
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_after_persisting_set_last_request_at
ben = users(:ben)
refute UserSession.create(ben).new_session?
set_cookie_for(ben)
old_last_request_at = ben.last_request_at
assert UserSession.find
ben.reload
assert ben.last_request_at > old_last_request_at
end
def test_valid_increase_failed_login_count
ben = users(:ben)
old_failed_login_count = ben.failed_login_count
session = UserSession.create(login: ben.login, password: "wrong")
assert session.new_session?
ben.reload
assert_equal old_failed_login_count + 1, ben.failed_login_count
end
def test_before_save_update_info
aaron = users(:aaron)
# increase failed login count
session = UserSession.create(login: aaron.login, password: "wrong")
assert session.new_session?
aaron.reload
assert_equal 0, aaron.login_count
assert_nil aaron.current_login_at
assert_nil aaron.current_login_ip
session = UserSession.create(login: aaron.login, password: "aaronrocks")
assert session.valid?
aaron.reload
assert_equal 1, aaron.login_count
assert_equal 0, aaron.failed_login_count
assert_nil aaron.last_login_at
assert_not_nil aaron.current_login_at
assert_nil aaron.last_login_ip
assert_equal "1.1.1.1", aaron.current_login_ip
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/persistence_test.rb | test/session_test/persistence_test.rb | # frozen_string_literal: true
require "test_helper"
require "authlogic/controller_adapters/rails_adapter"
module SessionTest
class PersistenceTest < ActiveSupport::TestCase
def test_find
aaron = users(:aaron)
refute UserSession.find
UserSession.allow_http_basic_auth = true
http_basic_auth_for(aaron) { assert UserSession.find }
set_cookie_for(aaron)
assert UserSession.find
unset_cookie
set_session_for(aaron)
session = UserSession.find
assert session
end
def test_find_in_api
@controller = Authlogic::TestCase::MockAPIController.new
UserSession.controller =
Authlogic::ControllerAdapters::RailsAdapter.new(@controller)
aaron = users(:aaron)
refute UserSession.find
UserSession.single_access_allowed_request_types = ["application/json"]
set_params_for(aaron)
set_request_content_type("application/json")
assert UserSession.find
end
def test_persisting
# tested thoroughly in test_find
end
def test_should_set_remember_me_on_the_next_request
aaron = users(:aaron)
session = UserSession.new(aaron)
session.remember_me = true
refute UserSession.remember_me
assert session.save
assert session.remember_me?
session = UserSession.find(aaron)
assert session.remember_me?
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/perishability_test.rb | test/session_test/perishability_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
class PerishabilityTest < ActiveSupport::TestCase
def test_after_save
ben = users(:ben)
old_perishable_token = ben.perishable_token
UserSession.create(ben)
assert_not_equal old_perishable_token, ben.perishable_token
drew = employees(:drew)
refute UserSession.create(drew).new_session?
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/scopes_test.rb | test/session_test/scopes_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
class ScopesTest < ActiveSupport::TestCase
def test_scope_method
assert_nil Authlogic::Session::Base.scope
thread1 = Thread.new do
scope = { id: :scope1 }
Authlogic::Session::Base.send(:scope=, scope)
assert_equal scope, Authlogic::Session::Base.scope
end
thread1.join
assert_nil Authlogic::Session::Base.scope
thread2 = Thread.new do
scope = { id: :scope2 }
Authlogic::Session::Base.send(:scope=, scope)
assert_equal scope, Authlogic::Session::Base.scope
end
thread2.join
assert_nil Authlogic::Session::Base.scope
end
def test_with_scope_method
assert_raise(ArgumentError) { UserSession.with_scope }
UserSession.with_scope(find_options: { conditions: "awesome = 1" }, id: "some_id") do
assert_equal(
{ find_options: { conditions: "awesome = 1" }, id: "some_id" },
UserSession.scope
)
end
assert_nil UserSession.scope
end
def test_initialize
UserSession.with_scope(find_options: { conditions: "awesome = 1" }, id: "some_id") do
session = UserSession.new
assert_equal(
{ find_options: { conditions: "awesome = 1" }, id: "some_id" },
session.scope
)
session.id = :another_id
assert_equal "another_id_some_id_test", session.send(:build_key, "test")
end
end
def test_search_for_record_with_scopes
binary_logic = companies(:binary_logic)
ben = users(:ben)
zack = users(:zack)
session = UserSession.new
assert_equal zack, session.send(:search_for_record, "find_by_login", zack.login)
session.scope = { find_options: { conditions: ["company_id = ?", binary_logic.id] } }
assert_nil session.send(:search_for_record, "find_by_login", zack.login)
assert_equal ben, session.send(:search_for_record, "find_by_login", ben.login)
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/active_record_trickery_test.rb | test/session_test/active_record_trickery_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module ActiveRecordTrickeryTest
class ClassMethodsTest < ActiveSupport::TestCase
# If test_human_name is executed after test_i18n_of_human_name the test will fail.
i_suck_and_my_tests_are_order_dependent!
def test_human_attribute_name
assert_equal "Some attribute", UserSession.human_attribute_name("some_attribute")
assert_equal "Some attribute", UserSession.human_attribute_name(:some_attribute)
end
def test_human_name
assert_equal "Usersession", UserSession.human_name
end
def test_i18n_of_human_name
I18n.backend.store_translations "en", authlogic: { models: { user_session: "MySession" } }
assert_equal "MySession", UserSession.human_name
end
def test_i18n_of_model_name_human
I18n.backend.store_translations "en", authlogic: { models: { user_session: "MySession" } }
assert_equal "MySession", UserSession.model_name.human
end
def test_model_name
assert_equal "UserSession", UserSession.model_name.name
assert_equal "user_session", UserSession.model_name.singular
assert_equal "user_sessions", UserSession.model_name.plural
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_new_record
session = UserSession.new
assert session.new_record?
end
def test_to_key
ben = users(:ben)
session = UserSession.new(ben)
assert_nil session.to_key
session.save
assert_not_nil session.to_key
assert_equal ben.to_key, session.to_key
end
def test_persisted
session = UserSession.new(users(:ben))
refute session.persisted?
session.save
assert session.persisted?
session.destroy
refute session.persisted?
end
def test_destroyed?
session = UserSession.create(users(:ben))
refute session.destroyed?
session.destroy
assert session.destroyed?
end
def test_to_model
session = UserSession.new
assert_equal session, session.to_model
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/params_test.rb | test/session_test/params_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module ParamsTest
class ConfigTest < ActiveSupport::TestCase
def test_params_key
UserSession.params_key = "my_params_key"
assert_equal "my_params_key", UserSession.params_key
UserSession.params_key "user_credentials"
assert_equal "user_credentials", UserSession.params_key
end
def test_single_access_allowed_request_types
UserSession.single_access_allowed_request_types = ["my request type"]
assert_equal ["my request type"], UserSession.single_access_allowed_request_types
UserSession.single_access_allowed_request_types(
["application/rss+xml", "application/atom+xml"]
)
assert_equal(
["application/rss+xml", "application/atom+xml"],
UserSession.single_access_allowed_request_types
)
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_persist_persist_by_params
ben = users(:ben)
session = UserSession.new
refute session.persisting?
set_params_for(ben)
refute session.persisting?
refute session.unauthorized_record
refute session.record
assert_nil controller.session["user_credentials"]
set_request_content_type("text/plain")
refute session.persisting?
refute session.unauthorized_record
assert_nil controller.session["user_credentials"]
set_request_content_type("application/atom+xml")
assert session.persisting?
assert_equal ben, session.record
# should not persist since this is single access
assert_nil controller.session["user_credentials"]
set_request_content_type("application/rss+xml")
assert session.persisting?
assert_equal ben, session.unauthorized_record
assert_nil controller.session["user_credentials"]
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/activation_test.rb | test/session_test/activation_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module ActivationTest
class ClassMethodsTest < ActiveSupport::TestCase
def test_activated
assert UserSession.activated?
Authlogic::Session::Base.controller = nil
refute UserSession.activated?
end
def test_controller
Authlogic::Session::Base.controller = nil
assert_nil Authlogic::Session::Base.controller
thread1 = Thread.new do
controller = MockController.new
Authlogic::Session::Base.controller = controller
assert_equal controller, Authlogic::Session::Base.controller
end
thread1.join
assert_nil Authlogic::Session::Base.controller
thread2 = Thread.new do
controller = MockController.new
Authlogic::Session::Base.controller = controller
assert_equal controller, Authlogic::Session::Base.controller
end
thread2.join
assert_nil Authlogic::Session::Base.controller
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_init
UserSession.controller = nil
assert_raise(Authlogic::Session::Activation::NotActivatedError) { UserSession.new }
UserSession.controller = controller
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/existence_test.rb | test/session_test/existence_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module ExistenceTest
class ClassMethodsTest < ActiveSupport::TestCase
def test_create_with_good_credentials
ben = users(:ben)
session = UserSession.create(login: ben.login, password: "benrocks")
refute session.new_session?
end
def test_create_with_bad_credentials
session = UserSession.create(login: "somelogin", password: "badpw2")
assert session.new_session?
end
def test_create_bang
ben = users(:ben)
err = assert_raise(Authlogic::Session::Existence::SessionInvalidError) do
UserSession.create!(login: ben.login, password: "badpw")
end
assert_includes err.message, "Password is not valid"
refute UserSession.create!(login: ben.login, password: "benrocks").new_session?
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_new_session
session = UserSession.new
assert session.new_session?
set_session_for(users(:ben))
session = UserSession.find
refute session.new_session?
end
def test_save_with_nothing
session = UserSession.new
refute session.save
assert session.new_session?
end
def test_save_with_block
session = UserSession.new
block_result = session.save do |result|
refute result
end
refute block_result
assert session.new_session?
end
def test_save_with_bang
session = UserSession.new
assert_raise(Authlogic::Session::Existence::SessionInvalidError) { session.save! }
session.unauthorized_record = users(:ben)
assert_nothing_raised { session.save! }
end
def test_destroy
ben = users(:ben)
session = UserSession.new
refute session.valid?
refute session.errors.empty?
assert session.destroy
assert session.errors.empty?
session.unauthorized_record = ben
assert session.save
assert session.record
assert session.destroy
refute session.record
end
end
class SessionInvalidErrorTest < ActiveSupport::TestCase
def test_message
session = UserSession.new
assert !session.valid?
error = Authlogic::Session::Existence::SessionInvalidError.new(session)
message = "Your session is invalid and has the following errors: " +
session.errors.full_messages.to_sentence
assert_equal message, error.message
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/timeout_test.rb | test/session_test/timeout_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module TimeoutTest
class ConfigTest < ActiveSupport::TestCase
def test_logout_on_timeout
UserSession.logout_on_timeout = true
assert UserSession.logout_on_timeout
UserSession.logout_on_timeout false
refute UserSession.logout_on_timeout
end
end
class InstanceMethods < ActiveSupport::TestCase
def test_stale_state
UserSession.logout_on_timeout = true
ben = users(:ben)
ben.last_request_at = 3.years.ago
ben.save
set_session_for(ben)
session = UserSession.new
assert session.persisting?
assert session.stale?
assert_equal ben, session.stale_record
assert_nil session.record
assert_nil controller.session["user_credentials_id"]
set_session_for(ben)
ben.last_request_at = Time.now
ben.save
assert session.persisting?
refute session.stale?
assert_nil session.stale_record
UserSession.logout_on_timeout = false
end
def test_should_be_stale_with_expired_remember_date
UserSession.logout_on_timeout = true
UserSession.remember_me = true
UserSession.remember_me_for = 3.months
ben = users(:ben)
assert ben.save
session = UserSession.new(ben)
assert session.save
Timecop.freeze(Time.now + 4.month)
assert session.persisting?
assert session.stale?
UserSession.remember_me = false
end
def test_should_not_be_stale_with_valid_remember_date
UserSession.logout_on_timeout = true # Default is 10.minutes
UserSession.remember_me = true
UserSession.remember_me_for = 3.months
ben = users(:ben)
assert ben.save
session = UserSession.new(ben)
assert session.save
Timecop.freeze(Time.now + 2.months)
assert session.persisting?
refute session.stale?
UserSession.remember_me = false
end
def test_successful_login
UserSession.logout_on_timeout = true
ben = users(:ben)
session = UserSession.create(login: ben.login, password: "benrocks")
refute session.new_session?
session = UserSession.find
assert session
assert_equal ben, session.record
UserSession.logout_on_timeout = false
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/credentials_test.rb | test/session_test/credentials_test.rb | ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false | |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/validation_test.rb | test/session_test/validation_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
class ValidationTest < ActiveSupport::TestCase
def test_errors
session = UserSession.new
assert_kind_of ::ActiveModel::Errors, session.errors
end
def test_valid
session = UserSession.new
refute session.valid?
assert_nil session.record
assert session.errors.count > 0
ben = users(:ben)
session.unauthorized_record = ben
assert session.valid?
assert_equal ben, session.attempted_record
assert session.errors.empty?
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/callbacks_test.rb | test/session_test/callbacks_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
class CallbacksTest < ActiveSupport::TestCase
def setup
WackyUserSession.reset_callbacks(:persist)
end
def test_no_callbacks
assert_equal [], WackyUserSession._persist_callbacks.map(&:filter)
session = WackyUserSession.new
session.send(:run_callbacks, :persist)
assert_equal 0, session.counter
end
def test_true_callback_cancelling_later_callbacks
WackyUserSession.persist :persist_by_true, :persist_by_false
assert_equal(
%i[persist_by_true persist_by_false],
WackyUserSession._persist_callbacks.map(&:filter)
)
session = WackyUserSession.new
session.send(:run_callbacks, :persist)
assert_equal 1, session.counter
end
def test_false_callback_continuing_to_later_callbacks
WackyUserSession.persist :persist_by_false, :persist_by_true
assert_equal(
%i[persist_by_false persist_by_true],
WackyUserSession._persist_callbacks.map(&:filter)
)
session = WackyUserSession.new
session.send(:run_callbacks, :persist)
assert_equal 2, session.counter
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/session_test/password_test.rb | test/session_test/password_test.rb | # frozen_string_literal: true
require "test_helper"
module SessionTest
module PasswordTest
class ConfigTest < ActiveSupport::TestCase
def test_find_by_login_method_is_deprecated
expected_warning = Regexp.new(
Regexp.escape(::Authlogic::Session::Base::E_DPR_FIND_BY_LOGIN_METHOD)
)
assert_output(nil, expected_warning) do
UserSession.find_by_login_method = "my_login_method"
end
assert_equal "my_login_method", UserSession.record_selection_method
assert_output(nil, expected_warning) do
UserSession.find_by_login_method "find_by_login"
end
assert_equal "find_by_login", UserSession.record_selection_method
end
def test_record_selection_method
UserSession.record_selection_method = "my_login_method"
assert_equal "my_login_method", UserSession.record_selection_method
UserSession.record_selection_method "find_by_login"
assert_equal "find_by_login", UserSession.record_selection_method
end
def test_verify_password_method
UserSession.verify_password_method = "my_login_method"
assert_equal "my_login_method", UserSession.verify_password_method
UserSession.verify_password_method "valid_password?"
assert_equal "valid_password?", UserSession.verify_password_method
end
def test_generalize_credentials_error_mesages_set_to_false
UserSession.generalize_credentials_error_messages false
refute UserSession.generalize_credentials_error_messages
session = UserSession.create(login: users(:ben).login, password: "invalud-password")
assert_equal ["Password is not valid"], session.errors.full_messages
end
def test_generalize_credentials_error_messages_set_to_true
UserSession.generalize_credentials_error_messages true
assert UserSession.generalize_credentials_error_messages
session = UserSession.create(login: users(:ben).login, password: "invalud-password")
assert_equal ["Login/Password combination is not valid"], session.errors.full_messages
end
def test_generalize_credentials_error_messages_set_to_string
UserSession.generalize_credentials_error_messages = "Custom Error Message"
assert UserSession.generalize_credentials_error_messages
session = UserSession.create(login: users(:ben).login, password: "invalud-password")
assert_equal ["Custom Error Message"], session.errors.full_messages
end
def test_login_field
UserSession.configured_password_methods = false
UserSession.login_field = :saweet
assert_equal :saweet, UserSession.login_field
session = UserSession.new
assert session.respond_to?(:saweet)
UserSession.login_field :login
assert_equal :login, UserSession.login_field
session = UserSession.new
assert session.respond_to?(:login)
end
def test_password_field
UserSession.configured_password_methods = false
UserSession.password_field = :saweet
assert_equal :saweet, UserSession.password_field
session = UserSession.new
assert session.respond_to?(:saweet)
UserSession.password_field :password
assert_equal :password, UserSession.password_field
session = UserSession.new
assert session.respond_to?(:password)
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_init
session = UserSession.new
assert session.respond_to?(:login)
assert session.respond_to?(:login=)
assert session.respond_to?(:password)
assert session.respond_to?(:password=)
assert session.respond_to?(:protected_password, true)
end
def test_credentials
session = UserSession.new
session.credentials = { login: "login", password: "pass" }
assert_equal "login", session.login
assert_nil session.password
assert_equal "pass", session.send(:protected_password)
assert_equal({ password: "<protected>", login: "login" }, session.credentials)
end
def test_credentials_are_params_safe
session = UserSession.new
assert_nothing_raised { session.credentials = { hacker_method: "error!" } }
end
def test_save_with_credentials
aaron = users(:aaron)
session = UserSession.new(login: aaron.login, password: "aaronrocks")
assert session.save
refute session.new_session?
assert_equal 1, session.record.login_count
assert Time.now >= session.record.current_login_at
assert_equal "1.1.1.1", session.record.current_login_ip
assert_equal env_session_options[:renew], true
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/sha512_test.rb | test/crypto_provider_test/sha512_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
class Sha512Test < ActiveSupport::TestCase
def setup
@default_stretches = Authlogic::CryptoProviders::Sha512.stretches
end
def teardown
Authlogic::CryptoProviders::Sha512.stretches = @default_stretches
end
def test_encrypt
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "9508ba2964d65501aa1d7798e8f250b35f50fadb870871f2bc1f" \
"390872e8456e785633d06e17ffa4984a04cfa1a0e1ec29f15c31187b991e591393c6c0bffb61"
digest = Authlogic::CryptoProviders::Sha512.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_encrypt_with_3_stretches
Authlogic::CryptoProviders::Sha512.stretches = 3
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "ed507752ef2e985a9e5661fedcbac8ad7536d4b80c87183c2027" \
"3f568afb6f2112886fd786de00458eb2a14c640d9060c4688825e715cc1c3ecde8997d4ae556"
digest = Authlogic::CryptoProviders::Sha512.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "9508ba2964d65501aa1d7798e8f250b35f50fadb870871f2bc1f" \
"390872e8456e785633d06e17ffa4984a04cfa1a0e1ec29f15c31187b991e591393c6c0bffb61"
assert Authlogic::CryptoProviders::Sha512.matches?(expected_digest, password, salt)
end
def test_not_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
bad_digest = "12345"
assert !Authlogic::CryptoProviders::Sha512.matches?(bad_digest, password, salt)
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/md5_test.rb | test/crypto_provider_test/md5_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
class MD5Test < ActiveSupport::TestCase
def setup
@default_stretches = Authlogic::CryptoProviders::MD5.stretches
end
def teardown
Authlogic::CryptoProviders::MD5.stretches = @default_stretches
end
def test_encrypt
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "3d16884295a68fec30a2ae7ff0634b1e"
digest = Authlogic::CryptoProviders::MD5.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_encrypt_with_3_stretches
Authlogic::CryptoProviders::MD5.stretches = 3
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "9ac3a3a2e68f822f3482cbea3cbed9a3"
digest = Authlogic::CryptoProviders::MD5.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "3d16884295a68fec30a2ae7ff0634b1e"
assert Authlogic::CryptoProviders::MD5.matches?(expected_digest, password, salt)
end
def test_not_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
bad_digest = "12345"
assert !Authlogic::CryptoProviders::MD5.matches?(bad_digest, password, salt)
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/scrypt_test.rb | test/crypto_provider_test/scrypt_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
class SCryptTest < ActiveSupport::TestCase
def test_encrypt
assert Authlogic::CryptoProviders::SCrypt.encrypt("mypass")
end
def test_matches
hash = Authlogic::CryptoProviders::SCrypt.encrypt("mypass")
assert Authlogic::CryptoProviders::SCrypt.matches?(hash, "mypass")
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/sha1_test.rb | test/crypto_provider_test/sha1_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
class Sha1Test < ActiveSupport::TestCase
def setup
@default_stretches = Authlogic::CryptoProviders::Sha1.stretches
end
def teardown
Authlogic::CryptoProviders::Sha1.stretches = @default_stretches
end
def test_encrypt
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "5723d69f7ca1f8d63122c9cef4cf3c10d0482d3e"
digest = Authlogic::CryptoProviders::Sha1.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_encrypt_with_3_stretches
Authlogic::CryptoProviders::Sha1.stretches = 3
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "969f681d90a7d25679256e38cce3dc10db6d49c5"
digest = Authlogic::CryptoProviders::Sha1.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "5723d69f7ca1f8d63122c9cef4cf3c10d0482d3e"
assert Authlogic::CryptoProviders::Sha1.matches?(expected_digest, password, salt)
end
def test_not_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
bad_digest = "12345"
assert !Authlogic::CryptoProviders::Sha1.matches?(bad_digest, password, salt)
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/sha256_test.rb | test/crypto_provider_test/sha256_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
class Sha256Test < ActiveSupport::TestCase
def setup
@default_stretches = Authlogic::CryptoProviders::Sha256.stretches
end
def teardown
Authlogic::CryptoProviders::Sha256.stretches = @default_stretches
end
def test_encrypt
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "3c4f802953726704088a3cd6d89237e9a279a8e8f43fa6de8549ca54b80b766c"
digest = Authlogic::CryptoProviders::Sha256.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_encrypt_with_3_stretches
Authlogic::CryptoProviders::Sha256.stretches = 3
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "06a2e9cd5552f2cdbc01ec61d52ce80d0bfba8f1bb689a356ac0193d42adc831"
digest = Authlogic::CryptoProviders::Sha256.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "3c4f802953726704088a3cd6d89237e9a279a8e8f43fa6de8549ca54b80b766c"
assert Authlogic::CryptoProviders::Sha256.matches?(expected_digest, password, salt)
end
def test_not_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
bad_digest = "12345"
assert !Authlogic::CryptoProviders::Sha256.matches?(bad_digest, password, salt)
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/bcrypt_test.rb | test/crypto_provider_test/bcrypt_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
class BCryptTest < ActiveSupport::TestCase
def test_encrypt
assert Authlogic::CryptoProviders::BCrypt.encrypt("mypass")
end
def test_matches
hash = Authlogic::CryptoProviders::BCrypt.encrypt("mypass")
assert Authlogic::CryptoProviders::BCrypt.matches?(hash, "mypass")
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/sha1/v2_test.rb | test/crypto_provider_test/sha1/v2_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
module VSHA1
class V2Test < ActiveSupport::TestCase
def setup
@default_stretches = Authlogic::CryptoProviders::Sha1::V2.stretches
end
def teardown
Authlogic::CryptoProviders::Sha1::V2.stretches = @default_stretches
end
def test_encrypt
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "12d995b1f0af7d24d6f89d2e63dfbcb752384815"
digest = Authlogic::CryptoProviders::Sha1::V2.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_encrypt_with_3_stretches
Authlogic::CryptoProviders::Sha1::V2.stretches = 3
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "af1e00f841ccc742c1e5879af35ca02b1978a1ac"
digest = Authlogic::CryptoProviders::Sha1::V2.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "12d995b1f0af7d24d6f89d2e63dfbcb752384815"
assert Authlogic::CryptoProviders::Sha1::V2.matches?(expected_digest, password, salt)
end
def test_not_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
bad_digest = "12345"
assert !Authlogic::CryptoProviders::Sha1::V2.matches?(bad_digest, password, salt)
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/md5/v2_test.rb | test/crypto_provider_test/md5/v2_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
module MD5
class V2Test < ActiveSupport::TestCase
def setup
@default_stretches = Authlogic::CryptoProviders::MD5::V2.stretches
end
def teardown
Authlogic::CryptoProviders::MD5::V2.stretches = @default_stretches
end
def test_encrypt
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "3d16884295a68fec30a2ae7ff0634b1e"
digest = Authlogic::CryptoProviders::MD5::V2.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_encrypt_with_3_stretches
Authlogic::CryptoProviders::MD5::V2.stretches = 3
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "da62ac8b983606f684cea0b93a558283"
digest = Authlogic::CryptoProviders::MD5::V2.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "3d16884295a68fec30a2ae7ff0634b1e"
assert Authlogic::CryptoProviders::MD5::V2.matches?(expected_digest, password, salt)
end
def test_not_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
bad_digest = "12345"
assert !Authlogic::CryptoProviders::MD5::V2.matches?(bad_digest, password, salt)
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/sha512/v2_test.rb | test/crypto_provider_test/sha512/v2_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
module SHA512
class V2Test < ActiveSupport::TestCase
def setup
@default_stretches = Authlogic::CryptoProviders::Sha512::V2.stretches
end
def teardown
Authlogic::CryptoProviders::Sha512::V2.stretches = @default_stretches
end
def test_encrypt
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "60e86eec0e7f858cc5cc6b42b31a847819b65e06317709ce27" \
"79245d0776f18094dff9afbc66ae1e509f2b5e49f4d2ff3f632c8ee7c4683749f5fd028de5b085"
digest = Authlogic::CryptoProviders::Sha512::V2.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_encrypt_with_3_stretches
Authlogic::CryptoProviders::Sha512::V2.stretches = 3
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "c4f546026f67a4fcce0e4df5905b845f75d9cfe1371eeaba99" \
"a2c045940a7d08aa81837344752a9d4fb93883402114edd03955ed5962cd89b6e335c2ec5ca4a5"
digest = Authlogic::CryptoProviders::Sha512::V2.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "60e86eec0e7f858cc5cc6b42b31a847819b65e06317709ce27" \
"79245d0776f18094dff9afbc66ae1e509f2b5e49f4d2ff3f632c8ee7c4683749f5fd028de5b085"
assert Authlogic::CryptoProviders::Sha512::V2.matches?(expected_digest, password, salt)
end
def test_not_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
bad_digest = "12345"
assert !Authlogic::CryptoProviders::Sha512::V2.matches?(bad_digest, password, salt)
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/crypto_provider_test/sha256/v2_test.rb | test/crypto_provider_test/sha256/v2_test.rb | # frozen_string_literal: true
require "test_helper"
module CryptoProviderTest
module SHA256
class V2Test < ActiveSupport::TestCase
def setup
@default_stretches = Authlogic::CryptoProviders::Sha256::V2.stretches
end
def teardown
Authlogic::CryptoProviders::Sha256::V2.stretches = @default_stretches
end
def test_encrypt
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "7f42a368b64a3c284c87b3ed3145b0c89f6bc49de931ca083e9c56a5c6b98e22"
digest = Authlogic::CryptoProviders::Sha256::V2.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_encrypt_with_3_stretches
Authlogic::CryptoProviders::Sha256::V2.stretches = 3
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "1560ebc3b08d86828a7e9267379f7dbb847b6cc255135fc13210a4155a58b981"
digest = Authlogic::CryptoProviders::Sha256::V2.encrypt(password, salt)
assert_equal digest, expected_digest
end
def test_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
expected_digest = "7f42a368b64a3c284c87b3ed3145b0c89f6bc49de931ca083e9c56a5c6b98e22"
assert Authlogic::CryptoProviders::Sha256::V2.matches?(expected_digest, password, salt)
end
def test_not_matches
password = "test"
salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd"
bad_digest = "12345"
assert !Authlogic::CryptoProviders::Sha256::V2.matches?(bad_digest, password, salt)
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/email_test.rb | test/acts_as_authentic_test/email_test.rb | # frozen_string_literal: true
require "test_helper"
module ActsAsAuthenticTest
class EmailTest < ActiveSupport::TestCase
def test_email_field_config
assert_equal :email, User.email_field
assert_equal :email, Employee.email_field
User.email_field = :nope
assert_equal :nope, User.email_field
User.email_field :email
assert_equal :email, User.email_field
end
def test_deferred_error_message_translation
# ensure we successfully loaded the test locale
assert I18n.available_locales.include?(:lol), "Test locale failed to load"
I18n.with_locale("lol") do
cat = User.new
cat.email = "meow"
cat.validate
assert_includes(
cat.errors[:email],
I18n.t("authlogic.error_messages.email_invalid")
)
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
binarylogic/authlogic | https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/perishable_token_test.rb | test/acts_as_authentic_test/perishable_token_test.rb | # frozen_string_literal: true
require "test_helper"
module ActsAsAuthenticTest
class PerishableTokenTest < ActiveSupport::TestCase
def test_perishable_token_valid_for_config
assert_equal 10.minutes.to_i, User.perishable_token_valid_for
assert_equal 10.minutes.to_i, Employee.perishable_token_valid_for
User.perishable_token_valid_for = 1.hour
assert_equal 1.hour.to_i, User.perishable_token_valid_for
User.perishable_token_valid_for 10.minutes
assert_equal 10.minutes.to_i, User.perishable_token_valid_for
end
def test_disable_perishable_token_maintenance_config
refute User.disable_perishable_token_maintenance
refute Employee.disable_perishable_token_maintenance
User.disable_perishable_token_maintenance = true
assert User.disable_perishable_token_maintenance
User.disable_perishable_token_maintenance false
refute User.disable_perishable_token_maintenance
end
def test_validates_uniqueness_of_perishable_token
u = User.new
u.perishable_token = users(:ben).perishable_token
refute u.valid?
refute u.errors[:perishable_token].empty?
end
def test_before_save_reset_perishable_token
ben = users(:ben)
old_perishable_token = ben.perishable_token
assert ben.save
assert_not_equal old_perishable_token, ben.perishable_token
end
def test_reset_perishable_token
ben = users(:ben)
old_perishable_token = ben.perishable_token
assert ben.reset_perishable_token
assert_not_equal old_perishable_token, ben.perishable_token
ben.reload
assert_equal old_perishable_token, ben.perishable_token
assert ben.reset_perishable_token!
assert_not_equal old_perishable_token, ben.perishable_token
ben.reload
assert_not_equal old_perishable_token, ben.perishable_token
end
def test_find_using_perishable_token
ben = users(:ben)
assert_equal ben, User.find_using_perishable_token(ben.perishable_token)
end
def test_find_using_perishable_token_when_perished
ben = users(:ben)
ActiveRecord::Base.connection.execute(
"UPDATE users set updated_at = '#{1.week.ago.to_formatted_s(:db)}' where id = #{ben.id}"
)
assert_nil User.find_using_perishable_token(ben.perishable_token)
end
def test_find_using_perishable_token_when_perished_2
User.perishable_token_valid_for = 1.minute
ben = users(:ben)
ActiveRecord::Base.connection.execute(
"UPDATE users set updated_at = '#{2.minutes.ago.to_formatted_s(:db)}' where id = #{ben.id}"
)
assert_nil User.find_using_perishable_token(ben.perishable_token)
User.perishable_token_valid_for = 10.minutes
end
def test_find_using_perishable_token_when_passing_threshold
User.perishable_token_valid_for = 1.minute
ben = users(:ben)
ActiveRecord::Base.connection.execute(
"UPDATE users set updated_at = '#{10.minutes.ago.to_formatted_s(:db)}' where id = #{ben.id}"
)
assert_nil User.find_using_perishable_token(ben.perishable_token, 5.minutes)
assert_equal ben, User.find_using_perishable_token(ben.perishable_token, 20.minutes)
User.perishable_token_valid_for = 10.minutes
end
def test_find_perishable_token_with_bang
assert_raises ActiveRecord::RecordNotFound do
User.find_using_perishable_token!("some_bad_value")
end
end
end
end
| ruby | MIT | 77da613d09fe8e2be2c980d5a5d3c76109590edd | 2026-01-04T15:46:27.836259Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.