Created
December 8, 2011 21:58
-
-
Save petewarden/1448826 to your computer and use it in GitHub Desktop.
A simple smoketest script for sanity checking websites from the command line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
# | |
# A module for a quick sanity test on whether a web page is working (for small values of working) | |
# See http://petewarden.typepad.com for more info | |
# | |
# | |
require 'rubygems' if RUBY_VERSION < '1.9' | |
require 'net/http' | |
require 'net/https' | |
require 'uri' | |
# Returns a response object for the given URL, containing body and code members, amongst others | |
def load_from_url(url) | |
begin | |
# Do some dancing around so that we can handle both http and https URLs here | |
uri = URI.parse(url) | |
http = Net::HTTP.new(uri.host, uri.port) | |
if uri.scheme == 'https' | |
http.use_ssl = true | |
else | |
http.use_ssl = false | |
end | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Don't do this in production code! But skips config problems for test purposes | |
request = Net::HTTP::Get.new(uri.request_uri) | |
response = http.request(request) | |
rescue Exception => e | |
$stderr.puts "load_from_url Exception: #{e}: #{e.message}" | |
response = nil | |
end | |
response | |
end | |
def is_page_up(url) | |
response = load_from_url(url) | |
# Did we get any response at all? | |
if !response | |
$stderr.puts "is_page_up nil response for #{url}" | |
return false | |
end | |
# Was it a valid code? Note we're being picky and not accepting redirects, etc. | |
if response.code != '200' | |
$stderr.puts "is_page_up Bad #{response.code} response code for #{url}" | |
return false | |
end | |
# Was there any content in the body? If not, probably not a success! | |
if response.body.length < 1 | |
$stderr.puts "is_page_up Bad #{response.code} response code for #{url}" | |
return false | |
end | |
# We passed all the tests, so report our victory | |
return true | |
end | |
# If this file is invoked as a standalone command, rather than included as a module | |
if __FILE__ == $0 | |
if ARGV.length < 1 | |
# There's no url input, just run the unit test | |
test_urls = ['http://www.google.com', 'http://www.gogogoglego.com', 'http://www.google.com/notapage'] | |
test_urls.each do | url | | |
is_ok = is_page_up(url) | |
$stderr.puts "#{url} is #{if is_ok then 'up' else 'down' end}" | |
end | |
else | |
# Pull the url from the command-line arguments | |
url = ARGV[0] | |
is_ok = is_page_up(url) | |
$stderr.puts "#{url} is #{if is_ok then 'up' else 'down' end}" | |
# exit with a return code here so that we can use this in a shell script | |
exit(is_ok) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment