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/test/test_mechanize_page_frame.rb | test/test_mechanize_page_frame.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizePageFrame < Mechanize::TestCase
def test_content
page = page 'http://example/referer'
frame = node 'frame', 'name' => 'frame1', 'src' => 'http://example/'
frame = Mechanize::Page::Frame.new frame, @mech, page
frame.content
assert_equal 'http://example/referer', requests.first['Referer']
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_http_auth_challenge.rb | test/test_mechanize_http_auth_challenge.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeHttpAuthChallenge < Mechanize::TestCase
def setup
super
@uri = URI 'http://example/'
@AR = Mechanize::HTTP::AuthRealm
@AC = Mechanize::HTTP::AuthChallenge
@challenge = @AC.new 'Digest', { 'realm' => 'r' }, 'Digest realm=r'
end
def test_realm_basic
@challenge.scheme = 'Basic'
expected = @AR.new 'Basic', @uri, 'r'
assert_equal expected, @challenge.realm(@uri + '/foo')
end
def test_realm_digest
expected = @AR.new 'Digest', @uri, 'r'
assert_equal expected, @challenge.realm(@uri + '/foo')
end
def test_realm_digest_case
challenge = @AC.new 'Digest', { 'realm' => 'R' }, 'Digest realm=R'
expected = @AR.new 'Digest', @uri, 'R'
assert_equal expected, challenge.realm(@uri + '/foo')
end
def test_realm_unknown
@challenge.scheme = 'Unknown'
e = assert_raises Mechanize::Error do
@challenge.realm(@uri + '/foo')
end
assert_equal 'unknown HTTP authentication scheme Unknown', e.message
end
def test_realm_name
assert_equal 'r', @challenge.realm_name
end
def test_realm_name_case
challenge = @AC.new 'Digest', { 'realm' => 'R' }, 'Digest realm=R'
assert_equal 'R', challenge.realm_name
end
def test_realm_name_ntlm
challenge = @AC.new 'Negotiate, NTLM'
assert_nil challenge.realm_name
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_page_image.rb | test/test_mechanize_page_image.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizePageImage < Mechanize::TestCase
def setup
super
@uri = URI 'http://example/'
@src = (@uri + 'a.jpg').to_s
@empty_page = Mechanize::Page.new(@uri, nil, '', 200, @mech)
end
def img attributes
img = node 'img', attributes
Mechanize::Page::Image.new img, @empty_page
end
def test_initialize
image = img("src" => "a.jpg", "alt" => "alt", "width" => "100",
"height" => "200", "title" => "title", "id" => "id",
"class" => "class")
assert_equal "a.jpg", image.src
assert_equal "alt", image.alt
assert_equal "100", image.width
assert_equal "200", image.height
assert_equal "title", image.title
assert_equal "id", image.dom_id
assert_equal "class", image.dom_class
end
def test_initialize_no_attributes
image = img({})
assert_nil image.src
assert_nil image.alt
assert_nil image.width
assert_nil image.height
assert_nil image.title
assert_nil image.dom_id
assert_nil image.dom_class
end
def test_caption
assert_equal "", img("src" => @src).caption
assert_equal "alt", img("src" => @src, "alt" => "alt").caption
assert_equal "title", img("src" => @src, "title" => "title").caption
assert_equal "title", img("src" => @src,
"alt" => "alt", "title" => "title").caption
end
def test_url
assert_equal ".jpg", img('src' => @src).extname
assert_equal "http://example/a.jpg", img('src' => @src).url.to_s
assert_equal "http://example/a%20.jpg", img('src' => 'http://example/a .jpg' ).url.to_s
end
def test_url_base
page = html_page <<-BODY
<head>
<base href="http://other.example/">
</head>
<body>
<img src="a.jpg">
</body>
BODY
assert_equal "http://other.example/a.jpg", page.images.first.url
end
def test_extname
assert_equal ".jpg", img("src" => "a.jpg").extname
assert_equal ".PNG", img("src" => "a.PNG").extname
assert_equal ".aaa", img("src" => "unknown.aaa").extname
assert_equal "", img("src" => "nosuffiximage").extname
assert_nil img("width" => "1", "height" => "1").extname
assert_equal ".jpg", img("src" => "a.jpg?cache_buster").extname
end
def test_mime_type
assert_equal "image/jpeg", img("src" => "a.jpg").mime_type
assert_equal "image/png", img("src" => "a.PNG").mime_type
assert_nil img("src" => "unknown.aaa").mime_type
assert_nil img("src" => "nosuffiximage").mime_type
end
def test_fetch
image = img "src" => "http://localhost/button.jpg"
fetched = image.fetch
assert_equal fetched, @mech.page
assert_equal "http://localhost/button.jpg", fetched.uri.to_s
assert_equal "http://example/", requests.first['Referer']
assert @mech.visited? "http://localhost/button.jpg"
end
def test_fetch_referer_http_page_rel_src
# | rel-src http-src https-src
# http page | *page* page page
# https page | page empty empty
page = html_page '<img src="./button.jpg">'
page.images.first.fetch
assert_equal 'http', page.uri.scheme
assert_equal true, page.images.first.relative?
assert_equal "http://example/", requests.first['Referer']
end
def test_fetch_referer_http_page_abs_src
# | rel-src http-src https-src
# http page | page *page* *page*
# https page | page empty empty
page = html_page '<img src="http://localhost/button.jpg">'
page.images.first.fetch
assert_equal 'http', page.uri.scheme
assert_equal false, page.images.first.relative?
assert_equal "http://example/", requests.first['Referer']
end
def test_fetch_referer_https_page_rel_src
# | rel-src http-src https-src
# http page | page page page
# https page | *page* empty empty
page = html_page '<img src="./button.jpg">'
page.uri = URI 'https://example/'
page.images.first.fetch
assert_equal 'https', page.uri.scheme
assert_equal true, page.images.first.relative?
assert_equal "https://example/", requests.first['Referer']
end
def test_fetch_referer_https_page_abs_src
# | rel-src http-src https-src
# http page | page page page
# https page | page *empty* *empty*
page = html_page '<img src="http://localhost/button.jpg">'
page.uri = URI 'https://example/'
page.images.first.fetch
assert_equal 'https', page.uri.scheme
assert_equal false, page.images.first.relative?
assert_nil requests.first['Referer']
end
def test_image_referer_http_page_abs_src
page = html_page '<img src="http://localhost/button.jpg">'
assert_equal 'http', page.uri.scheme
assert_equal @uri, page.images.first.image_referer.uri
end
def test_image_referer_http_page_rel_src
page = html_page '<img src="./button.jpg">'
assert_equal 'http', page.uri.scheme
assert_equal @uri, page.images.first.image_referer.uri
end
def test_image_referer_https_page_abs_src
page = html_page '<img src="http://localhost/button.jpg">'
page.uri = URI 'https://example/'
assert_equal 'https', page.uri.scheme
assert_nil page.images.first.image_referer.uri
end
def test_image_referer_https_page_rel_src
page = html_page '<img src="./button.jpg">'
page.uri = URI 'https://example/'
assert_equal 'https', page.uri.scheme
assert_equal URI('https://example/'), page.images.first.image_referer.uri
end
def test_no_src_attribute
page = html_page '<img width="10" height="10" class="foo" />'
page.uri = URI 'https://example/'
assert_equal URI('https://example/'), page.images.first.url
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_xml_file.rb | test/test_mechanize_xml_file.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeXmlFile < Mechanize::TestCase
def setup
super
uri = URI 'http://example.com/foo.xml'
@xml = Mechanize::XmlFile.new uri, nil, <<-XML
<languages>
<language>Ruby</language>
<language>Perl</language>
</languages>
XML
end
def test_xml
assert_kind_of Nokogiri::XML::Document, @xml.xml
end
def test_search
assert_equal ['Ruby', 'Perl'], @xml.search('language').map { |n| n.text }
end
def test_at
assert_equal 'Perl', @xml.at('//language[2]').text
end
end | ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_subclass.rb | test/test_mechanize_subclass.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeSubclass < Mechanize::TestCase
class Parent < Mechanize
@html_parser = :parser
@log = :log
end
class Child < Parent
end
def test_subclass_inherits_html_parser
assert_equal :parser, Child.html_parser
end
def test_subclass_inherits_log
assert_equal :log, Child.log
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_radio_button.rb | test/test_mechanize_form_radio_button.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormRadioButton < Mechanize::TestCase
def setup
super
@page = html_page <<-BODY
<form name="form1" method="post" action="/form_post">
<label for="blue">Blue</label>
<input type="radio" name="color" value="blue" id="blue">
<input type="radio" name="color" value="brown">
<input type="radio" name="color" value="green">
<input type="radio" name="color" value="red">
<input type="radio" name="color" value="yellow" id="a">
<input type="radio" name="color" value="yellow" id="b">
<input type="submit" value="Submit">
</form>
BODY
@form = @page.forms.first
@blue = @form.radiobutton_with :value => 'blue'
@brown = @form.radiobutton_with :value => 'brown'
@green = @form.radiobutton_with :value => 'green'
@red = @form.radiobutton_with :value => 'red'
@yellow = @form.radiobutton_with :id => 'a'
end
def test_check
@blue.check
assert @blue.checked?
refute @brown.checked?
refute @green.checked?
refute @red.checked?
refute @yellow.checked?
end
def test_check_multiple
@blue.check
@brown.check
refute @blue.checked?
assert @brown.checked?
refute @green.checked?
refute @red.checked?
refute @yellow.checked?
end
def test_click
@blue.click
assert @blue.checked?
@blue.click
refute @blue.checked?
end
def test_equals2
refute_equal @yellow, @red
other_yellow = @form.radiobutton_with :id => 'b'
assert_equal @yellow, other_yellow
end
def test_hash
refute_equal @yellow.hash, @red.hash
other_yellow = @form.radiobutton_with :id => 'b'
assert_equal @yellow.hash, other_yellow.hash
end
def test_label
assert_equal 'Blue', @blue.label.text
end
def test_uncheck
@blue.check
@blue.uncheck
refute @blue.checked?
refute @brown.checked?
refute @green.checked?
refute @red.checked?
refute @yellow.checked?
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_image.rb | test/test_mechanize_image.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeImage < Mechanize::TestCase
# empty subclass, no tests
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_file_response.rb | test/test_mechanize_file_response.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFileResponse < Mechanize::TestCase
def test_file_path
res = Mechanize::FileResponse.new("/path/to/foo.html")
assert_equal("/path/to/foo.html", res.file_path)
end
def test_content_type
Tempfile.open %w[pi .nothtml] do |tempfile|
res = Mechanize::FileResponse.new tempfile.path
assert_nil res['content-type']
end
Tempfile.open %w[pi .xhtml] do |tempfile|
res = Mechanize::FileResponse.new tempfile.path
assert_equal 'text/html', res['content-type']
end
Tempfile.open %w[pi .html] do |tempfile|
res = Mechanize::FileResponse.new tempfile.path
assert_equal 'text/html', res['Content-Type']
end
end
def test_read_body
Tempfile.open %w[pi .html] do |tempfile|
tempfile.write("asdfasdfasdf")
tempfile.close
res = Mechanize::FileResponse.new(tempfile.path)
res.read_body do |input|
assert_equal("asdfasdfasdf", input)
end
end
end
def test_read_body_does_not_allow_command_injection
skip if windows?
in_tmpdir do
FileUtils.touch('| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\'')
res = Mechanize::FileResponse.new('| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\'')
res.read_body { |_| }
refute_operator(File, :exist?, "vul.txt")
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_redirect_not_get_or_head_error.rb | test/test_mechanize_redirect_not_get_or_head_error.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeRedirectNotGetOrHead < Mechanize::TestCase
def test_to_s
page = fake_page
error = Mechanize::RedirectNotGetOrHeadError.new(page, :put)
assert_match(/ PUT /, error.to_s)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_http_content_disposition_parser.rb | test/test_mechanize_http_content_disposition_parser.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeHttpContentDispositionParser < Mechanize::TestCase
def setup
super
@parser = Mechanize::HTTP::ContentDispositionParser.new
end
def test_parse
now = Time.at Time.now.to_i
content_disposition = @parser.parse \
'attachment;' \
'filename=value;' \
"creation-date=\"#{now.rfc822}\";" \
"modification-date=\"#{(now + 1).rfc822}\";" \
"read-date=\"#{(now + 2).rfc822}\";" \
'size=5;' \
'arbitrary=value'
assert_equal 'attachment', content_disposition.type
assert_equal 'value', content_disposition.filename
assert_equal now, content_disposition.creation_date
assert_equal((now + 1), content_disposition.modification_date)
assert_equal((now + 2), content_disposition.read_date)
assert_equal 5, content_disposition.size
expected = { 'arbitrary' => 'value' }
assert_equal expected, content_disposition.parameters
end
def test_parse_date_iso8601_fallback
now = Time.at Time.now.to_i
content_disposition = @parser.parse \
'attachment;' \
'filename=value;' \
"creation-date=\"#{now.iso8601}\";" \
"modification-date=\"#{(now + 1).iso8601}\""
assert_equal 'attachment', content_disposition.type
assert_equal 'value', content_disposition.filename
assert_equal now, content_disposition.creation_date
assert_equal((now + 1), content_disposition.modification_date)
end
def test_parse_date_invalid
now = Time.at Time.now.to_i
content_disposition = @parser.parse \
'attachment;' \
'filename=value;' \
"creation-date=\"#{now.to_s}\";" \
"modification-date=\"#{(now + 1).to_s}\""
assert_nil content_disposition
end
def test_parse_header
content_disposition = @parser.parse \
'content-disposition: attachment;filename=value', true
assert_equal 'attachment', content_disposition.type
assert_equal 'value', content_disposition.filename
end
def test_parse_no_type
content_disposition = @parser.parse 'filename=value'
assert_nil content_disposition.type
assert_equal 'value', content_disposition.filename
end
def test_parse_semicolons
content_disposition = @parser.parse 'attachment;;filename=value'
assert_equal 'attachment', content_disposition.type
assert_equal 'value', content_disposition.filename
end
def test_parse_quoted_size
content_disposition = @parser.parse 'size="5"'
assert_equal 5, content_disposition.size
end
def test_rfc_2045_quoted_string
@parser.scanner = StringScanner.new '"text"'
string = @parser.rfc_2045_quoted_string
assert_equal 'text', string
end
def test_rfc_2045_quoted_string_bad
@parser.scanner = StringScanner.new '"text'
assert_nil @parser.rfc_2045_quoted_string
end
def test_rfc_2045_quoted_string_crlf
@parser.scanner = StringScanner.new "\"multiline\\\r\n\ttext\""
string = @parser.rfc_2045_quoted_string
assert_equal "multiline\r\n\ttext", string
end
def test_rfc_2045_quoted_string_escape
@parser.scanner = StringScanner.new "\"escape\\ text\""
string = @parser.rfc_2045_quoted_string
assert_equal 'escape text', string
end
def test_rfc_2045_quoted_string_escape_bad
@parser.scanner = StringScanner.new '"escape\\'
string = @parser.rfc_2045_quoted_string
assert_nil string
end
def test_rfc_2045_quoted_string_folded
@parser.scanner = StringScanner.new "\"multiline\r\n\ttext\""
string = @parser.rfc_2045_quoted_string
assert_equal 'multiline text', string
end
def test_rfc_2045_quoted_string_quote
@parser.scanner = StringScanner.new '"escaped \\" here"'
string = @parser.rfc_2045_quoted_string
assert_equal 'escaped " here', string
end
def test_rfc_2045_quoted_string_quote_end
@parser.scanner = StringScanner.new '"end \\""'
string = @parser.rfc_2045_quoted_string
assert_equal 'end "', string
end
def test_parse_uppercase
content_disposition = @parser.parse \
'content-disposition: attachment; Filename=value', true
assert_equal 'attachment', content_disposition.type
assert_equal 'value', content_disposition.filename
end
def test_parse_filename_starting_with_escaped_quote
content_disposition = @parser.parse \
'content-disposition: attachment; Filename="\"value\""', true
assert_equal '"value"', content_disposition.filename
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_page.rb | test/test_mechanize_page.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizePage < Mechanize::TestCase
def setup
super
@uri = URI 'http://example/'
end
def test_selector_methods
page = html_page <<-BODY
<html>
<meta>
<head><title></title>
<body>
<span class="name" id="out">Eamonn</span>
<span>/</span>
<span class="name" id="bloody">Esther</span>
<span>/</span>
<span class="name" id="rageous">Fletcher</span>
</body>
</html>
BODY
# at(css_selector), % css_selector
assert_equal('Eamonn', page.at('#out').text)
assert_equal('Eamonn', (page % '#out').text)
# at(xpath_selector), % xpath_selector
assert_equal('Esther', page.at('//span[@id="bloody"]').text)
assert_equal('Esther', (page % '//span[@id="bloody"]').text)
# at_css()
assert_equal('Eamonn', page.at_css('#out').text)
# css()
assert_equal('Fletcher', page.css('.name')[2].text)
# at_xpath()
assert_equal('Esther', page.at_xpath('//span[@id="bloody"]').text)
# xpath()
assert_equal('Fletcher', page.xpath('//*[@class="name"]')[2].text)
end
def test_initialize_good_content_type
page = Mechanize::Page.new
assert_equal('text/html', page.content_type)
[
'text/html',
'Text/HTML',
'text/html; charset=UTF-8',
'text/html ; charset=US-ASCII',
'application/xhtml+xml',
'Application/XHTML+XML',
'application/xhtml+xml; charset=UTF-8',
'application/xhtml+xml ; charset=US-ASCII',
].each { |content_type|
page = Mechanize::Page.new(URI('http://example/'),
{ 'content-type' => content_type }, 'hello', '200')
assert_equal(content_type, page.content_type, content_type)
}
end
def test_initialize_bad_content_type
[
'text/xml',
'text/xhtml',
'text/htmlfu',
'footext/html',
'application/xhtml+xmlfu',
'fooapplication/xhtml+xml',
].each { |content_type|
page = Mechanize::Page.new(URI('http://example/'),
{ 'content-type' => content_type }, 'hello', '200')
assert_equal(content_type, page.content_type, content_type)
}
end
def test_frames
page = html_page <<-BODY
<TITLE>A simple frameset document</TITLE>
<FRAMESET cols="20%, 80%">
<FRAMESET rows="100, 200">
<FRAME name="frame1" src="/google.html">
<FRAME name="frame2" src="/form_test.html">
</FRAMESET>
<FRAMESET rows="100, 200">
<FRAME name="frame3" src="/file_upload.html">
<IFRAME src="http://google.com/" name="frame4"></IFRAME>
</FRAMESET>
</FRAMESET>
BODY
assert_equal 3, page.frames.size
assert_equal "frame1", page.frames[0].name
assert_equal "/google.html", page.frames[0].src
assert_equal "Google", page.frames[0].content.title
assert_equal "frame2", page.frames[1].name
assert_equal "/form_test.html", page.frames[1].src
assert_equal "Page Title", page.frames[1].content.title
assert_equal "frame3", page.frames[2].name
assert_equal "/file_upload.html", page.frames[2].src
assert_equal "File Upload Form", page.frames[2].content.title
assert_equal %w[/google.html /file_upload.html], page.frames_with(search: '*[name=frame1], *[name=frame3]').map(&:src)
end
def test_iframes
page = html_page <<-BODY
<TITLE>A simple frameset document</TITLE>
<FRAME name="frame1" src="/google.html">
<IFRAME src="/file_upload.html" name="frame4">
</IFRAME>
BODY
assert_equal 1, page.iframes.size
assert_equal "frame4", page.iframes.first.name
assert_equal "/file_upload.html", page.iframes.first.src
assert_equal "File Upload Form", page.iframes.first.content.title
end unless RUBY_ENGINE == 'jruby' # NekoHTML does not parse IFRAME
def test_image_with
page = html_page <<-BODY
<img src="a.jpg">
<img src="b.jpg">
<img src="c.png">
BODY
assert_equal "http://example/b.jpg",
page.image_with(:src => 'b.jpg').url.to_s
end
def test_images_with
page = html_page <<-BODY
<img src="a.jpg">
<img src="b.jpg">
<img src="c.png">
BODY
images = page.images_with(:src => /jpg\Z/).map { |img| img.url.to_s }
assert_equal %w[http://example/a.jpg http://example/b.jpg], images
end
def test_links
page = html_page <<-BODY
<a href="foo.html">
BODY
assert_equal page.links.first.href, "foo.html"
end
def test_parser_no_attributes
page = html_page <<-BODY
<html>
<meta>
<head><title></title>
<body>
<a>Hello</a>
<a><img /></a>
<form>
<input />
<select>
<option />
</select>
<textarea></textarea>
</form>
<frame></frame>
</body>
</html>
BODY
# HACK weak assertion
assert_kind_of Nokogiri::HTML::Document, page.root
end
def test_search_links
page = html_page <<-BODY
<html>
<meta>
<head><title></title>
<body>
<span id="spany">
<a href="b.html">b</a>
<a href="a.html">a</a>
</span>
<a href="6.html">6</a>
</body>
</html>
BODY
links = page.links_with(:search => "#spany a")
assert_equal 2, links.size
assert_equal "b.html", links[0].href
assert_equal "b", links[0].text
assert_equal "a.html", links[1].href
assert_equal "a", links[1].text
end
def test_search_images
page = html_page <<-BODY
<html>
<meta>
<head><title></title>
<body>
<img src="1.jpg" class="unpretty">
<img src="a.jpg" class="pretty">
<img src="b.jpg">
<img src="c.png" class="pretty">
</body>
</html>
BODY
{
:search => "//img[@class='pretty']",
:xpath => "//img[@class='pretty']",
:css => "img.pretty",
:class => "pretty",
:dom_class => "pretty",
}.each { |key, expr|
images = page.images_with(key => expr)
message = "selecting with #{key.inspect}"
assert_equal 2, images.size
assert_equal "pretty", images[0].dom_class, message
assert_equal "a.jpg", images[0].src, message
assert_equal "pretty", images[1].dom_class, message
assert_equal "c.png", images[1].src, message
}
end
def test_search_bad_selectors
page = html_page <<-BODY
<a href="foo.html">foo</a>
<img src="foo.jpg" />
BODY
assert_empty page.images_with(:search => '//a')
assert_empty page.links_with(:search => '//img')
end
def test_multiple_titles
page = html_page <<-BODY
<!doctype html>
<html>
<head>
<title>HTML>TITLE</title>
</head>
<body>
<svg>
<title>SVGTITLE</title>
<metadata id="metadata5">
<rdf:RDF>
<cc:Work>
<dc:title>RDFDCTITLE</dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g></g>
</svg>
</body>
</html>
BODY
assert_equal page.title, "HTML>TITLE"
end
def test_frozen_string_body
html = (<<~HTML).freeze
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p>Hello World</p>
</body>
</html>
HTML
html_page(html) # refute_raises
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_http_auth_store.rb | test/test_mechanize_http_auth_store.rb | # coding: utf-8
# frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeHttpAuthStore < Mechanize::TestCase
def setup
super
@store = Mechanize::HTTP::AuthStore.new
@uri = URI.parse 'http://example/'
end
def test_add_auth
@store.add_auth @uri + '/path', 'user', 'pass'
expected = {
@uri => {
nil => ['user', 'pass', nil],
}
}
assert_equal expected, @store.auth_accounts
end
def test_add_auth_domain
@store.add_auth @uri + '/path', 'user1', 'pass', nil, 'domain'
expected = {
@uri => {
nil => %w[user1 pass domain],
}
}
assert_equal expected, @store.auth_accounts
e = assert_raises ArgumentError do
@store.add_auth @uri, 'user3', 'pass', 'realm', 'domain'
end
assert_equal 'NTLM domain given with realm which NTLM does not use',
e.message
end
def test_add_auth_realm
@store.add_auth @uri, 'user1', 'pass'
@store.add_auth @uri, 'user2', 'pass', 'realm'
expected = {
@uri => {
nil => ['user1', 'pass', nil],
'realm' => ['user2', 'pass', nil],
}
}
assert_equal expected, @store.auth_accounts
end
def test_add_auth_realm_case
@store.add_auth @uri, 'user1', 'pass', 'realm'
@store.add_auth @uri, 'user2', 'pass', 'Realm'
expected = {
@uri => {
'realm' => ['user1', 'pass', nil],
'Realm' => ['user2', 'pass', nil],
}
}
assert_equal expected, @store.auth_accounts
end
def test_add_auth_string
@store.add_auth "#{@uri}/path", 'user', 'pass'
expected = {
@uri => {
nil => ['user', 'pass', nil],
}
}
assert_equal expected, @store.auth_accounts
end
def test_add_default_auth
_, err = capture_io do
@store.add_default_auth 'user', 'pass'
end
expected = ['user', 'pass', nil]
assert_equal expected, @store.default_auth
assert_match 'DISCLOSURE WITHOUT YOUR KNOWLEDGE', err
capture_io do
@store.add_default_auth 'user', 'pass', 'realm'
end
expected = %w[user pass realm]
assert_equal expected, @store.default_auth
end
def test_credentials_eh
challenges = [
Mechanize::HTTP::AuthChallenge.new('Basic', 'realm' => 'r'),
Mechanize::HTTP::AuthChallenge.new('Digest', 'realm' => 'r'),
]
refute @store.credentials? @uri, challenges
@store.add_auth @uri, 'user', 'pass'
assert @store.credentials? @uri, challenges
assert @store.credentials? "#{@uri}/path", challenges
end
def test_credentials_for
assert_nil @store.credentials_for(@uri, 'realm')
@store.add_auth @uri, 'user', 'pass', 'realm'
assert_equal ['user', 'pass', nil], @store.credentials_for(@uri, 'realm')
assert_equal ['user', 'pass', nil],
@store.credentials_for(@uri.to_s, 'realm')
assert_nil @store.credentials_for(@uri, 'other')
end
def test_credentials_for_default
assert_nil @store.credentials_for(@uri, 'realm')
capture_io do
@store.add_default_auth 'user1', 'pass'
end
assert_equal ['user1', 'pass', nil], @store.credentials_for(@uri, 'realm')
@store.add_auth @uri, 'user2', 'pass'
assert_equal ['user2', 'pass', nil], @store.credentials_for(@uri, 'realm')
assert_equal ['user2', 'pass', nil], @store.credentials_for(@uri, 'other')
end
def test_credentials_for_no_realm
@store.add_auth @uri, 'user', 'pass' # no realm set
assert_equal ['user', 'pass', nil], @store.credentials_for(@uri, 'realm')
end
def test_credentials_for_realm
@store.add_auth @uri, 'user1', 'pass'
@store.add_auth @uri, 'user2', 'pass', 'realm'
assert_equal ['user2', 'pass', nil], @store.credentials_for(@uri, 'realm')
assert_equal ['user1', 'pass', nil], @store.credentials_for(@uri, 'other')
end
def test_credentials_for_realm_case
@store.add_auth @uri, 'user1', 'pass', 'realm'
@store.add_auth @uri, 'user2', 'pass', 'Realm'
assert_equal ['user1', 'pass', nil], @store.credentials_for(@uri, 'realm')
assert_equal ['user2', 'pass', nil], @store.credentials_for(@uri, 'Realm')
end
def test_credentials_for_path
@store.add_auth @uri, 'user', 'pass', 'realm'
uri = @uri + '/path'
assert_equal ['user', 'pass', nil], @store.credentials_for(uri, 'realm')
end
def test_remove_auth
@store.remove_auth @uri
assert_empty @store.auth_accounts
end
def test_remove_auth_both
@store.add_auth @uri, 'user1', 'pass'
@store.add_auth @uri, 'user2', 'pass', 'realm'
uri = @uri + '/path'
@store.remove_auth uri
assert_empty @store.auth_accounts
end
def test_remove_auth_realm
@store.add_auth @uri, 'user1', 'pass'
@store.add_auth @uri, 'user2', 'pass', 'realm'
@store.remove_auth @uri, 'realm'
expected = {
@uri => {
nil => ['user1', 'pass', nil]
}
}
assert_equal expected, @store.auth_accounts
end
def test_remove_auth_realm_case
@store.add_auth @uri, 'user1', 'pass', 'realm'
@store.add_auth @uri, 'user2', 'pass', 'Realm'
@store.remove_auth @uri, 'Realm'
expected = {
@uri => {
'realm' => ['user1', 'pass', nil]
}
}
assert_equal expected, @store.auth_accounts
end
def test_remove_auth_string
@store.add_auth @uri, 'user1', 'pass'
@store.remove_auth "#{@uri}/path"
assert_empty @store.auth_accounts
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_pluggable_parser.rb | test/test_mechanize_pluggable_parser.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizePluggableParser < Mechanize::TestCase
def setup
super
@pp = @mech.pluggable_parser
end
def test_aref
@pp['text/html'] = Mechanize::Download
assert_equal Mechanize::Download, @pp['text/html']
end
def test_csv
@pp.csv = Mechanize::Download
assert_equal Mechanize::Download, @pp['text/csv']
end
def test_html
assert_equal Mechanize::Page, @pp['text/html']
@pp.html = Mechanize::Download
assert_equal Mechanize::Download, @pp['text/html']
end
def test_parser
assert_equal Mechanize::XmlFile, @pp.parser('text/xml')
assert_equal Mechanize::File, @pp.parser(nil)
end
def test_parser_mime
@pp['image/png'] = :png
assert_equal :png, @pp.parser('x-image/x-png')
assert_equal :png, @pp.parser('image/png')
assert_equal Mechanize::Image, @pp.parser('image')
end
def test_parser_bogus
assert_nil @pp['bogus']
assert_equal Mechanize::File, @pp.parser('bogus')
end
def test_pdf
@pp.pdf = Mechanize::Download
assert_equal Mechanize::Download, @pp['application/pdf']
end
def test_xml
assert_equal Mechanize::XmlFile, @pp['text/xml']
assert_equal Mechanize::XmlFile, @pp['application/xml']
@pp.xml = Mechanize::Download
assert_equal Mechanize::Download, @pp['text/xml']
assert_equal Mechanize::Download, @pp['application/xml']
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_textarea.rb | test/test_mechanize_form_textarea.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormTextarea < Mechanize::TestCase
def setup
super
@page = @mech.get("http://localhost/tc_textarea.html")
end
def test_empty_text_area
form = @page.forms_with(:name => 'form1').first
assert_equal('', form.field_with(:name => 'text1').value)
form.text1 = 'Hello World'
assert_equal('Hello World', form.field_with(:name => 'text1').value)
page = @mech.submit(form)
assert_equal(1, page.links.length)
assert_equal('text1:Hello World', page.links[0].text)
end
def test_non_empty_textfield
form = @page.forms_with(:name => 'form2').first
assert_equal('sample text', form.field_with(:name => 'text1').value)
page = @mech.submit(form)
assert_equal(1, page.links.length)
assert_equal('text1:sample text', page.links[0].text)
end
def test_multi_textfield
form = @page.form_with(:name => 'form3')
assert_equal(2, form.fields_with(:name => 'text1').length)
assert_equal('', form.fields_with(:name => 'text1')[0].value)
assert_equal('sample text', form.fields_with(:name => 'text1')[1].value)
form.text1 = 'Hello World'
assert_equal('Hello World', form.fields_with(:name => 'text1')[0].value)
assert_equal('sample text', form.fields_with(:name => 'text1')[1].value)
page = @mech.submit(form)
assert_equal(2, page.links.length)
link = page.links_with(:text => 'text1:sample text')
assert_equal(1, link.length)
link = page.links_with(:text => 'text1:Hello World')
assert_equal(1, link.length)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_option.rb | test/test_mechanize_form_option.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormOption < Mechanize::TestCase
def setup
super
page = html_page <<-BODY
<form name="form1" method="post" action="/form_post">
<select name="select">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
</select>
</form>
BODY
form = page.forms.first
@select = form.fields.first
@option1 = @select.options.first
@option2 = @select.options.last
end
def test_inspect
assert_match "value: 2", @select.inspect
end
def test_value_missing_value
option = node 'option'
option.inner_html = 'blah'
option = Mechanize::Form::Option.new option, nil
assert_equal 'blah', option.value
end
def test_click
@option1.click
assert @option1.selected?
end
def test_select
@option1.select
assert @option1.selected?
end
def test_unselect
@option2.unselect
refute @option2.selected?
end
def test_selected_eh
refute @option1.selected?
assert @option2.selected?
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_keygen.rb | test/test_mechanize_form_keygen.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormKeygen < Mechanize::TestCase
def setup
super
keygen = node('keygen',
'name' => 'userkey',
'challenge' => 'f4832e1d200df3df8c5c859edcabe52f')
@keygen = Mechanize::Form::Keygen.new keygen
end
def test_challenge
assert_equal "f4832e1d200df3df8c5c859edcabe52f", @keygen.challenge
end
def test_key
assert @keygen.key.kind_of?(OpenSSL::PKey::PKey), "Not an OpenSSL key"
assert @keygen.key.private?, "Not a private key"
end
def test_spki_signature
skip("JRuby PKI doesn't handle this for reasons I've been unable to understand") if RUBY_ENGINE=~/jruby/
spki = OpenSSL::Netscape::SPKI.new @keygen.value
assert_equal @keygen.challenge, spki.challenge
assert_equal @keygen.key.public_key.to_pem, spki.public_key.to_pem
assert spki.verify(@keygen.key.public_key)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_download.rb | test/test_mechanize_download.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeDownload < Mechanize::TestCase
def setup
super
@parser = Mechanize::Download
end
def test_body
uri = URI.parse 'http://example/foo.html'
body_io = StringIO.new '0123456789'
download = @parser.new uri, nil, body_io
assert_equal '0123456789', download.body
assert_equal 0, download.body_io.pos
end
def test_save_string_io
uri = URI.parse 'http://example/foo.html'
body_io = StringIO.new '0123456789'
download = @parser.new uri, nil, body_io
in_tmpdir do
filename = download.save
assert File.exist? 'foo.html'
assert_equal "foo.html", filename
end
end
def test_save_bang
uri = URI.parse 'http://example/foo.html'
body_io = StringIO.new '0123456789'
download = @parser.new uri, nil, body_io
in_tmpdir do
filename = download.save!
assert File.exist? 'foo.html'
assert_equal "foo.html", filename
end
end
def test_save_bang_does_not_allow_command_injection
skip if windows?
uri = URI.parse 'http://example/foo.html'
body_io = StringIO.new '0123456789'
download = @parser.new uri, nil, body_io
in_tmpdir do
download.save!('| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\'')
refute_operator(File, :exist?, "vul.txt")
end
end
def test_save_tempfile
uri = URI.parse 'http://example/foo.html'
Tempfile.open @NAME do |body_io|
body_io.unlink
body_io.write '0123456789'
body_io.flush
body_io.rewind
download = @parser.new uri, nil, body_io
in_tmpdir do
filename = download.save
assert File.exist? 'foo.html'
assert_equal "foo.html", filename
filename = download.save
assert File.exist? 'foo.html.1'
assert_equal "foo.html.1", filename
filename = download.save
assert File.exist? 'foo.html.2'
assert_equal "foo.html.2", filename
end
end
end
def test_filename
uri = URI.parse 'http://example/foo.html'
body_io = StringIO.new '0123456789'
download = @parser.new uri, nil, body_io
assert_equal "foo.html", download.filename
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_file_connection.rb | test/test_mechanize_file_connection.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFileConnection < Mechanize::TestCase
def test_request
file_path = File.expand_path(__FILE__)
uri = URI.parse "file://#{file_path}"
conn = Mechanize::FileConnection.new
body = +''
conn.request uri, nil do |response|
assert_equal(file_path, response.file_path)
response.read_body do |part|
body << part
end
end
assert_equal File.read(__FILE__), body.gsub(/\r\n/, "\n")
end
def test_request_on_uri_with_windows_drive
uri_string = "file://C:/path/to/file.html"
expected_file_path = "C:/path/to/file.html"
uri = URI.parse(uri_string)
conn = Mechanize::FileConnection.new
called = false
yielded_file_path = nil
conn.request(uri, nil) do |response|
called = true
yielded_file_path = response.file_path
end
assert(called)
assert_equal(expected_file_path, yielded_file_path)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_page_meta_refresh.rb | test/test_mechanize_page_meta_refresh.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizePageMetaRefresh < Mechanize::TestCase
def setup
super
@MR = Mechanize::Page::MetaRefresh
@uri = URI 'http://example/here/'
end
def util_page delay, uri
body = <<-BODY
<head><meta http-equiv="refresh" content="#{delay};url=#{uri}"></head>
BODY
Mechanize::Page.new(@uri, nil, body, 200, @mech)
end
def util_meta_refresh page
node = page.search('meta').first
@MR.from_node node, page
end
def test_class_parse
delay, uri, link_self = @MR.parse "0; url=http://localhost:8080/path", @uri
assert_equal "0", delay
assert_equal "http://localhost:8080/path", uri.to_s
refute link_self
delay, uri, link_self =
@MR.parse "100.001; url=http://localhost:8080/path", @uri
assert_equal "100.001", delay
assert_equal "http://localhost:8080/path", uri.to_s
refute link_self
delay, uri, link_self =
@MR.parse "0; url='http://localhost:8080/path'", @uri
assert_equal "0", delay
assert_equal "http://localhost:8080/path", uri.to_s
refute link_self
delay, uri, link_self =
@MR.parse "0; url=\"http://localhost:8080/path\"", @uri
assert_equal "0", delay
assert_equal "http://localhost:8080/path", uri.to_s
refute link_self
delay, uri, link_self = @MR.parse "0; url=", @uri
assert_equal "0", delay
assert_equal "http://example/here/", uri.to_s
assert link_self
delay, uri, link_self = @MR.parse "0", @uri
assert_equal "0", delay
assert_equal "http://example/here/", uri.to_s
assert link_self
delay, uri, link_self = @MR.parse " 0; ", @uri
assert_equal "0", delay
assert_equal "http://example/here/", uri.to_s
assert link_self
delay, uri, link_self = @MR.parse " 0 ; ", @uri
assert_equal "0", delay
assert_equal "http://example/here/", uri.to_s
assert link_self
delay, uri, link_self = @MR.parse "0; UrL=http://localhost:8080/path", @uri
assert_equal "0", delay
assert_equal "http://localhost:8080/path", uri.to_s
refute link_self
delay, uri, link_self = @MR.parse "0 ; UrL = http://localhost:8080/path", @uri
assert_equal "0", delay
assert_equal "http://localhost:8080/path", uri.to_s
refute link_self
end
def test_class_parse_funky
delay, uri, link_self = @MR.parse "0; url=/funky?<b>Welcome<%2Fb>", @uri
assert_equal "0", delay
assert_equal "http://example/funky?%3Cb%3EWelcome%3C%2Fb%3E",
uri.to_s
refute link_self
end
def test_class_from_node
page = util_page 5, 'http://b.example'
link = util_meta_refresh page
assert_equal 5, link.delay
assert_equal 'http://b.example', link.href
page = util_page 5, 'http://example/a'
link = util_meta_refresh page
assert_equal 5, link.delay
assert_equal 'http://example/a', link.href
page = util_page 5, 'test'
link = util_meta_refresh page
assert_equal 5, link.delay
assert_equal 'test', link.href
page = util_page 5, '/test'
link = util_meta_refresh page
assert_equal 5, link.delay
assert_equal '/test', link.href
page = util_page 5, nil
link = util_meta_refresh page
assert_equal 5, link.delay
assert_nil link.href
page = util_page 5, @uri
link = util_meta_refresh page
assert_equal 5, link.delay
assert_equal 'http://example/here/', link.href
end
def test_class_from_node_no_content
body = <<-BODY
<head><meta http-equiv="refresh"></head>
BODY
page = Mechanize::Page.new(@uri, nil, body, 200, @mech)
assert_nil util_meta_refresh page
end
def test_class_from_node_not_refresh
body = <<-BODY
<head><meta http-equiv="other-thing" content="0;"></head>
BODY
page = Mechanize::Page.new(@uri, nil, body, 200, @mech)
assert_nil util_meta_refresh page
end
def test_meta_refresh_click_sends_no_referer
page = util_page 0, '/referer'
link = util_meta_refresh page
refreshed = link.click
assert_equal '', refreshed.body
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_image_button.rb | test/test_mechanize_form_image_button.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormImageButton < Mechanize::TestCase
def test_query_value
button = Mechanize::Form::ImageButton.new 'name' => 'image_button'
assert_equal [%w[image_button.x 0], %w[image_button.y 0]],
button.query_value
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_http_auth_realm.rb | test/test_mechanize_http_auth_realm.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeHttpAuthRealm < Mechanize::TestCase
def setup
super
@uri = URI 'http://example/'
@AR = Mechanize::HTTP::AuthRealm
@realm = @AR.new 'Digest', @uri, 'r'
end
def test_initialize
assert_equal 'r', @realm.realm
realm = @AR.new 'Digest', @uri, 'R'
refute_equal 'r', realm.realm
realm = @AR.new 'Digest', @uri, 'R'
assert_equal 'R', realm.realm
realm = @AR.new 'Digest', @uri, nil
assert_nil realm.realm
end
def test_equals2
other = @realm.dup
assert_equal @realm, other
other = @AR.new 'Basic', @uri, 'r'
refute_equal @realm, other
other = @AR.new 'Digest', URI('http://other.example/'), 'r'
refute_equal @realm, other
other = @AR.new 'Digest', @uri, 'R'
refute_equal @realm, other
other = @AR.new 'Digest', @uri, 's'
refute_equal @realm, other
end
def test_hash
h = {}
h[@realm] = 1
other = @realm.dup
assert_equal 1, h[other]
other = @AR.new 'Basic', @uri, 'r'
assert_nil h[other]
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_multi_select.rb | test/test_multi_select.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class MultiSelectTest < Mechanize::TestCase
def setup
super
@page = @mech.get("http://localhost/form_multi_select.html")
@form = @page.forms.first
end
def test_option_with
o = @form.field_with(:name => 'list').option_with(:value => '1')
assert_equal '1', o.value
end
def test_options_with
os = @form.field_with(:name => 'list').options_with(:value => /1|2/)
assert_equal ['1', '2'].sort, os.map { |x| x.value }.sort
end
def test_select_none
page = @mech.get("http://localhost/form_multi_select.html")
form = page.forms.first
form.field_with(:name => 'list').select_none
page = @mech.submit(form)
assert_equal(0, page.links.length)
end
def test_select_all
page = @mech.get("http://localhost/form_multi_select.html")
form = page.forms.first
form.field_with(:name => 'list').select_all
page = @mech.submit(form)
assert_equal(6, page.links.length)
assert_equal(1, page.links_with(:text => 'list:1').length)
assert_equal(1, page.links_with(:text => 'list:2').length)
assert_equal(1, page.links_with(:text => 'list:3').length)
assert_equal(1, page.links_with(:text => 'list:4').length)
assert_equal(1, page.links_with(:text => 'list:5').length)
assert_equal(1, page.links_with(:text => 'list:6').length)
end
def test_click_all
page = @mech.get("http://localhost/form_multi_select.html")
form = page.forms.first
form.field_with(:name => 'list').options.each { |o| o.click }
page = @mech.submit(form)
assert_equal(5, page.links.length)
assert_equal(1, page.links_with(:text => 'list:1').length)
assert_equal(1, page.links_with(:text => 'list:3').length)
assert_equal(1, page.links_with(:text => 'list:4').length)
assert_equal(1, page.links_with(:text => 'list:5').length)
assert_equal(1, page.links_with(:text => 'list:6').length)
end
def test_select_default
page = @mech.get("http://localhost/form_multi_select.html")
form = page.forms.first
page = @mech.submit(form)
assert_equal(1, page.links.length)
assert_equal(1, page.links_with(:text => 'list:2').length)
end
def test_select_one
page = @mech.get("http://localhost/form_multi_select.html")
form = page.forms.first
form.list = 'Aaron'
assert_equal(['Aaron'], form.list)
page = @mech.submit(form)
assert_equal(1, page.links.length)
assert_equal('list:Aaron', page.links.first.text)
end
def test_select_two
page = @mech.get("http://localhost/form_multi_select.html")
form = page.forms.first
form.list = ['1', 'Aaron']
page = @mech.submit(form)
assert_equal(2, page.links.length)
assert_equal(1, page.links_with(:text => 'list:1').length)
assert_equal(1, page.links_with(:text => 'list:Aaron').length)
end
def test_select_three
page = @mech.get("http://localhost/form_multi_select.html")
form = page.forms.first
form.list = ['1', '2', '3']
page = @mech.submit(form)
assert_equal(3, page.links.length)
assert_equal(1, page.links_with(:text => 'list:1').length)
assert_equal(1, page.links_with(:text => 'list:2').length)
assert_equal(1, page.links_with(:text => 'list:3').length)
end
def test_select_three_twice
page = @mech.get("http://localhost/form_multi_select.html")
form = page.forms.first
form.list = ['1', '2', '3']
form.list = ['1', '2', '3']
page = @mech.submit(form)
assert_equal(3, page.links.length)
assert_equal(1, page.links_with(:text => 'list:1').length)
assert_equal(1, page.links_with(:text => 'list:2').length)
assert_equal(1, page.links_with(:text => 'list:3').length)
end
def test_select_with_click
page = @mech.get("http://localhost/form_multi_select.html")
form = page.forms.first
form.list = ['1', 'Aaron']
form.field_with(:name => 'list').options[3].tick
assert_equal(['1', 'Aaron', '4'].sort, form.list.sort)
page = @mech.submit(form)
assert_equal(3, page.links.length)
assert_equal(1, page.links_with(:text => 'list:1').length)
assert_equal(1, page.links_with(:text => 'list:Aaron').length)
assert_equal(1, page.links_with(:text => 'list:4').length)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_directory_saver.rb | test/test_mechanize_directory_saver.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeDirectorySaver < Mechanize::TestCase
def setup
super
@uri = URI 'http://example/relative/tc_relative_links.html'
@io = StringIO.new 'hello world'
end
def test_self_save_to
in_tmpdir do
saver = Mechanize::DirectorySaver.save_to 'dir'
saver.new @uri, nil, @io, 200
assert File.exist? 'dir/tc_relative_links.html'
refute File.exist? 'dir/relative'
end
end
def test_self_save_to_cd
in_tmpdir do
saver = Mechanize::DirectorySaver.save_to 'dir'
FileUtils.mkdir 'other'
Dir.chdir 'other' do
saver.new @uri, nil, @io, 200
end
assert File.exist? 'dir/tc_relative_links.html'
refute File.exist? 'dir/relative'
end
end
def test_with_decode_filename
in_tmpdir do
saver = Mechanize::DirectorySaver.save_to 'dir', :decode_filename => true
uri = URI 'http://example.com/foo+bar.html'
saver.new uri, nil, @io, 200
assert File.exist? 'dir/foo bar.html'
end
end
def test_initialize_no_save_dir
in_tmpdir do
e = assert_raises Mechanize::Error do
Mechanize::DirectorySaver.new @uri, nil, @io, 200
end
assert_match %r%no save directory specified%, e.message
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_http_agent.rb | test/test_mechanize_http_agent.rb | # coding: utf-8
# frozen_string_literal: true
require 'mechanize/test_case'
unless RUBY_PLATFORM == 'java'
require 'brotli'
require 'zstd-ruby'
end
class TestMechanizeHttpAgent < Mechanize::TestCase
def setup
super
@agent = @mech.agent
@uri = URI.parse 'http://example/'
@req = Net::HTTP::Get.new '/'
@res = Net::HTTPOK.allocate
@res.instance_variable_set :@code, 200
@res.instance_variable_set :@header, {}
@headers = %w[accept accept-encoding user-agent]
end
def auth_realm uri, scheme, type
base_uri = uri + '/'
realm = Mechanize::HTTP::AuthRealm.new scheme, base_uri, 'r'
@agent.authenticate_methods[base_uri][type] << realm
realm
end
def skip_if_jruby_zlib
if RUBY_ENGINE == 'jruby'
meth = caller_locations(1,1).first.base_label
skip "#{meth}: skipped because how Zlib handles error is different in JRuby"
end
end
def test_agent_is_named
assert_equal 'mechanize', Mechanize::HTTP::Agent.new.http.name
assert_equal 'unique', Mechanize::HTTP::Agent.new('unique').http.name
end
def test_auto_io
Tempfile.open 'input' do |input_io|
input_io.binmode
input_io.write '12345'
input_io.rewind
out_io = @agent.auto_io @NAME, 1024, input_io
assert_equal '12345', out_io.string
assert_equal Encoding::BINARY, out_io.string.encoding if
Object.const_defined? :Encoding
end
end
def test_auto_io_chunk
Tempfile.open 'input' do |input_io|
chunks = []
input_io.binmode
input_io.write '12345'
input_io.rewind
@agent.auto_io @NAME, 1, input_io do |chunk|
chunks << chunk
end
assert_equal %w[1 2 3 4 5], chunks
end
end
def test_auto_io_tempfile
@agent.max_file_buffer = 3
Tempfile.open 'input' do |input_io|
input_io.binmode
input_io.write '12345'
input_io.rewind
out_io = @agent.auto_io @NAME, 1, input_io
result = out_io.read
assert_equal '12345', result
assert_equal Encoding::BINARY, result.encoding if
Object.const_defined? :Encoding
end
end
def test_auto_io_yield
Tempfile.open 'input' do |input_io|
input_io.binmode
input_io.write '12345'
input_io.rewind
out_io = @agent.auto_io @NAME, 1024, input_io do |chunk|
"x#{chunk}"
end
assert_equal 'x12345', out_io.string
end
end
def test_certificate_equals
cert_path = File.expand_path '../data/server.crt', __FILE__
cert = OpenSSL::X509::Certificate.new File.read cert_path
@agent.certificate = cert
assert_equal cert.to_pem, @agent.certificate.to_pem
end
def test_certificate_equals_file
cert_path = File.expand_path '../data/server.crt', __FILE__
cert = OpenSSL::X509::Certificate.new File.read cert_path
@agent.certificate = cert_path
assert_equal cert.to_pem, @agent.certificate.to_pem
end
def test_connection_for_file
uri = URI.parse 'file:///nonexistent'
conn = @agent.connection_for uri
assert_equal Mechanize::FileConnection.new, conn
end
def test_connection_for_http
conn = @agent.connection_for @uri
assert_equal @agent.http, conn
end
def test_disable_keep_alive
@agent.disable_keep_alive @req
refute @req['connection']
end
def test_disable_keep_alive_no
@agent.keep_alive = false
@agent.disable_keep_alive @req
assert_equal 'close', @req['connection']
end
def test_enable_gzip
@agent.enable_gzip @req
assert_equal 'gzip,deflate,identity', @req['accept-encoding']
end
def test_enable_gzip_no
@agent.gzip_enabled = false
@agent.enable_gzip @req
assert_equal 'identity', @req['accept-encoding']
end
def test_fetch_file_nonexistent
in_tmpdir do
nonexistent = File.join Dir.pwd, 'nonexistent'
uri = URI.parse "file:///#{nonexistent}"
e = assert_raises Mechanize::ResponseCodeError do
@agent.fetch uri
end
assert_match "404 => Net::HTTPNotFound for #{uri}", e.message
end
end
def test_fetch_file_plus
Tempfile.open '++plus++' do |io|
content = 'plusses +++'
io.write content
io.rewind
uri = URI.parse "file://#{Mechanize::Util.uri_escape io.path}"
page = @agent.fetch uri
assert_equal content, page.body
assert_kind_of Mechanize::File, page
end
end
def test_fetch_file_space
foo = File.expand_path("../htdocs/dir with spaces/foo.html", __FILE__)
uri = URI.parse "file://#{Mechanize::Util.uri_escape foo}"
page = @agent.fetch uri
assert_equal File.read(foo), page.body.gsub(/\r\n/, "\n")
assert_kind_of Mechanize::Page, page
end
def test_fetch_head_gzip
uri = @uri + '/gzip?file=index.html'
page = @agent.fetch uri, :head
assert_kind_of Mechanize::Page, page
end
def test_fetch_hooks
@agent.pre_connect_hooks << proc do |agent, request|
assert_equal '/index.html', request.path
assert_equal @agent, agent
end
@agent.post_connect_hooks << proc do |agent, uri, response, body|
assert_equal @agent, agent
assert_equal URI('http://example/index.html'), uri
assert_equal '200', response.code
assert_kind_of String, body
end
@agent.fetch URI 'http://example/index.html'
end
def test_fetch_ignore_bad_chunking
@agent.ignore_bad_chunking = true
file = @agent.fetch 'http://example/bad_chunking'
assert_equal '0123456789', file.content
end
def test_fetch_post_connect_hook
response = nil
@agent.post_connect_hooks << lambda { |_, _, res, _| response = res }
@agent.fetch 'http://localhost/'
assert response
end
def test_fetch_redirect_header
page = @agent.fetch('http://example/redirect', :get,
'X-Location' => '/http_headers',
'Range' => 'bytes=0-99999')
assert_match 'range|bytes=0-999', page.body
end
def test_fetch_server_error
e = assert_raises Mechanize::ResponseCodeError do
@mech.get 'http://localhost/response_code?code=500'
end
assert_equal '500', e.response_code
end
def test_fetch_allowed_error_codes
@agent.allowed_error_codes = ['500']
page = @mech.get 'http://localhost/response_code?code=500'
assert_equal '500', page.code
end
def test_fetch_allowed_error_codes_int
@agent.allowed_error_codes = [500]
page = @mech.get 'http://localhost/response_code?code=500'
assert_equal '500', page.code
end
def test_get_meta_refresh_header_follow_self
@agent.follow_meta_refresh = true
@agent.follow_meta_refresh_self = true
page = Mechanize::Page.new(@uri, nil, '', 200, @mech)
@res.instance_variable_set :@header, 'refresh' => ['0']
refresh = @agent.get_meta_refresh @res, @uri, page
assert_equal [0.0, URI('http://example/')], refresh
end
def test_get_meta_refresh_header_no_follow
page = Mechanize::Page.new(@uri, nil, '', 200, @mech)
@res.instance_variable_set :@header, 'refresh' => ['0']
refresh = @agent.get_meta_refresh @res, @uri, page
assert_nil refresh
end
def test_get_meta_refresh_header_no_follow_self
@agent.follow_meta_refresh = true
page = Mechanize::Page.new(@uri, nil, '', 200, @mech)
@res.instance_variable_set :@header, 'refresh' => ['0']
refresh = @agent.get_meta_refresh @res, @uri, page
assert_nil refresh
end
def test_get_meta_refresh_meta_follow_self
@agent.follow_meta_refresh = true
@agent.follow_meta_refresh_self = true
body = <<-BODY
<title></title>
<meta http-equiv="refresh" content="0">
BODY
page = Mechanize::Page.new(@uri, nil, body, 200, @mech)
refresh = @agent.get_meta_refresh @res, @uri, page
assert_equal [0, nil], refresh
end
def test_get_meta_refresh_meta_no_follow
body = <<-BODY
<title></title>
<meta http-equiv="refresh" content="0">
BODY
page = Mechanize::Page.new(@uri, nil, body, 200, @mech)
refresh = @agent.get_meta_refresh @res, @uri, page
assert_nil refresh
end
def test_get_meta_refresh_meta_no_follow_self
@agent.follow_meta_refresh = true
body = <<-BODY
<title></title>
<meta http-equiv="refresh" content="0">
BODY
page = Mechanize::Page.new(@uri, nil, body, 200, @mech)
refresh = @agent.get_meta_refresh @res, @uri, page
assert_nil refresh
end
def test_get_robots
robotstxt = @agent.get_robots 'http://localhost/robots.txt'
refute_equal '', robotstxt
robotstxt = @agent.get_robots 'http://localhost/response_code?code=404'
assert_equal '', robotstxt
end
def test_hook_content_encoding_response
@mech.content_encoding_hooks << lambda{|agent, uri, response, response_body_io|
response['content-encoding'] = 'gzip' if response['content-encoding'] == 'agzip'}
@res.instance_variable_set :@header, 'content-encoding' => %w[agzip]
body_io = StringIO.new 'part'
@agent.hook_content_encoding @res, @uri, body_io
assert_equal 'gzip', @res['content-encoding']
end
def test_http_request_file
uri = URI.parse 'file:///nonexistent'
request = @agent.http_request uri, :get
assert_kind_of Mechanize::FileRequest, request
assert_equal '/nonexistent', request.path
end
def test_http_request_get
request = @agent.http_request @uri, :get
assert_kind_of Net::HTTP::Get, request
assert_equal '/', request.path
end
def test_http_request_post
request = @agent.http_request @uri, :post
assert_kind_of Net::HTTP::Post, request
assert_equal '/', request.path
end
def test_idle_timeout_equals
@agent.idle_timeout = 1
assert_equal 1, @agent.http.idle_timeout
end
def test_inflate
body_io = StringIO.new "x\x9C+H,*\x01\x00\x04?\x01\xB8"
result = @agent.inflate body_io
assert_equal 'part', result.read
end
def test_post_connect
@agent.post_connect_hooks << proc { |agent, uri, response, body|
assert_equal @agent, agent
assert_equal @res, response
assert_equal 'body', body
throw :called
}
io = StringIO.new 'body'
assert_throws :called do
@agent.post_connect @uri, @res, io
end
assert_equal 0, io.pos
end
def test_pre_connect
@agent.pre_connect_hooks << proc { |agent, request|
assert_equal @agent, agent
assert_equal @req, request
throw :called
}
assert_throws :called do
@agent.pre_connect @req
end
end
def test_request_add_headers
@agent.request_add_headers @req, 'Content-Length' => 300
assert_equal '300', @req['content-length']
end
def test_request_add_headers_etag
@agent.request_add_headers @req, :etag => '300'
assert_equal '300', @req['etag']
end
def test_request_add_headers_if_modified_since
@agent.request_add_headers @req, :if_modified_since => 'some_date'
assert_equal 'some_date', @req['if-modified-since']
end
def test_request_add_headers_none
@agent.request_add_headers @req
assert_equal @headers, @req.to_hash.keys.sort
end
def test_request_add_headers_request_headers
@agent.request_headers['X-Foo'] = 'bar'
@agent.request_add_headers @req
assert_equal @headers + %w[x-foo], @req.to_hash.keys.sort
end
def test_request_add_headers_symbol
e = assert_raises ArgumentError do
@agent.request_add_headers @req, :content_length => 300
end
assert_equal 'unknown header symbol content_length', e.message
end
def test_request_auth_basic
@agent.add_auth @uri, 'user', 'password'
auth_realm @uri, 'Basic', :basic
@agent.request_auth @req, @uri
assert_match %r%^Basic %, @req['Authorization']
end
def test_request_auth_digest
@agent.add_auth @uri, 'user', 'password'
realm = auth_realm @uri, 'Digest', :digest
@agent.digest_challenges[realm] = 'Digest realm=r, qop="auth"'
@agent.request_auth @req, @uri
assert_match %r%^Digest %, @req['Authorization']
assert_match %r%qop=auth%, @req['Authorization']
@req['Authorization'] = nil
@agent.request_auth @req, @uri
assert_match %r%^Digest %, @req['Authorization']
assert_match %r%qop=auth%, @req['Authorization']
end
def test_request_auth_iis_digest
@agent.add_auth @uri, 'user', 'password'
realm = auth_realm @uri, 'Digest', :digest
@agent.digest_challenges[realm] = 'Digest realm=r, qop="auth"'
@agent.request_auth @req, @uri
assert_match %r%^Digest %, @req['Authorization']
assert_match %r%qop=auth%, @req['Authorization']
end
def test_request_auth_none
@agent.request_auth @req, @uri
assert_nil @req['Authorization']
end
def test_request_cookies
uri = URI.parse 'http://host.example.com'
@agent.cookie_jar.parse 'hello=world domain=.example.com', uri
@agent.request_cookies @req, uri
assert_equal 'hello="world domain=.example.com"', @req['Cookie']
end
def test_request_cookies_many
uri = URI.parse 'http://host.example.com'
cookie_str = 'a=b domain=.example.com, c=d domain=.example.com'
@agent.cookie_jar.parse cookie_str, uri
@agent.request_cookies @req, uri
expected_variant1 = /a="b domain=\.example\.com"; c="d domain=\.example\.com"/
expected_variant2 = /c="d domain=\.example\.com"; a="b domain=\.example\.com"/
assert_match(/^(#{expected_variant1}|#{expected_variant2})$/, @req['Cookie'])
end
def test_request_cookies_none
@agent.request_cookies @req, @uri
assert_nil @req['Cookie']
end
def test_request_cookies_wrong_domain
uri = URI.parse 'http://host.example.com'
@agent.cookie_jar.parse 'hello=world domain=.example.com', uri
@agent.request_cookies @req, @uri
assert_nil @req['Cookie']
end
def test_request_host
@agent.request_host @req, @uri
assert_equal 'example', @req['host']
end
def test_request_host_nonstandard
@uri.port = 81
@agent.request_host @req, @uri
assert_equal 'example:81', @req['host']
end
def test_request_language_charset
@agent.request_language_charset @req
assert_equal('en-us,en;q=0.5', @req['accept-language'])
assert_nil(@req['accept-charset'])
end
def test_request_referer
referer = URI.parse 'http://old.example'
@agent.request_referer @req, @uri, referer
assert_equal 'http://old.example', @req['referer']
end
def test_request_referer_https
uri = URI.parse 'https://example'
referer = URI.parse 'https://old.example'
@agent.request_referer @req, uri, referer
assert_equal 'https://old.example', @req['referer']
end
def test_request_referer_https_downgrade
referer = URI.parse 'https://old.example'
@agent.request_referer @req, @uri, referer
assert_nil @req['referer']
end
def test_request_referer_https_downgrade_case
uri = URI.parse 'http://example'
referer = URI.parse 'httpS://old.example'
@agent.request_referer @req, uri, referer
assert_nil @req['referer']
end
def test_request_referer_https_upgrade
uri = URI.parse 'https://example'
referer = URI.parse 'http://old.example'
@agent.request_referer @req, uri, referer
assert_equal 'http://old.example', @req['referer']
end
def test_request_referer_none
@agent.request_referer @req, @uri, nil
assert_nil @req['referer']
end
def test_request_referer_strip
uri = URI.parse 'http://example.com/index.html'
host_path = "old.example/page.html?q=x"
referer = "http://#{host_path}"
[
"",
"@",
"user1@",
":@",
"user1:@",
":password1@",
"user1:password1@",
].each { |userinfo|
['', '#frag'].each { |frag|
url = URI.parse "http://#{userinfo}#{host_path}#{frag}"
@agent.request_referer @req, uri, url
assert_equal referer, @req['referer'], url
}
}
end
def test_request_user_agent
@agent.request_user_agent @req
assert_match %r%^Mechanize/#{Mechanize::VERSION}%, @req['user-agent']
ruby_version = if RUBY_PATCHLEVEL >= 0 then
"#{RUBY_VERSION}p#{RUBY_PATCHLEVEL}"
else
"#{RUBY_VERSION}dev#{RUBY_REVISION}"
end
assert_match %r%Ruby/#{ruby_version}%, @req['user-agent']
end
def test_resolve_bad_uri
e = assert_raises ArgumentError do
@agent.resolve 'google'
end
assert_equal 'absolute URL needed (not google)', e.message
end
def test_resolve_uri_without_path
e = assert_raises ArgumentError do
@agent.resolve 'http:%5C%5Cfoo'
end
assert_equal 'hierarchical URL needed (not http:%5C%5Cfoo)', e.message
end
def test_resolve_utf8
uri = 'http://example?q=ü'
resolved = @agent.resolve uri
assert_equal '/?q=%C3%BC', resolved.request_uri
end
def test_resolve_parameters_body
input_params = { :q => 'hello' }
uri, params = @agent.resolve_parameters @uri, :post, input_params
assert_equal 'http://example/', uri.to_s
assert_equal input_params, params
end
def test_resolve_parameters_query
uri, params = @agent.resolve_parameters @uri, :get, :q => 'hello'
assert_equal 'http://example/?q=hello', uri.to_s
assert_nil params
end
def test_resolve_parameters_query_append
input_params = { :q => 'hello' }
@uri.query = 'a=b'
uri, params = @agent.resolve_parameters @uri, :get, input_params
assert_equal 'http://example/?a=b&q=hello', uri.to_s
assert_nil params
end
def test_resolve_slashes
page = Mechanize::Page.new URI('http://example/foo/'), nil, '', 200, @mech
uri = '/bar/http://example/test/'
resolved = @agent.resolve uri, page
assert_equal 'http://example/bar/http://example/test/', resolved.to_s
end
def test_response_authenticate
@agent.add_auth @uri, 'user', 'password'
@res.instance_variable_set :@header, 'www-authenticate' => ['Basic realm=r']
@agent.response_authenticate @res, nil, @uri, @req, {}, nil, nil
base_uri = @uri + '/'
realm = Mechanize::HTTP::AuthRealm.new 'Basic', base_uri, 'r'
assert_equal [realm], @agent.authenticate_methods[base_uri][:basic]
end
def test_response_authenticate_digest
@agent.add_auth @uri, 'user', 'password'
@res.instance_variable_set(:@header,
'www-authenticate' => ['Digest realm=r'])
@agent.response_authenticate @res, nil, @uri, @req, {}, nil, nil
base_uri = @uri + '/'
realm = Mechanize::HTTP::AuthRealm.new 'Digest', base_uri, 'r'
assert_equal [realm], @agent.authenticate_methods[base_uri][:digest]
challenge = Mechanize::HTTP::AuthChallenge.new('Digest',
{ 'realm' => 'r' },
'Digest realm=r')
assert_equal challenge, @agent.digest_challenges[realm]
end
def test_response_authenticate_digest_iis
@agent.add_auth @uri, 'user', 'password'
@res.instance_variable_set(:@header,
'www-authenticate' => ['Digest realm=r'],
'server' => ['Microsoft-IIS'])
@agent.response_authenticate @res, nil, @uri, @req, {}, nil, nil
base_uri = @uri + '/'
realm = Mechanize::HTTP::AuthRealm.new 'Digest', base_uri, 'r'
assert_equal [realm], @agent.authenticate_methods[base_uri][:iis_digest]
end
def test_response_authenticate_multiple
@agent.add_auth @uri, 'user', 'password'
@res.instance_variable_set(:@header,
'www-authenticate' =>
['Basic realm=r, Digest realm=r'])
@agent.response_authenticate @res, nil, @uri, @req, {}, nil, nil
base_uri = @uri + '/'
realm = Mechanize::HTTP::AuthRealm.new 'Digest', base_uri, 'r'
assert_equal [realm], @agent.authenticate_methods[base_uri][:digest]
assert_empty @agent.authenticate_methods[base_uri][:basic]
end
def test_response_authenticate_no_credentials
@res.instance_variable_set :@header, 'www-authenticate' => ['Basic realm=r']
e = assert_raises Mechanize::UnauthorizedError do
@agent.response_authenticate @res, fake_page, @uri, @req, {}, nil, nil
end
assert_match 'no credentials', e.message
assert_match 'available realms: r', e.message
end
def test_response_authenticate_no_www_authenticate
@agent.add_auth @uri, 'user', 'password'
denied_uri = URI('http://example/denied')
denied = page denied_uri, 'text/html', '', 401
e = assert_raises Mechanize::UnauthorizedError do
@agent.response_authenticate @res, denied, @uri, @req, {}, nil, nil
end
assert_equal "401 => Net::HTTPUnauthorized for #{denied_uri} -- " \
"WWW-Authenticate header missing in response",
e.message
end
def test_response_authenticate_ntlm
@uri += '/ntlm'
@agent.add_auth @uri, 'user', 'password'
@res.instance_variable_set(:@header,
'www-authenticate' => ['Negotiate, NTLM'])
begin
page = @agent.response_authenticate @res, nil, @uri, @req, {}, nil, nil
rescue OpenSSL::Digest::DigestError
skip "It looks like OpenSSL is not configured to support MD4"
end
assert_equal 'ok', page.body # lame test
end
def test_response_authenticate_unknown
@agent.add_auth @uri, 'user', 'password'
page = Mechanize::File.new nil, nil, nil, 401
@res.instance_variable_set(:@header,
'www-authenticate' => ['Unknown realm=r'])
assert_raises Mechanize::UnauthorizedError do
@agent.response_authenticate @res, page, @uri, @req, nil, nil, nil
end
end
def test_response_content_encoding_7_bit
@res.instance_variable_set :@header, 'content-encoding' => %w[7bit]
body = @agent.response_content_encoding @res, StringIO.new('part')
assert_equal 'part', body.read
end
def test_response_content_encoding_deflate
@res.instance_variable_set :@header, 'content-encoding' => %w[deflate]
body_io = StringIO.new "x\x9C+H,*\x01\x00\x04?\x01\xB8"
body = @agent.response_content_encoding @res, body_io
assert_equal 'part', body.read
assert body_io.closed?
end
def test_response_content_encoding_deflate_chunked
@res.instance_variable_set :@header, 'content-encoding' => %w[deflate]
body_io = StringIO.new "x\x9C+H,*\x01\x00\x04?\x01\xB8"
body = @agent.response_content_encoding @res, body_io
assert_equal 'part', body.read
end
def test_response_content_encoding_deflate_corrupt
@res.instance_variable_set :@header, 'content-encoding' => %w[deflate]
body_io = StringIO.new "x\x9C+H,*\x01\x00\x04?\x01" # missing 1 byte
e = assert_raises Mechanize::Error do
@agent.response_content_encoding @res, body_io
end
assert_match %r%error handling content-encoding deflate:%, e.message
assert_match %r%Zlib%, e.message
assert body_io.closed?
end
def test_response_content_encoding_deflate_empty
@res.instance_variable_set :@header, 'content-encoding' => %w[deflate]
body = @agent.response_content_encoding @res, StringIO.new
assert_equal '', body.read
end
# IIS/6.0 ASP.NET/2.0.50727 does not wrap deflate with zlib, WTF?
def test_response_content_encoding_deflate_no_zlib
@res.instance_variable_set :@header, 'content-encoding' => %w[deflate]
body = @agent.response_content_encoding @res, StringIO.new("+H,*\001\000")
assert_equal 'part', body.read
end
def test_response_content_encoding_gzip
@res.instance_variable_set :@header, 'content-encoding' => %w[gzip]
body_io = StringIO.new \
"\037\213\b\0002\002\225M\000\003+H,*\001\000\306p\017I\004\000\000\000"
body = @agent.response_content_encoding @res, body_io
assert_equal 'part', body.read
assert body_io.closed?
end
def test_response_content_encoding_gzip_chunked
def @res.content_length() nil end
@res.instance_variable_set :@header, 'content-encoding' => %w[gzip]
body_io = StringIO.new \
"\037\213\b\0002\002\225M\000\003+H,*\001\000\306p\017I\004\000\000\000"
body = @agent.response_content_encoding @res, body_io
assert_equal 'part', body.read
end
def test_response_content_encoding_brotli_when_brotli_not_loaded
skip("only test this on jruby which doesn't have brotli support") unless RUBY_ENGINE == 'jruby'
@res.instance_variable_set :@header, 'content-encoding' => %w[br]
body_io = StringIO.new("content doesn't matter for this test")
e = assert_raises(Mechanize::Error) do
@agent.response_content_encoding(@res, body_io)
end
assert_includes(e.message, "cannot deflate brotli-encoded response")
assert(body_io.closed?)
end
def test_response_content_encoding_brotli
skip("jruby does not have brotli support") if RUBY_ENGINE == 'jruby'
@res.instance_variable_set :@header, 'content-encoding' => %w[br]
body_io = StringIO.new(Brotli.deflate("this is compressed by brotli"))
body = @agent.response_content_encoding(@res, body_io)
assert_equal("this is compressed by brotli", body.read)
assert(body_io.closed?)
end
def test_response_content_encoding_brotli_corrupt
skip("jruby does not have brotli support") if RUBY_ENGINE == 'jruby'
@res.instance_variable_set :@header, 'content-encoding' => %w[br]
body_io = StringIO.new("not a brotli payload")
e = assert_raises(Mechanize::Error) do
@agent.response_content_encoding(@res, body_io)
end
assert_includes(e.message, "error inflating brotli-encoded response")
assert_kind_of(Brotli::Error, e.cause)
assert(body_io.closed?)
end
def test_response_content_encoding_zstd_when_zstd_not_loaded
skip("only test this on jruby which doesn't have zstd support") unless RUBY_ENGINE == 'jruby'
@res.instance_variable_set :@header, 'content-encoding' => %w[zstd]
body_io = StringIO.new("content doesn't matter for this test")
e = assert_raises(Mechanize::Error) do
@agent.response_content_encoding(@res, body_io)
end
assert_includes(e.message, 'cannot deflate zstd-encoded response')
assert(body_io.closed?)
end
def test_response_content_encoding_zstd
skip('jruby does not have zstd support') if RUBY_ENGINE == 'jruby'
@res.instance_variable_set :@header, 'content-encoding' => %w[zstd]
body_io = StringIO.new(Zstd.compress('this is compressed by zstd'))
body = @agent.response_content_encoding(@res, body_io)
assert_equal('this is compressed by zstd', body.read)
assert(body_io.closed?)
end
def test_response_content_encoding_zstd_corrupt
skip('jruby does not have zstd support') if RUBY_ENGINE == 'jruby'
@res.instance_variable_set :@header, 'content-encoding' => %w[zstd]
body_io = StringIO.new('not a zstd payload')
e = assert_raises(Mechanize::Error) do
@agent.response_content_encoding(@res, body_io)
end
assert_includes(e.message, 'error decompressing zstd-encoded response')
assert_kind_of(RuntimeError, e.cause)
assert(body_io.closed?)
end
def test_response_content_encoding_gzip_corrupt
log = StringIO.new
logger = Logger.new log
@agent.context.log = logger
@res.instance_variable_set :@header, 'content-encoding' => %w[gzip]
body_io = StringIO.new \
"\037\213\b\0002\002\225M\000\003+H,*\001"
skip_if_jruby_zlib
e = assert_raises Mechanize::Error do
@agent.response_content_encoding @res, body_io
end
assert_match %r%error handling content-encoding gzip:%, e.message
assert_match %r%Zlib%, e.message
assert_match %r%unable to gunzip response: unexpected end of file%,
log.string
assert_match %r%unable to inflate response: buffer error%,
log.string
assert body_io.closed?
end
def test_response_content_encoding_gzip_checksum_corrupt_crc
log = StringIO.new
logger = Logger.new log
@agent.context.log = logger
@res.instance_variable_set :@header, 'content-encoding' => %w[gzip]
body_io = StringIO.new \
"\037\213\b\0002\002\225M\000\003+H,*\001\000\306p\017J\004\000\000\000"
body = @agent.response_content_encoding @res, body_io
assert_equal 'part', body.read
assert body_io.closed?
assert_match %r%invalid compressed data -- crc error%, log.string
rescue IOError
skip_if_jruby_zlib
raise
end
def test_response_content_encoding_gzip_checksum_corrupt_length
log = StringIO.new
logger = Logger.new log
@agent.context.log = logger
@res.instance_variable_set :@header, 'content-encoding' => %w[gzip]
body_io = StringIO.new \
"\037\213\b\0002\002\225M\000\003+H,*\001\000\306p\017I\005\000\000\000"
@agent.response_content_encoding @res, body_io
assert body_io.closed?
assert_match %r%invalid compressed data -- length error%, log.string
rescue IOError
skip_if_jruby_zlib
raise
end
def test_response_content_encoding_gzip_checksum_truncated
log = StringIO.new
logger = Logger.new log
@agent.context.log = logger
@res.instance_variable_set :@header, 'content-encoding' => %w[gzip]
body_io = StringIO.new \
"\037\213\b\0002\002\225M\000\003+H,*\001\000\306p\017I\004\000\000"
@agent.response_content_encoding @res, body_io
assert body_io.closed?
assert_match %r%unable to gunzip response: footer is not found%, log.string
rescue IOError
skip_if_jruby_zlib
raise
end
def test_response_content_encoding_gzip_empty
@res.instance_variable_set :@header, 'content-encoding' => %w[gzip]
body = @agent.response_content_encoding @res, StringIO.new
assert_equal '', body.read
end
def test_response_content_encoding_gzip_encoding_bad
@res.instance_variable_set(:@header,
'content-encoding' => %w[gzip],
'content-type' => 'text/html; charset=UTF-8')
# "test\xB2"
body_io = StringIO.new \
"\037\213\b\000*+\314N\000\003+I-.\331\004\000x\016\003\376\005\000\000\000"
body = @agent.response_content_encoding @res, body_io
expected = +"test\xB2"
expected.force_encoding Encoding::BINARY if have_encoding?
content = body.read
assert_equal expected, content
assert_equal Encoding::BINARY, content.encoding if have_encoding?
end
def test_response_content_encoding_gzip_no_footer
@res.instance_variable_set :@header, 'content-encoding' => %w[gzip]
body_io = StringIO.new \
"\037\213\b\0002\002\225M\000\003+H,*\001\000"
body = @agent.response_content_encoding @res, body_io
assert_equal 'part', body.read
assert body_io.closed?
rescue IOError
skip_if_jruby_zlib
raise
end
def test_response_content_encoding_none
@res.instance_variable_set :@header, 'content-encoding' => %w[none]
body = @agent.response_content_encoding @res, StringIO.new('part')
assert_equal 'part', body.read
end
def test_response_content_encoding_empty_string
@res.instance_variable_set :@header, 'content-encoding' => %w[]
body = @agent.response_content_encoding @res, StringIO.new('part')
assert_equal 'part', body.read
end
def test_response_content_encoding_identity
@res.instance_variable_set :@header, 'content-encoding' => %w[identity]
body = @agent.response_content_encoding @res, StringIO.new('part')
assert_equal 'part', body.read
end
def test_response_content_encoding_tempfile_7_bit
body_io = tempfile 'part'
@res.instance_variable_set :@header, 'content-encoding' => %w[7bit]
body = @agent.response_content_encoding @res, body_io
assert_equal 'part', body.read
refute body_io.closed?
ensure
begin
body_io.close! if body_io and not body_io.closed?
rescue IOError
# HACK for ruby 1.8
end
end
def test_response_content_encoding_tempfile_gzip
body_io = tempfile "x\x9C+H,*\x01\x00\x04?\x01\xB8"
@res.instance_variable_set :@header, 'content-encoding' => %w[deflate]
body = @agent.response_content_encoding @res, body_io
assert_equal 'part', body.read
assert body_io.closed?
ensure
body_io.close! if body_io and not body_io.closed?
end
def test_response_content_encoding_unknown
@res.instance_variable_set :@header, 'content-encoding' => %w[unknown]
body = StringIO.new 'part'
e = assert_raises Mechanize::Error do
@agent.response_content_encoding @res, body
end
assert_equal 'unsupported content-encoding: unknown', e.message
end
def test_response_content_encoding_x_gzip
@res.instance_variable_set :@header, 'content-encoding' => %w[x-gzip]
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | true |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_field.rb | test/test_mechanize_form_field.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormField < Mechanize::TestCase
def test_inspect
field = node 'input'
field = Mechanize::Form::Field.new field, 'a&b'
assert_match "value: a&b", field.inspect
end
def test_name
field = node 'input', 'name' => 'a&b'
field = Mechanize::Form::Field.new field
assert_equal 'a&b', field.name
end
def test_name_entity
field = node 'input', 'name' => 'a&b'
field = Mechanize::Form::Field.new field
assert_equal 'a&b', field.name
end
def test_name_entity_numeric
field = node 'input', 'name' => 'a&b'
field = Mechanize::Form::Field.new field
assert_equal 'a&b', field.name
end
def test_spaceship
doc = Nokogiri::HTML::Document.new
node = doc.create_element('input')
node['name'] = 'foo'
node['value'] = 'bar'
a = Mechanize::Form::Field.new(node)
b = Mechanize::Form::Field.new({'name' => 'foo'}, 'bar')
c = Mechanize::Form::Field.new({'name' => 'foo'}, 'bar')
assert_equal [a, b], [a, b].sort
assert_equal [a, b], [b, a].sort
assert_equal [b, c].sort, [b, c].sort
end
def test_value
field = node 'input'
field = Mechanize::Form::Field.new field, 'a&b'
assert_equal 'a&b', field.value
end
def test_value_entity
field = node 'input'
field = Mechanize::Form::Field.new field, 'a&b'
assert_equal 'a&b', field.value
end
def test_value_entity_numeric
field = node 'input'
field = Mechanize::Form::Field.new field, 'a&b'
assert_equal 'a&b', field.value
end
def test_raw_value
field = node 'input'
field = Mechanize::Form::Field.new field, 'a&b'
assert_equal 'a&b', field.raw_value
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_history.rb | test/test_mechanize_history.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeHistory < Mechanize::TestCase
def setup
super
@uri = URI 'http://example/'
@uri2 = @uri + '/a'
@history = Mechanize::History.new
end
def test_initialize
assert_empty @history
end
def test_clear
@history.push :page, @uri
@history.clear
assert_empty @history
end
def test_pop
assert_nil @history.pop
@history.push :page1, @uri
@history.push :page2, @uri2
assert_equal :page2, @history.pop
refute_empty @history
end
def test_push
p1 = page @uri
obj = @history.push p1
assert_same @history, obj
assert_equal 1, @history.length
p2 = page @uri2
@history.push p2
assert_equal 2, @history.length
end
def test_push_max_size
@history = Mechanize::History.new 2
@history.push :page1, @uri
assert_equal 1, @history.length
@history.push :page2, @uri
assert_equal 2, @history.length
@history.push :page3, @uri
assert_equal 2, @history.length
end
def test_push_uri
obj = @history.push :page, @uri
assert_same @history, obj
assert_equal 1, @history.length
@history.push :page2, @uri
assert_equal 2, @history.length
end
def test_shift
assert_nil @history.shift
@history.push :page1, @uri
@history.push :page2, @uri2
page = @history.shift
assert_equal :page1, page
refute_empty @history
@history.shift
assert_empty @history
end
def test_visited_eh
refute @history.visited? @uri
@history.push page @uri
assert @history.visited? URI('http://example')
assert @history.visited? URI('http://example/')
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_util.rb | test/test_mechanize_util.rb | # coding: utf-8
# frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeUtil < Mechanize::TestCase
INPUTTED_VALUE = "テスト" # "test" in Japanese UTF-8 encoding
CONTENT_ENCODING = 'Shift_JIS' # one of Japanese encoding
ENCODED_VALUE = "\x83\x65\x83\x58\x83\x67".dup.force_encoding(::Encoding::SHIFT_JIS) # "test" in Japanese Shift_JIS encoding
ENCODING_ERRORS = [EncodingError, Encoding::ConverterNotFoundError] # and so on
ERROR_LOG_MESSAGE = /from_native_charset: Encoding::ConverterNotFoundError: form encoding: "UTF-eight"/
INVALID_ENCODING = 'UTF-eight'
def setup
super
@MU = Mechanize::Util
@result = "not set"
end
def test_from_native_charset
@result = @MU.from_native_charset(INPUTTED_VALUE, CONTENT_ENCODING)
assert_equal ENCODED_VALUE, @result
end
def test_from_native_charset_returns_nil_when_no_string
@result = @MU.from_native_charset(nil, CONTENT_ENCODING)
assert_nil @result
end
def test_from_native_charset_doesnot_convert_when_no_encoding
@result = @MU.from_native_charset(INPUTTED_VALUE, nil)
refute_equal ENCODED_VALUE, @result
assert_equal INPUTTED_VALUE, @result
end
def test_from_native_charset_doesnot_convert_when_not_nokogiri
parser = Mechanize.html_parser
Mechanize.html_parser = 'Another HTML Parser'
@result = @MU.from_native_charset(INPUTTED_VALUE, CONTENT_ENCODING)
refute_equal ENCODED_VALUE, @result
assert_equal INPUTTED_VALUE, @result
ensure
Mechanize.html_parser = parser
end
def test_from_native_charset_raises_error_with_bad_encoding
assert_raises(*ENCODING_ERRORS) do
@MU.from_native_charset(INPUTTED_VALUE, INVALID_ENCODING)
end
end
def test_from_native_charset_suppress_encoding_error_when_3rd_arg_is_true
@MU.from_native_charset(INPUTTED_VALUE, INVALID_ENCODING, true)
# HACK no assertion
end
def test_from_native_charset_doesnot_convert_when_encoding_error_raised_and_ignored
@result = @MU.from_native_charset(INPUTTED_VALUE, INVALID_ENCODING, true)
refute_equal ENCODED_VALUE, @result
assert_equal INPUTTED_VALUE, @result
end
def test_from_native_charset_logs_form_when_encoding_error_raised
sio = StringIO.new
log = Logger.new(sio)
log.level = Logger::DEBUG
assert_raises(*ENCODING_ERRORS) do
@MU.from_native_charset(INPUTTED_VALUE, INVALID_ENCODING, nil, log)
end
assert_match ERROR_LOG_MESSAGE, sio.string
end
def test_from_native_charset_logs_form_when_encoding_error_is_ignored
sio = StringIO.new
log = Logger.new(sio)
log.level = Logger::DEBUG
@MU.from_native_charset(INPUTTED_VALUE, INVALID_ENCODING, true, log)
assert_match ERROR_LOG_MESSAGE, sio.string
end
def test_self_html_unescape_entity
assert_equal '&', @MU::html_unescape('&')
assert_equal '&', @MU::html_unescape('&')
end
def test_uri_escape
assert_equal "%25", @MU.uri_escape("%")
assert_equal "%", @MU.uri_escape("%", /[^%]/)
end
def test_build_query_string_simple
input_params = [
[:ids, 1],
[:action, 'delete'],
[:ids, 5],
]
expected_params = [
['ids', '1'],
['action', 'delete'],
['ids', '5'],
]
query = @MU.build_query_string(input_params)
assert_equal expected_params, URI.decode_www_form(query)
end
def test_build_query_string_complex
input_params = {
number: 7,
name: "\u{6B66}\u{8005}",
"ids[]" => [1, 3, 5, 7],
words: ["Sing", "Now!"],
params: { x: "50%", y: "100%", t: [80, 160] },
}
expected_params = [
['number', '7'],
['name', "\u{6B66}\u{8005}"],
['ids[]', '1'], ['ids[]', '3'], ['ids[]', '5'], ['ids[]', '7'],
['words', 'Sing'], ['words', 'Now!'],
['params[x]', '50%'],
['params[y]', '100%'],
['params[t]', '80'], ['params[t]', '160'],
]
query = @MU.build_query_string(input_params)
assert_equal expected_params, URI.decode_www_form(query)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_headers.rb | test/test_mechanize_headers.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeHeaders < Mechanize::TestCase
def setup
super
@headers = Mechanize::Headers.new
@headers['content-type'] = 'text/html'
@headers['Content-encoding'] = 'gzip'
@headers['SERVER'] = 'Apache/2.2'
end
def test_aref
assert_equal('Apache/2.2', @headers['server'])
assert_equal('text/html', @headers['Content-Type'])
end
def test_key?
assert_equal(true, @headers.key?('content-Encoding'))
end
def test_canonical_each
all_keys = ['Content-Type', 'Content-Encoding', 'Server']
keys = all_keys.dup
@headers.canonical_each { |key, value|
case keys.delete(key)
when *all_keys
# ok
else
flunk "unexpected key: #{key}"
end
}
assert_equal([], keys)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_encoding.rb | test/test_mechanize_form_encoding.rb | # coding: utf-8
# frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormEncoding < Mechanize::TestCase
# See also: tests of Util.from_native_charset
# Encoding test should do with non-utf-8 characters
INPUTTED_VALUE = "テスト" # "test" in Japanese UTF-8 encoding
CONTENT_ENCODING = 'Shift_JIS' # one of Japanese encoding
encoded_value = "\x83\x65\x83\x58\x83\x67".dup.force_encoding(::Encoding::SHIFT_JIS) # "test" in Japanese Shift_JIS encoding
EXPECTED_QUERY = "first_name=#{CGI.escape(encoded_value)}&first_name=&gender=&green%5Beggs%5D="
ENCODING_ERRORS = [EncodingError, Encoding::ConverterNotFoundError] # and so on
ENCODING_LOG_MESSAGE = /INFO -- : form encoding: Shift_JIS/
INVALID_ENCODING = 'UTF-eight'
def set_form_with_encoding(enc)
page = @mech.get("http://localhost/form_set_fields.html")
form = page.forms.first
form.encoding = enc
form['first_name'] = INPUTTED_VALUE
form
end
def test_form_encoding_returns_accept_charset
page = @mech.get("http://localhost/rails_3_encoding_hack_form_test.html")
form = page.forms.first
accept_charset = form.form_node['accept-charset']
assert accept_charset
assert_equal accept_charset, form.encoding
refute_equal page.encoding, form.encoding
end
def test_form_encoding_returns_page_encoding_when_no_accept_charset
page = @mech.get("http://localhost/form_set_fields.html")
form = page.forms.first
accept_charset = form.form_node['accept-charset']
assert_nil accept_charset
refute_equal accept_charset, form.encoding
assert_equal page.encoding, form.encoding
end
def test_form_encoding_equals_sets_new_encoding
page = @mech.get("http://localhost/form_set_fields.html")
form = page.forms.first
refute_equal CONTENT_ENCODING, form.encoding
form.encoding = CONTENT_ENCODING
assert_equal CONTENT_ENCODING, form.encoding
end
def test_form_encoding_returns_nil_when_no_page_in_initialize
# this sequence is seen at Mechanize#post(url, query_hash)
node = {}
# Create a fake form
class << node
def search(*args); []; end
end
node['method'] = 'POST'
node['enctype'] = 'application/x-www-form-urlencoded'
form = Mechanize::Form.new(node)
assert_nil form.encoding
end
def test_post_form_with_form_encoding
form = set_form_with_encoding CONTENT_ENCODING
form.submit
# we can not use "links.find{|l| l.text == 'key:val'}" assertion here
# because the link text encoding is always UTF-8 regaredless of html encoding
assert EXPECTED_QUERY, @mech.page.at('div#query').inner_text
end
def test_post_form_with_problematic_encoding
form = set_form_with_encoding INVALID_ENCODING
assert_raises(*ENCODING_ERRORS){ form.submit }
end
def test_form_ignore_encoding_error_is_true
form = set_form_with_encoding INVALID_ENCODING
form.ignore_encoding_error = true
form.submit
# HACK no assertions
end
def test_post_form_logs_form_encoding
sio = StringIO.new
@mech.log = Logger.new(sio)
@mech.log.level = Logger::INFO
form = set_form_with_encoding CONTENT_ENCODING
form.submit
assert_match ENCODING_LOG_MESSAGE, sio.string
@mech.log = nil
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize.rb | test/test_mechanize.rb | # coding: utf-8
# frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanize < Mechanize::TestCase
def setup
super
@uri = URI 'http://example/'
@req = Net::HTTP::Get.new '/'
@res = Net::HTTPOK.allocate
@res.instance_variable_set :@code, 200
@res.instance_variable_set :@header, {}
end
def test_back
0.upto(5) do |i|
assert_equal(i, @mech.history.size)
@mech.get("http://localhost/")
end
@mech.get("http://localhost/form_test.html")
assert_equal("http://localhost/form_test.html",
@mech.history.last.uri.to_s)
assert_equal("http://localhost/",
@mech.history[-2].uri.to_s)
assert_equal(7, @mech.history.size)
@mech.back
assert_equal(6, @mech.history.size)
assert_equal("http://localhost/",
@mech.history.last.uri.to_s)
end
def test_basic_auth
_, err = capture_io do
@mech.basic_auth 'user', 'pass' # warns
end
line = __LINE__ - 3
file = File.basename __FILE__
assert_match "#{file} line #{line}", err
page = @mech.get @uri + '/basic_auth'
assert_equal 'You are authenticated', page.body
end
def test_cert_key_file
in_tmpdir do
open 'key.pem', 'w' do |io| io.write ssl_private_key.to_pem end
open 'cert.pem', 'w' do |io| io.write ssl_certificate.to_pem end
mech = Mechanize.new do |a|
a.cert = 'cert.pem'
a.key = 'key.pem'
end
# Certificate#== seems broken
assert_equal ssl_certificate.to_pem, mech.certificate.to_pem
end
end
def test_cert_key_object
mech = Mechanize.new do |a|
a.cert = ssl_certificate
a.key = ssl_private_key
end
assert_equal ssl_certificate, mech.certificate
assert_equal ssl_certificate, mech.cert
assert_equal ssl_private_key, mech.key
end
def test_cert_store
assert_nil @mech.cert_store
store = OpenSSL::X509::Store.new
@mech.cert_store = store
assert_equal store, @mech.cert_store
end
def test_click
@mech.user_agent_alias = 'Mac Safari'
page = @mech.get("http://localhost/frame_test.html")
link = page.link_with(:text => "Form Test")
page = @mech.click(link)
assert_equal("http://localhost/form_test.html",
@mech.history.last.uri.to_s)
end unless RUBY_ENGINE == 'jruby' # NekoHTML does not parse body of NOFRAMES
def test_click_bogus_link_with_cookies
@mech.cookie_jar = cookie_jar("a=b")
page = html_page <<-BODY
<a href="http:///index.html">yes really</a>
BODY
page.links[0].click
assert_equal '/index.html', requests.first.path
end
def test_click_image_button
page = @mech.get("http://localhost/form_test.html")
get_form = page.forms.find { |f| f.name == "get_form1" }
image_button = get_form.buttons.first
new_page = @mech.click(image_button)
assert_equal "http://localhost/form_post?first_name=&button.x=0&button.y=0", new_page.uri.to_s
end
def test_click_submit_button
page = @mech.get("http://localhost/form_test.html")
get_form = page.forms.find { |f| f.name == "get_form1" }
submit_button = get_form.submits.first
new_page = @mech.click(submit_button)
assert_equal "http://localhost/form_post?first_name=", new_page.uri.to_s
end
def test_click_frame
frame = node 'frame', 'src' => '/index.html'
frame = Mechanize::Page::Frame.new frame, @mech, fake_page
@mech.click frame
assert_equal '/index.html', requests.first.path
end
def test_click_frame_hpricot_style
page = @mech.get("http://localhost/frame_test.html")
link = (page/"//frame[@name='frame2']").first
page = @mech.click(link)
assert_equal("http://localhost/form_test.html",
@mech.history.last.uri.to_s)
end
def test_click_hpricot_style # HACK move to test_divide in Page
page = @mech.get("http://localhost/frame_test.html")
link = (page/"//a[@class='bar']").first
page = @mech.click(link)
assert_equal("http://localhost/form_test.html",
@mech.history.last.uri.to_s)
end unless RUBY_ENGINE == 'jruby' # NekoHTML does not parse body of NOFRAMES
def test_click_link
link = node 'a', 'href' => '/index.html'
link = Mechanize::Page::Link.new link, @mech, fake_page
@mech.click link
assert_equal '/index.html', requests.first.path
assert_equal 'http://fake.example/', requests.first['Referer']
end
def test_click_link_nofollow
page = html_page <<-BODY
<meta name="ROBOTS" content="nofollow">
<p>Do not follow <a href="/index.html">this</a> or <a href="/">this</a>!
BODY
page.links[0].click
page.links[1].click
@mech.robots = true
assert_raises Mechanize::RobotsDisallowedError do
page.links[0].click
end
assert_raises Mechanize::RobotsDisallowedError do
page.links[1].click
end
end
def test_click_link_noreferrer
link = node 'a', 'href' => '/index.html', 'rel' => 'noreferrer'
link = Mechanize::Page::Link.new link, @mech, fake_page
@mech.click link
assert_nil requests.first['referer']
end
def test_click_link_rel_nofollow
page = html_page <<-BODY
<p>You can follow <a href="/index.html">this link</a>
but not <a href="/" rel="me nofollow">this</a>!
BODY
page.links[0].click
page.links[1].click
@mech.robots = true
page.links[0].click
assert_raises Mechanize::RobotsDisallowedError do
page.links[1].click
end
end
def test_click_link_parent
page = page URI 'http://example/a/index.html'
link = node 'a', 'href' => '../index.html'
link = Mechanize::Page::Link.new link, @mech, page
@mech.click link
assert_equal '/index.html', requests.first.path
end
def test_click_link_parent_extra
page = page URI 'http://example/a/index.html'
link = node 'a', 'href' => '../../index.html'
link = Mechanize::Page::Link.new link, @mech, page
@mech.click link
assert_equal '/index.html', requests.first.path
end
def test_click_link_hpricot_style # HACK move to test_search in Page
page = @mech.get("http://localhost/tc_encoded_links.html")
page = @mech.click(page.search('a').first)
assert_equal("http://localhost/form_post?a=b&b=c", page.uri.to_s)
end
def test_click_link_query
page = @mech.get("http://localhost/tc_encoded_links.html")
link = page.links.first
assert_equal('/form_post?a=b&b=c', link.href)
page = @mech.click(link)
assert_equal("http://localhost/form_post?a=b&b=c", page.uri.to_s)
end
def test_click_link_space
page = @mech.get("http://localhost/tc_bad_links.html")
@mech.click page.links.first
assert_match(/alt_text.html$/, @mech.history.last.uri.to_s)
assert_equal(2, @mech.history.length)
end
def test_click_more
@mech.get 'http://localhost/test_click.html'
@mech.click 'A Button'
assert_equal 'http://localhost/frame_test.html?words=nil',
@mech.page.uri.to_s
@mech.back
@mech.click 'A Link'
assert_equal 'http://localhost/index.html',
@mech.page.uri.to_s
@mech.back
@mech.click @mech.page.link_with(:text => 'A Link')
assert_equal 'http://localhost/index.html',
@mech.page.uri.to_s
end
def test_cookies
uri = URI 'http://example'
jar = HTTP::CookieJar.new
jar.parse 'a=b', uri
@mech.cookie_jar = jar
refute_empty @mech.cookies
end
def test_cookie_jar
assert_kind_of Mechanize::CookieJar, @mech.cookie_jar
jar = HTTP::CookieJar.new
@mech.cookie_jar = jar
assert_equal jar, @mech.cookie_jar
end
def test_delete
page = @mech.delete('http://localhost/verb', { 'q' => 'foo' })
assert_equal 1, @mech.history.length
assert_equal 'DELETE', page.header['X-Request-Method']
end
def test_delete_redirect
page = @mech.delete('http://localhost/redirect')
assert_equal(page.uri.to_s, 'http://localhost/verb')
assert_equal 'GET', page.header['X-Request-Method']
end
def test_download
page = nil
in_tmpdir do
open 'download', 'w' do |io|
page = @mech.download 'http://example', io
refute io.closed?
end
assert_operator 1, :<=, File.stat('download').size
end
assert_empty @mech.history
assert_kind_of Mechanize::Page, page
end
def test_download_filename
page = nil
in_tmpdir do
page = @mech.download 'http://example', 'download'
assert_operator 1, :<=, File.stat('download').size
end
assert_empty @mech.history
assert_kind_of Mechanize::Page, page
end
def test_download_filename_error
in_tmpdir do
assert_raises Mechanize::UnauthorizedError do
@mech.download 'http://example/digest_auth', 'download'
end
refute File.exist? 'download'
end
end
def test_download_does_not_allow_command_injection
skip if windows?
in_tmpdir do
@mech.download('http://example', '| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\'')
refute_operator(File, :exist?, "vul.txt")
end
end
def test_get
uri = URI 'http://localhost'
page = @mech.get uri, { :q => 'h' }, 'http://example', { 'X-H' => 'v' }
assert_equal URI('http://localhost/?q=h'), page.uri
assert_equal URI('http://localhost'), uri
end
def test_get_HTTP
page = @mech.get('HTTP://localhost/', { :q => 'hello' })
assert_kind_of URI::HTTP, page.uri
assert_equal 'localhost', page.uri.host
assert_equal 80, page.uri.port
assert_equal '/?q=hello', page.uri.request_uri
end
def test_get_anchor
page = @mech.get('http://localhost/?foo=bar"')
assert_equal('http://localhost/?foo=bar%22', page.uri.to_s)
end
def test_get_bad_url
assert_raises ArgumentError do
@mech.get '/foo.html'
end
end
def test_get_auth
@mech.add_auth @uri, 'user', 'pass'
page = @mech.get @uri + '/basic_auth'
assert_equal 'You are authenticated', page.body
end
def test_get_auth_bad
@mech.add_auth(@uri, 'aaron', 'aaron')
e = assert_raises Mechanize::UnauthorizedError do
@mech.get(@uri + '/basic_auth')
end
assert_equal("401", e.response_code)
end
def test_get_auth_none
e = assert_raises Mechanize::UnauthorizedError do
@mech.get(@uri + '/basic_auth')
end
assert_equal("401", e.response_code)
end
def test_get_auth_realm
@mech.add_auth @uri, 'user', 'pass', 'Blah'
page = @mech.get @uri + '/basic_auth'
assert_equal 'You are authenticated', page.body
end
def test_get_conditional
assert_empty @mech.history
page = @mech.get 'http://localhost/if_modified_since'
assert_match(/You did not send/, page.body)
assert_equal 1, @mech.history.length
page2 = @mech.get 'http://localhost/if_modified_since'
assert_equal 2, @mech.history.length
assert_equal page.object_id, page2.object_id
end
def test_get_digest_auth
@mech.add_auth @uri, 'user', 'pass'
page = @mech.get @uri + '/digest_auth'
assert_equal 'You are authenticated', page.body
end
def test_get_follow_meta_refresh
@mech.follow_meta_refresh = true
page = @mech.get('http://localhost/tc_follow_meta.html')
assert_equal(2, @mech.history.length)
assert_equal('http://localhost/tc_follow_meta.html',
@mech.history.first.uri.to_s)
assert_equal('http://localhost/index.html', page.uri.to_s)
assert_equal('http://localhost/index.html', @mech.history.last.uri.to_s)
[5, 6].each { |limit|
@mech.redirection_limit = limit
begin
@mech.get('http://localhost/tc_follow_meta_loop_1.html')
rescue => e
assert_instance_of Mechanize::RedirectLimitReachedError, e
assert_equal limit, e.redirects
if limit % 2 == 0
assert_equal '/tc_follow_meta_loop_1.html', e.page.uri.path
else
assert_equal '/tc_follow_meta_loop_2.html', e.page.uri.path
end
end
}
end
def test_get_follow_meta_refresh_anywhere
@mech.follow_meta_refresh = :anywhere
@mech.get('http://localhost/tc_meta_in_body.html')
assert_equal 2, requests.length
end
def test_get_follow_meta_refresh_disabled
page = @mech.get('http://localhost/tc_follow_meta.html')
assert_equal('http://localhost/tc_follow_meta.html', page.uri.to_s)
assert_equal(1, page.meta_refresh.length)
end
def test_get_follow_meta_refresh_empty_url
@mech.follow_meta_refresh = true
@mech.follow_meta_refresh_self = true
page = @mech.get('http://example/refresh_with_empty_url')
assert_equal(3, @mech.history.length)
assert_equal('http://example/refresh_with_empty_url',
@mech.history[0].uri.to_s)
assert_equal('http://example/refresh_with_empty_url',
@mech.history[1].uri.to_s)
assert_equal('http://example/', page.uri.to_s)
assert_equal('http://example/', @mech.history.last.uri.to_s)
end
def test_get_follow_meta_refresh_in_body
@mech.follow_meta_refresh = true
@mech.get('http://localhost/tc_meta_in_body.html')
assert_equal 1, requests.length
end
def test_get_follow_meta_refresh_no_url
@mech.follow_meta_refresh = true
@mech.follow_meta_refresh_self = true
page = @mech.get('http://example/refresh_without_url')
assert_equal(3, @mech.history.length)
assert_equal('http://example/refresh_without_url',
@mech.history[0].uri.to_s)
assert_equal('http://example/refresh_without_url',
@mech.history[1].uri.to_s)
assert_equal('http://example/', page.uri.to_s)
assert_equal('http://example/', @mech.history.last.uri.to_s)
end
def test_get_follow_meta_refresh_referer_not_sent
@mech.follow_meta_refresh = true
@mech.get('http://localhost/tc_follow_meta.html')
assert_equal 2, @mech.history.length
assert_nil requests.last['referer']
end
def test_get_referer_download
download = Mechanize::Download.new URI 'http://example/prev'
uri = URI 'http://example'
page = @mech.get uri, { :q => 'h' }, download, { 'X-H' => 'v' }
assert_equal URI('http://example/?q=h'), page.uri
assert_equal URI('http://example'), uri
assert_equal 'http://example/prev', requests.first['referer']
end
def test_get_robots
@mech.robots = true
assert_equal "Page Title", @mech.get("http://localhost/index.html").title
assert_raises Mechanize::RobotsDisallowedError do
@mech.get "http://localhost/norobots.html"
end
end
def test_follow_meta_refresh_self
refute @mech.agent.follow_meta_refresh_self
@mech.follow_meta_refresh_self = true
assert @mech.agent.follow_meta_refresh_self
end
def test_get_gzip
page = @mech.get("http://localhost/gzip?file=index.html")
assert_kind_of(Mechanize::Page, page)
assert_match('Hello World', page.body)
end
def test_content_encoding_hooks_header
h = {'X-ResponseContentEncoding' => 'agzip'}
# test of X-ResponseContentEncoding feature
assert_raises(Mechanize::Error, 'Unsupported Content-Encoding: agzip') do
@mech.get("http://localhost/gzip?file=index.html", nil, nil, h)
end
@mech.content_encoding_hooks << lambda{|agent, uri, response, response_body_io|
response['content-encoding'] = 'gzip' if response['content-encoding'] == 'agzip'}
page = @mech.get("http://localhost/gzip?file=index.html", nil, nil, h)
assert_match('Hello World', page.body)
end
def external_cmd(io); Zlib::GzipReader.new(io).read; end
def test_content_encoding_hooks_body_io
h = {'X-ResponseContentEncoding' => 'unsupported_content_encoding'}
@mech.content_encoding_hooks << lambda{|agent, uri, response, response_body_io|
if response['content-encoding'] == 'unsupported_content_encoding'
response['content-encoding'] = 'none'
response_body_io.string = external_cmd(response_body_io)
end}
page = @mech.get("http://localhost/gzip?file=index.html", nil, nil, h)
assert_match('Hello World', page.body)
end
def test_get_http_refresh
@mech.follow_meta_refresh = true
page = @mech.get('http://example/http_refresh?refresh_time=0')
assert_equal('http://example/', page.uri.to_s)
assert_equal(2, @mech.history.length)
assert_nil requests.last['referer']
end
def test_get_http_refresh_delay
@mech.follow_meta_refresh = true
class << @mech.agent
attr_accessor :slept
def sleep *args
@slept = args
end
end
@mech.get('http://localhost/http_refresh?refresh_time=1')
assert_equal [1], @mech.agent.slept
end
def test_get_http_refresh_disabled
page = @mech.get('http://localhost/http_refresh?refresh_time=0')
assert_equal('http://localhost/http_refresh?refresh_time=0', page.uri.to_s)
end
def test_get_query
page = @mech.get('http://localhost/', { :q => 'hello' })
assert_equal('http://localhost/?q=hello', page.uri.to_s)
page = @mech.get('http://localhost/', { :q => %w[hello world]})
assert_equal('http://localhost/?q=hello&q=world', page.uri.to_s)
page = @mech.get('http://localhost/', { :paging => { start: 1, limit: 25 } })
assert_equal('http://localhost/?paging%5Bstart%5D=1&paging%5Blimit%5D=25', page.uri.to_s)
end
def test_get_redirect
page = @mech.get('http://localhost/redirect')
assert_equal(page.uri.to_s, 'http://localhost/verb')
assert_equal 'GET', page.header['X-Request-Method']
end
def test_get_redirect_found
page = @mech.get('http://localhost/response_code?code=302&ct=test/xml')
assert_equal('http://localhost/index.html', page.uri.to_s)
assert_equal(2, @mech.history.length)
end
def test_get_redirect_infinite
assert_raises(Mechanize::RedirectLimitReachedError) {
@mech.get('http://localhost/infinite_refresh')
}
end
def test_get_referer
request = nil
@mech.pre_connect_hooks << lambda { |_, req|
request = req
}
@mech.get('http://localhost/', [], 'http://tenderlovemaking.com/')
assert_equal 'http://tenderlovemaking.com/', request['Referer']
end
def test_get_referer_file
uri = URI 'http://tenderlovemaking.com/crossdomain.xml'
file = Mechanize::File.new uri
@mech.get('http://localhost', [], file)
# HACK no assertion of behavior
end
def test_get_referer_none
@mech.get('http://localhost/')
@mech.get('http://localhost/')
assert_equal(2, requests.length)
requests.each do |request|
assert_nil request['referer']
end
end
def test_get_scheme_unsupported
assert_raises Mechanize::UnsupportedSchemeError do
begin
@mech.get('ftp://server.com/foo.html')
rescue Mechanize::UnsupportedSchemeError => error
assert_equal 'ftp', error.scheme
assert_equal 'ftp://server.com/foo.html', error.uri.to_s
raise
end
end
end
def test_get_space
@mech.get("http://localhost/tc_bad_links.html ")
assert_match(/tc_bad_links.html$/, @mech.history.last.uri.to_s)
assert_equal(1, @mech.history.length)
end
def test_get_tilde
page = @mech.get('http://localhost/?foo=~2')
assert_equal('http://localhost/?foo=~2', page.uri.to_s)
end
def test_get_weird
@mech.get('http://localhost/?action=bing&bang=boom=1|a=|b=|c=')
@mech.get('http://localhost/?a=b&b=c&c=d')
@mech.get("http://localhost/?a=#{[0xd6].pack('U')}")
# HACK no assertion of behavior
end
def test_get_yield
pages = nil
@mech.get("http://localhost/file_upload.html") { |page|
pages = page
}
assert pages
assert_equal('File Upload Form', pages.title)
end
def test_get_file
body = @mech.get_file 'http://localhost/frame_test.html'
assert_kind_of String, body
refute_empty body
end
def test_get_file_download
# non-Mechanize::File
body = @mech.get_file 'http://localhost/button.jpg'
assert_kind_of String, body
refute_empty body
end
def test_head
page = @mech.head('http://localhost/verb', { 'q' => 'foo' })
assert_equal 0, @mech.history.length
assert_equal 'HEAD', page.header['X-Request-Method']
end
def test_head_redirect
page = @mech.head('http://localhost/redirect')
assert_equal(page.uri.to_s, 'http://localhost/verb')
assert_equal 'HEAD', page.header['X-Request-Method']
end
def test_history
2.times do |i|
assert_equal(i, @mech.history.size)
@mech.get("http://localhost/")
end
page = @mech.get("http://localhost/form_test.html")
assert_equal("http://localhost/form_test.html",
@mech.history.last.uri.to_s)
assert_equal("http://localhost/",
@mech.history[-2].uri.to_s)
assert @mech.visited?("http://localhost/")
assert @mech.visited?("/form_test.html"), 'relative'
assert !@mech.visited?("http://google.com/")
assert @mech.visited?(page.links.first)
end
def test_history_added_gets_called
added_page = nil
@mech.history_added = lambda { |page|
added_page = page
}
assert_equal @mech.get('http://localhost/tc_blank_form.html'), added_page
end
def test_history_order
@mech.max_history = 2
assert_equal(0, @mech.history.length)
@mech.get('http://localhost/form_test.html')
assert_equal(1, @mech.history.length)
@mech.get('http://localhost/empty_form.html')
assert_equal(2, @mech.history.length)
@mech.get('http://localhost/tc_checkboxes.html')
assert_equal(2, @mech.history.length)
assert_equal('http://localhost/empty_form.html', @mech.history[0].uri.to_s)
assert_equal('http://localhost/tc_checkboxes.html',
@mech.history[1].uri.to_s)
end
def test_initialize
mech = Mechanize.new
assert_equal 50, mech.max_history
end
def test_html_parser_equals
@mech.html_parser = {}
assert_raises(NoMethodError) {
@mech.get('http://localhost/?foo=~2').links
}
end
def test_idle_timeout_default
assert_equal 5, Mechanize.new.idle_timeout
end
def test_idle_timeout_equals
@mech.idle_timeout = 15
assert_equal 15, @mech.idle_timeout
end
def test_keep_alive_equals
assert @mech.keep_alive
@mech.keep_alive = false
refute @mech.keep_alive
end
def test_keep_alive_time
assert_equal 0, @mech.keep_alive_time
@mech.keep_alive_time = 1
assert_equal 1, @mech.keep_alive_time
end
def test_log
assert_nil @mech.log
end
def test_log_equals
@mech.log = Logger.new $stderr
refute_nil @mech.log
assert_nil Mechanize.log
end
def test_max_file_buffer_equals
@mech.max_file_buffer = 1024
assert_equal 1024, @mech.agent.max_file_buffer
end
def test_max_history_equals
@mech.max_history = 10
0.upto(10) do |i|
assert_equal(i, @mech.history.size)
@mech.get("http://localhost/")
end
0.upto(10) do |i|
assert_equal(10, @mech.history.size)
@mech.get("http://localhost/")
end
end
def test_open_timeout_equals
@mech.open_timeout = 5
assert_equal 5, @mech.open_timeout
end
def test_parse_download
@mech.pluggable_parser['application/octet-stream'] = Mechanize::Download
response = Net::HTTPOK.allocate
response.instance_variable_set(:@header,
'content-type' =>
['application/octet-stream'])
download = @mech.parse @uri, response, StringIO.new('raw')
assert_kind_of Mechanize::Download, download
assert_kind_of StringIO, download.content
end
def test_parse_html
response = Net::HTTPOK.allocate
response.instance_variable_set :@header, 'content-type' => ['text/html']
page = @mech.parse URI('http://example/'), response, ''
assert_kind_of Mechanize::Page, page
end
def test_post
@mech.post "http://example", 'gender' => 'female'
assert_equal "gender=female", requests.first.body
end
def test_post_auth
requests = []
@mech.pre_connect_hooks << proc { |agent, request|
requests << request.class
}
@mech.add_auth(@uri, 'user', 'pass')
page = @mech.post(@uri + '/basic_auth')
assert_equal('You are authenticated', page.body)
assert_equal(2, requests.length)
r1 = requests[0]
r2 = requests[1]
assert_equal(r1, r2)
end
def test_post_entity
@mech.post "http://localhost/form_post", 'json' => '["""]'
assert_equal "json=%5B%22%22%22%5D", requests.first.body
end
def test_post_multiple_values
@mech.post "http://localhost/form_post",
[%w[gender female], %w[gender male]]
assert_equal "gender=female&gender=male", requests.first.body
end
def test_post_multipart
page = @mech.post('http://localhost/file_upload', {
:name => 'Some file',
:userfile1 => File.open(__FILE__)
})
name = File.basename __FILE__
assert_match(
"Content-Disposition: form-data; name=\"userfile1\"; filename=\"#{name}\"",
page.body
)
assert_operator page.body.bytesize, :>, file_contents_without_cr(__FILE__).length
end
def test_post_file_upload_nonascii
name = 'ユーザファイル1'
file_upload = Mechanize::Form::FileUpload.new({'name' => 'userfile1'}, name)
file_upload.file_data = File.read(__FILE__)
file_upload.mime_type = 'application/zip'
page = @mech.post('http://localhost/file_upload', {
:name => 'Some file',
:userfile1 => file_upload
})
assert_match(
"Content-Disposition: form-data; name=\"userfile1\"; filename=\"#{name}\"".dup.force_encoding(Encoding::ASCII_8BIT),
page.body
)
assert_match("Content-Type: application/zip", page.body)
assert_operator page.body.bytesize, :>, file_contents_without_cr(__FILE__).length
end
def test_post_file_upload
name = File.basename(__FILE__)
file_upload = Mechanize::Form::FileUpload.new({'name' => 'userfile1'}, name)
file_upload.file_data = File.read(__FILE__)
file_upload.mime_type = 'application/zip'
page = @mech.post('http://localhost/file_upload', {
:name => 'Some file',
:userfile1 => file_upload
})
assert_match(
"Content-Disposition: form-data; name=\"userfile1\"; filename=\"#{name}\"",
page.body
)
assert_match("Content-Type: application/zip", page.body)
assert_operator page.body.bytesize, :>, file_contents_without_cr(__FILE__).length
end
def test_post_redirect
page = @mech.post('http://localhost/redirect')
assert_equal(page.uri.to_s, 'http://localhost/verb')
assert_equal 'GET', page.header['X-Request-Method']
end
def test_put
page = @mech.put('http://localhost/verb', 'foo')
assert_equal 1, @mech.history.length
assert_equal 'PUT', page.header['X-Request-Method']
end
def test_put_redirect
page = @mech.put('http://localhost/redirect', 'foo')
assert_equal(page.uri.to_s, 'http://localhost/verb')
assert_equal 'GET', page.header['X-Request-Method']
end
def test_read_timeout_equals
@mech.read_timeout = 5
assert_equal 5, @mech.read_timeout
assert @mech.get('http://localhost/response_code?code=200')
assert_equal 5, @mech.agent.http.read_timeout
end
def test_write_timeout_equals
@mech.write_timeout = 7
assert_equal 7, @mech.write_timeout
assert @mech.get('http://localhost/response_code?code=200')
assert_equal 7, @mech.agent.http.write_timeout
end
def test_timeouts_for_file_connection
uri = URI.parse "file://#{File.expand_path __FILE__}"
@mech.read_timeout = 5
@mech.open_timeout = 5
assert @mech.get(uri)
end
def test_referer
host_path = "localhost/tc_referer.html?t=1"
['http', 'https'].each { |proto|
referer = "#{proto}://#{host_path}"
[
"",
"@",
"user1@",
":@",
"user1:@",
":password1@",
"user1:password1@",
].each { |userinfo|
url = "#{proto}://#{userinfo}#{host_path}"
[url, url + "#foo"].each { |furl|
[
['relative', true],
['insecure', proto == 'http'],
['secure', true],
['relative noreferrer', false],
['insecure noreferrer', false],
['secure noreferrer', false],
].each_with_index { |(type, bool), i|
rpage = @mech.get(furl)
page = rpage.links[i].click
assert_equal bool ? referer : '', page.body, "%s link from %s" % [type, furl]
}
rpage = @mech.get(furl)
page = rpage.forms.first.submit
assert_equal referer, page.body, "post from %s" % furl
}
}
}
end
def test_retry_change_requests_equals
unless Gem::Requirement.new("< 4.0.0").satisfied_by?(Gem::Version.new(Net::HTTP::Persistent::VERSION))
# see https://github.com/drbrain/net-http-persistent/pull/100
skip("net-http-persistent 4.0.0 and later does not support retry_change_requests")
end
refute @mech.retry_change_requests
@mech.retry_change_requests = true
assert @mech.retry_change_requests
end
def test_set_proxy
http = @mech.agent.http
@mech.set_proxy 'localhost', 8080, 'user', 'pass'
assert_equal 'localhost', @mech.proxy_addr
assert_equal 8080, @mech.proxy_port
assert_equal 'user', @mech.proxy_user
assert_equal 'pass', @mech.proxy_pass
assert_equal URI('http://user:pass@localhost:8080'), http.proxy_uri
end
def test_shutdown
uri = URI 'http://localhost'
jar = HTTP::CookieJar.new
jar.parse 'a=b', uri
@mech.cookie_jar = jar
@mech.get("http://localhost/")
assert_match(/Hello World/, @mech.current_page.body)
refute_empty @mech.cookies
@mech.shutdown
assert_empty @mech.history
assert_empty @mech.cookies
end
def test_start
body = nil
Mechanize.start do |m|
body = m.get("http://localhost/").body
end
assert_match(/Hello World/, body)
end
def test_submit_bad_form_method
page = @mech.get("http://localhost/bad_form_test.html")
assert_raises ArgumentError do
@mech.submit(page.forms.first)
end
end
def test_submit_check_one
page = @mech.get('http://localhost/tc_checkboxes.html')
form = page.forms.first
form.checkboxes_with(:name => 'green')[1].check
page = @mech.submit(form)
assert_equal(1, page.links.length)
assert_equal('green:on', page.links.first.text)
end
def test_submit_check_two
page = @mech.get('http://localhost/tc_checkboxes.html')
form = page.forms.first
form.checkboxes_with(:name => 'green')[0].check
form.checkboxes_with(:name => 'green')[1].check
page = @mech.submit(form)
assert_equal(2, page.links.length)
assert_equal('green:on', page.links[0].text)
assert_equal('green:on', page.links[1].text)
end
def test_submit_enctype
page = @mech.get("http://localhost/file_upload.html")
assert_equal('multipart/form-data', page.forms[0].enctype)
form = page.forms.first
form.file_uploads.first.file_name = __FILE__
form.file_uploads.first.mime_type = "text/plain"
form.file_uploads.first.file_data = "Hello World\n\n"
page = @mech.submit(form)
basename = File.basename __FILE__
assert_match(
"Content-Disposition: form-data; name=\"userfile1\"; filename=\"#{basename}\"",
page.body
)
assert_match(
"Content-Disposition: form-data; name=\"name\"",
page.body
)
assert_match('Content-Type: text/plain', page.body)
assert_match('Hello World', page.body)
assert_match('foo[aaron]', page.body)
end
def test_submit_file_data
page = @mech.get("http://localhost/file_upload.html")
assert_equal('multipart/form-data', page.forms[1].enctype)
form = page.forms[1]
form.file_uploads.first.file_name = __FILE__
form.file_uploads.first.file_data = File.read __FILE__
page = @mech.submit(form)
contents = File.binread(__FILE__).gsub(/\r\n/, "\n")
basename = File.basename __FILE__
assert_match(
"Content-Disposition: form-data; name=\"green[eggs]\"; filename=\"#{basename}\"",
page.body
)
assert_match(contents, page.body)
end
def test_submit_file_name
page = @mech.get("http://localhost/file_upload.html")
assert_equal('multipart/form-data', page.forms[1].enctype)
form = page.forms[1]
form.file_uploads.first.file_name = __FILE__
page = @mech.submit(form)
contents = File.binread __FILE__
basename = File.basename __FILE__
assert_match(
"Content-Disposition: form-data; name=\"green[eggs]\"; filename=\"#{basename}\"",
page.body
)
assert_match(contents, page.body)
end
def test_submit_get
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | true |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_file_request.rb | test/test_mechanize_file_request.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFileRequest < Mechanize::TestCase
def setup
@uri = URI.parse 'file:///nonexistent'
@r = Mechanize::FileRequest.new @uri
end
def test_initialize
assert_equal @uri, @r.uri
assert_equal '/nonexistent', @r.path
assert_respond_to @r, :[]=
assert_respond_to @r, :add_field
assert_respond_to @r, :each_header
end
def test_response_body_permitted_eh
assert @r.response_body_permitted?
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_multi_select_list.rb | test/test_mechanize_form_multi_select_list.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormMultiSelectList < Mechanize::TestCase
def setup
super
page = html_page <<-BODY
<form name="form1" method="post" action="/form_post">
<select name="select" multiple>
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select>
</form>
BODY
form = page.forms.first
@select = form.fields.first
end
def test_inspect
assert_match "value: #{%w[2]}", @select.inspect
end
def test_inspect_select_all
@select.select_all
assert_match "value: #{%w[1 2 3 4 5 6]}", @select.inspect
end
def test_option_with
option = @select.option_with value: '1'
assert_equal '1', option.value
option = @select.option_with search: 'option[@selected]'
assert_equal '2', option.value
end
def test_options_with
options = @select.options_with :value => /[12]/
assert_equal 2, options.length
end
def test_query_value
assert_equal [%w[select 2]], @select.query_value
@select.options.last.click
assert_equal [%w[select 2], %w[select 6]], @select.query_value
end
def test_query_value_empty
@select.options.last.click
@select.options.last.instance_variable_set :@value, ''
assert_equal [%w[select 2], ['select', '']], @select.query_value
end
def test_select_all
@select.select_all
assert_equal %w[1 2 3 4 5 6], @select.value
end
def test_select_none
@select.select_none
assert_empty @select.value
end
def test_selected_options
assert_equal [@select.options[1]], @select.selected_options
@select.options.last.click
assert_equal [@select.options[1], @select.options.last],
@select.selected_options
end
def test_value
assert_equal %w[2], @select.value
end
def test_value_equals
@select.value = %w[a 1 2]
assert_equal %w[a 1 2], @select.value
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_file.rb | test/test_mechanize_file.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFile < Mechanize::TestCase
def setup
super
@parser = Mechanize::File
end
def test_save
uri = URI 'http://example/name.html'
page = Mechanize::File.new uri, nil, '0123456789'
Dir.mktmpdir do |dir|
Dir.chdir dir do
filename = page.save 'test.html'
assert File.exist? 'test.html'
assert_equal '0123456789', File.read('test.html')
assert_equal "test.html", filename
filename = page.save 'test.html'
assert File.exist? 'test.html.1'
assert_equal '0123456789', File.read('test.html.1')
assert_equal "test.html.1", filename
filename = page.save 'test.html'
assert File.exist? 'test.html.2'
assert_equal '0123456789', File.read('test.html.2')
assert_equal "test.html.2", filename
end
end
end
def test_save_default
uri = URI 'http://example/test.html'
page = Mechanize::File.new uri, nil, ''
Dir.mktmpdir do |dir|
Dir.chdir dir do
filename = page.save
assert File.exist? 'test.html'
assert_equal "test.html", filename
filename = page.save
assert File.exist? 'test.html.1'
assert_equal "test.html.1", filename
filename = page.save
assert File.exist? 'test.html.2'
assert_equal "test.html.2", filename
end
end
end
def test_save_default_dots
uri = URI 'http://localhost/../test.html'
page = Mechanize::File.new uri, nil, ''
Dir.mktmpdir do |dir|
Dir.chdir dir do
filename = page.save
assert File.exist? 'test.html'
assert_equal "test.html", filename
filename = page.save
assert File.exist? 'test.html.1'
assert_equal "test.html.1", filename
end
end
end
def test_filename
uri = URI 'http://localhost/test.html'
page = Mechanize::File.new uri, nil, ''
assert_equal "test.html", page.filename
end
def test_save_overwrite
uri = URI 'http://example/test.html'
page = Mechanize::File.new uri, nil, ''
Dir.mktmpdir do |dir|
Dir.chdir dir do
filename = page.save 'test.html'
assert File.exist? 'test.html'
assert_equal "test.html", filename
filename = page.save! 'test.html'
assert File.exist? 'test.html'
refute File.exist? 'test.html.1'
assert_equal "test.html", filename
end
end
end
def test_save_bang_does_not_allow_command_injection
skip if windows?
uri = URI 'http://example/test.html'
page = Mechanize::File.new uri, nil, ''
in_tmpdir do
page.save!('| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\'')
refute_operator(File, :exist?, "vul.txt")
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_element_not_found_error.rb | test/test_mechanize_element_not_found_error.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeRedirectLimitReachedError < Mechanize::TestCase
def test_to_s
page = fake_page
error = Mechanize::ElementNotFoundError.new(page, :element, :conditions)
assert_match(/element/, error.to_s)
assert_match(/conditions/, error.to_s)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form.rb | test/test_mechanize_form.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeForm < Mechanize::TestCase
def setup
super
@uri = URI 'http://example'
@page = page @uri
@form = Mechanize::Form.new node('form', 'name' => @NAME), @mech, @page
end
def test_action
form = Mechanize::Form.new node('form', 'action' => '?a=b&b=c')
assert_equal '?a=b&b=c', form.action
end
def test_add_button_to_query
button = Mechanize::Form::Button.new node('input', 'type' => 'submit')
e = assert_raises ArgumentError do
@form.add_button_to_query button
end
assert_equal "#{button.inspect} does not belong to the same page " \
"as the form \"#{@NAME}\" in #{@uri}",
e.message
end
def test_aset
assert_empty @form.keys
@form['intarweb'] = 'Aaron'
assert_equal 'Aaron', @form['intarweb']
end
def test_aset_exists
page = html_page <<-BODY
<title>Page Title</title>
<form name="post_form">
<input name="first" type="text" id="name_first">
<input name="first" type="text">
<input type="submit" value="Submit">
</form>
BODY
form = page.form_with(:name => 'post_form')
assert_equal %w[first first], form.keys
form['first'] = 'Aaron'
assert_equal 'Aaron', form['first']
assert_equal ['Aaron', ''], form.values
end
def test_build_query_blank_form
page = @mech.get('http://localhost/tc_blank_form.html')
form = page.forms.first
query = form.build_query
assert(query.length > 0)
assert query.all? { |x| x[1] == '' }
end
def test_build_query_blank_input_name
html = Nokogiri::HTML <<-HTML
<form>
<input type="text" name="" value="foo" />
</form>
HTML
form = Mechanize::Form.new html.at('form'), @mech, @page
assert_equal [], form.build_query
end
def test_build_query_radio_button_duplicate
html = Nokogiri::HTML <<-HTML
<form>
<input type=radio name=name value=a checked=true>
<input type=radio name=name value=a checked=true>
</form>
HTML
form = Mechanize::Form.new html.at('form'), @mech, @page
query = form.build_query
assert_equal [%w[name a]], query
end
def test_build_query_radio_button_multiple_checked
html = Nokogiri::HTML <<-HTML
<form>
<input type=radio name=name value=a checked=true>
<input type=radio name=name value=b checked=true>
</form>
HTML
form = Mechanize::Form.new html.at('form'), @mech, @page
e = assert_raises Mechanize::Error do
form.build_query
end
assert_equal 'radiobuttons "a, b" are checked in the "name" group, ' \
'only one is allowed',
e.message
end
def test_method_missing_get
page = html_page <<-BODY
<form>
<input name="not_a_method" value="some value">
</form>
BODY
form = page.forms.first
assert_equal 'some value', form.not_a_method
end
def test_method_missing_set
page = html_page <<-BODY
<form>
<input name="not_a_method">
</form>
BODY
form = page.forms.first
form.not_a_method = 'some value'
assert_equal [%w[not_a_method some\ value]], form.build_query
end
def test_parse_buttons
page = html_page <<-BODY
<form>
<input type="submit" value="submit">
<input type="button" value="submit">
<button type="submit" value="submit">
<button type="button" value="submit">
<input type="image" name="submit" src="/button.jpeg">
<input type="image" src="/button.jpeg">
</form>
BODY
form = page.forms.first
buttons = form.buttons.sort
assert buttons.all? { |b| Mechanize::Form::Button === b }
assert_equal 'submit', buttons.shift.type
assert_equal 'button', buttons.shift.type
assert_equal 'submit', buttons.shift.type
assert_equal 'button', buttons.shift.type
assert_equal 'image', buttons.shift.type
assert_equal 'image', buttons.shift.type
assert_empty buttons
end
def test_parse_select
page = html_page <<-BODY
<form>
<select name="multi" multiple></select>
<select name="single"></select>
</form>
BODY
form = page.forms.first
selects = form.fields.sort
multi = selects.shift
assert_kind_of Mechanize::Form::MultiSelectList, multi
single = selects.shift
assert_kind_of Mechanize::Form::SelectList, single
assert_empty selects
end
def test_checkboxes_no_input_name
page = @mech.get('http://localhost/form_no_input_name.html')
form = page.forms.first
assert_equal(0, form.checkboxes.length)
end
def test_field_with
page = @mech.get("http://localhost/google.html")
search = page.forms.find { |f| f.name == "f" }
assert(search.field_with(:name => 'q'))
assert(search.field_with(:name => 'hl'))
assert(search.fields.find { |f| f.name == 'ie' })
end
def test_fields_no_input_name
page = @mech.get('http://localhost/form_no_input_name.html')
form = page.forms.first
assert_equal(0, form.fields.length)
end
def test_file_uploads_no_value
page = @mech.get("http://localhost/file_upload.html")
form = page.form('value_test')
assert_nil(form.file_uploads.first.value)
assert_nil(form.file_uploads.first.file_name)
end
def test_forms_no_input_name
page = @mech.get('http://localhost/form_no_input_name.html')
form = page.forms.first
assert_equal(0, form.radiobuttons.length)
end
def test_has_field_eh
refute @form.has_field? 'name'
@form['name'] = 'Aaron'
assert_equal true, @form.has_field?('name')
end
def test_has_value_eh
refute @form.has_value? 'Aaron'
@form['name'] = 'Aaron'
assert_equal true, @form.has_value?('Aaron')
end
def test_keys
assert_empty @form.keys
@form['name'] = 'Aaron'
assert_equal %w[name], @form.keys
end
def test_parse_textarea
form = Nokogiri::HTML <<-FORM
<form>
<textarea name="t">hi</textarea>
</form>
FORM
form = Mechanize::Form.new form, @mech
textarea = form.fields.first
assert_kind_of Mechanize::Form::Textarea, textarea
assert_equal 'hi', textarea.value
end
def test_post_with_rails_3_encoding_hack
page = @mech.get("http://localhost/rails_3_encoding_hack_form_test.html")
form = page.forms.first
form.submit
end
def test_post_with_blank_encoding
page = @mech.get("http://localhost/form_test.html")
form = page.form('post_form1')
form.page.encoding = nil
form.submit
end
def test_set_fields_duplicate
page = html_page '<form><input name="a" value="b"><input name="a"></form>'
form = page.forms.first
form.set_fields :a => 'c'
assert_equal 'c', form.fields.first.value
assert_equal '', form.fields.last.value
end
def test_set_fields_none
page = html_page '<form><input name="a" value="b"></form>'
form = page.forms.first
form.set_fields
assert_equal 'b', form.fields.first.value
end
def test_set_fields_many
page = html_page '<form><input name="a" value="b"><input name="b"></form>'
form = page.forms.first
form.set_fields :a => 'c', :b => 'd'
assert_equal 'c', form.fields.first.value
assert_equal 'd', form.fields.last.value
end
def test_set_fields_one
page = html_page '<form><input name="a" value="b"></form>'
form = page.forms.first
form.set_fields :a => 'c'
assert_equal 'c', form.fields.first.value
end
def test_set_fields_position
page = html_page '<form><input name="a" value="b"><input name="a"></form>'
form = page.forms.first
form.set_fields :a => { 0 => 'c', 1 => 'd' }
assert_equal 'c', form.fields.first.value
assert_equal 'd', form.fields.last.value
end
def test_set_fields_position_crappily
page = html_page '<form><input name="a" value="b"><input name="a"></form>'
form = page.forms.first
form.set_fields :a => ['c', 1]
assert_equal 'b', form.fields.first.value
assert_equal 'c', form.fields.last.value
end
def test_values
assert_empty @form.values
@form['name'] = 'Aaron'
assert_equal %w[Aaron], @form.values
end
def test_no_form_action
page = @mech.get('http://localhost:2000/form_no_action.html')
page.forms.first.fields.first.value = 'Aaron'
page = @mech.submit(page.forms.first)
assert_match('/form_no_action.html?first=Aaron', page.uri.to_s)
end
def test_submit_first_field_wins
page = @mech.get('http://localhost/tc_field_precedence.html')
form = page.forms.first
assert !form.checkboxes.empty?
assert_equal "1", form.checkboxes.first.value
submitted = form.submit
assert_equal 'ticky=1&ticky=0', submitted.parser.at('#query').text
end
def test_submit_takes_arbitrary_headers
page = @mech.get('http://localhost:2000/form_no_action.html')
assert form = page.forms.first
form.action = '/http_headers'
page = @mech.submit(form, nil, { 'foo' => 'bar' })
headers = page.body.split("\n").map { |x| x.split('|', 2) }.flatten
headers = Hash[*headers]
assert_equal 'bar', headers['foo']
end
def test_submit_select_default_all
page = html_page <<-BODY
<form name="form1" method="post" action="/form_post">
<select name="list">
<option value="1" selected>Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3" selected>Option 3</option>
<option value="4" selected>Option 4</option>
<option value="5" selected>Option 5</option>
<option value="6" selected>Option 6</option>
</select>
<br />
<input type="submit" value="Submit" />
</form>
BODY
form = page.forms.first
assert_equal "6", form.list
page = @mech.submit form
assert_equal 1, page.links.length
assert_equal 1, page.links_with(:text => 'list:6').length
end
def test_submit_select_default_none
page = html_page <<-BODY
<form name="form1" method="post" action="/form_post">
<select name="list">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option>Option No Value</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select>
<br />
<input type="submit" value="Submit" />
</form>
BODY
form = page.forms.first
assert_equal "1", form.list
page = @mech.submit form
assert_equal 1, page.links.length
assert_equal 1, page.links_with(:text => 'list:1').length
end
def test_form_select_default_noopts
page = html_page <<-BODY
<form name="form1" method="post" action="/form_post">
<select name="list">
</select>
<br />
<input type="submit" value="Submit" />
</form>
BODY
form = page.forms.first
assert form.field 'list'
assert_nil form.list
page = @mech.submit form
assert_empty page.links
end
# Test submitting form with two fields of the same name
def test_post_multival
page = @mech.get("http://localhost/form_multival.html")
form = page.form_with(:name => 'post_form')
assert_equal(2, form.fields_with(:name => 'first').length)
form.fields_with(:name => 'first')[0].value = 'Aaron'
form.fields_with(:name => 'first')[1].value = 'Patterson'
page = @mech.submit(form)
assert_equal(2, page.links.length)
assert(page.link_with(:text => 'first:Aaron'))
assert(page.link_with(:text => 'first:Patterson'))
end
# Test calling submit on the form object
def test_submit_on_form
page = @mech.get("http://localhost/form_multival.html")
form = page.form_with(:name => 'post_form')
assert_equal(2, form.fields_with(:name => 'first').length)
form.fields_with(:name => 'first')[0].value = 'Aaron'
form.fields_with(:name => 'first')[1].value = 'Patterson'
page = form.submit
assert_equal(2, page.links.length)
assert(page.link_with(:text => 'first:Aaron'))
assert(page.link_with(:text => 'first:Patterson'))
end
# Test submitting form with two fields of the same name
def test_get_multival
page = @mech.get("http://localhost/form_multival.html")
form = page.form_with(:name => 'get_form')
assert_equal(2, form.fields_with(:name => 'first').length)
form.fields_with(:name => 'first')[0].value = 'Aaron'
form.fields_with(:name => 'first')[1].value = 'Patterson'
page = @mech.submit(form)
assert_equal(2, page.links.length)
assert(page.link_with(:text => 'first:Aaron'))
assert(page.link_with(:text => 'first:Patterson'))
end
def test_post_with_non_strings
page = @mech.get("http://localhost/form_test.html")
page.form('post_form1') do |form|
form.first_name = 10
end.submit
end
def test_post_with_bang
page = @mech.get("http://localhost/form_test.html")
page.form_with!(:name => 'post_form1') do |form|
form.first_name = 10
end.submit
end
def test_post
page = @mech.get("http://localhost/form_test.html")
post_form = page.forms.find { |f| f.name == "post_form1" }
assert_equal("post", post_form.method.downcase)
assert_equal("/form_post", post_form.action)
assert_equal(3, post_form.fields.size)
assert_equal(1, post_form.buttons.size)
assert_equal(2, post_form.radiobuttons.size)
assert_equal(3, post_form.checkboxes.size)
assert(post_form.fields.find { |f| f.name == "first_name" },
"First name field was nil")
assert(post_form.fields.find { |f| f.name == "country" },
"Country field was nil")
assert(post_form.radiobuttons.find { |f| f.name == "gender" && f.value == "male"},
"Gender male button was nil")
assert(post_form.radiobuttons.find {|f| f.name == "gender" && f.value == "female"},
"Gender female button was nil")
assert(post_form.checkboxes.find { |f| f.name == "cool person" },
"couldn't find cool person checkbox")
assert(post_form.checkboxes.find { |f| f.name == "likes ham" },
"couldn't find likes ham checkbox")
assert(post_form.checkboxes.find { |f| f.name == "green[eggs]" },
"couldn't find green[eggs] checkbox")
# Find the select list
s = post_form.fields.find { |f| f.name == "country" }
assert_equal(2, s.options.length)
assert_equal("USA", s.value)
assert_equal("USA", s.options.first.value)
assert_equal("USA", s.options.first.text)
assert_equal("CANADA", s.options[1].value)
assert_equal("CANADA", s.options[1].text)
# Now set all the fields
post_form.fields.find { |f| f.name == "first_name" }.value = "Aaron"
post_form.radiobuttons.find { |f|
f.name == "gender" && f.value == "male"
}.checked = true
post_form.checkboxes.find { |f| f.name == "likes ham" }.checked = true
post_form.checkboxes.find { |f| f.name == "green[eggs]" }.checked = true
page = @mech.submit(post_form, post_form.buttons.first)
# Check that the submitted fields exist
assert_equal(5, page.links.size, "Not enough links")
assert(page.links.find { |l| l.text == "likes ham:on" },
"likes ham check box missing")
assert(page.links.find { |l| l.text == "green[eggs]:on" },
"green[eggs] check box missing")
assert(page.links.find { |l| l.text == "first_name:Aaron" },
"first_name field missing")
assert(page.links.find { |l| l.text == "gender:male" },
"gender field missing")
assert(page.links.find { |l| l.text == "country:USA" },
"select box not submitted")
end
def test_post_multipart
page = @mech.get("http://localhost/form_test.html")
post_form = page.forms.find { |f| f.name == "post_form4_multipart" }
assert(post_form, "Post form is null")
assert_equal("post", post_form.method.downcase)
assert_equal("/form_post", post_form.action)
assert_equal(1, post_form.fields.size)
assert_equal(1, post_form.buttons.size)
page = @mech.submit(post_form, post_form.buttons.first)
assert page
end
def test_select_box
page = @mech.get("http://localhost/form_test.html")
post_form = page.forms.find { |f| f.name == "post_form1" }
assert(page.header)
assert(page.root)
assert_equal(0, page.iframes.length)
assert_equal("post", post_form.method.downcase)
assert_equal("/form_post", post_form.action)
# Find the select list
s = post_form.field_with(:name => /country/)
assert_equal(2, s.options.length)
assert_equal("USA", s.value)
assert_equal("USA", s.options.first.value)
assert_equal("USA", s.options.first.text)
assert_equal("CANADA", s.options[1].value)
assert_equal("CANADA", s.options[1].text)
# Now set all the fields
post_form.field_with(:name => /country/).value = s.options[1]
assert_equal('CANADA', post_form.country)
page = @mech.submit(post_form, post_form.buttons.first)
# Check that the submitted fields exist
assert(page.links.find { |l| l.text == "country:CANADA" },
"select box not submitted")
end
def test_get
page = @mech.get("http://localhost/form_test.html")
get_form = page.forms.find { |f| f.name == "get_form1" }
assert_equal("get", get_form.method.downcase)
assert_equal("/form_post", get_form.action)
assert_equal(1, get_form.fields.size)
assert_equal(2, get_form.buttons.size)
assert_equal(2, get_form.radiobuttons.size)
assert_equal(3, get_form.checkboxes.size)
assert(get_form.fields.find { |f| f.name == "first_name" },
"First name field was nil")
assert(get_form.radiobuttons.find { |f| f.name == "gender" && f.value == "male"},
"Gender male button was nil")
assert(get_form.radiobuttons.find {|f| f.name == "gender" && f.value == "female"},
"Gender female button was nil")
assert(get_form.checkboxes.find { |f| f.name == "cool person" },
"couldn't find cool person checkbox")
assert(get_form.checkboxes.find { |f| f.name == "likes ham" },
"couldn't find likes ham checkbox")
assert(get_form.checkboxes.find { |f| f.name == "green[eggs]" },
"couldn't find green[eggs] checkbox")
# Set up the image button
img = get_form.buttons.find { |f| f.name == "button" }
img.x = "9"
img.y = "10"
# Now set all the fields
get_form.fields.find { |f| f.name == "first_name" }.value = "Aaron"
get_form.radiobuttons.find { |f|
f.name == "gender" && f.value == "male"
}.checked = true
get_form.checkboxes.find { |f| f.name == "likes ham" }.checked = true
get_form.checkboxes.find { |f| f.name == "green[eggs]" }.checked = true
page = @mech.submit(get_form, get_form.buttons.first)
# Check that the submitted fields exist
assert_equal(6, page.links.size, "Not enough links")
assert(page.links.find { |l| l.text == "likes ham:on" },
"likes ham check box missing")
assert(page.links.find { |l| l.text == "green[eggs]:on" },
"green[eggs] check box missing")
assert(page.links.find { |l| l.text == "first_name:Aaron" },
"first_name field missing")
assert(page.links.find { |l| l.text == "gender:male" },
"gender field missing")
assert(page.links.find { |l| l.text == "button.y:10" },
"Image button missing")
assert(page.links.find { |l| l.text == "button.x:9" },
"Image button missing")
end
def test_reset
page = @mech.get("http://localhost/form_test.html")
get_form = page.forms.find { |f| f.name == "get_form1" }
image_button = get_form.buttons.first
submit_button = get_form.submits.first
new_page = @mech.submit(get_form, submit_button)
assert_equal "http://localhost/form_post?first_name=", new_page.uri.to_s
new_page = @mech.submit(get_form, image_button)
assert_equal "http://localhost/form_post?first_name=&button.x=0&button.y=0", new_page.uri.to_s
get_form.reset
new_page = @mech.submit(get_form, submit_button)
assert_equal "http://localhost/form_post?first_name=", new_page.uri.to_s
end
def test_post_with_space_in_action
page = @mech.get("http://localhost/form_test.html")
post_form = page.forms.find { |f| f.name == "post_form2" }
assert_equal("post", post_form.method.downcase)
assert_equal("/form post", post_form.action)
assert_equal(1, post_form.fields.size)
assert_equal(1, post_form.buttons.size)
assert_equal(2, post_form.radiobuttons.size)
assert_equal(2, post_form.checkboxes.size)
assert(post_form.fields.find { |f| f.name == "first_name" },
"First name field was nil")
assert(post_form.radiobuttons.find { |f| f.name == "gender" && f.value == "male"},
"Gender male button was nil")
assert(post_form.radiobuttons.find {|f| f.name == "gender" && f.value == "female"},
"Gender female button was nil")
assert(post_form.checkboxes.find { |f| f.name == "cool person" },
"couldn't find cool person checkbox")
assert(post_form.checkboxes.find { |f| f.name == "likes ham" },
"couldn't find likes ham checkbox")
# Now set all the fields
post_form.fields.find { |f| f.name == "first_name" }.value = "Aaron"
post_form.radiobuttons.find { |f|
f.name == "gender" && f.value == "male"
}.checked = true
post_form.checkboxes.find { |f| f.name == "likes ham" }.checked = true
page = @mech.submit(post_form, post_form.buttons.first)
# Check that the submitted fields exist
assert_equal(3, page.links.size, "Not enough links")
assert(page.links.find { |l| l.text == "likes ham:on" },
"likes ham check box missing")
assert(page.links.find { |l| l.text == "first_name:Aaron" },
"first_name field missing")
assert(page.links.find { |l| l.text == "gender:male" },
"gender field missing")
end
def test_get_with_space_in_action
page = @mech.get("http://localhost/form_test.html")
get_form = page.forms.find { |f| f.name == "get_form2" }
assert_equal("get", get_form.method.downcase)
assert_equal("/form post", get_form.action)
assert_equal(1, get_form.fields.size)
assert_equal(1, get_form.buttons.size)
assert_equal(2, get_form.radiobuttons.size)
assert_equal(2, get_form.checkboxes.size)
assert(get_form.fields.find { |f| f.name == "first_name" },
"First name field was nil")
assert(get_form.radiobuttons.find { |f| f.name == "gender" && f.value == "male"},
"Gender male button was nil")
assert(get_form.radiobuttons.find {|f| f.name == "gender" && f.value == "female"},
"Gender female button was nil")
assert(get_form.checkboxes.find { |f| f.name == "cool person" },
"couldn't find cool person checkbox")
assert(get_form.checkboxes.find { |f| f.name == "likes ham" },
"couldn't find likes ham checkbox")
# Now set all the fields
get_form.fields.find { |f| f.name == "first_name" }.value = "Aaron"
get_form.radiobuttons.find { |f|
f.name == "gender" && f.value == "male"
}.checked = true
get_form.checkboxes.find { |f| f.name == "likes ham" }.checked = true
page = @mech.submit(get_form, get_form.buttons.first)
# Check that the submitted fields exist
assert_equal(3, page.links.size, "Not enough links")
assert(page.links.find { |l| l.text == "likes ham:on" },
"likes ham check box missing")
assert(page.links.find { |l| l.text == "first_name:Aaron" },
"first_name field missing")
assert(page.links.find { |l| l.text == "gender:male" },
"gender field missing")
end
def test_post_with_param_in_action
page = @mech.get("http://localhost/form_test.html")
post_form = page.forms.find { |f| f.name == "post_form3" }
assert_equal("post", post_form.method.downcase)
assert_equal("/form_post?great day=yes&one=two", post_form.action)
assert_equal(1, post_form.fields.size)
assert_equal(1, post_form.buttons.size)
assert_equal(2, post_form.radiobuttons.size)
assert_equal(2, post_form.checkboxes.size)
assert(post_form.fields.find { |f| f.name == "first_name" },
"First name field was nil")
male_button = post_form.radiobuttons.find { |f|
f.name == "gender" && f.value == "male"
}
assert(male_button, "Gender male button was nil")
female_button = post_form.radiobuttons.find { |f|
f.name == "gender" && f.value == "female"
}
assert(female_button, "Gender female button was nil")
assert(post_form.checkbox_with(:name => "cool person"),
"couldn't find cool person checkbox")
assert(post_form.checkboxes.find { |f| f.name == "likes ham" },
"couldn't find likes ham checkbox")
# Now set all the fields
post_form.field_with(:name => 'first_name').value = "Aaron"
post_form.radiobuttons.find { |f|
f.name == "gender" && f.value == "male"
}.checked = true
post_form.checkboxes.find { |f| f.name == "likes ham" }.checked = true
page = @mech.submit(post_form, post_form.buttons.first)
# Check that the submitted fields exist
assert_equal(3, page.links.size, "Not enough links")
assert(page.links.find { |l| l.text == "likes ham:on" },
"likes ham check box missing")
assert(page.links.find { |l| l.text == "first_name:Aaron" },
"first_name field missing")
assert(page.links.find { |l| l.text == "gender:male" },
"gender field missing")
end
def test_get_with_param_in_action
page = @mech.get("http://localhost/form_test.html")
get_form = page.forms.find { |f| f.name == "get_form3" }
assert_equal("get", get_form.method.downcase)
assert_equal("/form_post?great day=yes&one=two", get_form.action)
assert_equal(1, get_form.fields.size)
assert_equal(1, get_form.buttons.size)
assert_equal(2, get_form.radiobuttons.size)
assert_equal(2, get_form.checkboxes.size)
assert(get_form.fields.find { |f| f.name == "first_name" },
"First name field was nil")
assert(get_form.radiobuttons.find { |f| f.name == "gender" && f.value == "male"},
"Gender male button was nil")
assert(get_form.radiobuttons.find {|f| f.name == "gender" && f.value == "female"},
"Gender female button was nil")
assert(get_form.checkboxes.find { |f| f.name == "cool person" },
"couldn't find cool person checkbox")
assert(get_form.checkboxes.find { |f| f.name == "likes ham" },
"couldn't find likes ham checkbox")
# Now set all the fields
get_form.fields.find { |f| f.name == "first_name" }.value = "Aaron"
get_form.radiobuttons.find { |f|
f.name == "gender" && f.value == "male"
}.checked = true
get_form.checkboxes.find { |f| f.name == "likes ham" }.checked = true
page = @mech.submit(get_form, get_form.buttons.first)
# Check that the submitted fields exist
assert_equal(3, page.links.size, "Not enough links")
assert(page.links.find { |l| l.text == "likes ham:on" },
"likes ham check box missing")
assert(page.links.find { |l| l.text == "first_name:Aaron" },
"first_name field missing")
assert(page.links.find { |l| l.text == "gender:male" },
"gender field missing")
end
def test_field_addition
page = @mech.get("http://localhost/form_test.html")
get_form = page.forms.find { |f| f.name == "get_form1" }
get_form.field("first_name").value = "Gregory"
assert_equal( "Gregory", get_form.field("first_name").value )
end
def test_fields_as_accessors
page = @mech.get("http://localhost/form_multival.html")
form = page.form_with(:name => 'post_form')
assert_equal(2, form.fields_with(:name => 'first').length)
form.first = 'Aaron'
assert_equal('Aaron', form.first)
end
def test_form_and_fields_dom_id
# blatant copypasta of test above
page = @mech.get("http://localhost/form_test.html")
form = page.form_with(dom_id: 'generic_form')
assert_equal(1, form.fields_with(dom_id: 'name_first').length)
assert_equal('first_name', form.field_with(dom_id: 'name_first').name)
assert_equal(form, page.form_with(id: 'generic_form'))
assert_equal(form, page.form_with(css: '#generic_form'))
fields_by_dom_id = form.fields_with(dom_id: 'name_first')
assert_equal(fields_by_dom_id, form.fields_with(id: 'name_first'))
assert_equal(fields_by_dom_id, form.fields_with(css: '#name_first'))
assert_equal(fields_by_dom_id, form.fields_with(xpath: '//*[@id="name_first"]'))
assert_equal(fields_by_dom_id, form.fields_with(search: '//*[@id="name_first"]'))
end
def test_form_and_fields_dom_class
# blatant copypasta of test above
page = @mech.get("http://localhost/form_test.html")
form = page.form_with(:dom_class => 'really_generic_form')
form_by_class = page.form_with(:class => 'really_generic_form')
assert_equal(1, form.fields_with(:dom_class => 'text_input').length)
assert_equal('first_name', form.field_with(:dom_class => 'text_input').name)
# *_with(:class => blah) should work exactly like (:dom_class => blah)
assert_equal(form, form_by_class)
assert_equal(form.fields_with(:dom_class => 'text_input'), form.fields_with(:class => 'text_input'))
end
def test_add_field
page = @mech.get("http://localhost/form_multival.html")
form = page.form_with(:name => 'post_form')
number_of_fields = form.fields.length
assert form.add_field!('intarweb')
assert_equal(number_of_fields + 1, form.fields.length)
end
def test_delete_field
page = @mech.get("http://localhost/form_multival.html")
form = page.form_with(:name => 'post_form')
number_of_fields = form.fields.length
assert_equal 2, number_of_fields
form.delete_field!('first')
assert_nil(form['first'])
assert_equal(number_of_fields - 2, form.fields.length)
end
def test_has_field
page = @mech.get("http://localhost/form_multival.html")
form = page.form_with(:name => 'post_form')
assert_equal false, form.has_field?('intarweb')
assert form.add_field!('intarweb')
assert_equal true, form.has_field?('intarweb')
end
def test_fill_unexisting_form
page = @mech.get("http://localhost/empty_form.html")
assert_raises(NoMethodError) {
page.form_with(:name => 'no form') { |f| f.foo = 'bar' }
}
begin
page.form_with!(:name => 'no form') { |f| f.foo = 'bar' }
rescue => e
assert_instance_of Mechanize::ElementNotFoundError, e
assert_kind_of Mechanize::Page, e.source
assert_equal :form, e.element
assert_kind_of Hash, e.conditions
assert_equal 'no form', e.conditions[:name]
end
end
def test_field_error
@page = @mech.get('http://localhost/empty_form.html')
form = @page.forms.first
assert_raises(NoMethodError) {
form.foo = 'asdfasdf'
}
assert_raises(NoMethodError) {
form.foo
}
end
def test_form_build_query
page = @mech.get("http://localhost/form_order_test.html")
get_form = page.forms.first
query = get_form.build_query
expected = [
%w[1 RADIO],
%w[3 nobody@example],
%w[2 TEXT],
%w[3 2011-10],
]
assert_equal expected, query
end
def test_form_input_disabled
page = html_page <<-BODY
<form name="form1" method="post" action="/form_post">
<input type="text" name="opa" value="omg" disabled />
<input type="submit" value="Submit" />
</form>
BODY
form = page.forms.first
page = @mech.submit form
assert_empty page.links
end
def test_form_built_from_array_post
submitted = @mech.post(
'http://example/form_post',
[
%w[order_matters 0],
%w[order_matters 1],
%w[order_matters 2],
%w[mess_it_up asdf]
]
)
assert_equal 'order_matters=0&order_matters=1&order_matters=2&mess_it_up=asdf', submitted.parser.at('#query').text
end
def test_form_built_from_hashes_submit
uri = URI 'http://example/form_post'
page = page uri
form = Mechanize::Form.new node('form', 'name' => @NAME, 'method' => 'POST'), @mech, page
form.fields << Mechanize::Form::Field.new({'name' => 'order_matters'}, '0')
form.fields << Mechanize::Form::Field.new({'name' => 'order_matters'}, '1')
form.fields << Mechanize::Form::Field.new({'name' => 'order_matters'}, '2')
form.fields << Mechanize::Form::Field.new({'name' => 'mess_it_up'}, 'asdf')
submitted = @mech.submit form
assert_equal 'order_matters=0&order_matters=1&order_matters=2&mess_it_up=asdf', submitted.parser.at('#query').text
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_cookie.rb | test/test_mechanize_cookie.rb | # frozen_string_literal: true
require 'mechanize/test_case'
module Enumerable
def combine
masks = inject([[], 1]){|(ar, m), e| [ar << m, m << 1 ] }[0]
all = masks.inject(0){ |al, m| al|m }
result = []
for i in 1..all do
tmp = []
each_with_index do |e, idx|
tmp << e unless (masks[idx] & i) == 0
end
result << tmp
end
result
end
end
class TestMechanizeCookie < Mechanize::TestCase
def assert_cookie_parse url, cookie_text, &block
cookie = nil
block ||= proc { |p_cookie| cookie = p_cookie }
exp_re = /The call of Mechanize::Cookie.parse/
assert_output "", exp_re do
Mechanize::Cookie.parse(url, cookie_text, &block)
end
cookie
end
alias silently capture_io
def test_parse_dates
url = URI.parse('http://localhost/')
yesterday = Time.now - 86400
dates = [ "14 Apr 89 03:20:12",
"14 Apr 89 03:20 GMT",
"Fri, 17 Mar 89 4:01:33",
"Fri, 17 Mar 89 4:01 GMT",
"Mon Jan 16 16:12 PDT 1989",
#"Mon Jan 16 16:12 +0130 1989",
"6 May 1992 16:41-JST (Wednesday)",
#"22-AUG-1993 10:59:12.82",
"22-AUG-1993 10:59pm",
"22-AUG-1993 12:59am",
"22-AUG-1993 12:59 PM",
#"Friday, August 04, 1995 3:54 PM",
#"06/21/95 04:24:34 PM",
#"20/06/95 21:07",
#"95-06-08 19:32:48 EDT",
]
dates.each do |date|
cookie = "PREF=1; expires=#{date}"
silently do
Mechanize::Cookie.parse(url, cookie) { |c|
assert c.expires, "Tried parsing: #{date}"
assert_equal(true, c.expires < yesterday)
}
end
end
end
def test_parse_empty
cookie_str = 'a=b; ; c=d'
uri = URI.parse 'http://example'
assert_cookie_parse uri, cookie_str do |cookie|
assert_equal 'a', cookie.name
assert_equal 'b', cookie.value
end
end
def test_parse_no_space
cookie_str = "foo=bar;Expires=Sun, 06 Nov 2011 00:28:06 GMT;Path=/"
uri = URI.parse 'http://example'
assert_cookie_parse uri, cookie_str do |cookie|
assert_equal 'foo', cookie.name
assert_equal 'bar', cookie.value
assert_equal '/', cookie.path
assert_equal Time.at(1320539286), cookie.expires
end
end
def test_parse_quoted
cookie_str =
"quoted=\"value\"; Expires=Sun, 06 Nov 2011 00:11:18 GMT; Path=/"
uri = URI.parse 'http://example'
assert_cookie_parse uri, cookie_str do |cookie|
assert_equal 'quoted', cookie.name
assert_equal 'value', cookie.value
end
end
def test_parse_weird_cookie
cookie = 'n/a, ASPSESSIONIDCSRRQDQR=FBLDGHPBNDJCPCGNCPAENELB; path=/'
url = URI.parse('http://www.searchinnovation.com/')
assert_cookie_parse url, cookie do |c|
assert_equal('ASPSESSIONIDCSRRQDQR', c.name)
assert_equal('FBLDGHPBNDJCPCGNCPAENELB', c.value)
end
end
def test_double_semicolon
double_semi = 'WSIDC=WEST;; domain=.williams-sonoma.com; path=/'
url = URI.parse('http://williams-sonoma.com/')
assert_cookie_parse url, double_semi do |cookie|
assert_equal('WSIDC', cookie.name)
assert_equal('WEST', cookie.value)
end
end
def test_parse_bad_version
bad_cookie = 'PRETANET=TGIAqbFXtt; Name=/PRETANET; Path=/; Version=1.2; Content-type=text/html; Domain=192.168.6.196; expires=Friday, 13-November-2026 23:01:46 GMT;'
url = URI.parse('http://localhost/')
assert_cookie_parse url, bad_cookie do |cookie|
assert_nil(cookie.version)
end
end
def test_parse_bad_max_age
bad_cookie = 'PRETANET=TGIAqbFXtt; Name=/PRETANET; Path=/; Max-Age=1.2; Content-type=text/html; Domain=192.168.6.196; expires=Friday, 13-November-2026 23:01:46 GMT;'
url = URI.parse('http://localhost/')
assert_cookie_parse url, bad_cookie do |cookie|
assert_nil(cookie.max_age)
end
end
def test_parse_date_fail
url = URI.parse('http://localhost/')
dates = [
"20/06/95 21:07",
]
silently do
dates.each do |date|
cookie = "PREF=1; expires=#{date}"
Mechanize::Cookie.parse(url, cookie) { |c|
assert_equal(true, c.expires.nil?)
}
end
end
end
def test_parse_domain_dot
url = URI.parse('http://host.example.com/')
cookie_str = 'a=b; domain=.example.com'
cookie = assert_cookie_parse url, cookie_str
assert_equal 'example.com', cookie.domain
assert cookie.for_domain?
end
def test_parse_domain_no_dot
url = URI.parse('http://host.example.com/')
cookie_str = 'a=b; domain=example.com'
cookie = assert_cookie_parse url, cookie_str
assert_equal 'example.com', cookie.domain
assert cookie.for_domain?
end
def test_parse_domain_none
url = URI.parse('http://example.com/')
cookie_str = 'a=b;'
cookie = assert_cookie_parse url, cookie_str
assert_equal 'example.com', cookie.domain
assert !cookie.for_domain?
end
def test_parse_max_age
url = URI.parse('http://localhost/')
date = 'Mon, 19 Feb 2012 19:26:04 GMT'
cookie_text = "name=Akinori; expires=#{date}"
cookie = assert_cookie_parse url, cookie_text
assert_equal Time.at(1329679564), cookie.expires
cookie_text = 'name=Akinori; max-age=3600'
cookie = assert_cookie_parse url, cookie_text
assert_in_delta Time.now + 3600, cookie.expires, 1
# Max-Age has precedence over Expires
cookie_text = "name=Akinori; max-age=3600; expires=#{date}"
cookie = assert_cookie_parse url, cookie_text
assert_in_delta Time.now + 3600, cookie.expires, 1
cookie_text = "name=Akinori; expires=#{date}; max-age=3600"
cookie = assert_cookie_parse url, cookie_text
assert_in_delta Time.now + 3600, cookie.expires, 1
end
def test_parse_expires_session
url = URI.parse('http://localhost/')
[
'name=Akinori',
'name=Akinori; expires',
'name=Akinori; max-age',
'name=Akinori; expires=',
'name=Akinori; max-age=',
].each { |str|
cookie = assert_cookie_parse url, str
assert cookie.session, str
}
[
'name=Akinori; expires=Mon, 19 Feb 2012 19:26:04 GMT',
'name=Akinori; max-age=3600',
].each { |str|
cookie = assert_cookie_parse url, str
assert !cookie.session, str
}
end
def test_parse_many
url = URI 'http://localhost/'
cookie_str =
"name=Aaron; Domain=localhost; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/, " \
"name=Aaron; Domain=localhost; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/, " \
"name=Aaron; Domain=localhost; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/, " \
"name=Aaron; Domain=localhost; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/; HttpOnly, " \
"expired=doh; Expires=Fri, 04 Nov 2011 00:29:51 GMT; Path=/, " \
"a_path=some_path; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/some_path, " \
"no_path1=no_path; Expires=Sun, 06 Nov 2011 00:29:52 GMT, no_expires=nope; Path=/, " \
"no_path2=no_path; Expires=Sun, 06 Nov 2011 00:29:52 GMT; no_expires=nope; Path, " \
"no_path3=no_path; Expires=Sun, 06 Nov 2011 00:29:52 GMT; no_expires=nope; Path=, " \
"no_domain1=no_domain; Expires=Sun, 06 Nov 2011 00:29:53 GMT; no_expires=nope, " \
"no_domain2=no_domain; Expires=Sun, 06 Nov 2011 00:29:53 GMT; no_expires=nope; Domain, " \
"no_domain3=no_domain; Expires=Sun, 06 Nov 2011 00:29:53 GMT; no_expires=nope; Domain="
cookies = nil
silently { cookies = Mechanize::Cookie.parse url, cookie_str }
assert_equal 13, cookies.length
name = cookies.find { |c| c.name == 'name' }
assert_equal "Aaron", name.value
assert_equal "/", name.path
assert_equal Time.at(1320539391), name.expires
a_path = cookies.find { |c| c.name == 'a_path' }
assert_equal "some_path", a_path.value
assert_equal "/some_path", a_path.path
assert_equal Time.at(1320539391), a_path.expires
no_expires = cookies.find { |c| c.name == 'no_expires' }
assert_equal "nope", no_expires.value
assert_equal "/", no_expires.path
assert_nil no_expires.expires
no_path_cookies = cookies.select { |c| c.value == 'no_path' }
assert_equal 3, no_path_cookies.size
no_path_cookies.each { |c|
assert_equal "/", c.path, c.name
assert_equal Time.at(1320539392), c.expires, c.name
}
no_domain_cookies = cookies.select { |c| c.value == 'no_domain' }
assert_equal 3, no_domain_cookies.size
no_domain_cookies.each { |c|
assert !c.for_domain?, c.name
assert_equal c.domain, url.host, c.name
assert_equal Time.at(1320539393), c.expires, c.name
}
assert cookies.find { |c| c.name == 'expired' }
end
def test_parse_valid_cookie
url = URI.parse('http://rubygems.org/')
cookie_params = {}
cookie_params['expires'] = 'expires=Sun, 27-Sep-2037 00:00:00 GMT'
cookie_params['path'] = 'path=/'
cookie_params['domain'] = 'domain=.rubygems.org'
cookie_params['httponly'] = 'HttpOnly'
cookie_value = '12345%7D=ASDFWEE345%3DASda'
expires = Time.parse('Sun, 27-Sep-2037 00:00:00 GMT')
cookie_params.keys.combine.each do |c|
cookie_text = +"#{cookie_value}; "
c.each_with_index do |key, idx|
if idx == (c.length - 1)
cookie_text << "#{cookie_params[key]}"
else
cookie_text << "#{cookie_params[key]}; "
end
end
cookie = assert_cookie_parse url, cookie_text
assert_equal('12345%7D=ASDFWEE345%3DASda', cookie.to_s)
assert_equal('/', cookie.path)
# if expires was set, make sure we parsed it
if c.find { |k| k == 'expires' }
assert_equal(expires, cookie.expires)
else
assert_nil(cookie.expires)
end
end
end
def test_parse_valid_cookie_empty_value
url = URI.parse('http://rubygems.org/')
cookie_params = {}
cookie_params['expires'] = 'expires=Sun, 27-Sep-2037 00:00:00 GMT'
cookie_params['path'] = 'path=/'
cookie_params['domain'] = 'domain=.rubygems.org'
cookie_params['httponly'] = 'HttpOnly'
cookie_value = '12345%7D='
expires = Time.parse('Sun, 27-Sep-2037 00:00:00 GMT')
cookie_params.keys.combine.each do |c|
cookie_text = +"#{cookie_value}; "
c.each_with_index do |key, idx|
if idx == (c.length - 1)
cookie_text << "#{cookie_params[key]}"
else
cookie_text << "#{cookie_params[key]}; "
end
end
cookie = assert_cookie_parse url, cookie_text
assert_equal('12345%7D=', cookie.to_s)
assert_equal('', cookie.value)
assert_equal('/', cookie.path)
# if expires was set, make sure we parsed it
if c.find { |k| k == 'expires' }
assert_equal(expires, cookie.expires)
else
assert_nil(cookie.expires)
end
end
end
# If no path was given, use the one from the URL
def test_cookie_using_url_path
url = URI.parse('http://rubygems.org/login.php')
cookie_params = {}
cookie_params['expires'] = 'expires=Sun, 27-Sep-2037 00:00:00 GMT'
cookie_params['path'] = 'path=/'
cookie_params['domain'] = 'domain=.rubygems.org'
cookie_params['httponly'] = 'HttpOnly'
cookie_value = '12345%7D=ASDFWEE345%3DASda'
expires = Time.parse('Sun, 27-Sep-2037 00:00:00 GMT')
cookie_params.keys.combine.each do |c|
next if c.find { |k| k == 'path' }
cookie_text = +"#{cookie_value}; "
c.each_with_index do |key, idx|
if idx == (c.length - 1)
cookie_text << "#{cookie_params[key]}"
else
cookie_text << "#{cookie_params[key]}; "
end
end
cookie = assert_cookie_parse url, cookie_text
assert_equal('12345%7D=ASDFWEE345%3DASda', cookie.to_s)
assert_equal('/', cookie.path)
# if expires was set, make sure we parsed it
if c.find { |k| k == 'expires' }
assert_equal(expires, cookie.expires)
else
assert_nil(cookie.expires)
end
end
end
# Test using secure cookies
def test_cookie_with_secure
url = URI.parse('http://rubygems.org/')
cookie_params = {}
cookie_params['expires'] = 'expires=Sun, 27-Sep-2037 00:00:00 GMT'
cookie_params['path'] = 'path=/'
cookie_params['domain'] = 'domain=.rubygems.org'
cookie_params['secure'] = 'secure'
cookie_value = '12345%7D=ASDFWEE345%3DASda'
expires = Time.parse('Sun, 27-Sep-2037 00:00:00 GMT')
cookie_params.keys.combine.each do |c|
next unless c.find { |k| k == 'secure' }
cookie_text = +"#{cookie_value}; "
c.each_with_index do |key, idx|
if idx == (c.length - 1)
cookie_text << "#{cookie_params[key]}"
else
cookie_text << "#{cookie_params[key]}; "
end
end
cookie = assert_cookie_parse url, cookie_text
assert_equal('12345%7D=ASDFWEE345%3DASda', cookie.to_s)
assert_equal('/', cookie.path)
assert_equal(true, cookie.secure)
# if expires was set, make sure we parsed it
if c.find { |k| k == 'expires' }
assert_equal(expires, cookie.expires)
else
assert_nil(cookie.expires)
end
end
end
def test_parse_cookie_no_spaces
url = URI.parse('http://rubygems.org/')
cookie_params = {}
cookie_params['expires'] = 'expires=Sun, 27-Sep-2037 00:00:00 GMT'
cookie_params['path'] = 'path=/'
cookie_params['domain'] = 'domain=.rubygems.org'
cookie_params['httponly'] = 'HttpOnly'
cookie_value = '12345%7D=ASDFWEE345%3DASda'
expires = Time.parse('Sun, 27-Sep-2037 00:00:00 GMT')
cookie_params.keys.combine.each do |c|
cookie_text = +"#{cookie_value};"
c.each_with_index do |key, idx|
if idx == (c.length - 1)
cookie_text << "#{cookie_params[key]}"
else
cookie_text << "#{cookie_params[key]};"
end
end
cookie = assert_cookie_parse url, cookie_text
assert_equal('12345%7D=ASDFWEE345%3DASda', cookie.to_s)
assert_equal('/', cookie.path)
# if expires was set, make sure we parsed it
if c.find { |k| k == 'expires' }
assert_equal(expires, cookie.expires)
else
assert_nil(cookie.expires)
end
end
end
def test_new
cookie = Mechanize::Cookie.new('key', 'value')
assert_equal 'key', cookie.name
assert_equal 'value', cookie.value
assert_nil cookie.expires
# Minimum unit for the expires attribute is second
expires = Time.at((Time.now + 3600).to_i)
cookie = Mechanize::Cookie.new('key', 'value', :expires => expires.dup)
assert_equal 'key', cookie.name
assert_equal 'value', cookie.value
assert_equal expires, cookie.expires
cookie = Mechanize::Cookie.new(:value => 'value', :name => 'key', :expires => expires.dup)
assert_equal 'key', cookie.name
assert_equal 'value', cookie.value
assert_equal expires, cookie.expires
end
def test_domain=
url = URI.parse('http://host.dom.example.com:8080/')
cookie_str = 'a=b; domain=Example.Com'
cookie = assert_cookie_parse url, cookie_str
assert 'example.com', cookie.domain
cookie.domain = DomainName(url.host)
assert 'host.dom.example.com', cookie.domain
cookie.domain = 'Dom.example.com'
assert 'dom.example.com', cookie.domain
new_domain = Object.new.tap { |o|
def o.to_str
'Example.com'
end
}
cookie.domain = new_domain
assert 'example.com', cookie.domain
new_domain = Object.new.tap { |o|
def o.to_str
'Example2.com'
end
}
assert_output nil, /The call of Mechanize::Cookie#set_domain/ do
cookie.set_domain(new_domain)
end
assert 'example2.com', cookie.domain
end
def test_cookie_httponly
url = URI.parse('http://rubygems.org/')
cookie_params = {}
cookie_params['httponly'] = 'HttpOnly'
cookie_value = '12345%7D=ASDFWEE345%3DASda'
expires = Time.parse('Sun, 27-Sep-2037 00:00:00 GMT')
cookie_params.keys.combine.each do |c|
cookie_text = +"#{cookie_value}; "
c.each_with_index do |key, idx|
if idx == (c.length - 1)
cookie_text << "#{cookie_params[key]}"
else
cookie_text << "#{cookie_params[key]}; "
end
end
cookie = assert_cookie_parse url, cookie_text
assert_equal(true, cookie.httponly)
# if expires was set, make sure we parsed it
if c.find { |k| k == 'expires' }
assert_equal(expires, cookie.expires)
else
assert_nil(cookie.expires)
end
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_http_www_authenticate_parser.rb | test/test_mechanize_http_www_authenticate_parser.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeHttpWwwAuthenticateParser < Mechanize::TestCase
def setup
super
@parser = Mechanize::HTTP::WWWAuthenticateParser.new
end
def test_auth_param
@parser.scanner = StringScanner.new 'realm=here'
param = @parser.auth_param
assert_equal %w[realm here], param
end
def test_auth_param_bad_no_value
@parser.scanner = StringScanner.new 'realm='
assert_nil @parser.auth_param
end
def test_auth_param_bad_token
@parser.scanner = StringScanner.new 'realm'
assert_nil @parser.auth_param
end
def test_auth_param_bad_value
@parser.scanner = StringScanner.new 'realm="this '
assert_nil @parser.auth_param
end
def test_auth_param_quoted
@parser.scanner = StringScanner.new 'realm="this site"'
param = @parser.auth_param
assert_equal ['realm', 'this site'], param
end
def test_parse
expected = [
challenge('Basic', { 'realm' => 'foo', 'qop' => 'auth,auth-int' }, 'Basic realm=foo, qop="auth,auth-int"'),
]
assert_equal expected, @parser.parse('Basic realm=foo, qop="auth,auth-int"')
end
def test_parse_without_comma_delimiter
expected = [
challenge('Basic', { 'realm' => 'foo', 'qop' => 'auth,auth-int' }, 'Basic realm=foo qop="auth,auth-int"'),
]
assert_equal expected, @parser.parse('Basic realm=foo qop="auth,auth-int"')
end
def test_parse_multiple
expected = [
challenge('Basic', { 'realm' => 'foo' }, 'Basic realm=foo'),
challenge('Digest', { 'realm' => 'bar' }, 'Digest realm=bar'),
]
assert_equal expected, @parser.parse('Basic realm=foo, Digest realm=bar')
end
def test_parse_multiple_without_comma_delimiter
expected = [
challenge('Basic', { 'realm' => 'foo' }, 'Basic realm=foo'),
challenge('Digest', { 'realm' => 'bar' }, 'Digest realm=bar'),
]
assert_equal expected, @parser.parse('Basic realm=foo Digest realm=bar')
end
def test_parse_multiple_blank
expected = [
challenge('Basic', { 'realm' => 'foo' }, 'Basic realm=foo'),
challenge('Digest', { 'realm' => 'bar' }, 'Digest realm=bar'),
]
assert_equal expected, @parser.parse('Basic realm=foo,, Digest realm=bar')
end
def test_parse_ntlm_init
expected = [
challenge('NTLM', nil, 'NTLM'),
]
assert_equal expected, @parser.parse('NTLM')
end
def test_parse_ntlm_type_2_3
expected = [
challenge('NTLM', 'foo=', 'NTLM foo='),
]
assert_equal expected, @parser.parse('NTLM foo=')
end
def test_parse_realm_uppercase
expected = [
challenge('Basic', { 'realm' => 'foo' }, 'Basic ReAlM=foo'),
]
assert_equal expected, @parser.parse('Basic ReAlM=foo')
end
def test_parse_realm_value_case
expected = [
challenge('Basic', { 'realm' => 'Foo' }, 'Basic realm=Foo'),
]
assert_equal expected, @parser.parse('Basic realm=Foo')
end
def test_parse_scheme_uppercase
expected = [
challenge('Basic', { 'realm' => 'foo' }, 'BaSiC realm=foo'),
]
assert_equal expected, @parser.parse('BaSiC realm=foo')
end
def test_parse_bad_whitespace_around_auth_param
expected = [
challenge('Basic', { 'realm' => 'foo' }, 'Basic realm = "foo"'),
]
assert_equal expected, @parser.parse('Basic realm = "foo"')
end
def test_parse_bad_single_quote
expected = [
challenge('Basic', { 'realm' => "'foo" }, "Basic realm='foo"),
]
assert_equal expected, @parser.parse("Basic realm='foo bar', qop='baz'")
end
def test_quoted_string
@parser.scanner = StringScanner.new '"text"'
string = @parser.quoted_string
assert_equal 'text', string
end
def test_quoted_string_bad
@parser.scanner = StringScanner.new '"text'
assert_nil @parser.quoted_string
end
def test_quoted_string_quote
@parser.scanner = StringScanner.new '"escaped \\" here"'
string = @parser.quoted_string
assert_equal 'escaped \\" here', string
end
def test_quoted_string_quote_end
@parser.scanner = StringScanner.new '"end \""'
string = @parser.quoted_string
assert_equal 'end \"', string
end
def test_token
@parser.scanner = StringScanner.new 'text'
string = @parser.token
assert_equal 'text', string
end
def test_token_space
@parser.scanner = StringScanner.new 't ext'
string = @parser.token
assert_equal 't', string
end
def test_token_special
@parser.scanner = StringScanner.new "t\text"
string = @parser.token
assert_equal 't', string
end
def challenge scheme, params, raw
Mechanize::HTTP::AuthChallenge.new scheme, params, raw
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_response_read_error.rb | test/test_mechanize_response_read_error.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeResponseReadError < Mechanize::TestCase
def setup
super
@error = 'error message'
@response = Response.new
@response['content-length'] = 3
@body_io = StringIO.new 'body'
end
def test_force_parse
@response['content-type'] = 'text/html'
uri = URI 'http://example/'
e = Mechanize::ResponseReadError.new @error, @response, @body_io, uri, @mech
page = e.force_parse
assert_kind_of Mechanize::Page, page
assert_equal 'body', page.body
assert_equal @mech, page.mech
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_redirect_limit_reached_error.rb | test/test_mechanize_redirect_limit_reached_error.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeRedirectLimitReachedError < Mechanize::TestCase
def setup
super
@error = Mechanize::RedirectLimitReachedError.new fake_page, 10
end
def test_message
assert_equal 'Redirect limit of 10 reached', @error.message
end
def test_redirects
assert_equal 10, @error.redirects
end
def test_response_code
assert_equal 200, @error.response_code
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_select_list.rb | test/test_mechanize_form_select_list.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormSelectList < Mechanize::TestCase
def setup
super
page = html_page <<-BODY
<form name="form1" method="post" action="/form_post">
<select name="select">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select>
</form>
BODY
form = page.forms.first
@select = form.fields.first
end
def test_inspect
assert_match "value: 2", @select.inspect
end
def test_option_with
option = @select.option_with :value => '1'
assert_equal '1', option.value
end
def test_options_with
options = @select.options_with :value => /[12]/
assert_equal 2, options.length
end
def test_query_value
assert_equal [%w[select 2]], @select.query_value
@select.select_all
assert_equal [%w[select 6]], @select.query_value
end
def test_select_all
@select.select_all
assert_equal "6", @select.value
end
def test_select_none
@select.select_none
assert_equal "1", @select.value
end
def test_selected_options
assert_equal [@select.options[1]], @select.selected_options
@select.options.last.click
assert_equal [@select.options.last], @select.selected_options
end
def test_value
assert_equal "2", @select.value
end
def test_value_equals
@select.value = %w[a 1 2]
assert_equal "a", @select.value
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_file_upload.rb | test/test_mechanize_form_file_upload.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormFileUpload < Mechanize::TestCase
def test_file_name
field = node 'input'
field = Mechanize::Form::FileUpload.new field, 'a&b'
assert_equal 'a&b', field.file_name
end
def test_file_name_entity
field = node 'input'
field = Mechanize::Form::FileUpload.new field, 'a&b'
assert_equal 'a&b', field.file_name
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/examples/proxy_req.rb | examples/proxy_req.rb | require 'rubygems'
require 'mechanize'
agent = Mechanize.new
agent.set_proxy('localhost', '8000')
page = agent.get(ARGV[0])
puts page.body
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/examples/flickr_upload.rb | examples/flickr_upload.rb | require 'rubygems'
require 'mechanize'
agent = Mechanize.new
# Get the flickr sign in page
page = agent.get 'http://flickr.com/signin/flickr/'
# Fill out the login form
form = page.form_with :name => 'flickrloginform'
form.email = ARGV[0]
form.password = ARGV[1]
form.submit
# Go to the upload page
page = page.link_with(:text => 'Upload').click
# Fill out the form
form = page.forms.action('/photos_upload_process.gne').first
form.file_uploads.name('file1').first.file_name = ARGV[2]
form.submit
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/examples/latest_user_agents.rb | examples/latest_user_agents.rb | require 'mechanize'
require 'ostruct'
# LatestUAFetcher fetches latest user agents from `WhatIsMyBrowser.com`.
# It can use to update `Mechanize::AGENT_ALIASES`.
class LatestUAFetcher
attr_reader :user_agents
USER_AGENT_TYPES = OpenStruct.new(
linux_firefox: "Linux Firefox",
mac_firefox: "Mac Firefox",
mac_safari: "Mac Safari",
windows_chrome: "Windows Chrome",
windows_edge: "Windows Edge",
windows_firefox: "Windows Firefox",
android: "Android",
iphone: "iPhone",
ipad: "iPad",
)
BASE_URL = 'https://www.whatismybrowser.com/guides/the-latest-user-agent'
def initialize
@agent = Mechanize.new.tap { |a| a.user_agent_alias = 'Mac Firefox' }
@user_agents = {}
end
def run
return unless user_agents.empty?
sleep_time = 1
fetch_user_agents('chrome')
fetch_user_agents('firefox')
fetch_user_agents('safari')
fetch_user_agents('edge')
end
def ordered_user_agents
USER_AGENT_TYPES.to_h.values.each_with_object({}) do |type, ordered_user_agents|
ordered_user_agents[type] = user_agents[type]
end
end
private
def fetch_user_agents(browser_name, sleep_time = 1)
puts "fetch #{browser_name} UA..."
send(browser_name)
puts "sleeping... (#{sleep_time}s)"
sleep sleep_time
end
def edge
page = @agent.get("#{BASE_URL}/edge")
windows_dom = page.css("h2:contains('Latest Edge on Windows User Agents')")
@user_agents[USER_AGENT_TYPES.windows_edge] = windows_dom.css('+ .listing-of-useragents .code').first.text
end
def firefox
page = @agent.get("#{BASE_URL}/firefox")
desktop_dom = page.css("h2:contains('Latest Firefox on Desktop User Agents')")
table_dom = desktop_dom.css('+ .listing-of-useragents')
@user_agents[USER_AGENT_TYPES.linux_firefox] = table_dom.css('td:contains("Linux")').css("+ td .code:contains('Ubuntu; Linux x86_64')").text
@user_agents[USER_AGENT_TYPES.windows_firefox] = table_dom.css('td:contains("Windows")').css('+ td .code').text
@user_agents[USER_AGENT_TYPES.mac_firefox] = table_dom.css('td:contains("Macos")').css('+ td .code').text
end
def safari
page = @agent.get("#{BASE_URL}/safari")
macos_dom = page.css("h2:contains('Latest Safari on macOS User Agents')")
ios_dom = page.css("h2:contains('Latest Safari on iOS User Agents')")
@user_agents[USER_AGENT_TYPES.mac_safari] = macos_dom.css('+ .listing-of-useragents .code').first.text
@user_agents[USER_AGENT_TYPES.iphone] = ios_dom.css('+ .listing-of-useragents').css("tr:contains('Iphone') .code").text
@user_agents[USER_AGENT_TYPES.ipad] = ios_dom.css('+ .listing-of-useragents').css("tr:contains('Ipad') .code").text
end
def chrome
page = @agent.get("#{BASE_URL}/chrome")
windows_dom = page.css("h2:contains('Latest Chrome on Windows 10 User Agents')")
android_dom = page.css("h2:contains('Latest Chrome on Android User Agents')")
@user_agents[USER_AGENT_TYPES.windows_chrome] = windows_dom.css('+ .listing-of-useragents .code').first.text
@user_agents[USER_AGENT_TYPES.android] = android_dom.css('+ .listing-of-useragents .code').first.text
end
end
if $0 == __FILE__
agent = LatestUAFetcher.new
agent.run
pp agent.ordered_user_agents
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/examples/rubygems.rb | examples/rubygems.rb | # This example logs a user in to rubygems and prints out the body of the
# page after logging the user in.
require 'rubygems'
require 'mechanize'
require 'logger'
# Create a new mechanize object
mech = Mechanize.new
mech.log = Logger.new $stderr
mech.agent.http.debug_output = $stderr
# Load the rubygems website
page = mech.get('https://rubygems.org/')
page = mech.click page.link_with(:text => /Sign in/) # Click the login link
form = page.forms[1] # Select the first form
form["session[who]"] = ARGV[0]
form["session[password]"] = ARGV[1]
form["commit"] = "Sign in"
# Submit the form
page = form.submit form.buttons.first
puts page.body # Print out the body
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/examples/mech-dump.rb | examples/mech-dump.rb | require 'rubygems'
require 'mechanize'
agent = Mechanize.new
puts agent.get(ARGV[0]).inspect
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/examples/wikipedia_links_to_philosophy.rb | examples/wikipedia_links_to_philosophy.rb | require 'mechanize'
require 'tsort'
##
# This example implements the alt-text of http://xkcd.com/903/ which states:
#
# Wikipedia trivia: if you take any article, click on the first link in the
# article text not in parentheses or italics, and then repeat, you will
# eventually end up at "Philosophy".
class WikipediaLinksToPhilosophy
def initialize
@agent = Mechanize.new
@agent.user_agent_alias = 'Mac Safari' # Wikipedia blocks "mechanize"
@history = @agent.history
@wiki_url = URI 'http://en.wikipedia.org'
@search_url = @wiki_url + '/w/index.php'
@random_url = @wiki_url + '/wiki/Special:Random'
@title = nil
@seen = nil
end
##
# Retrieves the title of the current page
def extract_title
@page.title =~ /(.*) - Wikipedia/
@title = $1
end
##
# Retrieves the initial page. If +query+ is not given a random page is
# chosen
def fetch_first_page query
if query then
search query
else
random
end
end
##
# The search is finished if we've seen the page before or we've reached
# Philosophy
def finished?
@seen or @title == 'Philosophy'
end
##
# Follows the first non-parenthetical, non-italic link in the main body of
# the article.
def follow_first_link
puts "#{@title} (#{@page.uri})"
# > p > a rejects italics
links = @page.root.css('.mw-content-ltr p > a[href^="/wiki/"]')
# reject disambiguation and special pages, images and files
links = links.reject do |link_node|
link_node['href'] =~ %r%/wiki/\w+:|\(disambiguation\)%
end
links = links.reject do |link_node|
in_parenthetical? link_node
end
link = links.first
if link.nil?
puts "Could not parse #{@page.uri}"
exit 1
end
# convert a Nokogiri HTML element back to a mechanize link
link = Mechanize::Page::Link.new link, @agent, @page
return if @seen = @agent.visited?(link)
@page = link.click
extract_title
end
##
# Is +link_node+ in an open parenthetical section?
def in_parenthetical? link_node
siblings = link_node.parent.children
seen = false
before = siblings.reject do |node|
seen or (seen = node == link_node)
end
preceding_text = before.map { |node| node.text }.join
open = preceding_text.count '('
close = preceding_text.count ')'
open > close
end
##
# Prints the result of the search
def print_result
if @seen then
puts "[Loop detected]"
else
puts @title
end
puts
# subtract initial search or Special:Random
puts "After #{@agent.history.length - 1} pages"
end
##
# Retrieves a random page from wikipedia
def random
@page = @agent.get @random_url
extract_title
end
##
# Entry point
def run query = nil
fetch_first_page query
follow_first_link until finished?
print_result
end
##
# Searches for +query+ on wikipedia
def search query
@page = @agent.get @search_url, search: query
extract_title
end
end
WikipediaLinksToPhilosophy.new.run ARGV.shift if $0 == __FILE__
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/examples/spider.rb | examples/spider.rb | require 'rubygems'
require 'mechanize'
agent = Mechanize.new
agent.max_history = nil # unlimited history
stack = agent.get(ARGV[0]).links
while l = stack.pop
next unless l.uri
host = l.uri.host
next unless host.nil? or host == agent.history.first.uri.host
next if agent.visited? l.href
puts "crawling #{l.uri}"
begin
page = l.click
next unless Mechanize::Page === page
stack.push(*page.links)
rescue Mechanize::ResponseCodeError
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize.rb | lib/mechanize.rb | # frozen_string_literal: true
require 'mechanize/version'
require 'fileutils'
require 'forwardable'
require 'net/http/digest_auth'
require 'net/http/persistent'
require 'nokogiri'
require 'openssl'
require 'pp'
require 'stringio'
require 'uri'
require 'webrick/httputils'
require 'zlib'
##
# The Mechanize library is used for automating interactions with a website. It
# can follow links and submit forms. Form fields can be populated and
# submitted. A history of URLs is maintained and can be queried.
#
# == Example
#
# require 'mechanize'
# require 'logger'
#
# agent = Mechanize.new
# agent.log = Logger.new "mech.log"
# agent.user_agent_alias = 'Mac Safari'
#
# page = agent.get "http://www.google.com/"
# search_form = page.form_with :name => "f"
# search_form.field_with(:name => "q").value = "Hello"
#
# search_results = agent.submit search_form
# puts search_results.body
#
# == Issues with mechanize
#
# If you think you have a bug with mechanize, but aren't sure, please file a
# ticket at https://github.com/sparklemotion/mechanize/issues
#
# Here are some common problems you may experience with mechanize
#
# === Problems connecting to SSL sites
#
# Mechanize defaults to validating SSL certificates using the default CA
# certificates for your platform. At this time, Windows users do not have
# integration between the OS default CA certificates and OpenSSL. #cert_store
# explains how to download and use Mozilla's CA certificates to allow SSL
# sites to work.
#
# === Problems with content-length
#
# Some sites return an incorrect content-length value. Unlike a browser,
# mechanize raises an error when the content-length header does not match the
# response length since it does not know if there was a connection problem or
# if the mismatch is a server bug.
#
# The error raised, Mechanize::ResponseReadError, can be converted to a parsed
# Page, File, etc. depending upon the content-type:
#
# agent = Mechanize.new
# uri = URI 'http://example/invalid_content_length'
#
# begin
# page = agent.get uri
# rescue Mechanize::ResponseReadError => e
# page = e.force_parse
# end
class Mechanize
##
# Base mechanize error class
class Error < RuntimeError
end
ruby_version = if RUBY_PATCHLEVEL >= 0 then
"#{RUBY_VERSION}p#{RUBY_PATCHLEVEL}"
else
"#{RUBY_VERSION}dev#{RUBY_REVISION}"
end
##
# Supported User-Agent aliases for use with user_agent_alias=. The
# description in parenthesis is for informative purposes and is not part of
# the alias name.
#
# The default User-Agent alias:
#
# * "Mechanize"
#
# Linux User-Agent aliases:
#
# * "Linux Firefox"
# * "Linux Konqueror"
# * "Linux Mozilla"
#
# Mac User-Agent aliases:
#
# * "Mac Firefox"
# * "Mac Mozilla"
# * "Mac Safari 4"
# * "Mac Safari"
#
# Windows User-Agent aliases:
#
# * "Windows Chrome"
# * "Windows Edge"
# * "Windows Firefox"
# * "Windows IE 6"
# * "Windows IE 7"
# * "Windows IE 8"
# * "Windows IE 9"
# * "Windows IE 10"
# * "Windows IE 11"
# * "Windows Mozilla"
#
# Mobile User-Agent aliases:
#
# * "Android"
# * "iPad"
# * "iPhone"
#
# Example:
#
# agent = Mechanize.new
# agent.user_agent_alias = 'Mac Safari'
#
AGENT_ALIASES = {
'Mechanize' => "Mechanize/#{VERSION} Ruby/#{ruby_version} (http://github.com/sparklemotion/mechanize/)",
'Linux Firefox' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/121.0',
'Linux Konqueror' => 'Mozilla/5.0 (compatible; Konqueror/3; Linux)',
'Linux Mozilla' => 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030624',
'Mac Firefox' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14.2; rv:109.0) Gecko/20100101 Firefox/121.0',
'Mac Mozilla' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4a) Gecko/20030401',
'Mac Safari 4' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; de-at) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10',
'Mac Safari' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_2_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15',
'Windows Chrome' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Windows Edge' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.2210.133',
'Windows Firefox' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0',
'Windows IE 6' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Windows IE 7' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
'Windows IE 8' => 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
'Windows IE 9' => 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)',
'Windows IE 10' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)',
'Windows IE 11' => 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Windows Mozilla' => 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030516 Mozilla Firebird/0.6',
'Android' => 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.210 Mobile Safari/537.36',
'iPad' => 'Mozilla/5.0 (iPad; CPU OS 17_2_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1',
'iPhone' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_2_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1',
}
AGENT_ALIASES.default_proc = proc { |hash, key|
case key
when /FireFox/
if ua = hash[nkey = key.sub(/FireFox/, 'Firefox')]
warn "Mechanize#user_agent_alias: #{key.inspect} should be spelled as #{nkey.inspect}"
ua
end
end
}
def self.inherited(child) # :nodoc:
child.html_parser = html_parser
child.log = log
super
end
##
# Creates a new Mechanize instance and yields it to the given block.
#
# After the block executes, the instance is cleaned up. This includes
# closing all open connections.
#
# Mechanize.start do |m|
# m.get("http://example.com")
# end
def self.start
instance = new
yield(instance)
ensure
instance.shutdown
end
##
# Creates a new mechanize instance. If a block is given, the created
# instance is yielded to the block for setting up pre-connection state such
# as SSL parameters or proxies:
#
# agent = Mechanize.new do |a|
# a.proxy_addr = 'proxy.example'
# a.proxy_port = 8080
# end
#
# If you need segregated SSL connections give each agent a unique
# name. Otherwise the connections will be shared. This is
# particularly important if you are using certificates.
#
# agent_1 = Mechanize.new 'conn1'
# agent_2 = Mechanize.new 'conn2'
#
def initialize(connection_name = 'mechanize')
@agent = Mechanize::HTTP::Agent.new(connection_name)
@agent.context = self
@log = nil
# attr_accessors
@agent.user_agent = AGENT_ALIASES['Mechanize']
@watch_for_set = nil
@history_added = nil
# attr_readers
@pluggable_parser = PluggableParser.new
@keep_alive_time = 0
# Proxy
@proxy_addr = nil
@proxy_port = nil
@proxy_user = nil
@proxy_pass = nil
@html_parser = self.class.html_parser
@default_encoding = nil
@force_default_encoding = false
# defaults
@agent.max_history = 50
yield self if block_given?
@agent.set_proxy @proxy_addr, @proxy_port, @proxy_user, @proxy_pass
end
# :section: History
#
# Methods for navigating and controlling history
##
# Equivalent to the browser back button. Returns the previous page visited.
def back
@agent.history.pop
end
##
# Returns the latest page loaded by Mechanize
def current_page
@agent.current_page
end
alias page current_page
##
# The history of this mechanize run
def history
@agent.history
end
##
# Maximum number of items allowed in the history. The default setting is 50
# pages. Note that the size of the history multiplied by the maximum
# response body size
def max_history
@agent.history.max_size
end
##
# Sets the maximum number of items allowed in the history to +length+.
#
# Setting the maximum history length to nil will make the history size
# unlimited. Take care when doing this, mechanize stores response bodies in
# memory for pages and in the temporary files directory for other responses.
# For a long-running mechanize program this can be quite large.
#
# See also the discussion under #max_file_buffer=
def max_history= length
@agent.history.max_size = length
end
##
# Returns a visited page for the +url+ passed in, otherwise nil
def visited? url
url = url.href if url.respond_to? :href
@agent.visited_page url
end
##
# Returns whether or not a url has been visited
alias visited_page visited?
# :section: Hooks
#
# Hooks into the operation of mechanize
##
# A list of hooks to call before reading response header 'content-encoding'.
#
# The hook is called with the agent making the request, the URI of the
# request, the response an IO containing the response body.
def content_encoding_hooks
@agent.content_encoding_hooks
end
##
# Callback which is invoked with the page that was added to history.
attr_accessor :history_added
##
# A list of hooks to call after retrieving a response. Hooks are called with
# the agent, the URI, the response, and the response body.
def post_connect_hooks
@agent.post_connect_hooks
end
##
# A list of hooks to call before retrieving a response. Hooks are called
# with the agent, the URI, the response, and the response body.
def pre_connect_hooks
@agent.pre_connect_hooks
end
# :section: Requests
#
# Methods for making HTTP requests
##
# If the parameter is a string, finds the button or link with the
# value of the string on the current page and clicks it. Otherwise, clicks
# the Mechanize::Page::Link object passed in. Returns the page fetched.
def click link
case link
when Page::Link then
referer = link.page || current_page()
if @agent.robots
if (referer.is_a?(Page) and referer.parser.nofollow?) or
link.rel?('nofollow') then
raise RobotsDisallowedError.new(link.href)
end
end
if link.noreferrer?
href = @agent.resolve(link.href, link.page || current_page)
referer = Page.new
else
href = link.href
end
get href, [], referer
when String, Regexp then
if real_link = page.link_with(:text => link)
click real_link
else
button = nil
# Note that this will not work if we have since navigated to a different page.
# Should rather make each button aware of its parent form.
form = page.forms.find do |f|
button = f.button_with(:value => link)
button.is_a? Form::Submit
end
submit form, button if form
end
when Form::Submit, Form::ImageButton then
# Note that this will not work if we have since navigated to a different page.
# Should rather make each button aware of its parent form.
form = page.forms.find do |f|
f.buttons.include?(link)
end
submit form, link if form
else
referer = current_page()
href = link.respond_to?(:href) ? link.href :
(link['href'] || link['src'])
get href, [], referer
end
end
##
# GETs +uri+ and writes it to +io_or_filename+ without recording the request
# in the history. If +io_or_filename+ does not respond to #write it will be
# used as a file name. +parameters+, +referer+ and +headers+ are used as in
# #get.
#
# By default, if the Content-type of the response matches a Mechanize::File
# or Mechanize::Page parser, the response body will be loaded into memory
# before being saved. See #pluggable_parser for details on changing this
# default.
#
# For alternate ways of downloading files see Mechanize::FileSaver and
# Mechanize::DirectorySaver.
def download uri, io_or_filename, parameters = [], referer = nil, headers = {}
page = transact do
get uri, parameters, referer, headers
end
io = if io_or_filename.respond_to? :write then
io_or_filename
else
::File.open(io_or_filename, 'wb')
end
case page
when Mechanize::File then
io.write page.body
else
body_io = page.body_io
until body_io.eof? do
io.write body_io.read 16384
end
end
page
ensure
io.close if io and not io_or_filename.respond_to? :write
end
##
# DELETE +uri+ with +query_params+, and setting +headers+:
#
# +query_params+ is formatted into a query string using
# Mechanize::Util.build_query_string, which see.
#
# delete('http://example/', {'q' => 'foo'}, {})
def delete(uri, query_params = {}, headers = {})
page = @agent.fetch(uri, :delete, headers, query_params)
add_to_history(page)
page
end
##
# GET the +uri+ with the given request +parameters+, +referer+ and
# +headers+.
#
# The +referer+ may be a URI or a page.
#
# +parameters+ is formatted into a query string using
# Mechanize::Util.build_query_string, which see.
def get(uri, parameters = [], referer = nil, headers = {})
method = :get
referer ||=
if uri.to_s =~ %r{\Ahttps?://}
Page.new
else
current_page || Page.new
end
# FIXME: Huge hack so that using a URI as a referer works. I need to
# refactor everything to pass around URIs but still support
# Mechanize::Page#base
unless Mechanize::Parser === referer then
referer = if referer.is_a?(String) then
Page.new URI(referer)
else
Page.new referer
end
end
# fetch the page
headers ||= {}
page = @agent.fetch uri, method, headers, parameters, referer
add_to_history(page)
yield page if block_given?
page
end
##
# GET +url+ and return only its contents
def get_file(url)
get(url).body
end
##
# HEAD +uri+ with +query_params+ and +headers+:
#
# +query_params+ is formatted into a query string using
# Mechanize::Util.build_query_string, which see.
#
# head('http://example/', {'q' => 'foo'}, {})
def head(uri, query_params = {}, headers = {})
page = @agent.fetch uri, :head, headers, query_params
yield page if block_given?
page
end
##
# POST to the given +uri+ with the given +query+.
#
# +query+ is processed using Mechanize::Util.each_parameter (which
# see), and then encoded into an entity body. If any IO/FileUpload
# object is specified as a field value the "enctype" will be
# multipart/form-data, or application/x-www-form-urlencoded
# otherwise.
#
# Examples:
# agent.post 'http://example.com/', "foo" => "bar"
#
# agent.post 'http://example.com/', [%w[foo bar]]
#
# agent.post('http://example.com/', "<message>hello</message>",
# 'Content-Type' => 'application/xml')
def post(uri, query = {}, headers = {})
return request_with_entity(:post, uri, query, headers) if String === query
node = {}
# Create a fake form
class << node
def search(*args); []; end
end
node['method'] = 'POST'
node['enctype'] = 'application/x-www-form-urlencoded'
form = Form.new(node)
Mechanize::Util.each_parameter(query) { |k, v|
if v.is_a?(IO)
form.enctype = 'multipart/form-data'
ul = Form::FileUpload.new({'name' => k.to_s},::File.basename(v.path))
ul.file_data = v.read
form.file_uploads << ul
elsif v.is_a?(Form::FileUpload)
form.enctype = 'multipart/form-data'
form.file_uploads << v
else
form.fields << Form::Field.new({'name' => k.to_s},v)
end
}
post_form(uri, form, headers)
end
##
# PUT to +uri+ with +entity+, and setting +headers+:
#
# put('http://example/', 'new content', {'Content-Type' => 'text/plain'})
def put(uri, entity, headers = {})
request_with_entity(:put, uri, entity, headers)
end
##
# Makes an HTTP request to +url+ using HTTP method +verb+. +entity+ is used
# as the request body, if allowed.
def request_with_entity(verb, uri, entity, headers = {})
cur_page = current_page || Page.new
log.debug("query: #{ entity.inspect }") if log
headers = {
'Content-Type' => 'application/octet-stream',
'Content-Length' => entity.size.to_s,
}.update headers
page = @agent.fetch uri, verb, headers, [entity], cur_page
add_to_history(page)
page
end
##
# Submits +form+ with an optional +button+.
#
# Without a button:
#
# page = agent.get('http://example.com')
# agent.submit(page.forms.first)
#
# With a button:
#
# agent.submit(page.forms.first, page.forms.first.buttons.first)
def submit(form, button = nil, headers = {})
form.add_button_to_query(button) if button
case form.method.upcase
when 'POST'
post_form(form.action, form, headers)
when 'GET'
get(form.action.gsub(/\?[^\?]*$/, ''),
form.build_query,
form.page,
headers)
else
raise ArgumentError, "unsupported method: #{form.method.upcase}"
end
end
##
# Runs given block, then resets the page history as it was before. self is
# given as a parameter to the block. Returns the value of the block.
def transact
history_backup = @agent.history.dup
begin
yield self
ensure
@agent.history = history_backup
end
end
# :section: Settings
#
# Settings that adjust how mechanize makes HTTP requests including timeouts,
# keep-alives, compression, redirects and headers.
@html_parser = Nokogiri::HTML
@log = nil
class << self
##
# Default HTML parser for all mechanize instances
#
# Mechanize.html_parser = Nokogiri::XML
attr_accessor :html_parser
##
# Default logger for all mechanize instances
#
# Mechanize.log = Logger.new $stderr
attr_accessor :log
end
##
# A default encoding name used when parsing HTML parsing. When set it is
# used after any other encoding. The default is nil.
attr_accessor :default_encoding
##
# Overrides the encodings given by the HTTP server and the HTML page with
# the default_encoding when set to true.
attr_accessor :force_default_encoding
##
# The HTML parser to be used when parsing documents
attr_accessor :html_parser
##
# HTTP/1.0 keep-alive time. This is no longer supported by mechanize as it
# now uses net-http-persistent which only supports HTTP/1.1 persistent
# connections
attr_accessor :keep_alive_time
##
# The pluggable parser maps a response Content-Type to a parser class. The
# registered Content-Type may be either a full content type like 'image/png'
# or a media type 'text'. See Mechanize::PluggableParser for further
# details.
#
# Example:
#
# agent.pluggable_parser['application/octet-stream'] = Mechanize::Download
attr_reader :pluggable_parser
##
# The HTTP proxy address
attr_reader :proxy_addr
##
# The HTTP proxy password
attr_reader :proxy_pass
##
# The HTTP proxy port
attr_reader :proxy_port
##
# The HTTP proxy username
attr_reader :proxy_user
##
# *NOTE*: These credentials will be used as a default for any challenge
# exposing your password to disclosure to malicious servers. Use of this
# method will warn. This method is deprecated and will be removed in
# mechanize 3.
#
# Sets the +user+ and +password+ as the default credentials to be used for
# HTTP authentication for any server. The +domain+ is used for NTLM
# authentication.
def auth user, password, domain = nil
c = caller_locations(1,1).first
warn <<-WARNING
At #{c.absolute_path} line #{c.lineno}
Use of #auth and #basic_auth are deprecated due to a security vulnerability.
WARNING
@agent.add_default_auth user, password, domain
end
alias basic_auth auth
##
# 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
@agent.add_auth uri, user, password, realm, domain
end
##
# Are If-Modified-Since conditional requests enabled?
def conditional_requests
@agent.conditional_requests
end
##
# Disables If-Modified-Since conditional requests (enabled by default)
def conditional_requests= enabled
@agent.conditional_requests = enabled
end
##
# A Mechanize::CookieJar which stores cookies
def cookie_jar
@agent.cookie_jar
end
##
# Replaces the cookie jar with +cookie_jar+
def cookie_jar= cookie_jar
@agent.cookie_jar = cookie_jar
end
##
# Returns a list of cookies stored in the cookie jar.
def cookies
@agent.cookie_jar.to_a
end
##
# Follow HTML meta refresh and HTTP Refresh headers. If set to +:anywhere+
# meta refresh tags outside of the head element will be followed.
def follow_meta_refresh
@agent.follow_meta_refresh
end
##
# Controls following of HTML meta refresh and HTTP Refresh headers in
# responses.
def follow_meta_refresh= follow
@agent.follow_meta_refresh = follow
end
##
# Follow an HTML meta refresh and HTTP Refresh headers that have no "url="
# in the content attribute.
#
# Defaults to false to prevent infinite refresh loops.
def follow_meta_refresh_self
@agent.follow_meta_refresh_self
end
##
# Alters the following of HTML meta refresh and HTTP Refresh headers that
# point to the same page.
def follow_meta_refresh_self= follow
@agent.follow_meta_refresh_self = follow
end
##
# Is gzip compression of responses enabled?
def gzip_enabled
@agent.gzip_enabled
end
##
# Disables HTTP/1.1 gzip compression (enabled by default)
def gzip_enabled=enabled
@agent.gzip_enabled = enabled
end
##
# Connections that have not been used in this many seconds will be reset.
def idle_timeout
@agent.idle_timeout
end
# Sets the idle timeout to +idle_timeout+. The default timeout is 5
# seconds. If you experience "too many connection resets", reducing this
# value may help.
def idle_timeout= idle_timeout
@agent.idle_timeout = idle_timeout
end
##
# 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.
#
# Net::HTTP does not inform mechanize of where in the chunked stream the EOF
# occurred. Usually it is after the last-chunk but before the terminating
# CRLF (invalid termination) but it may occur earlier. In the second case
# your response body may be incomplete.
def ignore_bad_chunking
@agent.ignore_bad_chunking
end
##
# When set to true mechanize will ignore an EOF during chunked transfer
# encoding. See ignore_bad_chunking for further details
def ignore_bad_chunking= ignore_bad_chunking
@agent.ignore_bad_chunking = ignore_bad_chunking
end
##
# Are HTTP/1.1 keep-alive connections enabled?
def keep_alive
@agent.keep_alive
end
##
# Disable HTTP/1.1 keep-alive connections if +enable+ is set to false. If
# you are experiencing "too many connection resets" errors setting this to
# false will eliminate them.
#
# You should first investigate reducing idle_timeout.
def keep_alive= enable
@agent.keep_alive = enable
end
##
# The current logger. If no logger has been set Mechanize.log is used.
def log
@log || Mechanize.log
end
##
# Sets the +logger+ used by this instance of mechanize
def log= logger
@log = logger
end
##
# Responses larger than this will be written to a Tempfile instead of stored
# in memory. The default is 100,000 bytes.
#
# A value of nil disables creation of Tempfiles.
def max_file_buffer
@agent.max_file_buffer
end
##
# Sets the maximum size of a response body that will be stored in memory to
# +bytes+. A value of nil causes all response bodies to be stored in
# memory.
#
# Note that for Mechanize::Download subclasses, the maximum buffer size
# multiplied by the number of pages stored in history (controlled by
# #max_history) is an approximate upper limit on the amount of memory
# Mechanize will use. By default, Mechanize can use up to ~5MB to store
# response bodies for non-File and non-Page (HTML) responses.
#
# See also the discussion under #max_history=
def max_file_buffer= bytes
@agent.max_file_buffer = bytes
end
##
# Length of time to wait until a connection is opened in seconds
def open_timeout
@agent.open_timeout
end
##
# Sets the connection open timeout to +open_timeout+
def open_timeout= open_timeout
@agent.open_timeout = open_timeout
end
##
# Length of time to wait for data from the server
def read_timeout
@agent.read_timeout
end
##
# Sets the timeout for each chunk of data read from the server to
# +read_timeout+. A single request may read many chunks of data.
def read_timeout= read_timeout
@agent.read_timeout = read_timeout
end
##
# Length of time to wait for data to be sent to the server
def write_timeout
@agent.write_timeout
end
##
# Sets the timeout for each chunk of data to be sent to the server to
# +write_timeout+. A single request may write many chunks of data.
def write_timeout= write_timeout
@agent.write_timeout = write_timeout
end
##
# Controls how mechanize 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
def redirect_ok
@agent.redirect_ok
end
alias follow_redirect? redirect_ok
##
# Sets the mechanize redirect handling policy. See redirect_ok for allowed
# values
def redirect_ok= follow
@agent.redirect_ok = follow
end
alias follow_redirect= redirect_ok=
##
# Maximum number of redirections to follow
def redirection_limit
@agent.redirection_limit
end
##
# Sets the maximum number of redirections to follow to +limit+
def redirection_limit= limit
@agent.redirection_limit = limit
end
##
# Resolve the full path of a link / uri
def resolve link
@agent.resolve link
end
##
# A hash of custom request headers that will be sent on every request
def request_headers
@agent.request_headers
end
##
# Replaces the custom request headers that will be sent on every request
# with +request_headers+
def request_headers= request_headers
@agent.request_headers = request_headers
end
##
# Retry POST and other non-idempotent requests. See RFC 2616 9.1.2.
def retry_change_requests
@agent.retry_change_requests
end
##
# When setting +retry_change_requests+ to true you are stating that, for all
# the URLs you access with mechanize, making POST and other non-idempotent
# requests is safe and will not cause data duplication or other harmful
# results.
#
# If you are experiencing "too many connection resets" errors you should
# instead investigate reducing the idle_timeout or disabling keep_alive
# connections.
def retry_change_requests= retry_change_requests
@agent.retry_change_requests = retry_change_requests
end
##
# Will <code>/robots.txt</code> files be obeyed?
def robots
@agent.robots
end
##
# When +enabled+ mechanize will retrieve and obey <code>robots.txt</code>
# files
def robots= enabled
@agent.robots = enabled
end
##
# The handlers for HTTP and other URI protocols.
def scheme_handlers
@agent.scheme_handlers
end
##
# Replaces the URI scheme handler table with +scheme_handlers+
def scheme_handlers= scheme_handlers
@agent.scheme_handlers = scheme_handlers
end
##
# The identification string for the client initiating a web request
def user_agent
@agent.user_agent
end
##
# Sets the User-Agent used by mechanize to +user_agent+. See also
# user_agent_alias
def user_agent= user_agent
@agent.user_agent = user_agent
end
##
# Set the user agent for the Mechanize object based on the given +name+.
#
# See also AGENT_ALIASES
def user_agent_alias= name
self.user_agent = AGENT_ALIASES[name] ||
raise(ArgumentError, "unknown agent alias #{name.inspect}")
end
##
# The value of watch_for_set is passed to pluggable parsers for retrieved
# content
attr_accessor :watch_for_set
# :section: SSL
#
# SSL settings for mechanize. These must be set in the block given to
# Mechanize.new
##
# Path to an OpenSSL server certificate file
def ca_file
@agent.ca_file
end
##
# Sets the certificate file used for SSL connections
def ca_file= ca_file
@agent.ca_file = ca_file
end
##
# An OpenSSL client certificate or the path to a certificate file.
def cert
@agent.certificate
end
##
# Sets the OpenSSL client certificate +cert+ to the given path or
# certificate instance
def cert= cert
@agent.certificate = cert
end
##
# An OpenSSL certificate store for verifying server certificates. This
# defaults to the default certificate store for your system.
#
# If your system does not ship with a default set of certificates you can
# retrieve a copy of the set from Mozilla here:
# http://curl.haxx.se/docs/caextract.html
#
# (Note that this set does not have an HTTPS download option so you may
# wish to use the firefox-db2pem.sh script to extract the certificates
# from a local install to avoid man-in-the-middle attacks.)
#
# After downloading or generating a cacert.pem from the above link you
# can create a certificate store from the pem file like this:
#
# cert_store = OpenSSL::X509::Store.new
# cert_store.add_file 'cacert.pem'
#
# And have mechanize use it with:
#
# agent.cert_store = cert_store
def cert_store
@agent.cert_store
end
##
# Sets the OpenSSL certificate store to +store+.
#
# See also #cert_store
def cert_store= cert_store
@agent.cert_store = cert_store
end
##
# What is this?
#
# Why is it different from #cert?
def certificate # :nodoc:
@agent.certificate
end
##
# An OpenSSL private key or the path to a private key
def key
@agent.private_key
end
##
# Sets the OpenSSL client +key+ to the given path or key instance. If a
# path is given, the path must contain an RSA key file.
def key= key
@agent.private_key = key
end
##
# OpenSSL client key password
def pass
@agent.pass
end
##
# Sets the client key password to +pass+
def pass= pass
@agent.pass = pass
end
##
# SSL version to use.
def ssl_version
@agent.ssl_version
end
##
# Sets the SSL version to use to +version+ without client/server
# negotiation.
def ssl_version= ssl_version
@agent.ssl_version = ssl_version
end
##
# A callback for additional certificate verification. See
# OpenSSL::SSL::SSLContext#verify_callback
#
# The callback can be used for debugging or to ignore errors by always
# returning +true+. Specifying nil uses the default method that was valid
# when the SSLContext was created
def verify_callback
@agent.verify_callback
end
##
# Sets the OpenSSL certificate verification callback
def verify_callback= verify_callback
@agent.verify_callback = verify_callback
end
##
# the OpenSSL server certificate verification method. The default is
# OpenSSL::SSL::VERIFY_PEER and certificate verification uses the default
# system certificates. See also cert_store
def verify_mode
@agent.verify_mode
end
##
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | true |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/redirect_not_get_or_head_error.rb | lib/mechanize/redirect_not_get_or_head_error.rb | # frozen_string_literal: true
##
# Raised when a POST, PUT, or DELETE request results in a redirect
# see RFC 2616 10.3.2, 10.3.3 http://www.ietf.org/rfc/rfc2616.txt
class Mechanize::RedirectNotGetOrHeadError < Mechanize::Error
attr_reader :page, :response_code, :verb, :uri
def initialize(page, verb)
@page = page
@verb = verb
@uri = page.uri
@response_code = page.code
end
def to_s
method = @verb.to_s.upcase
"#{@response_code} redirect received after a #{method} request"
end
alias :inspect :to_s
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/chunked_termination_error.rb | lib/mechanize/chunked_termination_error.rb | # frozen_string_literal: true
##
# Raised when Mechanize detects the chunked transfer-encoding may be
# incorrectly terminated.
class Mechanize::ChunkedTerminationError < Mechanize::ResponseReadError
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/download.rb | lib/mechanize/download.rb | # frozen_string_literal: true
##
# Download is a pluggable parser for downloading files without loading them
# into memory first. You may subclass this class to handle content types you
# do not wish to load into memory first.
#
# See Mechanize::PluggableParser for instructions on using this class.
class Mechanize::Download
include Mechanize::Parser
##
# The filename for this file based on the content-disposition of the
# response or the basename of the URL
attr_accessor :filename
##
# Accessor for the IO-like that contains the body
attr_reader :body_io
alias content body_io
##
# Creates a new download retrieved from the given +uri+ and +response+
# object. The +body_io+ is an IO-like containing the HTTP response body and
# +code+ is the HTTP status.
def initialize uri = nil, response = nil, body_io = nil, code = nil
@uri = uri
@body_io = body_io
@code = code
@full_path = false unless defined? @full_path
fill_header response
extract_filename
yield self if block_given?
end
##
# The body of this response as a String.
#
# Take care, this may use lots of memory if the response body is large.
def body
@body_io.read.tap { @body_io.rewind }
end
##
# Saves a copy of the body_io to +filename+
# returns the filename
def save filename = nil
filename = find_free_name filename
save! filename
end
alias save_as save
##
# Use this method to save the content of body_io to +filename+.
# This method will overwrite any existing filename that exists with the
# same name.
# returns the filename
def save! filename = nil
filename ||= @filename
dirname = File.dirname filename
FileUtils.mkdir_p dirname
::File.open(filename, 'wb')do |io|
until @body_io.eof? do
io.write @body_io.read 16384
end
end
filename
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.rb | lib/mechanize/test_case.rb | # frozen_string_literal: true
require 'mechanize'
require 'logger'
require 'tempfile'
require 'tmpdir'
require 'webrick'
require 'zlib'
require 'rubygems'
begin
gem 'minitest'
rescue Gem::LoadError
end
require 'minitest/autorun'
##
# A generic test case for testing mechanize. Using a subclass of
# Mechanize::TestCase for your tests will create an isolated mechanize
# instance that won't pollute your filesystem or other tests.
#
# Once Mechanize::TestCase is loaded no HTTP requests will be made outside
# mechanize itself. All requests are handled via WEBrick servlets.
#
# Mechanize uses WEBrick servlets to test some functionality. You can run
# other HTTP clients against the servlets using:
#
# ruby -rmechanize/test_case/server -e0
#
# Which will launch a test server at http://localhost:8000
class Mechanize::TestCase < Minitest::Test
TEST_DIR = File.expand_path '../../../test', __FILE__
REQUESTS = []
##
# Creates a clean mechanize instance +@mech+ for use in tests.
def setup
super
REQUESTS.clear
@mech = Mechanize.new
@ssl_private_key = nil
@ssl_certificate = nil
end
##
# Creates a fake page with URI http://fake.example and an empty, submittable
# form.
def fake_page agent = @mech
uri = URI 'http://fake.example/'
html = String.new(<<~END)
<html>
<body>
<form><input type="submit" value="submit" /></form>
</body>
</html>
END
Mechanize::Page.new uri, nil, html, 200, agent
end
##
# Is the Encoding constant defined?
def have_encoding?
Object.const_defined? :Encoding
end
##
# Creates a Mechanize::Page with the given +body+
def html_page body
uri = URI 'http://example/'
Mechanize::Page.new uri, nil, body, 200, @mech
end
##
# Creates a Mechanize::CookieJar by parsing the given +str+
def cookie_jar str, uri = URI('http://example')
Mechanize::CookieJar.new.tap do |jar|
jar.parse str, uri
end
end
##
# Runs the block inside a temporary directory
def in_tmpdir
Dir.mktmpdir do |dir|
Dir.chdir dir do
yield
end
end
end
##
# Creates a Nokogiri Node +element+ with the given +attributes+
def node element, attributes = {}
Nokogiri::XML::Node.new(element, Nokogiri::HTML::Document.new).tap do |node|
attributes.each do |name, value|
node[name] = value
end
end
end
##
# Creates a Mechanize::Page for the given +uri+ with the given
# +content_type+, response +body+ and HTTP status +code+
def page uri, content_type = 'text/html', body = String.new, code = 200
uri = URI uri unless URI::Generic === uri
Mechanize::Page.new(uri, { 'content-type' => content_type }, body, code,
@mech)
end
##
# Requests made during this tests
def requests
REQUESTS
end
##
# An SSL private key. This key is the same across all test runs
def ssl_private_key
@ssl_private_key ||= OpenSSL::PKey::RSA.new <<-KEY
-----BEGIN RSA PRIVATE KEY-----
MIG7AgEAAkEA8pmEfmP0Ibir91x6pbts4JmmsVZd3xvD5p347EFvBCbhBW1nv1Gs
bCBEFlSiT1q2qvxGb5IlbrfdhdgyqdTXUQIBAQIBAQIhAPumXslvf6YasXa1hni3
p80joKOug2UUgqOLD2GUSO//AiEA9ssY6AFxjHWuwo/+/rkLmkfO2s1Lz3OeUEWq
6DiHOK8CAQECAQECIQDt8bc4vS6wh9VXApNSKIpVygtxSFe/IwLeX26n77j6Qg==
-----END RSA PRIVATE KEY-----
KEY
end
##
# An X509 certificate. This certificate is the same across all test runs
def ssl_certificate
@ssl_certificate ||= OpenSSL::X509::Certificate.new <<-CERT
-----BEGIN CERTIFICATE-----
MIIBQjCB7aADAgECAgEAMA0GCSqGSIb3DQEBBQUAMCoxDzANBgNVBAMMBm5vYm9k
eTEXMBUGCgmSJomT8ixkARkWB2V4YW1wbGUwIBcNMTExMTAzMjEwODU5WhgPOTk5
OTEyMzExMjU5NTlaMCoxDzANBgNVBAMMBm5vYm9keTEXMBUGCgmSJomT8ixkARkW
B2V4YW1wbGUwWjANBgkqhkiG9w0BAQEFAANJADBGAkEA8pmEfmP0Ibir91x6pbts
4JmmsVZd3xvD5p347EFvBCbhBW1nv1GsbCBEFlSiT1q2qvxGb5IlbrfdhdgyqdTX
UQIBATANBgkqhkiG9w0BAQUFAANBAAAB////////////////////////////////
//8AMCEwCQYFKw4DAhoFAAQUePiv+QrJxyjtEJNnH5pB9OTWIqA=
-----END CERTIFICATE-----
CERT
end
##
# Creates a Tempfile with +content+ that is immediately unlinked
def tempfile content
Tempfile.new(@NAME).tap do |body_io|
body_io.unlink
body_io.write content
body_io.flush
body_io.rewind
end
end
##
# Returns true if the current platform is a Windows platform
def windows?
::RUBY_PLATFORM =~ /mingw|mswin/
end
##
# Return the contents of the file without Windows carriage returns
def file_contents_without_cr(path)
File.read(path).gsub(/\r\n/, "\n")
end
end
require 'mechanize/test_case/servlets'
module Net # :nodoc:
end
class Net::HTTP # :nodoc:
alias :old_do_start :do_start
def do_start
@started = true
end
PAGE_CACHE = {}
alias :old_request :request
def request(req, *data, &block)
url = URI.parse(req.path)
path = WEBrick::HTTPUtils.unescape(url.path)
path = '/index.html' if path == '/'
res = ::Response.new
res.query_params = url.query
req.query = if 'POST' != req.method && url.query then
WEBrick::HTTPUtils.parse_query url.query
elsif req['content-type'] =~ /www-form-urlencoded/ then
WEBrick::HTTPUtils.parse_query req.body
elsif req['content-type'] =~ /boundary=(.+)/ then
boundary = WEBrick::HTTPUtils.dequote $1
WEBrick::HTTPUtils.parse_form_data req.body, boundary
else
{}
end
req.cookies = WEBrick::Cookie.parse(req['Cookie'])
Mechanize::TestCase::REQUESTS << req
if servlet_klass = MECHANIZE_TEST_CASE_SERVLETS[path]
servlet = servlet_klass.new({})
servlet.send "do_#{req.method}", req, res
else
filename = "htdocs#{path.gsub(/[^\/\\.\w\s]/, '_')}"
unless PAGE_CACHE[filename]
::File.open("#{Mechanize::TestCase::TEST_DIR}/#{filename}", 'rb') do |io|
PAGE_CACHE[filename] = io.read
end
end
res.body = PAGE_CACHE[filename]
case filename
when /\.txt$/
res['Content-Type'] = 'text/plain'
when /\.jpg$/
res['Content-Type'] = 'image/jpeg'
end
end
res['Content-Type'] ||= 'text/html'
res.code ||= "200"
response_klass = Net::HTTPResponse::CODE_TO_OBJ[res.code.to_s]
response = response_klass.new res.http_version, res.code, res.message
res.header.each do |k,v|
v = v.first if v.length == 1
response[k] = v
end
res.cookies.each do |cookie|
response.add_field 'Set-Cookie', cookie.to_s
end
response['Content-Type'] ||= 'text/html'
response['Content-Length'] = res['Content-Length'] || res.body.length.to_s
io = StringIO.new(res.body)
response.instance_variable_set :@socket, io
def io.read clen, dest = nil, _ = nil
if dest then
dest << super(clen)
else
super clen
end
end
body_exist = req.response_body_permitted? &&
response_klass.body_permitted?
response.instance_variable_set :@body_exist, body_exist
yield response if block_given?
response
end
end
class Net::HTTPRequest # :nodoc:
attr_accessor :query, :body, :cookies, :user
def host
'example'
end
def port
80
end
end
class Response # :nodoc:
include Net::HTTPHeader
attr_reader :code
attr_accessor :body, :query, :cookies
attr_accessor :query_params, :http_version
attr_accessor :header
def code=(c)
@code = c.to_s
end
alias :status :code
alias :status= :code=
def initialize
@header = {}
@body = String.new
@code = nil
@query = nil
@cookies = []
@http_version = '1.1'
end
def read_body
yield body
end
def message
''
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/version.rb | lib/mechanize/version.rb | # frozen_string_literal: true
class Mechanize
VERSION = "2.14.0"
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/cookie_jar.rb | lib/mechanize/cookie_jar.rb | # frozen_string_literal: true
warn 'mechanize/cookie_jar will be deprecated. Please migrate to the http-cookie APIs.' if $VERBOSE
require 'http/cookie_jar'
require 'http/cookie_jar/yaml_saver'
require 'mechanize/cookie'
class Mechanize
module CookieJarIMethods
include CookieDeprecated
def add(arg1, arg2 = nil)
if arg2
__deprecated__ 'add and origin='
super arg2.dup.tap { |ncookie|
begin
ncookie.origin = arg1
rescue
return nil
end
}
else
super arg1
end
end
# See HTTP::CookieJar#add.
def add!(cookie)
__deprecated__ :add
cookie.domain.nil? and raise NoMethodError, 'raised for compatibility'
@store.add(cookie)
self
end
# See HTTP::CookieJar#save.
def save_as(filename, *options)
__deprecated__ :save
save(filename, *options)
end
# See HTTP::CookieJar#clear.
def clear!
__deprecated__ :clear
clear
end
# See HTTP::CookieJar#store.
def jar
__deprecated__ :store
@store.instance_variable_get(:@jar)
end
# See HTTP::CookieJar#load.
def load_cookiestxt(io)
__deprecated__ :load
load(io, :cookiestxt)
end
# See HTTP::CookieJar#save.
def dump_cookiestxt(io)
__deprecated__ :save
save(io, :cookiestxt)
end
end
class CookieJar < ::HTTP::CookieJar
def save(output, *options)
output.respond_to?(:write) or
return ::File.open(output, 'w') { |io| save(io, *options) }
opthash = {
:format => :yaml,
:session => false,
}
case options.size
when 0
when 1
case options = options.first
when Symbol
opthash[:format] = options
else
opthash.update(options) if options
end
when 2
opthash[:format], options = options
opthash.update(options) if options
else
raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size)
end
return super(output, opthash) if opthash[:format] != :yaml
session = opthash[:session]
nstore = HashStore.new
each { |cookie|
next if !session && cookie.session?
if cookie.max_age
cookie = cookie.dup
cookie.expires = cookie.expires # convert max_age to expires
end
nstore.add(cookie)
}
yaml = YAML.dump(nstore.instance_variable_get(:@jar))
# a gross hack
yaml.gsub!(%r{^( [^ ].*: !ruby/object:)HTTP::Cookie$}) {
$1 + 'Mechanize::Cookie'
}
yaml.gsub!(%r{^( expires: )(?:|!!null|(.+?)) *$}) {
$1 + ($2 ? Time.parse($2).httpdate : '')
}
output.write yaml
self
end
def load(input, *options)
input.respond_to?(:write) or
return ::File.open(input, 'r') { |io| load(io, *options) }
opthash = {
:format => :yaml,
:session => false,
}
case options.size
when 0
when 1
case options = options.first
when Symbol
opthash[:format] = options
else
if hash = Hash.try_convert(options)
opthash.update(hash)
end
end
when 2
opthash[:format], options = options
if hash = Hash.try_convert(options)
opthash.update(hash)
end
else
raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size)
end
return super(input, opthash) if opthash[:format] != :yaml
begin
data = load_yaml(input)
rescue ArgumentError
@logger.warn "unloadable YAML cookie data discarded" if @logger
return self
end
case data
when Array
# Forward compatibility
data.each { |cookie|
add(cookie)
}
when Hash
data.each { |domain, paths|
paths.each { |path, names|
names.each { |cookie_name, cookie|
add(cookie)
}
}
}
else
@logger.warn "incompatible YAML cookie data discarded" if @logger
return self
end
end
private
if YAML.name == "Psych" && Gem::Requirement.new(">= 3.1").satisfied_by?(Gem::Version.new(Psych::VERSION))
def load_yaml(yaml)
YAML.safe_load(yaml, aliases: true, permitted_classes: ["Mechanize::Cookie", "Time"])
end
else
def load_yaml(yaml)
YAML.load(yaml) # rubocop:disable Security/YAMLLoad
end
end
end
class ::HTTP::CookieJar
prepend CookieJarIMethods
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/content_type_error.rb | lib/mechanize/content_type_error.rb | # frozen_string_literal: true
##
# This error is raised when a pluggable parser tries to parse a content type
# that it does not know how to handle. For example if Mechanize::Page were to
# try to parse a PDF, a ContentTypeError would be thrown.
class Mechanize::ContentTypeError < Mechanize::Error
attr_reader :content_type
def initialize(content_type)
@content_type = content_type
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/prependable.rb | lib/mechanize/prependable.rb | # frozen_string_literal: true
# Fake implementation of prepend(), which does not support overriding
# inherited methods nor methods that are formerly overridden by
# another invocation of prepend().
#
# Here's what <Original>.prepend(<Wrapper>) does:
#
# - Create an anonymous stub module (hereinafter <Stub>) and define
# <Stub>#<method> that calls #<method>_without_<Wrapper> for each
# instance method of <Wrapper>.
#
# - Rename <Original>#<method> to #<method>_without_<Wrapper> for each
# instance method of <Wrapper>.
#
# - Include <Wrapper> and <Stub> into <Original> in that order.
#
# This way, a call of <Original>#<method> is dispatched to
# <Wrapper><method>, which may call super which is dispatched to
# <Stub>#<method>, which finally calls
# <Original>#<method>_without_<Wrapper> which is used to be called
# <Original>#<method>.
#
# Usage:
#
# class Mechanize
# # module with methods that overrides those of X
# module Y
# end
#
# unless X.respond_to?(:prepend, true)
# require 'mechanize/prependable'
# X.extend(Prependable)
# end
#
# class X
# prepend Y
# end
# end
module Mechanize::Prependable
def prepend(mod)
stub = Module.new
mod_id = (mod.name || 'Module__%d' % mod.object_id).gsub(/::/, '__')
mod.instance_methods.each { |name|
method_defined?(name) or next
original = instance_method(name)
if original.owner != self
warn "%s cannot override an inherited method: %s(%s)#%s" % [
__method__, self, original.owner, name
]
next
end
name = name.to_s
name_without = name.sub(/(?=[?!=]?\z)/) { '_without_%s' % mod_id }
arity = original.arity
arglist = (
if arity >= 0
(1..arity).map { |i| 'x%d' % i }
else
(1..(-arity - 1)).map { |i| 'x%d' % i } << '*a'
end << '&b'
).join(', ')
if name.end_with?('=')
stub.module_eval %{
def #{name}(#{arglist})
__send__(:#{name_without}, #{arglist})
end
}
else
stub.module_eval %{
def #{name}(#{arglist})
#{name_without}(#{arglist})
end
}
end
module_eval {
alias_method name_without, name
remove_method name
}
}
include(mod, stub)
end
private :prepend
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/directory_saver.rb | lib/mechanize/directory_saver.rb | # frozen_string_literal: true
##
# Unlike Mechanize::FileSaver, the directory saver places all downloaded files
# in a single pre-specified directory.
#
# You must register the directory to save to before using the directory saver:
#
# agent.pluggable_parser['image'] = \
# Mechanize::DirectorySaver.save_to 'images'
class Mechanize::DirectorySaver < Mechanize::Download
@directory = nil
@options = {}
##
# Creates a DirectorySaver subclass that will save responses to the given
# +directory+. If +options+ includes a +decode_filename+ value set to +true+
# then the downloaded filename will be ran through +CGI.unescape+ before
# being saved. If +options+ includes a +overwrite+ value set to +true+ then
# downloaded file will be overwritten if two files with the same names exist.
def self.save_to directory, options = {}
directory = File.expand_path directory
Class.new self do |klass|
klass.instance_variable_set :@directory, directory
klass.instance_variable_set :@options, options
end
end
##
# The directory downloaded files will be saved to.
def self.directory
@directory
end
##
# True if downloaded files should have their names decoded before saving.
def self.decode_filename?
@options[:decode_filename]
end
##
# Checks if +overwrite+ parameter is set to true
def self.overwrite?
@options[:overwrite]
end
##
# Saves the +body_io+ into the directory specified for this DirectorySaver
# by save_to. The filename is chosen by Mechanize::Parser#extract_filename.
def initialize uri = nil, response = nil, body_io = nil, code = nil
directory = self.class.directory
raise Mechanize::Error,
'no save directory specified - ' \
'use Mechanize::DirectorySaver.save_to ' \
'and register the resulting class' unless directory
super
@filename = CGI.unescape(@filename) if self.class.decode_filename?
path = File.join directory, @filename
if self.class.overwrite?
save! path
else
save path
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/file_saver.rb | lib/mechanize/file_saver.rb | # frozen_string_literal: true
##
# This is a pluggable parser that automatically saves every file it
# encounters. Unlike Mechanize::DirectorySaver, the file saver saves the
# responses as a tree, reflecting the host and file path.
#
# == Example
#
# This example saves all .pdf files
#
# require 'mechanize'
#
# agent = Mechanize.new
# agent.pluggable_parser.pdf = Mechanize::FileSaver
# agent.get 'http://example.com/foo.pdf'
#
# Dir['example.com/*'] # => foo.pdf
class Mechanize::FileSaver < Mechanize::Download
attr_reader :filename
def initialize uri = nil, response = nil, body_io = nil, code = nil
@full_path = true
super
save @filename
end
##
# The save_as alias is provided for backwards compatibility with mechanize
# 2.0. It will be removed in mechanize 3.
#--
# TODO remove in mechanize 3
alias save_as save
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/response_read_error.rb | lib/mechanize/response_read_error.rb | # frozen_string_literal: true
##
# Raised when Mechanize encounters an error while reading the response body
# from the server. Contains the response headers and the response body up to
# the error along with the initial error.
class Mechanize::ResponseReadError < Mechanize::Error
attr_reader :body_io
attr_reader :error
attr_reader :mechanize
attr_reader :response
attr_reader :uri
##
# Creates a new ResponseReadError with the +error+ raised, the +response+
# and the +body_io+ for content read so far.
def initialize error, response, body_io, uri, mechanize
@body_io = body_io
@error = error
@mechanize = mechanize
@response = response
@uri = uri
end
##
# Converts this error into a Page, File, etc. based on the content-type
def force_parse
@mechanize.parse @uri, @response, @body_io
end
def message # :nodoc:
"#{@error.message} (#{self.class})"
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/unauthorized_error.rb | lib/mechanize/unauthorized_error.rb | # frozen_string_literal: true
class Mechanize::UnauthorizedError < Mechanize::ResponseCodeError
attr_reader :challenges
def initialize page, challenges, message
super page, message
@challenges = challenges
end
def to_s
out = super
if @challenges then
realms = @challenges.map(&:realm_name).join ', '
out << " -- available realms: #{realms}"
end
out
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/page.rb | lib/mechanize/page.rb | # frozen_string_literal: true
##
# This class encapsulates an HTML page. If Mechanize finds a content
# type of 'text/html', this class will be instantiated and returned.
#
# Example:
#
# require 'mechanize'
#
# agent = Mechanize.new
# agent.get('http://google.com/').class # => Mechanize::Page
class Mechanize::Page < Mechanize::File
extend Forwardable
extend Mechanize::ElementMatcher
DEFAULT_RESPONSE = {
'content-type' => 'text/html',
}.freeze
attr_accessor :mech
##
# Possible encodings for this page based on HTTP headers and meta elements
attr_reader :encodings
def initialize(uri=nil, response=nil, body=nil, code=nil, mech=nil)
response ||= DEFAULT_RESPONSE
@meta_content_type = nil
@encoding = nil
@encodings = [nil]
raise 'no' if mech and not Mechanize === mech
@mech = mech
reset
@encodings << Mechanize::Util.detect_charset(body) if body
@encodings.concat self.class.response_header_charset(response)
if body
@encodings.concat self.class.meta_charset body
meta_content_type = self.class.meta_content_type body
@meta_content_type = meta_content_type if meta_content_type
end
@encodings << mech.default_encoding if mech and mech.default_encoding
super uri, response, body, code
end
def title
@title ||=
if doc = parser
title = doc.xpath('string(((/html/head | /html | /head | /)/title)[1])').to_s
title.empty? ? nil : title
end
end
def response_header_charset
self.class.response_header_charset(response)
end
def meta_charset
self.class.meta_charset(body)
end
def detected_encoding
Mechanize::Util.detect_charset(body)
end
def encoding=(encoding)
reset
@encoding = encoding
if @parser
parser_encoding = @parser.encoding
if parser_encoding && encoding && parser_encoding.casecmp(encoding) != 0
# lazy reinitialize the parser with the new encoding
@parser = nil
end
end
encoding
end
def encoding
parser.encoding
rescue NoMethodError
nil
end
# Return whether parser result has errors related to encoding or not.
# false indicates just parser has no encoding errors, not encoding is valid.
def encoding_error?(parser=nil)
parser = self.parser unless parser
return false if parser.errors.empty?
parser.errors.any? do |error|
error.message.scrub =~ /(indicate\ encoding)|
(Invalid\ bytes)|
(Invalid\ char)|
(input\ conversion\ failed)/x
end
end
def parser
return @parser if @parser
return unless @body
url = @uri && @uri.to_s
if @encoding
@parser = mech.html_parser.parse html_body, url, @encoding
elsif mech.force_default_encoding
@parser = mech.html_parser.parse html_body, url, @mech.default_encoding
else
@encodings.reverse_each do |encoding|
@parser = mech.html_parser.parse html_body, url, encoding
break unless encoding_error? @parser
end
end
@parser
end
alias :root :parser
def pretty_print(q) # :nodoc:
q.object_group(self) {
q.breakable
q.group(1, '{url', '}') {q.breakable; q.pp uri }
q.breakable
q.group(1, '{meta_refresh', '}') {
meta_refresh.each { |link| q.breakable; q.pp link }
}
q.breakable
q.group(1, '{title', '}') { q.breakable; q.pp title }
q.breakable
q.group(1, '{iframes', '}') {
iframes.each { |link| q.breakable; q.pp link }
}
q.breakable
q.group(1, '{frames', '}') {
frames.each { |link| q.breakable; q.pp link }
}
q.breakable
q.group(1, '{links', '}') {
links.each { |link| q.breakable; q.pp link }
}
q.breakable
q.group(1, '{forms', '}') {
forms.each { |form| q.breakable; q.pp form }
}
}
end
alias inspect pretty_inspect # :nodoc:
def reset
@bases = nil
@forms = nil
@frames = nil
@iframes = nil
@links = nil
@labels = nil
@labels_hash = nil
@meta_refresh = nil
@parser = nil
@title = nil
end
# Return the canonical URI for the page if there is a link tag
# with href="canonical".
def canonical_uri
link = at('link[@rel="canonical"][@href]')
return unless link
href = link['href']
URI href
rescue URI::InvalidURIError
URI Mechanize::Util.uri_escape href
end
# Get the content type
def content_type
@meta_content_type || response['content-type']
end
##
# :method: search
#
# Shorthand for +parser.search+.
#
# See Nokogiri::XML::Node#search for details.
##
# :method: css
#
# Shorthand for +parser.css+.
#
# See also Nokogiri::XML::Node#css for details.
##
# :method: xpath
#
# Shorthand for +parser.xpath+.
#
# See also Nokogiri::XML::Node#xpath for details.
##
# :method: at
#
# Shorthand for +parser.at+.
#
# See also Nokogiri::XML::Node#at for details.
##
# :method: at_css
#
# Shorthand for +parser.at_css+.
#
# See also Nokogiri::XML::Node#at_css for details.
##
# :method: at_xpath
#
# Shorthand for +parser.at_xpath+.
#
# See also Nokogiri::XML::Node#at_xpath for details.
def_delegators :parser, :search, :css, :xpath, :at, :at_css, :at_xpath
alias / search
alias % at
##
# :method: form_with
#
# :call-seq:
# form_with(criteria)
# form_with(criteria) { |form| ... }
#
# Find a single form matching +criteria+. See +forms_with+ for
# details of +criteria+.
#
# Examples:
# page.form_with(action: '/post/login.php') do |f|
# ...
# end
##
# :method: form_with!(criteria)
#
# :call-seq:
# form_with!(criteria)
# form_with!(criteria) { |form| ... }
#
# Same as +form_with+ but raises an ElementNotFoundError if no button matches
# +criteria+
##
# :method: forms_with
#
# :call-seq:
# forms_with(name)
# forms_with(name: name_matcher, id: id_matcher, class: class_matcher,
# search: search_expression, xpath: xpath_expression, css: css_expression,
# action: action_matcher, ...)
#
# Find all forms form matching criteria. If a string is given, it
# is taken as a name attribute value. If a hash is given, forms
# are narrowed by the key-value pairs as follows.
#
# :id, :dom_id: selects forms with a #dom_id value that matches this
# value.
#
# :class, :dom_class: selects forms with a #dom_class value that
# matches this value. Note that class attribute values are compared
# literally as string, so forms_with(class: "a") does not match a
# form with class="a b". Use forms_with(css: "form.a") instead.
#
# :search: only selects forms matching this selector expression.
#
# :xpath: only selects forms matching this XPath expression.
#
# :css: only selects forms matching this CSS selector expression.
#
# :action, :method, etc.: narrows forms by a given attribute value
# using the === operator.
#
# Example:
# page.forms_with(css: '#content table.login_box form', method: /\APOST\z/i, ).each do |f|
# ...
# end
elements_with :form
##
# :method: link_with
#
# :call-seq:
# link_with(criteria)
# link_with(criteria) { |link| ... }
#
# Find a single link matching +criteria+. See +forms_with+ for
# details of +criteria+, where for "form(s)" read "link(s)".
#
# Example:
# page.link_with(href: /foo/).click
##
# :method: link_with!
#
# :call-seq:
# link_with!(criteria)
# link_with!(criteria) { |link| ... }
#
# Same as +link_with+ but raises an ElementNotFoundError if no button matches
# +criteria+
##
# :method: links_with
#
# :call-seq:
# links_with(criteria)
#
# Find all links matching +criteria+. See +forms_with+ for details
# of +criteria+, where for "form(s)" read "link(s)".
#
# Example:
# page.links_with(href: /foo/).each do |link|
# puts link.href
# end
elements_with :link
##
# :method: base_with
#
# :call-seq:
# base_with(criteria)
# base_with(criteria) { |base| ... }
#
# Find a single base tag matching +criteria+. See +forms_with+ for
# details of +criteria+, where for "form(s)" read "base tag(s)".
#
# Example:
# page.base_with(href: /foo/).click
##
# :method: base_with!(criteria)
#
# :call-seq:
# base_with!(criteria)
# base_with!(criteria) { |base| ... }
#
# Same as +base_with+ but raises an ElementNotFoundError if no button matches
# +criteria+
##
# :method: bases_with
#
# :call-seq: bases_with(criteria)
#
# Find all base tags matching +criteria+. See +forms_with+ for
# details of +criteria+, where for "form(s)" read "base tag(s)".
#
# Example:
# page.bases_with(href: /foo/).each do |base|
# puts base.href
# end
elements_with :base
##
# :method: frame_with
#
# :call-seq:
# frame_with(criteria)
# frame_with(criteria) { |frame| ... }
#
# Find a single frame tag matching +criteria+. See +forms_with+ for
# details of +criteria+, where for "form(s)" read "frame tag(s)".
#
# Example:
# page.frame_with(src: /foo/).click
##
# :method: frame_with!
#
# :call-seq:
# frame_with!(criteria)
# frame_with!(criteria) { |frame| ... }
#
# Same as +frame_with+ but raises an ElementNotFoundError if no button matches
# +criteria+
##
# :method: frames_with
#
# :call-seq: frames_with(criteria)
#
# Find all frame tags matching +criteria+. See +forms_with+ for
# details of +criteria+, where for "form(s)" read "frame tag(s)".
#
# Example:
# page.frames_with(src: /foo/).each do |frame|
# p frame.src
# end
elements_with :frame
##
# :method: iframe_with
#
# :call-seq:
# iframe_with(criteria)
# iframe_with(criteria) { |iframe| ... }
#
# Find a single iframe tag matching +criteria+. See +forms_with+ for
# details of +criteria+, where for "form(s)" read "iframe tag(s)".
#
# Example:
# page.iframe_with(src: /foo/).click
##
# :method: iframe_with!
#
# :call-seq:
# iframe_with!(criteria)
# iframe_with!(criteria) { |iframe| ... }
#
# Same as +iframe_with+ but raises an ElementNotFoundError if no button
# matches +criteria+
##
# :method: iframes_with
#
# :call-seq: iframes_with(criteria)
#
# Find all iframe tags matching +criteria+. See +forms_with+ for
# details of +criteria+, where for "form(s)" read "iframe tag(s)".
#
# Example:
# page.iframes_with(src: /foo/).each do |iframe|
# p iframe.src
# end
elements_with :iframe
##
# :method: image_with
#
# :call-seq:
# image_with(criteria)
# image_with(criteria) { |image| ... }
#
# Find a single image matching +criteria+. See +forms_with+ for
# details of +criteria+, where for "form(s)" read "image(s)".
#
# Example:
# page.image_with(alt: /main/).fetch.save
##
# :method: image_with!
#
# :call-seq:
# image_with!(criteria)
# image_with!(criteria) { |image| ... }
#
# Same as +image_with+ but raises an ElementNotFoundError if no button matches
# +criteria+
##
# :method: images_with
#
# :call-seq: images_with(criteria)
#
# Find all images matching +criteria+. See +forms_with+ for
# details of +criteria+, where for "form(s)" read "image(s)".
#
# Example:
# page.images_with(src: /jpg\Z/).each do |img|
# img.fetch.save
# end
elements_with :image
##
# Return a list of all link and area tags
def links
@links ||= %w{ a area }.map do |tag|
search(tag).map do |node|
Link.new(node, @mech, self)
end
end.flatten
end
##
# Return a list of all form tags
def forms
@forms ||= search('form').map do |html_form|
form = Mechanize::Form.new(html_form, @mech, self)
form.action ||= @uri.to_s
form
end
end
##
# Return a list of all meta refresh elements
def meta_refresh
query = @mech.follow_meta_refresh == :anywhere ? 'meta' : 'head > meta'
@meta_refresh ||= search(query).map do |node|
MetaRefresh.from_node node, self
end.compact
end
##
# Return a list of all base tags
def bases
@bases ||=
search('base').map { |node| Base.new(node, @mech, self) }
end
##
# Return a list of all frame tags
def frames
@frames ||=
search('frame').map { |node| Frame.new(node, @mech, self) }
end
##
# Return a list of all iframe tags
def iframes
@iframes ||=
search('iframe').map { |node| Frame.new(node, @mech, self) }
end
##
# Return a list of all img tags
def images
@images ||=
search('img').map { |node| Image.new(node, self) }
end
def image_urls
@image_urls ||= images.map(&:url).uniq
end
##
# Return a list of all label tags
def labels
@labels ||=
search('label').map { |node| Label.new(node, self) }
end
def labels_hash
unless @labels_hash
hash = {}
labels.each do |label|
hash[label.node['for']] = label if label.for
end
@labels_hash = hash
end
return @labels_hash
end
class << self
def charset content_type
charset = content_type[/;(?:\s*,)?\s*charset\s*=\s*([^()<>@,;:\\\"\/\[\]?={}\s]+)/i, 1]
return nil if charset == 'none'
charset
end
alias charset_from_content_type charset
end
def self.response_header_charset response
charsets = []
response.each do |header, value|
next unless header == 'content-type'
next unless value =~ /charset/i
charsets << charset(value)
end
charsets
end
##
# Retrieves all charsets from +meta+ tags in +body+
def self.meta_charset body
# HACK use .map
body.scan(/<meta .*?>/i).map do |meta|
if meta =~ /charset\s*=\s*(["'])?\s*(.+)\s*\1/i then
$2
elsif meta =~ /http-equiv\s*=\s*(["'])?content-type\1/i then
meta =~ /content\s*=\s*(["'])?(.*?)\1/i
m_charset = charset $2 if $2
m_charset if m_charset
end
end.compact
end
##
# Retrieves the last <tt>content-type</tt> set by a +meta+ tag in +body+
def self.meta_content_type body
body.scan(/<meta .*?>/i).reverse.map do |meta|
if meta =~ /http-equiv\s*=\s*(["'])?content-type\1/i then
meta =~ /content=(["'])?(.*?)\1/i
return $2
end
end
nil
end
private
def html_body
if @body
@body.empty? ? '<html></html>' : @body
else
''
end
end
end
require 'mechanize/headers'
require 'mechanize/page/image'
require 'mechanize/page/label'
require 'mechanize/page/link'
require 'mechanize/page/base'
require 'mechanize/page/frame'
require 'mechanize/page/meta_refresh'
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/form.rb | lib/mechanize/form.rb | # frozen_string_literal: true
require 'mechanize/element_matcher'
# This class encapsulates a form parsed out of an HTML page. Each type of
# input field available in a form can be accessed through this object.
#
# == Examples
#
# Find a form and print out its fields
#
# form = page.forms.first # => Mechanize::Form
# form.fields.each { |f| puts f.name }
#
# Set the input field 'name' to "Aaron"
#
# form['name'] = 'Aaron'
# puts form['name']
class Mechanize::Form
extend Forwardable
extend Mechanize::ElementMatcher
attr_accessor :method, :action, :name
attr_reader :fields, :buttons, :file_uploads, :radiobuttons, :checkboxes
# Content-Type for form data (i.e. application/x-www-form-urlencoded)
attr_accessor :enctype
# Character encoding of form data (i.e. UTF-8)
attr_accessor :encoding
# When true, character encoding errors will never be never raised on form
# submission. Default is false
attr_accessor :ignore_encoding_error
alias :elements :fields
attr_reader :node
alias form_node node # for backward compatibility
attr_reader :page
def initialize(node, mech = nil, page = nil)
@enctype = node['enctype'] || 'application/x-www-form-urlencoded'
@node = node
@action = Mechanize::Util.html_unescape(node['action'])
@method = (node['method'] || 'GET').upcase
@name = node['name']
@clicked_buttons = []
@page = page
@mech = mech
@encoding = node['accept-charset'] || (page && page.encoding) || nil
@ignore_encoding_error = false
parse
end
# Returns whether or not the form contains a field with +field_name+
def has_field?(field_name)
fields.any? { |f| f.name == field_name }
end
alias :has_key? :has_field?
# Returns whether or not the form contains a field with +value+
def has_value?(value)
fields.any? { |f| f.value == value }
end
# Returns all field names (keys) for this form
def keys
fields.map(&:name)
end
# Returns all field values for this form
def values
fields.map(&:value)
end
# Returns all buttons of type Submit
def submits
@submits ||= buttons.select { |f| f.class == Submit }
end
# Returns all buttons of type Reset
def resets
@resets ||= buttons.select { |f| f.class == Reset }
end
# Returns all fields of type Text
def texts
@texts ||= fields.select { |f| f.class == Text }
end
# Returns all fields of type Hidden
def hiddens
@hiddens ||= fields.select { |f| f.class == Hidden }
end
# Returns all fields of type Textarea
def textareas
@textareas ||= fields.select { |f| f.class == Textarea }
end
# Returns all fields of type Keygen
def keygens
@keygens ||= fields.select { |f| f.class == Keygen }
end
# Returns whether or not the form contains a Submit button named +button_name+
def submit_button?(button_name)
submits.find { |f| f.name == button_name }
end
# Returns whether or not the form contains a Reset button named +button_name+
def reset_button?(button_name)
resets.find { |f| f.name == button_name }
end
# Returns whether or not the form contains a Text field named +field_name+
def text_field?(field_name)
texts.find { |f| f.name == field_name }
end
# Returns whether or not the form contains a Hidden field named +field_name+
def hidden_field?(field_name)
hiddens.find { |f| f.name == field_name }
end
# Returns whether or not the form contains a Textarea named +field_name+
def textarea_field?(field_name)
textareas.find { |f| f.name == field_name }
end
# This method is a shortcut to get form's DOM id.
# Common usage:
# page.form_with(:dom_id => "foorm")
# Note that you can also use +:id+ to get to this method:
# page.form_with(:id => "foorm")
def dom_id
@node['id']
end
# This method is a shortcut to get form's DOM class.
# Common usage:
# page.form_with(:dom_class => "foorm")
# Note that you can also use +:class+ to get to this method:
# page.form_with(:class => "foorm")
# However, attribute values are compared literally as string, so
# form_with(class: "a") does not match a form with class="a b".
# Use form_with(css: "form.a") instead.
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
# Add a field with +field_name+ and +value+
def add_field!(field_name, value = nil)
fields << Field.new({'name' => field_name}, value)
end
##
# This method sets multiple fields on the form. It takes a list of +fields+
# which are name, value pairs.
#
# If there is more than one field found with the same name, this method will
# set the first one found. If you want to set the value of a duplicate
# field, use a value which is a Hash with the key as the index in to the
# form. The index is zero based.
#
# For example, to set the second field named 'foo', you could do the
# following:
#
# form.set_fields :foo => { 1 => 'bar' }
def set_fields fields = {}
fields.each do |name, v|
case v
when Hash
v.each do |index, value|
self.fields_with(:name => name.to_s)[index].value = value
end
else
value = nil
index = 0
[v].flatten.each do |val|
index = val.to_i if value
value = val unless value
end
self.fields_with(:name => name.to_s)[index].value = value
end
end
end
# Fetch the value of the first input field with the name passed in. Example:
# puts form['name']
def [](field_name)
f = field(field_name)
f && f.value
end
# Set the value of the first input field with the name passed in. Example:
# form['name'] = 'Aaron'
def []=(field_name, value)
f = field(field_name)
if f
f.value = value
else
add_field!(field_name, value)
end
end
# Treat form fields like accessors.
def method_missing(meth, *args)
method = meth.to_s.chomp('=')
if field(method)
return field(method).value if args.empty?
return field(method).value = args[0]
end
super
end
# Submit the form. Does not include the +button+ as a form parameter.
# Use +click_button+ or provide button as a parameter.
def submit button = nil, headers = {}
@mech.submit(self, button, headers)
end
# Submit form using +button+. Defaults
# to the first button.
def click_button(button = buttons.first)
submit(button)
end
# This method is sub-method of build_query.
# It converts charset of query value of fields into expected one.
def proc_query(field)
return unless field.query_value
field.query_value.map{|(name, val)|
[from_native_charset(name), from_native_charset(val.to_s)]
}
end
private :proc_query
def from_native_charset str
Mechanize::Util.from_native_charset(str, encoding, @ignore_encoding_error,
@mech && @mech.log)
end
private :from_native_charset
# This method builds an array of arrays that represent the query
# parameters to be used with this form. The return value can then
# be used to create a query string for this form.
def build_query(buttons = [])
query = []
@mech.log.info("form encoding: #{encoding}") if @mech && @mech.log
save_hash_field_order
successful_controls = []
(fields + checkboxes).reject do |f|
f.node["disabled"] || f.node["name"] == ""
end.sort.each do |f|
case f
when Mechanize::Form::CheckBox
if f.checked
successful_controls << f
end
when Mechanize::Form::Field
successful_controls << f
end
end
radio_groups = {}
radiobuttons.each do |f|
fname = from_native_charset(f.name)
radio_groups[fname] ||= []
radio_groups[fname] << f
end
# take one radio button from each group
radio_groups.each_value do |g|
checked = g.select(&:checked)
if checked.uniq.size > 1 then
values = checked.map(&:value).join(', ').inspect
name = checked.first.name.inspect
raise Mechanize::Error,
"radiobuttons #{values} are checked in the #{name} group, " \
"only one is allowed"
else
successful_controls << checked.first unless checked.empty?
end
end
@clicked_buttons.each { |b|
successful_controls << b
}
successful_controls.sort.each do |ctrl| # DOM order
qval = proc_query(ctrl)
query.push(*qval)
end
query
end
# This method adds an index to all fields that have Hash nodes. This
# enables field sorting to maintain order.
def save_hash_field_order
index = 0
fields.each do |field|
if Hash === field.node
field.index = index
index += 1
end
end
end
# This method adds a button to the query. If the form needs to be
# submitted with multiple buttons, pass each button to this method.
def add_button_to_query(button)
unless button.node.document == @node.document then
message =
"#{button.inspect} does not belong to the same page as " \
"the form #{@name.inspect} in #{@page.uri}"
raise ArgumentError, message
end
@clicked_buttons << button
end
# This method allows the same form to be submitted second time
# with the different submit button being clicked.
def reset
# In the future, should add more functionality here to reset the form values to their defaults.
@clicked_buttons = []
end
CRLF = "\r\n".freeze
# This method calculates the request data to be sent back to the server
# for this form, depending on if this is a regular post, get, or a
# multi-part post,
def request_data
query_params = build_query()
case @enctype.downcase
when /^multipart\/form-data/
boundary = rand_string(20)
@enctype = "multipart/form-data; boundary=#{boundary}"
delimiter = "--#{boundary}\r\n"
data = ::String.new
query_params.each do |k,v|
if k
data << delimiter
param_to_multipart(k, v, data)
end
end
@file_uploads.each do |f|
data << delimiter
file_to_multipart(f, data)
end
data << "--#{boundary}--\r\n"
else
Mechanize::Util.build_query_string(query_params)
end
end
# Removes all fields with name +field_name+.
def delete_field!(field_name)
@fields.delete_if{ |f| f.name == field_name}
end
##
# :method: field_with(criteria)
#
# Find one field that matches +criteria+
# Example:
# form.field_with(:id => "exact_field_id").value = 'hello'
##
# :method: field_with!(criteria)
#
# Same as +field_with+ but raises an ElementNotFoundError if no field matches
# +criteria+
##
# :method: fields_with(criteria)
#
# Find all fields that match +criteria+
# Example:
# form.fields_with(:value => /foo/).each do |field|
# field.value = 'hello!'
# end
elements_with :field
##
# :method: button_with(criteria)
#
# Find one button that matches +criteria+
# Example:
# form.button_with(:value => /submit/).value = 'hello'
##
# :method: button_with!(criteria)
#
# Same as +button_with+ but raises an ElementNotFoundError if no button
# matches +criteria+
##
# :method: buttons_with(criteria)
#
# Find all buttons that match +criteria+
# Example:
# form.buttons_with(:value => /submit/).each do |button|
# button.value = 'hello!'
# end
elements_with :button
##
# :method: file_upload_with(criteria)
#
# Find one file upload field that matches +criteria+
# Example:
# form.file_upload_with(:file_name => /picture/).value = 'foo'
##
# :method: file_upload_with!(criteria)
#
# Same as +file_upload_with+ but raises an ElementNotFoundError if no button
# matches +criteria+
##
# :method: file_uploads_with(criteria)
#
# Find all file upload fields that match +criteria+
# Example:
# form.file_uploads_with(:file_name => /picutre/).each do |field|
# field.value = 'foo!'
# end
elements_with :file_upload
##
# :method: radiobutton_with(criteria)
#
# Find one radio button that matches +criteria+
# Example:
# form.radiobutton_with(:name => /woo/).check
##
# :method: radiobutton_with!(criteria)
#
# Same as +radiobutton_with+ but raises an ElementNotFoundError if no button
# matches +criteria+
##
# :method: radiobuttons_with(criteria)
#
# Find all radio buttons that match +criteria+
# Example:
# form.radiobuttons_with(:name => /woo/).each do |field|
# field.check
# end
elements_with :radiobutton
##
# :method: checkbox_with(criteria)
#
# Find one checkbox that matches +criteria+
# Example:
# form.checkbox_with(:name => /woo/).check
##
# :method: checkbox_with!(criteria)
#
# Same as +checkbox_with+ but raises an ElementNotFoundError if no button
# matches +criteria+
##
# :method: checkboxes_with(criteria)
#
# Find all checkboxes that match +criteria+
# Example:
# form.checkboxes_with(:name => /woo/).each do |field|
# field.check
# end
elements_with :checkbox, :checkboxes
def pretty_print(q) # :nodoc:
q.object_group(self) {
q.breakable; q.group(1, '{name', '}') { q.breakable; q.pp name }
q.breakable; q.group(1, '{method', '}') { q.breakable; q.pp method }
q.breakable; q.group(1, '{action', '}') { q.breakable; q.pp action }
q.breakable; q.group(1, '{fields', '}') {
fields.each do |field|
q.breakable
q.pp field
end
}
q.breakable; q.group(1, '{radiobuttons', '}') {
radiobuttons.each { |b| q.breakable; q.pp b }
}
q.breakable; q.group(1, '{checkboxes', '}') {
checkboxes.each { |b| q.breakable; q.pp b }
}
q.breakable; q.group(1, '{file_uploads', '}') {
file_uploads.each { |b| q.breakable; q.pp b }
}
q.breakable; q.group(1, '{buttons', '}') {
buttons.each { |b| q.breakable; q.pp b }
}
}
end
alias inspect pretty_inspect # :nodoc:
private
def parse
@fields = []
@buttons = []
@file_uploads = []
@radiobuttons = []
@checkboxes = []
# Find all input tags
@node.search('input').each do |node|
type = (node['type'] || 'text').downcase
name = node['name']
next if name.nil? && !%w[submit button image].include?(type)
case type
when 'radio'
@radiobuttons << RadioButton.new(node, self)
when 'checkbox'
@checkboxes << CheckBox.new(node, self)
when 'file'
@file_uploads << FileUpload.new(node, nil)
when 'submit'
@buttons << Submit.new(node)
when 'button'
@buttons << Button.new(node)
when 'reset'
@buttons << Reset.new(node)
when 'image'
@buttons << ImageButton.new(node)
when 'hidden'
@fields << Hidden.new(node, node['value'] || '')
when 'text'
@fields << Text.new(node, node['value'] || '')
when 'textarea'
@fields << Textarea.new(node, node['value'] || '')
else
@fields << Field.new(node, node['value'] || '')
end
end
# Find all textarea tags
@node.search('textarea').each do |node|
next unless node['name']
@fields << Textarea.new(node, node.inner_text)
end
# Find all select tags
@node.search('select').each do |node|
next unless node['name']
if node.has_attribute? 'multiple'
@fields << MultiSelectList.new(node)
else
@fields << SelectList.new(node)
end
end
# Find all submit button tags
# FIXME: what can I do with the reset buttons?
@node.search('button').each do |node|
type = (node['type'] || 'submit').downcase
next if type == 'reset'
@buttons << Button.new(node)
end
# Find all keygen tags
@node.search('keygen').each do |node|
@fields << Keygen.new(node, node['value'] || '')
end
end
def rand_string(len = 10)
chars = ("a".."z").to_a + ("A".."Z").to_a
string = ::String.new
1.upto(len) { |i| string << chars[rand(chars.size-1)] }
string
end
def mime_value_quote(str)
str.b.gsub(/(["\r\\])/, '\\\\\1')
end
def param_to_multipart(name, value, buf = ::String.new)
buf <<
"Content-Disposition: form-data; name=\"".freeze <<
mime_value_quote(name) <<
"\"\r\n\r\n".freeze <<
value.b <<
CRLF
end
def file_to_multipart(file, buf = ::String.new)
file_name = file.file_name ? ::File.basename(file.file_name) : ''
body = buf <<
"Content-Disposition: form-data; name=\"".freeze <<
mime_value_quote(file.name) <<
"\"; filename=\"".freeze <<
mime_value_quote(file_name) <<
"\"\r\nContent-Transfer-Encoding: binary\r\n".freeze
if file.file_data.nil? and file.file_name
file.file_data = File.binread(file.file_name)
file.mime_type =
WEBrick::HTTPUtils.mime_type(file.file_name,
WEBrick::HTTPUtils::DefaultMimeTypes)
end
if file.mime_type
body << "Content-Type: ".freeze << file.mime_type << CRLF
end
body << CRLF
if file_data = file.file_data
if file_data.respond_to? :read
body << file_data.read.force_encoding(Encoding::ASCII_8BIT)
else
body << file_data.b
end
end
body << CRLF
end
end
require 'mechanize/form/field'
require 'mechanize/form/button'
require 'mechanize/form/hidden'
require 'mechanize/form/text'
require 'mechanize/form/textarea'
require 'mechanize/form/submit'
require 'mechanize/form/reset'
require 'mechanize/form/file_upload'
require 'mechanize/form/keygen'
require 'mechanize/form/image_button'
require 'mechanize/form/multi_select_list'
require 'mechanize/form/option'
require 'mechanize/form/radio_button'
require 'mechanize/form/check_box'
require 'mechanize/form/select_list'
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/file.rb | lib/mechanize/file.rb | # frozen_string_literal: true
##
# This is the base class for the Pluggable Parsers. If Mechanize cannot find
# an appropriate class to use for the content type, this class will be used.
# For example, if you download an image/jpeg, Mechanize will not know how to
# parse it, so this class will be instantiated.
#
# This is a good class to use as the base class for building your own
# pluggable parsers.
#
# == Example
#
# require 'mechanize'
#
# agent = Mechanize.new
# agent.get('http://example.com/foo.jpg').class #=> Mechanize::File
class Mechanize::File
include Mechanize::Parser
##
# The HTTP response body, the raw file contents
attr_accessor :body
##
# The filename for this file based on the content-disposition of the
# response or the basename of the URL
attr_accessor :filename
alias content body
##
# Creates a new file retrieved from the given +uri+ and +response+ object.
# The +body+ is the HTTP response body and +code+ is the HTTP status.
def initialize uri = nil, response = nil, body = nil, code = nil
@uri = uri
@body = body
@code = code
@full_path = false unless defined? @full_path
fill_header response
extract_filename
yield self if block_given?
end
##
# Use this method to save the content of this object to +filename+.
# returns the filename
#
# file.save 'index.html'
# file.save 'index.html' # saves to index.html.1
#
# uri = URI 'http://localhost/test.html'
# file = Mechanize::File.new uri, nil, ''
# filename = file.save # saves to test.html
# puts filename # test.html
def save filename = nil
filename = find_free_name filename
save! filename
end
alias save_as save
##
# Use this method to save the content of this object to +filename+.
# This method will overwrite any existing filename that exists with the
# same name.
# returns the filename
#
# file.save 'index.html'
# file.save! 'index.html' # overwrite original file
# filename = file.save! 'index.html' # overwrite original file with filename 'index.html'
def save! filename = nil
filename ||= @filename
dirname = File.dirname filename
FileUtils.mkdir_p dirname
::File.open(filename, 'wb')do |f|
f.write body
end
filename
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/robots_disallowed_error.rb | lib/mechanize/robots_disallowed_error.rb | # frozen_string_literal: true
# Exception that is raised when an access to a resource is disallowed by
# robots.txt or by HTML document itself.
class Mechanize::RobotsDisallowedError < Mechanize::Error
def initialize(url)
if url.is_a?(URI)
@url = url.to_s
@uri = url
else
@url = url.to_s
end
end
# Returns the URL (string) of the resource that caused this error.
attr_reader :url
# Returns the URL (URI object) of the resource that caused this
# error. URI::InvalidURIError may be raised if the URL happens to
# be invalid or not understood by the URI library.
def uri
@uri ||= URI.parse(url)
end
def to_s
"Robots access is disallowed for URL: #{url}"
end
alias :inspect :to_s
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/xml_file.rb | lib/mechanize/xml_file.rb | # frozen_string_literal: true
##
# This class encapsulates an XML file. If Mechanize finds a content-type
# of 'text/xml' or 'application/xml' this class will be instantiated and
# returned. This class also opens up the +search+ and +at+ methods available
# on the underlying Nokogiri::XML::Document object.
#
# Example:
#
# require 'mechanize'
#
# agent = Mechanize.new
# xml = agent.get('http://example.org/some-xml-file.xml')
# xml.class #=> Mechanize::XmlFile
# xml.search('//foo[@attr="bar"]/etc')
class Mechanize::XmlFile < Mechanize::File
extend Forwardable
# The underlying Nokogiri::XML::Document object
attr_reader :xml
def initialize(uri = nil, response = nil, body = nil, code = nil)
super uri, response, body, code
@xml = Nokogiri.XML body
end
##
# :method: search
#
# Search for +paths+ in the page using Nokogiri's #search. The +paths+ can
# be XPath or CSS and an optional Hash of namespaces may be appended.
#
# See Nokogiri::XML::Node#search for further details.
def_delegator :xml, :search, :search
##
# :method: at
#
# Search through the page for +path+ under +namespace+ using Nokogiri's #at.
# The +path+ may be either a CSS or XPath expression.
#
# See also Nokogiri::XML::Node#at
def_delegator :xml, :at, :at
end | ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/parser.rb | lib/mechanize/parser.rb | # frozen_string_literal: true
##
# The parser module provides standard methods for accessing the headers and
# content of a response that are shared across pluggable parsers.
module Mechanize::Parser
extend Forwardable
special_filenames = Regexp.union %w[
AUX
COM1
COM2
COM3
COM4
COM5
COM6
COM7
COM8
COM9
CON
LPT1
LPT2
LPT3
LPT4
LPT5
LPT6
LPT7
LPT8
LPT9
NUL
PRN
]
##
# Special filenames that must be escaped
SPECIAL_FILENAMES = /\A#{special_filenames}/i
##
# The URI this file was retrieved from
attr_accessor :uri
##
# The Mechanize::Headers for this file
attr_accessor :response
alias header response
##
# The HTTP response code
attr_accessor :code
##
# :method: []
#
# :call-seq:
# [](header)
#
# Access HTTP +header+ by name
def_delegator :header, :[], :[]
##
# :method: []=
#
# :call-seq:
# []=(header, value)
#
# Set HTTP +header+ to +value+
def_delegator :header, :[]=, :[]=
##
# :method: key?
#
# :call-seq:
# key?(header)
#
# Is the named +header+ present?
def_delegator :header, :key?, :key?
##
# :method: each
#
# Enumerate HTTP headers
def_delegator :header, :each, :each
##
# :method: each
#
# Enumerate HTTP headers in capitalized (canonical) form
def_delegator :header, :canonical_each, :canonical_each
##
# Extracts the filename from a Content-Disposition header in the #response
# or from the URI. If +full_path+ is true the filename will include the
# host name and path to the resource, otherwise a filename in the current
# directory is given.
def extract_filename full_path = @full_path
handled = false
if @uri then
uri = @uri
uri += 'index.html' if uri.path.end_with? '/'
path = uri.path.split(/\//)
filename = path.pop || 'index.html'
else
path = []
filename = 'index.html'
end
# Set the filename
if (disposition = @response['content-disposition'])
content_disposition =
Mechanize::HTTP::ContentDispositionParser.parse disposition
if content_disposition && content_disposition.filename && content_disposition.filename != ''
filename = content_disposition.filename
filename = filename.rpartition(/[\\\/]/).last
handled = true
end
end
if not handled and @uri then
filename << '.html' unless filename =~ /\./
filename << "?#{@uri.query}" if @uri.query
end
if SPECIAL_FILENAMES =~ filename then
filename = "_#{filename}"
end
filename = filename.tr "\x00-\x20<>:\"/\\|?*", '_'
@filename = if full_path then
File.join @uri.host, path, filename
else
filename
end
end
##
# Creates a Mechanize::Header from the Net::HTTPResponse +response+.
#
# This allows the Net::HTTPResponse to be garbage collected sooner.
def fill_header response
@response = Mechanize::Headers.new
response.each { |k,v|
@response[k] = v
} if response
@response
end
##
# Finds a free filename based on +filename+, but is not race-free
def find_free_name filename
base_filename = filename ||= @filename
number = 1
while File.exist? filename do
filename = "#{base_filename}.#{number}"
number += 1
end
filename
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/file_connection.rb | lib/mechanize/file_connection.rb | # frozen_string_literal: true
##
# Wrapper to make a file URI work like an http URI
class Mechanize::FileConnection
@instance = nil
def self.new *a
@instance ||= super
end
def request uri, request
file_path = uri.select(:host, :path)
.select { |part| part && (part.length > 0) }
.join(":")
yield Mechanize::FileResponse.new(Mechanize::Util.uri_unescape(file_path))
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/element_matcher.rb | lib/mechanize/element_matcher.rb | # frozen_string_literal: true
module Mechanize::ElementMatcher
def elements_with singular, plural = "#{singular}s"
class_eval <<-CODE
def #{plural}_with criteria = {}
selector = method = nil
if String === criteria then
criteria = {:name => criteria}
else
criteria = criteria.each_with_object({}) { |(k, v), h|
case k = k.to_sym
when :id
h[:dom_id] = v
when :class
h[:dom_class] = v
when :search, :xpath, :css
if v
if method
warn "multiple search selectors are given; previous selector (\#{method}: \#{selector.inspect}) is ignored."
end
selector = v
method = k
end
else
h[k] = v
end
}
end
f = select_#{plural}(selector, method).find_all do |thing|
criteria.all? do |k,v|
v === thing.__send__(k)
end
end
yield f if block_given?
f
end
def #{singular}_with criteria = {}
f = #{plural}_with(criteria).first
yield f if block_given?
f
end
def #{singular}_with! criteria = {}
f = #{singular}_with(criteria)
raise Mechanize::ElementNotFoundError.new(self, :#{singular}, criteria) if f.nil?
yield f if block_given?
f
end
def select_#{plural} selector, method = :search
if selector.nil? then
#{plural}
else
nodes = __send__(method, selector)
#{plural}.find_all do |element|
nodes.include?(element.node)
end
end
end
alias :#{singular} :#{singular}_with
CODE
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/response_code_error.rb | lib/mechanize/response_code_error.rb | # frozen_string_literal: true
# This error is raised when Mechanize encounters a response code it does not
# know how to handle. Currently, this exception will be thrown if Mechanize
# encounters response codes other than 200, 301, or 302. Any other response
# code is up to the user to handle.
class Mechanize::ResponseCodeError < Mechanize::Error
attr_reader :response_code
attr_reader :page
def initialize(page, message = nil)
super message
@page = page
@response_code = page.code.to_s
end
def to_s
response_class = Net::HTTPResponse::CODE_TO_OBJ[@response_code]
out = String.new("#{@response_code} => #{response_class} ")
out << "for #{@page.uri} " if @page.respond_to? :uri # may be HTTPResponse
out << "-- #{super}"
end
alias inspect to_s
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/http.rb | lib/mechanize/http.rb | # frozen_string_literal: true
##
# Mechanize::HTTP contains classes for communicated with HTTP servers. All
# API under this namespace is considered private and is subject to change at
# any time.
class Mechanize::HTTP
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/unsupported_scheme_error.rb | lib/mechanize/unsupported_scheme_error.rb | # frozen_string_literal: true
class Mechanize::UnsupportedSchemeError < Mechanize::Error
attr_accessor :scheme, :uri
def initialize(scheme, uri)
@scheme = scheme
@uri = uri
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/pluggable_parsers.rb | lib/mechanize/pluggable_parsers.rb | # frozen_string_literal: true
require 'mechanize/file'
require 'mechanize/file_saver'
require 'mechanize/page'
require 'mechanize/xml_file'
require 'mime/types'
##
# Mechanize allows different parsers for different content types. Mechanize
# uses PluggableParser to determine which parser to use for any content type.
# To use your own parser or to change the default parsers, register them with
# this class through Mechanize#pluggable_parser.
#
# The default parser for unregistered content types is Mechanize::File.
#
# The module Mechanize::Parser provides basic functionality for any content
# type, so you may use it in custom parsers you write. For small files you
# wish to perform in-memory operations on, you should subclass
# Mechanize::File. For large files you should subclass Mechanize::Download as
# the content is only loaded into memory in small chunks.
#
# When writing your own pluggable parser, be sure to provide a method #body
# that returns a String containing the response body for compatibility with
# Mechanize#get_file.
#
# == Example
#
# To create your own parser, just create a class that takes four parameters in
# the constructor. Here is an example of registering a parser that handles
# CSV files:
#
# require 'csv'
#
# class CSVParser < Mechanize::File
# attr_reader :csv
#
# def initialize uri = nil, response = nil, body = nil, code = nil
# super uri, response, body, code
# @csv = CSV.parse body
# end
# end
#
# agent = Mechanize.new
# agent.pluggable_parser.csv = CSVParser
# agent.get('http://example.com/test.csv') # => CSVParser
#
# Now any response with a content type of 'text/csv' will initialize a
# CSVParser and return that object to the caller.
#
# To register a parser for a content type that Mechanize does not know about,
# use the hash syntax:
#
# agent.pluggable_parser['text/something'] = SomeClass
#
# To set the default parser, use #default:
#
# agent.pluggable_parser.default = Mechanize::Download
#
# Now all unknown content types will be saved to disk and not loaded into
# memory.
class Mechanize::PluggableParser
CONTENT_TYPES = {
:html => 'text/html',
:wap => 'application/vnd.wap.xhtml+xml',
:xhtml => 'application/xhtml+xml',
:pdf => 'application/pdf',
:csv => 'text/csv',
:xml => ['text/xml', 'application/xml'],
}
InvalidContentTypeError =
if defined?(MIME::Type::InvalidContentType)
# For mime-types >=2.1
MIME::Type::InvalidContentType
else
# For mime-types <2.1
MIME::InvalidContentType
end
attr_accessor :default
def initialize
@parsers = {
CONTENT_TYPES[:html] => Mechanize::Page,
CONTENT_TYPES[:xhtml] => Mechanize::Page,
CONTENT_TYPES[:wap] => Mechanize::Page,
'image' => Mechanize::Image,
'text/xml' => Mechanize::XmlFile,
'application/xml' => Mechanize::XmlFile,
}
@default = Mechanize::File
end
##
# Returns the parser registered for the given +content_type+
def parser content_type
return default unless content_type
parser = @parsers[content_type]
return parser if parser
mime_type = MIME::Type.new "content-type" => content_type
parser = @parsers[mime_type.to_s] ||
@parsers[mime_type.simplified] ||
# Starting from mime-types 3.0 x-prefix is deprecated as per IANA
(@parsers[MIME::Type.simplified(mime_type.to_s, remove_x_prefix: true)] rescue nil) ||
@parsers[mime_type.media_type] ||
default
rescue InvalidContentTypeError
default
end
def register_parser content_type, klass # :nodoc:
@parsers[content_type] = klass
end
##
# Registers +klass+ as the parser for text/html and application/xhtml+xml
# content
def html=(klass)
register_parser(CONTENT_TYPES[:html], klass)
register_parser(CONTENT_TYPES[:xhtml], klass)
end
##
# Registers +klass+ as the parser for application/xhtml+xml content
def xhtml=(klass)
register_parser(CONTENT_TYPES[:xhtml], klass)
end
##
# Registers +klass+ as the parser for application/pdf content
def pdf=(klass)
register_parser(CONTENT_TYPES[:pdf], klass)
end
##
# Registers +klass+ as the parser for text/csv content
def csv=(klass)
register_parser(CONTENT_TYPES[:csv], klass)
end
##
# Registers +klass+ as the parser for text/xml content
def xml=(klass)
CONTENT_TYPES[:xml].each do |content_type|
register_parser content_type, klass
end
end
##
# Retrieves the parser for +content_type+ content
def [](content_type)
@parsers[content_type]
end
##
# Sets the parser for +content_type+ content to +klass+
#
# The +content_type+ may either be a full MIME type a simplified MIME type
# ('text/x-csv' simplifies to 'text/csv') or a media type like 'image'.
def []= content_type, klass
register_parser content_type, klass
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/redirect_limit_reached_error.rb | lib/mechanize/redirect_limit_reached_error.rb | # frozen_string_literal: true
##
# Raised when too many redirects are sent
class Mechanize::RedirectLimitReachedError < Mechanize::Error
attr_reader :page
attr_reader :redirects
attr_reader :response_code
def initialize page, redirects
@page = page
@redirects = redirects
@response_code = page.code
super "Redirect limit of #{redirects} reached"
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/file_response.rb | lib/mechanize/file_response.rb | # frozen_string_literal: true
##
# Fake response for dealing with file:/// requests
class Mechanize::FileResponse
attr_reader :file_path
def initialize(file_path)
@file_path = file_path
@uri = nil
end
def read_body
raise Mechanize::ResponseCodeError.new(self) unless
File.exist? @file_path
if directory?
yield dir_body
else
::File.open(@file_path, 'rb') do |io|
yield io.read
end
end
end
def code
File.exist?(@file_path) ? 200 : 404
end
def content_length
return dir_body.length if directory?
File.exist?(@file_path) ? File.stat(@file_path).size : 0
end
def each_header; end
def [](key)
return nil if key.casecmp('Content-Type') != 0
return 'text/html' if directory?
return 'text/html' if ['.html', '.xhtml'].any? { |extn|
@file_path.end_with?(extn)
}
nil
end
def each
end
def get_fields(key)
[]
end
def http_version
'0'
end
def message
File.exist?(@file_path) ? 'OK' : 'Not Found'
end
def uri
@uri ||= URI "file://#{@file_path}"
end
private
def dir_body
body = %w[<html><body>]
body.concat Dir[File.join(@file_path, '*')].map { |f|
"<a href=\"file://#{f}\">#{File.basename(f)}</a>"
}
body << %w[</body></html>]
body.join("\n").force_encoding(Encoding::BINARY)
end
def directory?
File.directory?(@file_path)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/cookie.rb | lib/mechanize/cookie.rb | # frozen_string_literal: true
warn 'mechanize/cookie will be deprecated. Please migrate to the http-cookie APIs.' if $VERBOSE
require 'http/cookie'
class Mechanize
module CookieDeprecated
def __deprecated__(to = nil)
$VERBOSE or return
method = caller_locations(1,1).first.base_label
to ||= method
case self
when Class
lname = name[/[^:]+$/]
klass = 'Mechanize::%s' % lname
this = '%s.%s' % [klass, method]
that = 'HTTP::%s.%s' % [lname, to]
else
lname = self.class.name[/[^:]+$/]
klass = 'Mechanize::%s' % lname
this = '%s#%s' % [klass, method]
that = 'HTTP::%s#%s' % [lname, to]
end
warn '%s: The call of %s needs to be fixed to follow the new API (%s).' % [caller_locations(2,1).first, this, that]
end
private :__deprecated__
end
module CookieCMethods
include CookieDeprecated
def parse(arg1, arg2, arg3 = nil, &block)
if arg1.is_a?(URI)
__deprecated__
return [] if arg2.nil?
super(arg2, arg1, { :logger => arg3 })
else
super
end
end
end
module CookieIMethods
include CookieDeprecated
def set_domain(domain)
__deprecated__ :domain=
@domain = domain
end
end
Cookie = ::HTTP::Cookie
class Cookie
prepend CookieIMethods
class << self
prepend CookieCMethods
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/headers.rb | lib/mechanize/headers.rb | # frozen_string_literal: true
class Mechanize::Headers < Hash
def [](key)
super(key.downcase)
end
def []=(key, value)
super(key.downcase, value)
end
def key?(key)
super(key.downcase)
end
def canonical_each
block_given? or return enum_for(__method__)
each { |key, value|
key = key.capitalize
key.gsub!(/-([a-z])/) { "-#{$1.upcase}" }
yield [key, value]
}
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/element_not_found_error.rb | lib/mechanize/element_not_found_error.rb | # frozen_string_literal: true
##
# Raised when an an element was not found on the Page
class Mechanize::ElementNotFoundError < Mechanize::Error
attr_reader :source
attr_reader :element
attr_reader :conditions
def initialize source, element, conditions
@source = source
@element = element
@conditions = conditions
super "Element #{element} with conditions #{conditions} was not found"
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/history.rb | lib/mechanize/history.rb | # frozen_string_literal: true
##
# This class manages history for your mechanize object.
class Mechanize::History < Array
attr_accessor :max_size
def initialize(max_size = nil)
@max_size = max_size
@history_index = {}
end
def initialize_copy(orig)
super
@history_index = orig.instance_variable_get(:@history_index).dup
end
def inspect # :nodoc:
uris = map(&:uri).join ', '
"[#{uris}]"
end
def push(page, uri = nil)
super page
index = uri ? uri : page.uri
@history_index[index.to_s] = page
shift while length > @max_size if @max_size
self
end
alias :<< :push
def visited? uri
page = @history_index[uri.to_s]
return page if page # HACK
uri = uri.dup
uri.path = '/' if uri.path.empty?
@history_index[uri.to_s]
end
alias visited_page visited?
def clear
@history_index.clear
super
end
def shift
return nil if length == 0
page = self[0]
self[0] = nil
super
remove_from_index(page)
page
end
def pop
return nil if length == 0
page = super
remove_from_index(page)
page
end
private
def remove_from_index(page)
@history_index.each do |k,v|
@history_index.delete(k) if v == page
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/image.rb | lib/mechanize/image.rb | # frozen_string_literal: true
##
# An Image holds downloaded data for an image/* response.
class Mechanize::Image < Mechanize::Download
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/file_request.rb | lib/mechanize/file_request.rb | # frozen_string_literal: true
##
# A wrapper for a file URI that makes a request that works like a
# Net::HTTPRequest
class Mechanize::FileRequest
attr_accessor :uri
def initialize uri
@uri = uri
end
def add_field *a
end
alias []= add_field
def path
@uri.path
end
def each_header
end
def response_body_permitted?
true
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/util.rb | lib/mechanize/util.rb | # frozen_string_literal: true
require 'cgi'
require 'nkf'
class Mechanize::Util
# default mime type data for Page::Image#mime_type.
# You can use another Apache-compatible mimetab.
# mimetab = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types')
# Mechanize::Util::DefaultMimeTypes.replace(mimetab)
DefaultMimeTypes = WEBrick::HTTPUtils::DefaultMimeTypes
class << self
# Builds a query string from a given enumerable object
# +parameters+. This method uses Mechanize::Util.each_parameter
# as preprocessor, which see.
def build_query_string(parameters, enc = nil)
each_parameter(parameters).inject(nil) { |s, (k, v)|
# WEBrick::HTTP.escape* has some problems about m17n on ruby-1.9.*.
(s.nil? ? String.new : s << '&') << [CGI.escape(k.to_s), CGI.escape(v.to_s)].join('=')
} || ''
end
# Parses an enumerable object +parameters+ and iterates over the
# key-value pairs it contains.
#
# +parameters+ may be a hash, or any enumerable object which
# iterates over [key, value] pairs, typically an array of arrays.
#
# If a key is paired with an array-like object, the pair is
# expanded into multiple occurrences of the key, one for each
# element of the array. e.g. { a: [1, 2] } => [:a, 1], [:a, 2]
#
# If a key is paired with a hash-like object, the pair is expanded
# into hash-like multiple pairs, one for each pair of the hash.
# e.g. { a: { x: 1, y: 2 } } => ['a[x]', 1], ['a[y]', 2]
#
# An array-like value is allowed to be specified as hash value.
# e.g. { a: { q: [1, 2] } } => ['a[q]', 1], ['a[q]', 2]
#
# For a non-array-like, non-hash-like value, the key-value pair is
# yielded as is.
def each_parameter(parameters, &block)
return to_enum(__method__, parameters) if block.nil?
parameters.each { |key, value|
each_parameter_1(key, value, &block)
}
end
private
def each_parameter_1(key, value, &block)
return if key.nil?
case
when s = String.try_convert(value)
yield [key, s]
when a = Array.try_convert(value)
a.each { |avalue|
yield [key, avalue]
}
when h = Hash.try_convert(value)
h.each { |hkey, hvalue|
each_parameter_1('%s[%s]' % [key, hkey], hvalue, &block)
}
else
yield [key, value]
end
end
end
# Converts string +s+ from +code+ to UTF-8.
def self.from_native_charset(s, code, ignore_encoding_error = false, log = nil)
return s unless s && code
return s unless Mechanize.html_parser == Nokogiri::HTML
begin
s.encode(code)
rescue EncodingError => ex
log.debug("from_native_charset: #{ex.class}: form encoding: #{code.inspect} string: #{s}") if log
if ignore_encoding_error
s
else
raise
end
end
end
def self.html_unescape(s)
return s unless s
s.gsub(/&(\w+|#[0-9]+);/) { |match|
number = case match
when /&(\w+);/
Mechanize.html_parser::NamedCharacters[$1]
when /&#([0-9]+);/
$1.to_i
end
number ? ([number].pack('U') rescue match) : match
}
end
case NKF::BINARY
when Encoding
def self.guess_encoding(src)
# NKF.guess of JRuby may return nil
NKF.guess(src) || Encoding::US_ASCII
end
else
# Old NKF from 1.8, still bundled with Rubinius
NKF_ENCODING_MAP = {
NKF::UNKNOWN => Encoding::US_ASCII,
NKF::BINARY => Encoding::ASCII_8BIT,
NKF::ASCII => Encoding::US_ASCII,
NKF::JIS => Encoding::ISO_2022_JP,
NKF::EUC => Encoding::EUC_JP,
NKF::SJIS => Encoding::Shift_JIS,
NKF::UTF8 => Encoding::UTF_8,
NKF::UTF16 => Encoding::UTF_16BE,
NKF::UTF32 => Encoding::UTF_32BE,
}
def self.guess_encoding(src)
NKF_ENCODING_MAP[NKF.guess(src)]
end
end
def self.detect_charset(src)
if src
guess_encoding(src).name.upcase
else
Encoding::ISO8859_1.name
end
end
def self.uri_escape str, unsafe = nil
if URI == parser then
unsafe ||= URI::UNSAFE
else
unsafe ||= parser.regexp[:UNSAFE]
end
parser.escape str, unsafe
end
def self.uri_unescape str
parser.unescape str
end
def self.parser
@parser ||=
if defined?(URI::RFC2396_PARSER)
URI::RFC2396_PARSER
elsif defined?(URI::Parser)
URI::Parser.new
else
URI
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/robots_txt_servlet.rb | lib/mechanize/test_case/robots_txt_servlet.rb | # frozen_string_literal: true
class RobotsTxtServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
if /301/ === req['Host'] && req.path == '/robots.txt'
res['Location'] = 'http://301/robots_txt'
res.code = 301
else
res['Content-Type'] = 'text/plain'
res.body = <<-'EOF'
User-Agent: *
Disallow: /norobots
EOF
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/many_cookies_as_string_servlet.rb | lib/mechanize/test_case/many_cookies_as_string_servlet.rb | # frozen_string_literal: true
class ManyCookiesAsStringServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
cookies = []
name_cookie = WEBrick::Cookie.new("name", "Aaron")
name_cookie.path = "/"
name_cookie.expires = Time.now + 86400
name_cookie.domain = 'localhost'
cookies << name_cookie
cookies << name_cookie
cookies << name_cookie
cookies << "#{name_cookie}; HttpOnly"
expired_cookie = WEBrick::Cookie.new("expired", "doh")
expired_cookie.path = "/"
expired_cookie.expires = Time.now - 86400
cookies << expired_cookie
different_path_cookie = WEBrick::Cookie.new("a_path", "some_path")
different_path_cookie.path = "/some_path"
different_path_cookie.expires = Time.now + 86400
cookies << different_path_cookie
no_path_cookie = WEBrick::Cookie.new("no_path", "no_path")
no_path_cookie.expires = Time.now + 86400
cookies << no_path_cookie
no_exp_path_cookie = WEBrick::Cookie.new("no_expires", "nope")
no_exp_path_cookie.path = "/"
cookies << no_exp_path_cookie
res['Set-Cookie'] = cookies.join(', ')
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/send_cookies_servlet.rb | lib/mechanize/test_case/send_cookies_servlet.rb | # frozen_string_literal: true
class SendCookiesServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
res.content_type = 'text/html'
cookies = req.cookies.map do |c|
"<li><a href=\"#\">#{c.name}:#{c.value}</a>"
end.join "\n"
res.body = <<-BODY
<!DOCTYPE html>
<title>Your cookies</title>
<ul>
#{cookies}
</ul>
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/http_refresh_servlet.rb | lib/mechanize/test_case/http_refresh_servlet.rb | # frozen_string_literal: true
class HttpRefreshServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
res['Content-Type'] = req.query['ct'] || "text/html"
refresh_time = req.query['refresh_time'] || 0
refresh_url = req.query['refresh_url'] || '/'
res['Refresh'] = " #{refresh_time};url=#{refresh_url}";
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/content_type_servlet.rb | lib/mechanize/test_case/content_type_servlet.rb | # frozen_string_literal: true
class ContentTypeServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
ct = req.query['ct'] || "text/html; charset=utf-8"
res['Content-Type'] = ct
res.body = "Hello World"
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/many_cookies_servlet.rb | lib/mechanize/test_case/many_cookies_servlet.rb | # frozen_string_literal: true
class ManyCookiesServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
name_cookie = WEBrick::Cookie.new("name", "Aaron")
name_cookie.path = "/"
name_cookie.expires = Time.now + 86400
res.cookies << name_cookie
res.cookies << name_cookie
res.cookies << name_cookie
res.cookies << name_cookie
expired_cookie = WEBrick::Cookie.new("expired", "doh")
expired_cookie.path = "/"
expired_cookie.expires = Time.now - 86400
res.cookies << expired_cookie
different_path_cookie = WEBrick::Cookie.new("a_path", "some_path")
different_path_cookie.path = "/some_path"
different_path_cookie.expires = Time.now + 86400
res.cookies << different_path_cookie
no_path_cookie = WEBrick::Cookie.new("no_path", "no_path")
no_path_cookie.expires = Time.now + 86400
res.cookies << no_path_cookie
no_exp_path_cookie = WEBrick::Cookie.new("no_expires", "nope")
no_exp_path_cookie.path = "/"
res.cookies << no_exp_path_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/test_case/header_servlet.rb | lib/mechanize/test_case/header_servlet.rb | # frozen_string_literal: true
class HeaderServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
res.content_type = "text/plain"
req.query.each do |x,y|
res[x] = y
end
req.each do |k, v|
res.body << "#{k}|#{v}\n"
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/referer_servlet.rb | lib/mechanize/test_case/referer_servlet.rb | # frozen_string_literal: true
class RefererServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
res['Content-Type'] = "text/html"
res.body = req['Referer'] || ''
end
def do_POST(req, res)
res['Content-Type'] = "text/html"
res.body = req['Referer'] || ''
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_with_empty_url.rb | lib/mechanize/test_case/refresh_with_empty_url.rb | # frozen_string_literal: true
class RefreshWithEmptyUrl < 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; url=";
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/modified_since_servlet.rb | lib/mechanize/test_case/modified_since_servlet.rb | # frozen_string_literal: true
class ModifiedSinceServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
s_time = 'Fri, 04 May 2001 00:00:38 GMT'
my_time = Time.parse(s_time)
if req['If-Modified-Since']
your_time = Time.parse(req['If-Modified-Since'])
if my_time > your_time
res.body = 'This page was updated since you requested'
else
res.status = 304
end
else
res.body = 'You did not send an If-Modified-Since header'
end
res['Last-Modified'] = s_time
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/response_code_servlet.rb | lib/mechanize/test_case/response_code_servlet.rb | # frozen_string_literal: true
class ResponseCodeServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
res['Content-Type'] = req.query['ct'] || "text/html"
if req.query['code']
code = req.query['code'].to_i
case code
when 300, 301, 302, 303, 304, 305, 307
res['Location'] = "/index.html"
end
res.status = code
else
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/gzip_servlet.rb | lib/mechanize/test_case/gzip_servlet.rb | # frozen_string_literal: true
require 'stringio'
require 'zlib'
class GzipServlet < WEBrick::HTTPServlet::AbstractServlet
TEST_DIR = File.expand_path '../../../../test', __FILE__
def do_GET(req, res)
if req['Accept-Encoding'] !~ /gzip/ then
res.code = 400
res.body = 'Content-Encoding: gzip is not supported by your user-agent'
return
end
if name = req.query['file'] then
::File.open("#{TEST_DIR}/htdocs/#{name}") do |io|
string = String.new
zipped = StringIO.new string, 'w'
Zlib::GzipWriter.wrap zipped do |gz|
gz.write io.read
end
res.body = string
end
else
res.body = String.new
end
res['Content-Encoding'] = req['X-ResponseContentEncoding'] || 'gzip'
res['Content-Type'] = "text/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/file_upload_servlet.rb | lib/mechanize/test_case/file_upload_servlet.rb | # frozen_string_literal: true
class FileUploadServlet < WEBrick::HTTPServlet::AbstractServlet
def do_POST req, res
res.body = req.body
end
def do_GET req, res
res.content_type = 'text/html'
res.body = <<-BODY
<!DOCTYPE html>
<title>Fill in this form</title>
<p>You can POST anything to this endpoint, though
<form method="POST">
<textarea name="text"></textarea>
<input type="submit">
</form>
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/one_cookie_servlet.rb | lib/mechanize/test_case/one_cookie_servlet.rb | # frozen_string_literal: true
class OneCookieServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
cookie = WEBrick::Cookie.new("foo", "bar")
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/test_case/servlets.rb | lib/mechanize/test_case/servlets.rb | # frozen_string_literal: true
require 'mechanize/test_case/bad_chunking_servlet'
require 'mechanize/test_case/basic_auth_servlet'
require 'mechanize/test_case/content_type_servlet'
require 'mechanize/test_case/digest_auth_servlet'
require 'mechanize/test_case/file_upload_servlet'
require 'mechanize/test_case/form_servlet'
require 'mechanize/test_case/gzip_servlet'
require 'mechanize/test_case/header_servlet'
require 'mechanize/test_case/http_refresh_servlet'
require 'mechanize/test_case/infinite_redirect_servlet'
require 'mechanize/test_case/infinite_refresh_servlet'
require 'mechanize/test_case/many_cookies_as_string_servlet'
require 'mechanize/test_case/many_cookies_servlet'
require 'mechanize/test_case/modified_since_servlet'
require 'mechanize/test_case/ntlm_servlet'
require 'mechanize/test_case/one_cookie_no_spaces_servlet'
require 'mechanize/test_case/one_cookie_servlet'
require 'mechanize/test_case/quoted_value_cookie_servlet'
require 'mechanize/test_case/redirect_servlet'
require 'mechanize/test_case/referer_servlet'
require 'mechanize/test_case/refresh_with_empty_url'
require 'mechanize/test_case/refresh_without_url'
require 'mechanize/test_case/response_code_servlet'
require 'mechanize/test_case/robots_txt_servlet'
require 'mechanize/test_case/send_cookies_servlet'
require 'mechanize/test_case/verb_servlet'
MECHANIZE_TEST_CASE_SERVLETS = {
'/bad_chunking' => BadChunkingServlet,
'/basic_auth' => BasicAuthServlet,
'/content_type_test' => ContentTypeServlet,
'/digest_auth' => DigestAuthServlet,
'/file_upload' => FileUploadServlet,
'/form post' => FormServlet,
'/form_post' => FormServlet,
'/gzip' => GzipServlet,
'/http_headers' => HeaderServlet,
'/http_refresh' => HttpRefreshServlet,
'/if_modified_since' => ModifiedSinceServlet,
'/infinite_redirect' => InfiniteRedirectServlet,
'/infinite_refresh' => InfiniteRefreshServlet,
'/many_cookies' => ManyCookiesServlet,
'/many_cookies_as_string' => ManyCookiesAsStringServlet,
'/ntlm' => NTLMServlet,
'/one_cookie' => OneCookieServlet,
'/one_cookie_no_space' => OneCookieNoSpacesServlet,
'/quoted_value_cookie' => QuotedValueCookieServlet,
'/redirect' => RedirectServlet,
'/referer' => RefererServlet,
'/refresh_with_empty_url' => RefreshWithEmptyUrl,
'/refresh_without_url' => RefreshWithoutUrl,
'/response_code' => ResponseCodeServlet,
'/robots.txt' => RobotsTxtServlet,
'/robots_txt' => RobotsTxtServlet,
'/send_cookies' => SendCookiesServlet,
'/verb' => VerbServlet,
}
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/lib/mechanize/test_case/infinite_redirect_servlet.rb | lib/mechanize/test_case/infinite_redirect_servlet.rb | # frozen_string_literal: true
class InfiniteRedirectServlet < 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'
number = req.query['q'] ? req.query['q'].to_i : 0
res['Location'] = "/infinite_redirect?q=#{number + 1}"
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/infinite_refresh_servlet.rb | lib/mechanize/test_case/infinite_refresh_servlet.rb | # frozen_string_literal: true
class InfiniteRefreshServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
address = "#{req.host}:#{req.port}"
res['Content-Type'] = req.query['ct'] || "text/html"
res.status = req.query['code'] ? req.query['code'].to_i : '302'
number = req.query['q'] ? req.query['q'].to_i : 0
res['Refresh'] = "0;url=http://#{address}/infinite_refresh?q=#{number + 1}";
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/ntlm_servlet.rb | lib/mechanize/test_case/ntlm_servlet.rb | # frozen_string_literal: true
class NTLMServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
if req['Authorization'] =~ /^NTLM (.*)/ then
authorization = $1.unpack('m*').first
if authorization =~ /^NTLMSSP\000\001/ then
type_2 = 'TlRMTVNTUAACAAAADAAMADAAAAABAoEAASNFZ4mr' \
'ze8AAAAAAAAAAGIAYgA8AAAARABPAE0AQQBJAE4A' \
'AgAMAEQATwBNAEEASQBOAAEADABTAEUAUgBWAEUA' \
'UgAEABQAZABvAG0AYQBpAG4ALgBjAG8AbQADACIA' \
'cwBlAHIAdgBlAHIALgBkAG8AbQBhAGkAbgAuAGMA' \
'bwBtAAAAAAA='
res['WWW-Authenticate'] = "NTLM #{type_2}"
res.status = 401
elsif authorization =~ /^NTLMSSP\000\003/ then
res.body = 'ok'
else
res['WWW-Authenticate'] = 'NTLM'
res.status = 401
end
else
res['WWW-Authenticate'] = 'NTLM'
res.status = 401
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.