Handle up to 4 redirects in http fetch code, tests for it

This commit is contained in:
Stephen Sykes 2012-03-22 17:56:26 +02:00
parent cc7ac3f084
commit 34ce278d61
2 changed files with 52 additions and 1 deletions

View File

@ -143,7 +143,7 @@ class FastImage
@property = options[:type_only] ? :type : :size
@timeout = options[:timeout] || DefaultTimeout
@uri = uri
if uri.respond_to?(:read)
fetch_using_read(uri)
else
@ -172,9 +172,27 @@ class FastImage
private
def fetch_using_http
@redirect_count = 0
fetch_using_http_from_parsed_uri
end
def fetch_using_http_from_parsed_uri
setup_http
@http.request_get(@parsed_uri.request_uri) do |res|
if res.is_a?(Net::HTTPRedirection) && @redirect_count < 4
@redirect_count += 1
begin
@parsed_uri = URI.parse(res['Location'])
rescue URI::InvalidURIError
else
fetch_using_http_from_parsed_uri
break
end
end
raise ImageFetchFailure unless res.is_a?(Net::HTTPSuccess)
res.read_body do |str|
break if parse_packet(str)
end

View File

@ -139,4 +139,37 @@ class FastImageTest < Test::Unit::TestCase
FastImage.size(File.join(FixturePath, "faulty.jpg"), :raise_on_failure=>true)
end
end
def test_should_handle_permanent_redirect
url = "http://example.com/foo.jpeg"
register_redirect(url, TestUrl + GoodFixtures.keys.first)
assert_equal GoodFixtures[GoodFixtures.keys.first][1], FastImage.size(url, :raise_on_failure=>true)
end
def test_should_handle_permanent_redirect_4_times
first_url = "http://example.com/foo.jpeg"
register_redirect(first_url, "http://example.com/foo2.jpeg")
register_redirect("http://example.com/foo2.jpeg", "http://example.com/foo3.jpeg")
register_redirect("http://example.com/foo3.jpeg", "http://example.com/foo4.jpeg")
register_redirect("http://example.com/foo4.jpeg", TestUrl + GoodFixtures.keys.first)
assert_equal GoodFixtures[GoodFixtures.keys.first][1], FastImage.size(first_url, :raise_on_failure=>true)
end
def test_should_raise_on_permanent_redirect_5_times
first_url = "http://example.com/foo.jpeg"
register_redirect(first_url, "http://example.com/foo2.jpeg")
register_redirect("http://example.com/foo2.jpeg", "http://example.com/foo3.jpeg")
register_redirect("http://example.com/foo3.jpeg", "http://example.com/foo4.jpeg")
register_redirect("http://example.com/foo4.jpeg", "http://example.com/foo5.jpeg")
register_redirect("http://example.com/foo5.jpeg", TestUrl + GoodFixtures.keys.first)
assert_raises(FastImage::ImageFetchFailure) do
FastImage.size(first_url, :raise_on_failure=>true)
end
end
def register_redirect(from, to)
resp = Net::HTTPMovedPermanently.new(1.0, 302, "Moved")
resp['Location'] = to
FakeWeb.register_uri(:get, from, :response=>resp)
end
end