SlideShare a Scribd company logo
Fake my Party
      Tanja Otto

     24.11.2009
  Düsseldorf on Rails
SalesLentz::DevTeam
Über mich
• internes Entwicklerteam von Sales-Lentz
• IBEs für Reisen, Bustickets, Eventtickets
• seit 2006 entwickeln wir mit Ruby on Rails
• Mit Hussein Morsy Buch Ruby on Rails 2
  Galileo Press
  http://www.railsbuch.de
  http://twitter.com/ajnato
  http://devteam.sales-lentz.lu
HTTParty

• einfaches senden von HTTP-Anfragen
• JSON und XML werden automatisch in
  Ruby-Hashes umgewandelt
• http://github.com/jnunemaker/httparty
HTTParty

XML

         HTTParty   HASH

JSON
Installation


sudo gem install httparty
Ein erstes Beispiel
require "rubygems"
require "httparty"

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')

#   puts   response.body
#   puts   response.code # => 200
#   puts   response.message # => OK
#   puts   response.headers.inspect

response.each do |item|
  puts item['user']['screen_name']
end

#   =>   alexmedeiros59
#   =>   EmySayers
#   =>   ciquuuee
#   =>   bray1972
#   =>   shasoGORGEOUS
#   =>   kimix
Beispiel Twitter-API
class Twitter
  include HTTParty
  base_uri 'twitter.com'

  def initialize(u, p)
    @auth = {:username => u, :password => p}
  end

  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(USERNAME, PASSWORD)
pp twitter.timeline.map{|t| t['user']['name']}
weitere Beispiele

• http://github.com/jnunemaker/httparty/tree/
  master/examples
FakeWeb
• Helper, um HTTP-Anfragen zu stubben
• Testumgebungen von live-Anfragen
  entkoppeln
• Tests sind auch lauffähig, wenn keine
  Netzwerkverbindung besteht
• arbeitet mit allen Libraries die auf
  Net::HTTP basieren
• http://github.com/chrisk/fakeweb/
Installation


sudo gem install fakeweb
Mit einfacher
     Zeichenkette antworten
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json", :body => "Hello World!")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# => Hello World!

response = HTTParty.get('http://search.twitter.com/trends.json')
puts response.body
# es wird die Antwort der echten Anfrage zurückgeliefert
Einer Antwort einen
             Status hinzufügen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json",
                     :body => "Nothing found",
                     :status => ["404", "Not Found"])

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.code # => "404"
puts response.message # => "Not Found"
puts response.body # => "Nothing found"
Auf jede HTTP
            Methode antworten
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:any, "http://twitter.com/statuses/
public_timeline.json", :body => "response for any HTTP method")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# => response for any HTTP method

response = HTTParty.post('http://twitter.com/statuses/public_timeline.json')
puts response.body
# response for any HTTP method
Wiederholende Anfragen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/public_timeline.json",
                     [{:body => "Public Timeline", :status => ["200", "OK"]},
                      {:body => "Timeline not found", :status => ["404", "Not
Found"]}])

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Public Timeline
puts response.code # => 200
puts response.message # => OK

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Timeline not found
puts response.code # => 404
puts response.message # => Not Found

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Timeline not found
puts response.code # => 404
puts response.message # => Not Found
Wiederholende Anfragen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json",
                     [{:body => "Public Timeline", :status => ["200",
"OK"], :times => 2},
                       {:body => "Timeline not found", :status => ["404",
"Not Found"]}])

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Public Timeline

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Public Timeline

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Timeline not found
HTTP Authentifizierung
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://example.com/secret", :body =>
"Unauthorized", :status => ["401", "Unauthorized"])
FakeWeb.register_uri(:get, "http://user:pwd@example.com/secret", :body =>
"Authorized")

response = HTTParty.get('http://example.com/secret')
puts response.body # => Unauthorized

response = HTTParty.get('http://example.com/secret', :basic_auth => {:username
=> "user", :password => "pwd"})
puts response.body # => Authorized
Alle registrierten URIs
               löschen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json", :body => "Hello World!")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# => Hello World!

FakeWeb.clean_registry

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# es wird die Antwort der echten Anfrage zurückgeliefert
Alle live Anfragen
                   blockieren
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.allow_net_connect = false

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
# => raises FakeWeb::NetConnectNotAllowedError


require "rubygems"
require "fakeweb"
require "httparty"

# default
FakeWeb.allow_net_connect = true

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
# live Anfrage wird gesendet
automatisches einlesen
            einer Datei
<?xml version="1.0" encoding="UTF-8"?>
<countries>
  <country>Belgien</country>
  <country>Deutschland</country>
  <country>Luxembourg</country>
</countries>


require "rubygems"
require "httparty"
require "fakeweb"

FakeWeb.register_uri(:get, "http://example.com/countries.xml", :body =>
'fixtures/countries.xml', :content_type => "text/xml")

response = HTTParty.get('http://example.com/countries.xml')
puts response.inspect
# => {"countries"=>{"country"=>["Belgien", "Deutschland", "Luxembourg"]}}
HTTP response
             headers definieren
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json",
                     :body => "Hello World!",
                     :content_type => "text/plain")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Hello World!
puts response.headers.inspect # => {"content-type"=>["text/plain"]}

More Related Content

What's hot

A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops
deepfountainconsulting
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
PiXeL16
 
The report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyThe report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyYasuharu Nakano
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
Andy McKay
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
Peter Friese
 
Fun with Python
Fun with PythonFun with Python
Fun with Python
Narong Intiruk
 
Pydata-Python tools for webscraping
Pydata-Python tools for webscrapingPydata-Python tools for webscraping
Pydata-Python tools for webscraping
Jose Manuel Ortega Candel
 
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
Codemotion
 
Apache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestApache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestMyles Braithwaite
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
Steve Rhoades
 
KCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with SailsKCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with Sails
Justin James
 
Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
Workhorse Computing
 
Keep it simple web development stack
Keep it simple web development stackKeep it simple web development stack
Keep it simple web development stack
Eric Ahn
 
Web Scraping with Python
Web Scraping with PythonWeb Scraping with Python
Web Scraping with Python
Paul Schreiber
 
JavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the PlatformJavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the PlatformRobert Nyman
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
emptysquare
 
Desafios do Profissionalismo Ágil
Desafios do Profissionalismo ÁgilDesafios do Profissionalismo Ágil
Desafios do Profissionalismo Ágil
Victor Hugo Germano
 
Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014
Bruno Rocha
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeLogstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtime
Andrea Cardinale
 
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
Anton
 

What's hot (20)

A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
 
The report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyThe report of JavaOne2011 about groovy
The report of JavaOne2011 about groovy
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Fun with Python
Fun with PythonFun with Python
Fun with Python
 
Pydata-Python tools for webscraping
Pydata-Python tools for webscrapingPydata-Python tools for webscraping
Pydata-Python tools for webscraping
 
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
 
Apache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestApache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux Fest
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
 
KCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with SailsKCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with Sails
 
Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
 
Keep it simple web development stack
Keep it simple web development stackKeep it simple web development stack
Keep it simple web development stack
 
Web Scraping with Python
Web Scraping with PythonWeb Scraping with Python
Web Scraping with Python
 
JavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the PlatformJavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the Platform
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Desafios do Profissionalismo Ágil
Desafios do Profissionalismo ÁgilDesafios do Profissionalismo Ágil
Desafios do Profissionalismo Ágil
 
Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeLogstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtime
 
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
 

Similar to Fake My Party

Let's read code: python-requests library
Let's read code: python-requests libraryLet's read code: python-requests library
Let's read code: python-requests library
Susan Tan
 
Palestra VCR
Palestra VCRPalestra VCR
Palestra VCR
Cássio Marques
 
Let's read code: the python-requests library
Let's read code: the python-requests libraryLet's read code: the python-requests library
Let's read code: the python-requests library
Susan Tan
 
Api
ApiApi
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
Bareen Shaikh
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
JSON and the APInauts
JSON and the APInautsJSON and the APInauts
JSON and the APInauts
Wynn Netherland
 
Get Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsGet Real: Adventures in realtime web apps
Get Real: Adventures in realtime web apps
daviddemello
 
REST meets Semantic Web
REST meets Semantic WebREST meets Semantic Web
REST meets Semantic Web
Steve Speicher
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
Alona Mekhovova
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기
Jinho Jung
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
King Foo
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
Michelangelo van Dam
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTim Cull
 
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
andrewsmatt
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
Yusuke Wada
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
Paweł Kowalczuk
 
Spiffy Applications With JavaScript
Spiffy Applications With JavaScriptSpiffy Applications With JavaScript
Spiffy Applications With JavaScript
Mark Casias
 

Similar to Fake My Party (20)

Let's read code: python-requests library
Let's read code: python-requests libraryLet's read code: python-requests library
Let's read code: python-requests library
 
Palestra VCR
Palestra VCRPalestra VCR
Palestra VCR
 
Let's read code: the python-requests library
Let's read code: the python-requests libraryLet's read code: the python-requests library
Let's read code: the python-requests library
 
Api
ApiApi
Api
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
JSON and the APInauts
JSON and the APInautsJSON and the APInauts
JSON and the APInauts
 
Get Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsGet Real: Adventures in realtime web apps
Get Real: Adventures in realtime web apps
 
REST meets Semantic Web
REST meets Semantic WebREST meets Semantic Web
REST meets Semantic Web
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
 
YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
 
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Spiffy Applications With JavaScript
Spiffy Applications With JavaScriptSpiffy Applications With JavaScript
Spiffy Applications With JavaScript
 

Recently uploaded

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 

Recently uploaded (20)

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 

Fake My Party

  • 1. Fake my Party Tanja Otto 24.11.2009 Düsseldorf on Rails
  • 3. Über mich • internes Entwicklerteam von Sales-Lentz • IBEs für Reisen, Bustickets, Eventtickets • seit 2006 entwickeln wir mit Ruby on Rails • Mit Hussein Morsy Buch Ruby on Rails 2 Galileo Press http://www.railsbuch.de http://twitter.com/ajnato http://devteam.sales-lentz.lu
  • 4. HTTParty • einfaches senden von HTTP-Anfragen • JSON und XML werden automatisch in Ruby-Hashes umgewandelt • http://github.com/jnunemaker/httparty
  • 5. HTTParty XML HTTParty HASH JSON
  • 7. Ein erstes Beispiel require "rubygems" require "httparty" response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') # puts response.body # puts response.code # => 200 # puts response.message # => OK # puts response.headers.inspect response.each do |item| puts item['user']['screen_name'] end # => alexmedeiros59 # => EmySayers # => ciquuuee # => bray1972 # => shasoGORGEOUS # => kimix
  • 8. Beispiel Twitter-API class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {:username => u, :password => p} end 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(USERNAME, PASSWORD) pp twitter.timeline.map{|t| t['user']['name']}
  • 10. FakeWeb • Helper, um HTTP-Anfragen zu stubben • Testumgebungen von live-Anfragen entkoppeln • Tests sind auch lauffähig, wenn keine Netzwerkverbindung besteht • arbeitet mit allen Libraries die auf Net::HTTP basieren • http://github.com/chrisk/fakeweb/
  • 12. Mit einfacher Zeichenkette antworten require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Hello World!") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Hello World! response = HTTParty.get('http://search.twitter.com/trends.json') puts response.body # es wird die Antwort der echten Anfrage zurückgeliefert
  • 13. Einer Antwort einen Status hinzufügen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Nothing found", :status => ["404", "Not Found"]) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.code # => "404" puts response.message # => "Not Found" puts response.body # => "Nothing found"
  • 14. Auf jede HTTP Methode antworten require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:any, "http://twitter.com/statuses/ public_timeline.json", :body => "response for any HTTP method") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => response for any HTTP method response = HTTParty.post('http://twitter.com/statuses/public_timeline.json') puts response.body # response for any HTTP method
  • 15. Wiederholende Anfragen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/public_timeline.json", [{:body => "Public Timeline", :status => ["200", "OK"]}, {:body => "Timeline not found", :status => ["404", "Not Found"]}]) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Public Timeline puts response.code # => 200 puts response.message # => OK response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Timeline not found puts response.code # => 404 puts response.message # => Not Found response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Timeline not found puts response.code # => 404 puts response.message # => Not Found
  • 16. Wiederholende Anfragen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", [{:body => "Public Timeline", :status => ["200", "OK"], :times => 2}, {:body => "Timeline not found", :status => ["404", "Not Found"]}]) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Public Timeline response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Public Timeline response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Timeline not found
  • 17. HTTP Authentifizierung require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://example.com/secret", :body => "Unauthorized", :status => ["401", "Unauthorized"]) FakeWeb.register_uri(:get, "http://user:pwd@example.com/secret", :body => "Authorized") response = HTTParty.get('http://example.com/secret') puts response.body # => Unauthorized response = HTTParty.get('http://example.com/secret', :basic_auth => {:username => "user", :password => "pwd"}) puts response.body # => Authorized
  • 18. Alle registrierten URIs löschen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Hello World!") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Hello World! FakeWeb.clean_registry response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # es wird die Antwort der echten Anfrage zurückgeliefert
  • 19. Alle live Anfragen blockieren require "rubygems" require "fakeweb" require "httparty" FakeWeb.allow_net_connect = false response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') # => raises FakeWeb::NetConnectNotAllowedError require "rubygems" require "fakeweb" require "httparty" # default FakeWeb.allow_net_connect = true response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') # live Anfrage wird gesendet
  • 20. automatisches einlesen einer Datei <?xml version="1.0" encoding="UTF-8"?> <countries> <country>Belgien</country> <country>Deutschland</country> <country>Luxembourg</country> </countries> require "rubygems" require "httparty" require "fakeweb" FakeWeb.register_uri(:get, "http://example.com/countries.xml", :body => 'fixtures/countries.xml', :content_type => "text/xml") response = HTTParty.get('http://example.com/countries.xml') puts response.inspect # => {"countries"=>{"country"=>["Belgien", "Deutschland", "Luxembourg"]}}
  • 21. HTTP response headers definieren require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Hello World!", :content_type => "text/plain") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Hello World! puts response.headers.inspect # => {"content-type"=>["text/plain"]}