httparty-0.13.5/ 0000755 0000041 0000041 00000000000 12530444726 013516 5 ustar www-data www-data httparty-0.13.5/Rakefile 0000644 0000041 0000041 00000000303 12530444726 015157 0 ustar www-data www-data begin
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
rescue LoadError
end
require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:features)
task default: [:spec, :features]
httparty-0.13.5/bin/ 0000755 0000041 0000041 00000000000 12530444726 014266 5 ustar www-data www-data httparty-0.13.5/bin/httparty 0000755 0000041 0000041 00000005534 12530444726 016102 0 ustar www-data www-data #!/usr/bin/env ruby
require "optparse"
require "pp"
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "/../lib"))
require "httparty"
opts = {
action: :get,
headers: {},
verbose: false
}
OptionParser.new do |o|
o.banner = "USAGE: #{$PROGRAM_NAME} [options] [url]"
o.on("-f",
"--format [FORMAT]",
"Output format to use instead of pretty-print ruby: " \
"plain, csv, json or xml") do |f|
opts[:output_format] = f.downcase.to_sym
end
o.on("-a",
"--action [ACTION]",
"HTTP action: get (default), post, put, delete, head, or options") do |a|
opts[:action] = a.downcase.to_sym
end
o.on("-d",
"--data [BODY]",
"Data to put in request body (prefix with '@' for file)") do |d|
if d =~ /^@/
opts[:body] = open(d[1..-1]).read
else
opts[:body] = d
end
end
o.on("-H", "--header [NAME:VALUE]", "Additional HTTP headers in NAME:VALUE form") do |h|
abort "Invalid header specification, should be Name:Value" unless h =~ /.+:.+/
name, value = h.split(':')
opts[:headers][name.strip] = value.strip
end
o.on("-v", "--verbose", "If set, print verbose output") do |v|
opts[:verbose] = true
end
o.on("-u", "--user [CREDS]", "Use basic authentication. Value should be user:password") do |u|
abort "Invalid credentials format. Must be user:password" unless u =~ /.*:.+/
user, password = u.split(':')
opts[:basic_auth] = { username: user, password: password }
end
o.on("-r", "--response-code", "Command fails if response code >= 400") do
opts[:response_code] = true
end
o.on("-h", "--help", "Show help documentation") do |h|
puts o
exit
end
end.parse!
if ARGV.empty?
STDERR.puts "You need to provide a URL"
STDERR.puts "USAGE: #{$PROGRAM_NAME} [options] [url]"
end
def dump_headers(response)
resp_type = Net::HTTPResponse::CODE_TO_OBJ[response.code.to_s]
puts "#{response.code} #{resp_type.to_s.sub(/^Net::HTTP/, '')}"
response.headers.each do |n, v|
puts "#{n}: #{v}"
end
puts
end
if opts[:verbose]
puts "#{opts[:action].to_s.upcase} #{ARGV.first}"
opts[:headers].each do |n, v|
puts "#{n}: #{v}"
end
puts
end
response = HTTParty.send(opts[:action], ARGV.first, opts)
if opts[:output_format].nil?
dump_headers(response) if opts[:verbose]
pp response
else
print_format = opts[:output_format]
dump_headers(response) if opts[:verbose]
case opts[:output_format]
when :json
begin
require 'json'
puts JSON.pretty_generate(response)
rescue LoadError
puts YAML.dump(response)
end
when :xml
require 'rexml/document'
REXML::Document.new(response.body).write(STDOUT, 2)
puts
when :csv
require 'csv'
puts CSV.parse(response.body).map(&:to_s)
else
puts response
end
end
exit false if opts[:response_code] && response.code >= 400
httparty-0.13.5/Gemfile 0000644 0000041 0000041 00000000470 12530444726 015012 0 ustar www-data www-data source 'https://rubygems.org'
gemspec
gem 'rake'
gem 'fakeweb', '~> 1.3'
gem 'mongrel', '1.2.0.pre2'
group :development do
gem 'guard'
gem 'guard-rspec'
gem 'guard-bundler'
end
group :test do
gem 'rspec', '~> 3.1'
gem 'simplecov', require: false
gem 'aruba'
gem 'cucumber', '~> 1.3.17'
end
httparty-0.13.5/examples/ 0000755 0000041 0000041 00000000000 12530444726 015334 5 ustar www-data www-data httparty-0.13.5/examples/rescue_json.rb 0000644 0000041 0000041 00000001206 12530444726 020177 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
# Take note of the "; 1" at the end of the following line. It's required only if
# running this in IRB, because IRB will try to inspect the variable named
# "request", triggering the exception.
request = HTTParty.get 'https://rubygems.org/api/v1/versions/doesnotexist.json' ; 1
# Check an exception due to parsing the response
# because HTTParty evaluate the response lazily
begin
request.inspect
# This would also suffice by forcing the request to be parsed:
# request.parsed_response
rescue => e
puts "Rescued #{e.inspect}"
end
httparty-0.13.5/examples/custom_parsers.rb 0000644 0000041 0000041 00000002010 12530444726 020723 0 ustar www-data www-data class ParseAtom
include HTTParty
# Support Atom along with the default parsers: xml, json, etc.
class Parser::Atom < HTTParty::Parser
SupportedFormats.merge!({"application/atom+xml" => :atom})
protected
# perform atom parsing on body
def atom
body.to_atom
end
end
parser Parser::Atom
end
class OnlyParseAtom
include HTTParty
# Only support Atom
class Parser::OnlyAtom < HTTParty::Parser
SupportedFormats = {"application/atom+xml" => :atom}
protected
# perform atom parsing on body
def atom
body.to_atom
end
end
parser Parser::OnlyAtom
end
class SkipParsing
include HTTParty
# Parse the response body however you like
class Parser::Simple < HTTParty::Parser
def parse
body
end
end
parser Parser::Simple
end
class AdHocParsing
include HTTParty
parser(
proc do |body, format|
case format
when :json
body.to_json
when :xml
body.to_xml
else
body
end
end
)
end
httparty-0.13.5/examples/tripit_sign_in.rb 0000644 0000041 0000041 00000001507 12530444726 020705 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
class TripIt
include HTTParty
base_uri 'http://www.tripit.com'
debug_output
def initialize(email, password)
@email = email
response = self.class.get('/account/login')
response = self.class.post(
'/account/login',
body: {
login_email_address: email,
login_password: password
},
headers: {'Cookie' => response.headers['Set-Cookie']}
)
@cookie = response.request.options[:headers]['Cookie']
end
def account_settings
self.class.get('/account/edit', headers: {'Cookie' => @cookie})
end
def logged_in?
account_settings.include? "You're logged in as #{@email}"
end
end
tripit = TripIt.new('email', 'password')
puts "Logged in: #{tripit.logged_in?}"
httparty-0.13.5/examples/stackexchange.rb 0000644 0000041 0000041 00000001023 12530444726 020465 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class StackExchange
include HTTParty
base_uri 'api.stackexchange.com'
def initialize(service, page)
@options = { query: {site: service, page: page} }
end
def questions
self.class.get("/2.2/questions", @options)
end
def users
self.class.get("/2.2/users", @options)
end
end
stack_exchange = StackExchange.new("stackoverflow", 1)
pp stack_exchange.questions
pp stack_exchange.users
httparty-0.13.5/examples/aaws.rb 0000644 0000041 0000041 00000002011 12530444726 016606 0 ustar www-data www-data require 'rubygems'
require 'active_support'
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
config = YAML.load(File.read(File.join(ENV['HOME'], '.aaws')))
module AAWS
class Book
include HTTParty
base_uri 'http://ecs.amazonaws.com'
default_params Service: 'AWSECommerceService', Operation: 'ItemSearch', SearchIndex: 'Books'
def initialize(key)
self.class.default_params AWSAccessKeyId: key
end
def search(options = {})
raise ArgumentError, 'You must search for something' if options[:query].blank?
# amazon uses nasty camelized query params
options[:query] = options[:query].inject({}) { |h, q| h[q[0].to_s.camelize] = q[1]; h }
# make a request and return the items (NOTE: this doesn't handle errors at this point)
self.class.get('/onca/xml', options)['ItemSearchResponse']['Items']
end
end
end
aaws = AAWS::Book.new(config[:access_key])
pp aaws.search(query: {title: 'Ruby On Rails'})
httparty-0.13.5/examples/google.rb 0000644 0000041 0000041 00000000602 12530444726 017133 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class Google
include HTTParty
format :html
end
# google.com redirects to www.google.com so this is live test for redirection
pp Google.get('http://google.com')
puts '', '*' * 70, ''
# check that ssl is requesting right
pp Google.get('https://www.google.com')
httparty-0.13.5/examples/crack.rb 0000644 0000041 0000041 00000000652 12530444726 016747 0 ustar www-data www-data require 'rubygems'
require 'crack'
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class Rep
include HTTParty
parser(
proc do |body, format|
Crack::XML.parse(body)
end
)
end
pp Rep.get('http://whoismyrepresentative.com/getall_mems.php?zip=46544')
pp Rep.get('http://whoismyrepresentative.com/getall_mems.php', query: {zip: 46544})
httparty-0.13.5/examples/delicious.rb 0000644 0000041 0000041 00000002213 12530444726 017637 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
config = YAML.load(File.read(File.join(ENV['HOME'], '.delicious')))
class Delicious
include HTTParty
base_uri 'https://api.del.icio.us/v1'
def initialize(u, p)
@auth = {username: u, password: p}
end
# query params that filter the posts are:
# tag (optional). Filter by this tag.
# dt (optional). Filter by this date (CCYY-MM-DDThh:mm:ssZ).
# url (optional). Filter by this url.
# ie: posts(query: {tag: 'ruby'})
def posts(options = {})
options.merge!({basic_auth: @auth})
self.class.get('/posts/get', options)
end
# query params that filter the posts are:
# tag (optional). Filter by this tag.
# count (optional). Number of items to retrieve (Default:15, Maximum:100).
def recent(options = {})
options.merge!({basic_auth: @auth})
self.class.get('/posts/recent', options)
end
end
delicious = Delicious.new(config['username'], config['password'])
pp delicious.posts(query: {tag: 'ruby'})
pp delicious.recent
delicious.recent['posts']['post'].each { |post| puts post['href'] }
httparty-0.13.5/examples/logging.rb 0000644 0000041 0000041 00000001771 12530444726 017315 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'logger'
require 'pp'
my_logger = Logger.new "httparty.log"
my_logger.info "Logging can be used on the main HTTParty class. It logs redirects too."
HTTParty.get "http://google.com", logger: my_logger
my_logger.info '*' * 70
my_logger.info "It can be used also on a custom class."
class Google
include HTTParty
logger ::Logger.new "httparty.log"
end
Google.get "http://google.com"
my_logger.info '*' * 70
my_logger.info "The default formatter is :apache. The :curl formatter can also be used."
my_logger.info "You can tell wich method to call on the logger too. It is info by default."
HTTParty.get "http://google.com", logger: my_logger, log_level: :debug, log_format: :curl
my_logger.info '*' * 70
my_logger.info "These configs are also available on custom classes."
class Google
include HTTParty
logger ::Logger.new("httparty.log"), :debug, :curl
end
Google.get "http://google.com"
httparty-0.13.5/examples/rubyurl.rb 0000644 0000041 0000041 00000000531 12530444726 017364 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class Rubyurl
include HTTParty
base_uri 'rubyurl.com'
def self.shorten(website_url)
post('/api/links.json', query: { link: { website_url: website_url } })
end
end
pp Rubyurl.shorten('http://istwitterdown.com/')
httparty-0.13.5/examples/twitter.rb 0000644 0000041 0000041 00000001714 12530444726 017366 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
config = YAML.load(File.read(File.join(ENV['HOME'], '.twitter')))
class Twitter
include HTTParty
base_uri 'twitter.com'
def initialize(u, p)
@auth = {username: u, password: p}
end
# which can be :friends, :user or :public
# options[:query] can be things like since, since_id, count, etc.
def timeline(which = :friends, options = {})
options.merge!({basic_auth: @auth})
self.class.get("/statuses/#{which}_timeline.json", options)
end
def post(text)
options = { query: {status: text}, basic_auth: @auth }
self.class.post('/statuses/update.json', options)
end
end
twitter = Twitter.new(config['email'], config['password'])
pp twitter.timeline
# pp twitter.timeline(:friends, query: {since_id: 868482746})
# pp twitter.timeline(:friends, query: 'since_id=868482746')
# pp twitter.post('this is a test of 0.2.0')
httparty-0.13.5/examples/nokogiri_html_parser.rb 0000644 0000041 0000041 00000000536 12530444726 022106 0 ustar www-data www-data require 'rubygems'
require 'nokogiri'
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class HtmlParserIncluded < HTTParty::Parser
def html
Nokogiri::HTML(body)
end
end
class Page
include HTTParty
parser HtmlParserIncluded
end
pp Page.get('http://www.google.com')
httparty-0.13.5/examples/headers_and_user_agents.rb 0000644 0000041 0000041 00000000475 12530444726 022523 0 ustar www-data www-data # To send custom user agents to identify your application to a web service (or mask as a specific browser for testing), send "User-Agent" as a hash to headers as shown below.
require 'httparty'
APPLICATION_NAME = "Httparty"
response = HTTParty.get('http://example.com', headers: {"User-Agent" => APPLICATION_NAME})
httparty-0.13.5/examples/basic.rb 0000644 0000041 0000041 00000001447 12530444726 016750 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
# You can also use post, put, delete, head, options in the same fashion
response = HTTParty.get('https://api.stackexchange.com/2.2/questions?site=stackoverflow')
puts response.body, response.code, response.message, response.headers.inspect
# An example post to a minimal rails app in the development environment
# Note that "skip_before_filter :verify_authenticity_token" must be set in the
# "pears" controller for this example
class Partay
include HTTParty
base_uri 'http://localhost:3000'
end
options = {
body: {
pear: { # your resource
foo: '123', # your columns/data
bar: 'second',
baz: 'last thing'
}
}
}
pp Partay.post('/pears.xml', options)
httparty-0.13.5/examples/README.md 0000644 0000041 0000041 00000003712 12530444726 016616 0 ustar www-data www-data ## Examples
* [Amazon Book Search](aaws.rb)
* Httparty included into poro class
* Uses `get` requests
* Transforms query params to uppercased params
* [Google Search](google.rb)
* Httparty included into poro class
* Uses `get` requests
* [Crack Custom Parser](crack.rb)
* Creates a custom parser for XML using crack gem
* Uses `get` request
* [Create HTML Nokogiri parser](nokogiri_html_parser.rb)
* Adds Html as a format
* passed the body of request to Nokogiri
* [More Custom Parsers](custom_parsers.rb)
* Create an additional parser for atom or make it the ONLY parser
* [Basic Auth, Delicious](delicious.rb)
* Basic Auth, shows how to merge those into options
* Uses `get` requests
* [Passing Headers, User Agent](headers_and_user_agents.rb)
* Use the class method of Httparty
* Pass the User-Agent in the headers
* Uses `get` requests
* [Basic Post Request](basic.rb)
* Httparty included into poro class
* Uses `post` requests
* [Access Rubyurl Shortener](rubyurl.rb)
* Httparty included into poro class
* Uses `post` requests
* [Add a custom log file](logging.rb)
* create a log file and have httparty log requests
* [Accessing StackExchange](stackexchange.rb)
* Httparty included into poro class
* Creates methods for different endpoints
* Uses `get` requests
* [Accessing Tripit](tripit_sign_in.rb)
* Httparty included into poro class
* Example of using `debug_output` to see headers/urls passed
* Getting and using Cookies
* Uses `get` requests
* [Accessing Twitter](twitter.rb)
* Httparty included into poro class
* Basic Auth
* Loads settings from a config file
* Uses `get` requests
* Uses `post` requests
* [Accessing WhoIsMyRep](whoismyrep.rb)
* Httparty included into poro class
* Uses `get` requests
* Two ways to pass params to get, inline on the url or in query hash
* [Rescue Json Error](rescue_json.rb)
* Rescue errors due to parsing response httparty-0.13.5/examples/whoismyrep.rb 0000644 0000041 0000041 00000000467 12530444726 020076 0 ustar www-data www-data dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class Rep
include HTTParty
end
pp Rep.get('http://whoismyrepresentative.com/getall_mems.php?zip=46544')
pp Rep.get('http://whoismyrepresentative.com/getall_mems.php', query: {zip: 46544})
httparty-0.13.5/.rubocop_todo.yml 0000644 0000041 0000041 00000005362 12530444726 017023 0 ustar www-data www-data # This configuration was generated by `rubocop --auto-gen-config`
# on 2015-04-24 07:22:28 +0200 using RuboCop version 0.30.0.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 33
Lint/AmbiguousRegexpLiteral:
Enabled: false
# Offense count: 1
# Configuration parameters: AlignWith, SupportedStyles.
Lint/EndAlignment:
Enabled: false
# Offense count: 1
Lint/HandleExceptions:
Enabled: false
# Offense count: 5
Lint/UselessAssignment:
Enabled: false
# Offense count: 23
Metrics/AbcSize:
Max: 86
# Offense count: 1
# Configuration parameters: CountComments.
Metrics/ClassLength:
Max: 285
# Offense count: 8
Metrics/CyclomaticComplexity:
Max: 17
# Offense count: 332
# Configuration parameters: AllowURI, URISchemes.
Metrics/LineLength:
Max: 266
# Offense count: 17
# Configuration parameters: CountComments.
Metrics/MethodLength:
Max: 39
# Offense count: 8
Metrics/PerceivedComplexity:
Max: 20
# Offense count: 1
Style/AccessorMethodName:
Enabled: false
# Offense count: 1
Style/AsciiComments:
Enabled: false
# Offense count: 14
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, ProceduralMethods, FunctionalMethods, IgnoredMethods.
Style/BlockDelimiters:
Enabled: false
# Offense count: 2
Style/CaseEquality:
Enabled: false
# Offense count: 3
# Configuration parameters: IndentWhenRelativeTo, SupportedStyles, IndentOneStep.
Style/CaseIndentation:
Enabled: false
# Offense count: 4
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/ClassAndModuleChildren:
Enabled: false
# Offense count: 7
Style/ConstantName:
Enabled: false
# Offense count: 2
Style/EachWithObject:
Enabled: false
# Offense count: 2
# Cop supports --auto-correct.
Style/ElseAlignment:
Enabled: false
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/FirstParameterIndentation:
Enabled: false
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, UseHashRocketsWithSymbolValues.
Style/HashSyntax:
Enabled: false
# Offense count: 7
# Cop supports --auto-correct.
# Configuration parameters: MaxLineLength.
Style/IfUnlessModifier:
Enabled: false
# Offense count: 11
# Cop supports --auto-correct.
Style/Lambda:
Enabled: false
# Offense count: 1
# Configuration parameters: EnforcedStyle, MinBodyLength, SupportedStyles.
Style/Next:
Enabled: false
# Offense count: 2
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/RaiseArgs:
Enabled: false
httparty-0.13.5/script/ 0000755 0000041 0000041 00000000000 12530444726 015022 5 ustar www-data www-data httparty-0.13.5/script/release 0000744 0000041 0000041 00000001551 12530444726 016370 0 ustar www-data www-data #!/bin/sh
#/ Usage: release
#/
#/ Tag the version in the repo and push the gem.
#/
set -e
cd $(dirname "$0")/..
[ "$1" = "--help" -o "$1" = "-h" -o "$1" = "help" ] && {
grep '^#/' <"$0"| cut -c4-
exit 0
}
gem_name=httparty
# Build a new gem archive.
rm -rf $gem_name-*.gem
gem build -q $gem_name.gemspec
# Make sure we're on the master branch.
(git branch | grep -q '* master') || {
echo "Only release from the master branch."
exit 1
}
# Figure out what version we're releasing.
tag=v`ls $gem_name-*.gem | sed "s/^$gem_name-\(.*\)\.gem$/\1/"`
echo "Releasing $tag"
# Make sure we haven't released this version before.
git fetch -t origin
(git tag -l | grep -q "$tag") && {
echo "Whoops, there's already a '${tag}' tag."
exit 1
}
# Tag it and bag it.
gem push $gem_name-*.gem && git tag "$tag" &&
git push origin master && git push origin "$tag"
httparty-0.13.5/features/ 0000755 0000041 0000041 00000000000 12530444726 015334 5 ustar www-data www-data httparty-0.13.5/features/supports_timeout_option.feature 0000644 0000041 0000041 00000001161 12530444726 023745 0 ustar www-data www-data Feature: Supports the timeout option
In order to handle inappropriately slow response times
As a developer
I want my request to raise an exception after my specified timeout as elapsed
Scenario: A long running response
Given a remote service that returns '
Some HTML
'
And that service is accessed at the path '/long_running_service.html'
And that service takes 2 seconds to generate a response
When I set my HTTParty timeout option to 1
And I call HTTParty#get with '/long_running_service.html'
Then it should raise a Timeout::Error exception
And I wait for the server to recover
httparty-0.13.5/features/handles_compressed_responses.feature 0000644 0000041 0000041 00000002224 12530444726 024654 0 ustar www-data www-data Feature: Handles Compressed Responses
In order to save bandwidth
As a developer
I want to uncompress compressed responses
Scenario: Supports deflate encoding
Given a remote deflate service
And the response from the service has a body of 'Some HTML
'
And that service is accessed at the path '/deflate_service.html'
When I call HTTParty#get with '/deflate_service.html'
Then the return value should match 'Some HTML
'
Scenario: Supports gzip encoding
Given a remote gzip service
And the response from the service has a body of 'Some HTML
'
And that service is accessed at the path '/gzip_service.html'
When I call HTTParty#get with '/gzip_service.html'
Then the return value should match 'Some HTML
'
Scenario: Supports HEAD request with gzip encoding
Given a remote gzip service
And that service is accessed at the path '/gzip_head.gz.js'
When I call HTTParty#head with '/gzip_head.gz.js'
Then it should return a response with a 200 response code
Then it should return a response with a gzip content-encoding
Then it should return a response with a blank body
httparty-0.13.5/features/basic_authentication.feature 0000644 0000041 0000041 00000001675 12530444726 023102 0 ustar www-data www-data Feature: Basic Authentication
As a developer
I want to be able to use a service that requires Basic Authentication
Because that is not an uncommon requirement
Scenario: Passing no credentials to a page requiring Basic Authentication
Given a restricted page at '/basic_auth.html'
When I call HTTParty#get with '/basic_auth.html'
Then it should return a response with a 401 response code
Scenario: Passing proper credentials to a page requiring Basic Authentication
Given a remote service that returns 'Authenticated Page'
And that service is accessed at the path '/basic_auth.html'
And that service is protected by Basic Authentication
And that service requires the username 'jcash' with the password 'maninblack'
When I call HTTParty#get with '/basic_auth.html' and a basic_auth hash:
| username | password |
| jcash | maninblack |
Then the return value should match 'Authenticated Page'
httparty-0.13.5/features/steps/ 0000755 0000041 0000041 00000000000 12530444726 016472 5 ustar www-data www-data httparty-0.13.5/features/steps/httparty_response_steps.rb 0000644 0000041 0000041 00000003436 12530444726 024040 0 ustar www-data www-data # Not needed anymore in ruby 2.0, but needed to resolve constants
# in nested namespaces. This is taken from rails :)
def constantize(camel_cased_word)
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
constant = Object
names.each do |name|
constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
end
constant
end
Then /it should return an? (\w+)$/ do |class_string|
expect(@response_from_httparty).to be_a(class_string.class)
end
Then /the return value should match '(.*)'/ do |expected_text|
expect(@response_from_httparty.parsed_response).to eq(expected_text)
end
Then /it should return a Hash equaling:/ do |hash_table|
expect(@response_from_httparty).to be_a(Hash)
expect(@response_from_httparty.keys.length).to eq(hash_table.rows.length)
hash_table.hashes.each do |pair|
key, value = pair["key"], pair["value"]
expect(@response_from_httparty.keys).to include(key)
expect(@response_from_httparty[key]).to eq(value)
end
end
Then /it should return an Array equaling:/ do |array|
expect(@response_from_httparty).to be_a(Array)
expect(@response_from_httparty.parsed_response).to eq(array.raw)
end
Then /it should return a response with a (\d+) response code/ do |code|
expect(@response_from_httparty.code).to eq(code.to_i)
end
Then /it should return a response with a (.*) content\-encoding$/ do |content_type|
expect(@response_from_httparty.headers['content-encoding']).to eq('gzip')
end
Then /it should return a response with a blank body$/ do
expect(@response_from_httparty.body).to be_nil
end
Then /it should raise (?:an|a) ([\w:]+) exception/ do |exception|
expect(@exception_from_httparty).to_not be_nil
expect(@exception_from_httparty).to be_a constantize(exception)
end
httparty-0.13.5/features/steps/mongrel_helper.rb 0000644 0000041 0000041 00000004534 12530444726 022027 0 ustar www-data www-data require 'base64'
class BasicMongrelHandler < Mongrel::HttpHandler
attr_accessor :content_type, :custom_headers, :response_body, :response_code, :preprocessor, :username, :password
def initialize
@content_type = "text/html"
@response_body = ""
@response_code = 200
@custom_headers = {}
end
def process(request, response)
instance_eval(&preprocessor) if preprocessor
reply_with(response, response_code, response_body)
end
def reply_with(response, code, response_body)
response.start(code) do |head, body|
head["Content-Type"] = content_type
custom_headers.each { |k, v| head[k] = v }
body.write(response_body)
end
end
end
class DeflateHandler < BasicMongrelHandler
def process(request, response)
response.start do |head, body|
head['Content-Encoding'] = 'deflate'
body.write Zlib::Deflate.deflate(response_body)
end
end
end
class GzipHandler < BasicMongrelHandler
def process(request, response)
response.start do |head, body|
head['Content-Encoding'] = 'gzip'
body.write gzip(response_body)
end
end
protected
def gzip(string)
sio = StringIO.new('', 'r+')
gz = Zlib::GzipWriter.new sio
gz.write string
gz.finish
sio.rewind
sio.read
end
end
module BasicAuthentication
def self.extended(base)
base.custom_headers["WWW-Authenticate"] = 'Basic Realm="Super Secret Page"'
end
def process(request, response)
if authorized?(request)
super
else
reply_with(response, 401, "Incorrect. You have 20 seconds to comply.")
end
end
def authorized?(request)
request.params["HTTP_AUTHORIZATION"] == "Basic " + Base64.encode64("#{@username}:#{@password}").strip
end
end
module DigestAuthentication
def self.extended(base)
base.custom_headers["WWW-Authenticate"] = 'Digest realm="testrealm@host.com",qop="auth,auth-int",nonce="nonce",opaque="opaque"'
end
def process(request, response)
if authorized?(request)
super
else
reply_with(response, 401, "Incorrect. You have 20 seconds to comply.")
end
end
def authorized?(request)
request.params["HTTP_AUTHORIZATION"] =~ /Digest.*uri=/
end
end
def new_mongrel_redirector(target_url, relative_path = false)
target_url = "http://#{@host_and_port}#{target_url}" unless relative_path
Mongrel::RedirectHandler.new(target_url)
end
httparty-0.13.5/features/steps/remote_service_steps.rb 0000644 0000041 0000041 00000005031 12530444726 023247 0 ustar www-data www-data Given /a remote service that returns '(.*)'/ do |response_body|
@handler = BasicMongrelHandler.new
step "the response from the service has a body of '#{response_body}'"
end
Given /^a remote service that returns:$/ do |response_body|
@handler = BasicMongrelHandler.new
@handler.response_body = response_body
end
Given /a remote service that returns a (\d+) status code/ do |code|
@handler = BasicMongrelHandler.new
@handler.response_code = code
end
Given /that service is accessed at the path '(.*)'/ do |path|
@server.register(path, @handler)
end
Given /^that service takes (\d+) seconds to generate a response$/ do |time|
@server_response_time = time.to_i
@handler.preprocessor = proc { sleep time.to_i }
end
Given /^a remote deflate service$/ do
@handler = DeflateHandler.new
end
Given /^a remote deflate service on port '(\d+)'/ do |port|
run_server(port)
@handler = DeflateHandler.new
end
Given /^a remote gzip service$/ do
@handler = GzipHandler.new
end
Given /the response from the service has a Content-Type of '(.*)'/ do |content_type|
@handler.content_type = content_type
end
Given /the response from the service has a body of '(.*)'/ do |response_body|
@handler.response_body = response_body
end
Given /the url '(.*)' redirects to '(.*)'/ do |redirection_url, target_url|
@server.register redirection_url, new_mongrel_redirector(target_url)
end
Given /that service is protected by Basic Authentication/ do
@handler.extend BasicAuthentication
end
Given /that service is protected by Digest Authentication/ do
@handler.extend DigestAuthentication
end
Given /that service requires the username '(.*)' with the password '(.*)'/ do |username, password|
@handler.username = username
@handler.password = password
end
# customize aruba cucumber step
Then /^the output should contain '(.*)'$/ do |expected|
assert_partial_output(expected, all_output)
end
Given /a restricted page at '(.*)'/ do |url|
steps "
Given a remote service that returns 'A response I will never see'
And that service is accessed at the path '#{url}'
And that service is protected by Basic Authentication
And that service requires the username 'something' with the password 'secret'
"
end
# This joins the server thread, and halts cucumber, so you can actually hit the
# server with a browser. Runs until you kill it with Ctrl-c
Given /I want to hit this in a browser/ do
@server.acceptor.join
end
Then /I wait for the server to recover/ do
timeout = @request_options[:timeout] || 0
sleep @server_response_time - timeout
end
httparty-0.13.5/features/steps/env.rb 0000644 0000041 0000041 00000000752 12530444726 017613 0 ustar www-data www-data require 'mongrel'
require './lib/httparty'
require 'rspec/expectations'
require 'aruba/cucumber'
def run_server(port)
@host_and_port = "0.0.0.0:#{port}"
@server = Mongrel::HttpServer.new("0.0.0.0", port)
@server.run
@request_options = {}
end
def new_port
server = TCPServer.new('0.0.0.0', nil)
port = server.addr[1]
ensure
server.close
end
Before('~@command_line') do
port = ENV["HTTPARTY_PORT"] || new_port
run_server(port)
end
After do
@server.stop if @server
end
httparty-0.13.5/features/steps/httparty_steps.rb 0000644 0000041 0000041 00000002607 12530444726 022121 0 ustar www-data www-data When /^I set my HTTParty timeout option to (\d+)$/ do |timeout|
@request_options[:timeout] = timeout.to_i
end
When /^I set my HTTParty open_timeout option to (\d+)$/ do |timeout|
@request_options[:open_timeout] = timeout.to_i
end
When /^I set my HTTParty read_timeout option to (\d+)$/ do |timeout|
@request_options[:read_timeout] = timeout.to_i
end
When /I call HTTParty#get with '(.*)'$/ do |url|
begin
@response_from_httparty = HTTParty.get("http://#{@host_and_port}#{url}", @request_options)
rescue HTTParty::RedirectionTooDeep, Timeout::Error => e
@exception_from_httparty = e
end
end
When /^I call HTTParty#head with '(.*)'$/ do |url|
begin
@response_from_httparty = HTTParty.head("http://#{@host_and_port}#{url}", @request_options)
rescue HTTParty::RedirectionTooDeep, Timeout::Error => e
@exception_from_httparty = e
end
end
When /I call HTTParty#get with '(.*)' and a basic_auth hash:/ do |url, auth_table|
h = auth_table.hashes.first
@response_from_httparty = HTTParty.get(
"http://#{@host_and_port}#{url}",
basic_auth: { username: h["username"], password: h["password"] }
)
end
When /I call HTTParty#get with '(.*)' and a digest_auth hash:/ do |url, auth_table|
h = auth_table.hashes.first
@response_from_httparty = HTTParty.get(
"http://#{@host_and_port}#{url}",
digest_auth: { username: h["username"], password: h["password"] }
)
end
httparty-0.13.5/features/command_line.feature 0000644 0000041 0000041 00000007772 12530444726 021353 0 ustar www-data www-data @command_line
Feature: Command Line
As a developer
I want to be able to harness the power of HTTParty from the command line
Because that would make quick testing and debugging easy
Scenario: Show help information
When I run `httparty --help`
Then the output should contain "-f, --format [FORMAT]"
Scenario: Make a get request
Given a remote deflate service on port '4001'
And the response from the service has a body of 'GET request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4001/fun`
Then the output should contain "GET request"
Scenario: Make a post request
Given a remote deflate service on port '4002'
And the response from the service has a body of 'POST request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4002/fun --action post --data "a=1&b=2"`
Then the output should contain "POST request"
Scenario: Make a put request
Given a remote deflate service on port '4003'
And the response from the service has a body of 'PUT request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4003/fun --action put --data "a=1&b=2"`
Then the output should contain "PUT request"
Scenario: Make a delete request
Given a remote deflate service on port '4004'
And the response from the service has a body of 'DELETE request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4004/fun --action delete`
Then the output should contain "DELETE request"
Scenario: Set a verbose mode
Given a remote deflate service on port '4005'
And the response from the service has a body of 'Some request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4005/fun --verbose`
Then the output should contain "content-length"
Scenario: Use service with basic authentication
Given a remote deflate service on port '4006'
And the response from the service has a body of 'Successfull authentication'
And that service is accessed at the path '/fun'
And that service is protected by Basic Authentication
And that service requires the username 'user' with the password 'pass'
When I run `httparty http://0.0.0.0:4006/fun --user 'user:pass'`
Then the output should contain "Successfull authentication"
Scenario: Get response in plain format
Given a remote deflate service on port '4007'
And the response from the service has a body of 'Some request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4007/fun --format plain`
Then the output should contain "Some request"
Scenario: Get response in json format
Given a remote deflate service on port '4008'
Given a remote service that returns '{ "jennings": "waylon", "cash": "johnny" }'
And that service is accessed at the path '/service.json'
And the response from the service has a Content-Type of 'application/json'
When I run `httparty http://0.0.0.0:4008/service.json --format json`
Then the output should contain '"jennings": "waylon"'
Scenario: Get response in xml format
Given a remote deflate service on port '4009'
Given a remote service that returns 'waylon jennings'
And that service is accessed at the path '/service.xml'
And the response from the service has a Content-Type of 'text/xml'
When I run `httparty http://0.0.0.0:4009/service.xml --format xml`
Then the output should contain ""
Scenario: Get response in csv format
Given a remote deflate service on port '4010'
Given a remote service that returns:
"""
"Last Name","Name"
"jennings","waylon"
"cash","johnny"
"""
And that service is accessed at the path '/service.csv'
And the response from the service has a Content-Type of 'application/csv'
When I run `httparty http://0.0.0.0:4010/service.csv --format csv`
Then the output should contain '["Last Name", "Name"]' httparty-0.13.5/features/supports_redirection.feature 0000644 0000041 0000041 00000001654 12530444726 023205 0 ustar www-data www-data Feature: Supports Redirection
As a developer
I want to work with services that may redirect me
And I want it to follow a reasonable number of redirects
Because sometimes web services do that
Scenario: A service that redirects once
Given a remote service that returns 'Service Response'
And that service is accessed at the path '/landing_service.html'
And the url '/redirector.html' redirects to '/landing_service.html'
When I call HTTParty#get with '/redirector.html'
Then the return value should match 'Service Response'
# TODO: Look in to why this actually fails...
Scenario: A service that redirects to a relative URL
Scenario: A service that redirects infinitely
Given the url '/first.html' redirects to '/second.html'
And the url '/second.html' redirects to '/first.html'
When I call HTTParty#get with '/first.html'
Then it should raise an HTTParty::RedirectionTooDeep exception
httparty-0.13.5/features/deals_with_http_error_codes.feature 0000644 0000041 0000041 00000002240 12530444726 024457 0 ustar www-data www-data Feature: Deals with HTTP error codes
As a developer
I want to be informed of non-successful responses
Because sometimes thing explode
And I should probably know what happened
Scenario: A response of '404 - Not Found'
Given a remote service that returns a 404 status code
And that service is accessed at the path '/404_service.html'
When I call HTTParty#get with '/404_service.html'
Then it should return a response with a 404 response code
Scenario: A response of '500 - Internal Server Error'
Given a remote service that returns a 500 status code
And that service is accessed at the path '/500_service.html'
When I call HTTParty#get with '/500_service.html'
Then it should return a response with a 500 response code
Scenario: A non-successful response where I need the body
Given a remote service that returns a 400 status code
And the response from the service has a body of 'Bad response'
And that service is accessed at the path '/400_service.html'
When I call HTTParty#get with '/400_service.html'
Then it should return a response with a 400 response code
And the return value should match 'Bad response'
httparty-0.13.5/features/digest_authentication.feature 0000644 0000041 0000041 00000001725 12530444726 023274 0 ustar www-data www-data Feature: Digest Authentication
As a developer
I want to be able to use a service that requires Digest Authentication
Because that is not an uncommon requirement
Scenario: Passing no credentials to a page requiring Digest Authentication
Given a restricted page at '/digest_auth.html'
When I call HTTParty#get with '/digest_auth.html'
Then it should return a response with a 401 response code
Scenario: Passing proper credentials to a page requiring Digest Authentication
Given a remote service that returns 'Digest Authenticated Page'
And that service is accessed at the path '/digest_auth.html'
And that service is protected by Digest Authentication
And that service requires the username 'jcash' with the password 'maninblack'
When I call HTTParty#get with '/digest_auth.html' and a digest_auth hash:
| username | password |
| jcash | maninblack |
Then the return value should match 'Digest Authenticated Page'
httparty-0.13.5/features/handles_multiple_formats.feature 0000644 0000041 0000041 00000004513 12530444726 024000 0 ustar www-data www-data Feature: Handles Multiple Formats
As a developer
I want to be able to consume remote services of many different formats
And I want those formats to be automatically detected and handled
Because web services take many forms
And I don't want to have to do any extra work
Scenario: An HTML service
Given a remote service that returns 'Some HTML
'
And that service is accessed at the path '/html_service.html'
And the response from the service has a Content-Type of 'text/html'
When I call HTTParty#get with '/html_service.html'
Then it should return a String
And the return value should match 'Some HTML
'
Scenario: A CSV service
Given a remote service that returns:
"""
"Last Name","Name"
"jennings","waylon"
"cash","johnny"
"""
And that service is accessed at the path '/service.csv'
And the response from the service has a Content-Type of 'application/csv'
When I call HTTParty#get with '/service.csv'
Then it should return an Array equaling:
| Last Name | Name |
| jennings | waylon |
| cash | johnny |
Scenario: A JSON service
Given a remote service that returns '{ "jennings": "waylon", "cash": "johnny" }'
And that service is accessed at the path '/service.json'
And the response from the service has a Content-Type of 'application/json'
When I call HTTParty#get with '/service.json'
Then it should return a Hash equaling:
| key | value |
| jennings | waylon |
| cash | johnny |
Scenario: An XML Service
Given a remote service that returns 'waylon jennings'
And that service is accessed at the path '/service.xml'
And the response from the service has a Content-Type of 'text/xml'
When I call HTTParty#get with '/service.xml'
Then it should return a Hash equaling:
| key | value |
| singer | waylon jennings |
Scenario: A Javascript remote file
Given a remote service that returns '$(function() { alert("hi"); });'
And that service is accessed at the path '/service.js'
And the response from the service has a Content-Type of 'application/javascript'
When I call HTTParty#get with '/service.js'
Then it should return a String
And the return value should match '$(function() { alert("hi"); });'
httparty-0.13.5/features/supports_read_timeout_option.feature 0000644 0000041 0000041 00000001200 12530444726 024732 0 ustar www-data www-data Feature: Supports the read timeout option
In order to handle inappropriately slow response times
As a developer
I want my request to raise an exception after my specified read_timeout as elapsed
Scenario: A long running response
Given a remote service that returns 'Some HTML
'
And that service is accessed at the path '/long_running_service.html'
And that service takes 2 seconds to generate a response
When I set my HTTParty read_timeout option to 1
And I call HTTParty#get with '/long_running_service.html'
Then it should raise a Timeout::Error exception
And I wait for the server to recover
httparty-0.13.5/MIT-LICENSE 0000644 0000041 0000041 00000002041 12530444726 015147 0 ustar www-data www-data Copyright (c) 2008 John Nunemaker
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. httparty-0.13.5/spec/ 0000755 0000041 0000041 00000000000 12530444726 014450 5 ustar www-data www-data httparty-0.13.5/spec/spec_helper.rb 0000644 0000041 0000041 00000002333 12530444726 017267 0 ustar www-data www-data require "simplecov"
SimpleCov.start
require "httparty"
require "fakeweb"
def file_fixture(filename)
open(File.join(File.dirname(__FILE__), 'fixtures', "#{filename}")).read
end
Dir[File.expand_path(File.join(File.dirname(__FILE__), 'support', '**', '*.rb'))].each {|f| require f}
RSpec.configure do |config|
config.include HTTParty::StubResponse
config.include HTTParty::SSLTestHelper
config.before(:suite) do
FakeWeb.allow_net_connect = false
end
config.after(:suite) do
FakeWeb.allow_net_connect = true
end
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = false
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
config.warnings = true
if config.files_to_run.one?
config.default_formatter = 'doc'
end
config.profile_examples = 10
config.order = :random
Kernel.srand config.seed
end
RSpec::Matchers.define :use_ssl do
match(&:use_ssl?)
end
RSpec::Matchers.define :use_cert_store do |cert_store|
match do |connection|
connection.cert_store == cert_store
end
end
httparty-0.13.5/spec/fixtures/ 0000755 0000041 0000041 00000000000 12530444726 016321 5 ustar www-data www-data httparty-0.13.5/spec/fixtures/google.html 0000644 0000041 0000041 00000013354 12530444726 020471 0 ustar www-data www-data Google

Advertising Programs - Business Solutions - About Google©2008 - Privacy