# coding: utf-8 require 'mechanize/test_case' 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 = if RUBY_VERSION > '1.9' then %w[accept user-agent] else %w[accept] end 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 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_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_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 assert_kind_of Mechanize::Page, page end def test_fetch_file_nonexistent uri = URI.parse 'file:///nonexistent' e = assert_raises Mechanize::ResponseCodeError do @agent.fetch uri end assert_equal '404 => Net::HTTPNotFound', e.message 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_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_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_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.set_http @agent.idle_timeout = 1 assert_equal 1, @agent.http.idle_timeout 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_cookies uri = URI.parse 'http://host.example.com' Mechanize::Cookie.parse uri, 'hello=world domain=.example.com' do |cookie| @agent.cookie_jar.add uri, cookie end @agent.request_cookies @req, uri assert_equal 'hello=world domain=.example.com', @req['Cookie'] end def test_request_cookies_none @agent.request_cookies @req, @uri assert_nil @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' Mechanize::Cookie.parse uri, cookie_str do |cookie| @agent.cookie_jar.add uri, cookie end @agent.request_cookies @req, uri expected = cookie_str.sub ', ', '; ' assert_equal expected, @req['Cookie'] end def test_request_cookies_wrong_domain uri = URI.parse 'http://host.example.com' Mechanize::Cookie.parse uri, 'hello=world domain=.example.com' do |cookie| @agent.cookie_jar.add uri, cookie end @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_equal 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', @req['accept-charset'] 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_none @agent.request_auth @req, @uri assert_nil @req['Authorization'] end def test_request_auth_basic @agent.user = 'user' @agent.password = 'password' auth_realm @uri, 'Basic', :basic @agent.request_auth @req, @uri assert_match %r%^Basic %, @req['Authorization'] end def test_request_auth_digest @agent.user = 'user' @agent.password = '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_iis_digest @agent.user = 'user' @agent.password = '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_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_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_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_response_authenticate @res.instance_variable_set :@header, 'www-authenticate' => ['Basic realm=r'] @agent.user = 'user' @agent.password = 'password' @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 @res.instance_variable_set(:@header, 'www-authenticate' => ['Digest realm=r']) @agent.user = 'user' @agent.password = 'password' @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' assert_equal challenge, @agent.digest_challenges[realm] end def test_response_authenticate_digest_iis @res.instance_variable_set(:@header, 'www-authenticate' => ['Digest realm=r'], 'server' => ['Microsoft-IIS']) @agent.user = 'user' @agent.password = 'password' @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 @res.instance_variable_set(:@header, 'www-authenticate' => ['Basic realm=r, Digest realm=r']) @agent.user = 'user' @agent.password = 'password' @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_ntlm @uri += '/ntlm' @res.instance_variable_set(:@header, 'www-authenticate' => ['NTLM']) @agent.user = 'user' @agent.password = 'password' page = @agent.response_authenticate @res, nil, @uri, @req, {}, nil, nil assert_equal 'ok', page.body # lame test end def test_response_authenticate_unknown @agent.user = 'user' @agent.password = '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 def @res.content_length() 4 end @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 def @res.content_length() 12 end @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_chunked def @res.content_length() nil end @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 # IIS/6.0 ASP.NET/2.0.50727 does not wrap deflate with zlib, WTF? def test_response_content_encoding_deflate_no_zlib def @res.content_length() 6 end @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 def @res.content_length() 24 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_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_gzip_encoding_bad def @res.content_length() 24 end @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_none def @res.content_length() 4 end @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_x_gzip def @res.content_length() 24 end @res.instance_variable_set :@header, 'content-encoding' => %w[x-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_unknown def @res.content_length() 4 end @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_get_meta_refresh_header_follow_self @agent.follow_meta_refresh = true @agent.follow_meta_refresh_self = true page = Mechanize::Page.new(@uri, {'content-type' => 'text/html'}, '', 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, {'content-type' => 'text/html'}, '', 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, {'content-type' => 'text/html'}, '', 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