Skip to content

Instantly share code, notes, and snippets.

@swieton
Created November 7, 2010 19:00
Show Gist options
  • Save swieton/666326 to your computer and use it in GitHub Desktop.
Save swieton/666326 to your computer and use it in GitHub Desktop.
Simple validation of redirects and URL rewrites
require 'rubygems'
require 'http-access2' # from gem httpclient
tests = {
# A simple test: GET a URL and expect a successful response
"Home page" => {
:get => "http://www.myapp.com/",
:result => 200
},
# A simple test: GET a URL and expect a specific response code
"Home page" => {
:get => "http://www.myapp.com/whatever",
:result => 403 # forbidden
},
# More complicated: GET a URL and expect a redirect to an HTTPS login page
"Restricted area" => {
:get => "http://www.myapp.com/private",
:result => "https://secure.myapp.com/login"
},
}
require 'uri'
require 'pp'
test_count = 0
test_failures = 0
tests.each do |test_name, test_config|
puts "Running: #{test_name}"
begin
uri = URI.parse(test_config[:get])
client = HTTPClient.new
result = client.get(uri)
if String === test_config[:result] # assert redirected to a URL
if !result.status_code.to_s[/\A3..\Z/]
puts " Fail: Did not redirect, was [#{result.status_code}]"
test_failures += 1
elsif result.header['Location'].to_s != test_config[:result]
puts " Fail: Redirected to:\n got: [#{result.header['Location']}]\nexpected: [#{test_config[:result]}]\n"
test_failures += 1
end
elsif Numeric === test_config[:result]
if result.status_code != test_config[:result]
puts " Fail: Wrong response received [#{result.status_code}], expected [#{test_config[:result]}]"
end
else
puts "don't know how to validate #{test_config[:result].pretty_inspect}"
test_failures += 1
end
rescue Exception => ex
puts "Fail: #{ex.class.name}: #{ex.message}"
puts
puts ex.backtrace
puts
test_failures += 1
end
test_count += 1
end
puts
puts "#{test_count - test_failures} / #{test_count} tests passed"
exit (test_failures == 0 ? 0 : 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment