SlideShare a Scribd company logo
1 of 48
Download to read offline
Python tools for testing web
services over HTTP
Mykhailo Kolesnyk, back-end developer at Divio AG.
Agenda
area of interest
libraries
CLI tools
involving non-developers
Intro
– What are we interested in?
Intro
– What are we interested in?
– Anything that looks like an service, can fail
under certain conditions and speaks HTTP.
Intro
– What are we interested in?
– Anything that looks like an service, can fail
under certain conditions and speaks HTTP.
web service REST API
document-oriented database
sepecialised search engine interface
remote storage interface
maybe even your fridge? RTFM!
Standing on the shoulders of
the giants
Low-level protocols implement most of the
complexity involved in networking operations
if we operate on HTTP (application) level.
Communication flow in HTTP is really
straightforward and easy to understand, test
and debug.
HTTP is fairly simple
HTTP is fairly simple
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: xkcd.com
User-Agent: HTTPie/0.9.2
HTTP/1.1 200 OK
Accept-Ranges: bytes
Age: 56
Cache-Control: public, max-age=300
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 2762
Content-Type: text/html; charset=utf-8
Date: Wed, 11 Nov 2015 22:01:41 GMT
ETag: "4112135422"
Expires: Wed, 11 Nov 2015 05:05:40 GMT
Last-Modified: Wed, 11 Nov 2015 05:00:05 GMT
Server: lighttpd/1.4.28
Vary: Accept-Encoding
HTTP librar(y/ies) in Python
So, there must be some good Python library to
work with this stuff, right?
There should be one – and preferably only one
– obvious way to do it.
HTTP librar(y/ies) in Python
So, there must be some good Python library to
work with this stuff, right?
There should be one – and preferably only one
– obvious way to do it.
httplib (http.client in Python3)
HTTP librar(y/ies) in Python
So, there must be some good Python library to
work with this stuff, right?
There should be one – and preferably only one
– obvious way to do it.
httplib (http.client in Python3)
httplib2
HTTP librar(y/ies) in Python
So, there must be some good Python library to
work with this stuff, right?
There should be one – and preferably only one
– obvious way to do it.
httplib (http.client in Python3)
httplib2
urllib2
HTTP librar(y/ies) in Python
So, there must be some good Python library to
work with this stuff, right?
There should be one – and preferably only one
– obvious way to do it.
httplib (http.client in Python3)
httplib2
urllib2
urllib3
HTTP librar(y/ies) in Python
So, there must be some good Python library to
work with this stuff, right?
There should be one – and preferably only one
– obvious way to do it.
httplib (http.client in Python3)
httplib2
urllib2
urllib3
requests!
requests + purl + jpath = <3
Lots of utilities are being written on top of
requests these days.
Tools like furl/purl/jpath make parsing and
manipulating data way easier.
Before coding often comes
debugging
Debugging and exploring
external/blackboxed/undocumented HTTP service
might be unavoidable.
CLI tools can be of some use during
testing/debugging.
auth (penetration) testing
edge cases (payload size, wrong encoding)
Required knowledge
Minimal requrements:
HTTP basics
Cookies/sessions
Auth types
POST payload formats
UNIX shell
pipes
I/O redirection
JSON
HTTPie: a CLI, cURL-like tool
for humans
Written in Python, modular, based on
requests -> easy to extend!
And here are some basic examples...
HTTPie
Configurable output
HTTPie
Basic auth
$ http -a user1:password1 example.org
HTTPie
Session
Refer to the session by its name, and the
previously used headers will automatically be
set:
$ http --session=session1 example.org
$ http -a user1:password1 --session=session1 example.org X-Foo:Bar
HTTPie
JSON
$ http PUT api.example.com/person/1 
name=John 
age:=29 married:=false
hobbies:='["http", "pies"]'  # Raw JSON
description=@about-john.txt  # Embed text file
bookmarks:=@bookmarks.json # Embed JSON file
HTTPie
Enter multiline data
$ cat | http POST example.com/todos Content-Type:text/plain
- buy milk
- call parents
^D
HTTPie
Check response status and override
timeout
#!/bin/bash
if http --check-status --timeout=1.5 HEAD example.com/health-check &> /dev/null
echo 'OK!'
else
case $? in
2) echo 'Request timed out!' ;;
3) echo 'Unexpected HTTP 3xx Redirection!' ;;
4) echo 'HTTP 4xx Client Error!' ;;
5) echo 'HTTP 5xx Server Error!' ;;
*) echo 'Other Error!' ;;
esac
fi
HTTPie
Streamed response
Send each new tweet (JSON object)
mentioning "Apple" to another server as soon
as it arrives from the Twitter streaming API.
$ http --stream -f -a TWITTER-NAME 
https://stream.twitter.com/1/statuses/filter.json track=Apple 
| while read tweet; do echo "$tweet" | http POST example.org/tweets ;
Responsibility
– Who has to write integration (or system)
tests for an API?
Responsibility
– Who has to write integration (or system)
tests for an API?
– Maybe, the developer himself?
He'll be more capable fixing his own stuff, for
example.
Involving others
What if testing requires more resources than
you can afford?
Сonsumer of your API migth need precise and
up-to date docs sooner than you'll be able to
deliver them.
Involving others
What if testing requires more resources than
you can afford?
Сonsumer of your API migth need precise and
up-to date docs sooner than you'll be able to
deliver them.
– Rewrite everything in Haskel. Broader your
audience and give this people tools they can
use. Simple tools.
Behaviour Driven
Development
What if we start writing exact specifications
according to real-world requirements?
What if we reuse those specs to be our test cases
that run automatically?
BDD definition usually includes two or three of
the following buzz-words:
TDD
ATDD
DDD
OOAD
Take parts of BDD toolkit
and use them in weird way
BDD here looks like a replacement or a good
addition to the integration tests.
But it still allows you to go through the very
natural cycle:
you define behaviour
behaviour defines tests
tests define development direction
requirements_tester.txt
requirements_tester.txt
{"JSON": "JavaScript Object
Notation"}
requirements_tester.txt
{"JSON": "JavaScript Object
Notation"}
requirements_tester.txt
{"JSON": "JavaScript Object
Notation"}
Gherkin language - a business readable, DSL
that allows to describe software behaviour
without diving into implementation details.
Yet another API accessible
through HTTP
Let's imagine we are building some API.
And we are minimalists - so want it to use BasicAuth.
And we are purists - so we want proper HTTP status
codes, content headers, etc.
How can the authentication test look like?
Authentication test example
in Gherkin
yet_another_api.feature
Feature: Yet another API
As an API client
I want to be able to do some really useful fluffy awesome colorful stuff
Background: Set server name, and auth headers
Given I am using server "$SERVER"
And I set base URL to "$URL"
And I set "Accept" header to "application/json"
And I set "Content-Type" header to "application/json"
And I set BasicAuth username to "user@example.com" and password to "password
Scenario: Ensure account exists
When I make a GET request to "account"
Then the response status should be 200
Behave
Behaviour-driven development, Python style.
Steps implementation
examples
@behave.given('I set BasicAuth username to "{username}" and password to "{passw
@dereference_step_parameters_and_data
def set_basic_auth_headers(context, username, password):
context.auth = (username, password)
@behave.when('I make a GET request to "{url_path_segment}"')
@dereference_step_parameters_and_data
def get_request(context, url_path_segment):
url = append_path(context.server, url_path_segment)
context.response = requests.get(
url, headers=context.headers, auth=context.auth)
@behave.then('the response status should be one of "{statuses}"')
@dereference_step_parameters_and_data
def response_status_in(context, statuses):
ensure(context.response.status_code).is_in(
[int(s) for s in statuses.split(',')])
Your custom behave module
code layout
yourproject/
behave/
yet_another_api.feature # the only file for humans, everything else is
__init__.py
environment.py # setup, helpers
steps/
__init__.py # steps implementation
environment.py
from behave_http.environment import before_scenario
APP_ROOT = os.path.normpath(
os.path.abspath(os.path.join(os.path.dirname(__file__), '..'
parse_config_file(os.path.join(APP_ROOT, "settings.py"))
default_env = {
'SERVER': 'http://localhost:8081',
'API': 'api',
[...]
}
credentials = {
'password': 'featuretester',
'email': 'featuretester@example.com'
}
def _recreate_account(db, auth, params , [...]):
[...]
environment.py (continued)
def before_all(context):
for k,v in default_env.iteritems():
os.environ.setdefault(k, v)
app_url = URL(os.environ['SERVER'])
api_url = app_url.add_path_segment(os.environ['API'])
api_auth = (credentials['email'], credentials['password'])
# DB connection setup goes here
_recreate_account(db, auth, params , ...)
_add_account_data(api_url, api_auth)
def after_tag(context, tag):
"""Clean up database after destructive operation"""
if tag == 'modifies':
before_all(context)
Example tag usage
[...]
@modifies
Scenario: Delete account, ensure it does not exist
When I make a DELETE request to "account"
Then the response status should be 200
When I make a GET request to "account"
Then the response status should be 401
@wip
Scenario: Create account
[...]
Running tests
# behave -q -f progress3
HTTP requests # features/http.feature
Test getting context variable ......
Test GET request ......
Test POST request by checking we get the same JSON payload back .......
Test JSON path expection .......
Test JSON array length calculation .......
[...]
Test GET polling with checking for value that eventually succeeds ......
Test Basic Auth .......
1 feature passed, 0 failed, 0 skipped
17 scenarios passed, 0 failed, 0 skipped
121 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.516s
Failing tests
[...]
Test JSON array length calculation ......F
--------------------------------------------------------------------------------
FAILURE in step 'the JSON array length at path "array" should be 3'
(features/http.feature:55):
Assertion Failed: Expected [1, 2, 3, 4] to have length 3
--------------------------------------------------------------------------------
[...]
Failing scenarios:
features/http.feature:49 Test JSON array length calculation
0 features passed, 1 failed, 0 skipped
16 scenarios passed, 1 failed, 0 skipped
120 steps passed, 1 failed, 0 skipped, 0 undefined
Took 0m0.313s
Behave-HTTP
Implements basic reusable Behave steps for
testing HTTP services
Tools
Libraries and utilities
requests
purl, furl
jpath
HTTPie
Behave
Behave-HTTP
Resources
Specs
HTTP 1.1
Gherkin
Videos
"Cutting Off the Internet: Testing Applications that
Use Requests", Ian Cordasco
"Doing BDD with Python and PyCharm", Ilya
Kazakevich

More Related Content

What's hot

Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonHoang Nguyen
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroChristopher Pecoraro
 
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREYBUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREYCodeCore
 
An Introduction to Solr
An Introduction to SolrAn Introduction to Solr
An Introduction to Solrtomhill
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90minsLarry Cai
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flaskJeetendra singh
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversBrian Gesiak
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyAlessandro Cucci
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Cusomizing Burp Suite - Getting the Most out of Burp Extensions
Cusomizing Burp Suite - Getting the Most out of Burp ExtensionsCusomizing Burp Suite - Getting the Most out of Burp Extensions
Cusomizing Burp Suite - Getting the Most out of Burp ExtensionsAugust Detlefsen
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoIlian Iliev
 
Automation - fabric, django and more
Automation - fabric, django and moreAutomation - fabric, django and more
Automation - fabric, django and moreIlian Iliev
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2Graham Dumpleton
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Andres Almiray
 
Burp plugin development for java n00bs (44 con)
Burp plugin development for java n00bs (44 con)Burp plugin development for java n00bs (44 con)
Burp plugin development for java n00bs (44 con)Marc Wickenden
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparisonHiroshi Nakamura
 

What's hot (20)

Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
 
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREYBUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
 
An Introduction to Solr
An Introduction to SolrAn Introduction to Solr
An Introduction to Solr
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Cusomizing Burp Suite - Getting the Most out of Burp Extensions
Cusomizing Burp Suite - Getting the Most out of Burp ExtensionsCusomizing Burp Suite - Getting the Most out of Burp Extensions
Cusomizing Burp Suite - Getting the Most out of Burp Extensions
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Automation - fabric, django and more
Automation - fabric, django and moreAutomation - fabric, django and more
Automation - fabric, django and more
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
 
Burp plugin development for java n00bs (44 con)
Burp plugin development for java n00bs (44 con)Burp plugin development for java n00bs (44 con)
Burp plugin development for java n00bs (44 con)
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 

Viewers also liked

Building Automated REST APIs with Python
Building Automated REST APIs with PythonBuilding Automated REST APIs with Python
Building Automated REST APIs with PythonJeff Knupp
 
Python web frameworks
Python web frameworksPython web frameworks
Python web frameworksNEWLUG
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBDeveloping RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBNicola Iarocci
 
Django Performance Recipes
Django Performance RecipesDjango Performance Recipes
Django Performance RecipesJon Atkinson
 
Denoising auto encoders(d a)
Denoising auto encoders(d a)Denoising auto encoders(d a)
Denoising auto encoders(d a)Tae Young Lee
 
Python Network Programming
Python Network ProgrammingPython Network Programming
Python Network ProgrammingTae Young Lee
 
Network Security and Analysis with Python
Network Security and Analysis with PythonNetwork Security and Analysis with Python
Network Security and Analysis with Pythonpycontw
 
Cloud Architecture: Patterns and Best Practices
Cloud Architecture: Patterns and Best PracticesCloud Architecture: Patterns and Best Practices
Cloud Architecture: Patterns and Best PracticesSascha Möllering
 
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...Odoo
 
Why vREST?
Why vREST?Why vREST?
Why vREST?vrest_io
 
ethical hacking in the modern times
ethical hacking in the modern timesethical hacking in the modern times
ethical hacking in the modern timesjeshin jose
 
Network ppt
Network pptNetwork ppt
Network ppthlalu861
 
Hacking & its types
Hacking & its typesHacking & its types
Hacking & its typesSai Sakoji
 

Viewers also liked (16)

Building Automated REST APIs with Python
Building Automated REST APIs with PythonBuilding Automated REST APIs with Python
Building Automated REST APIs with Python
 
Python web frameworks
Python web frameworksPython web frameworks
Python web frameworks
 
Flask vs. Django
Flask vs. DjangoFlask vs. Django
Flask vs. Django
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBDeveloping RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDB
 
Django Performance Recipes
Django Performance RecipesDjango Performance Recipes
Django Performance Recipes
 
Integration Testing in Python
Integration Testing in PythonIntegration Testing in Python
Integration Testing in Python
 
Denoising auto encoders(d a)
Denoising auto encoders(d a)Denoising auto encoders(d a)
Denoising auto encoders(d a)
 
Python Network Programming
Python Network ProgrammingPython Network Programming
Python Network Programming
 
Network Security and Analysis with Python
Network Security and Analysis with PythonNetwork Security and Analysis with Python
Network Security and Analysis with Python
 
Cloud Architecture: Patterns and Best Practices
Cloud Architecture: Patterns and Best PracticesCloud Architecture: Patterns and Best Practices
Cloud Architecture: Patterns and Best Practices
 
Rest api with Python
Rest api with PythonRest api with Python
Rest api with Python
 
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
 
Why vREST?
Why vREST?Why vREST?
Why vREST?
 
ethical hacking in the modern times
ethical hacking in the modern timesethical hacking in the modern times
ethical hacking in the modern times
 
Network ppt
Network pptNetwork ppt
Network ppt
 
Hacking & its types
Hacking & its typesHacking & its types
Hacking & its types
 

Similar to Python tools for testing web services over HTTP

12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocratJonathan Linowes
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesciklum_ods
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developersPatrick Savalle
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Pythongturnquist
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocratlinoj
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Tim Burks
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swiftTim Burks
 
web2py:Web development like a boss
web2py:Web development like a bossweb2py:Web development like a boss
web2py:Web development like a bossFrancisco Ribeiro
 
REST in ( a mobile ) peace @ WHYMCA 05-21-2011
REST in ( a mobile ) peace @ WHYMCA 05-21-2011REST in ( a mobile ) peace @ WHYMCA 05-21-2011
REST in ( a mobile ) peace @ WHYMCA 05-21-2011Alessandro Nadalin
 
支撐英雄聯盟戰績網的那條巨蟒
支撐英雄聯盟戰績網的那條巨蟒支撐英雄聯盟戰績網的那條巨蟒
支撐英雄聯盟戰績網的那條巨蟒Toki Kanno
 

Similar to Python tools for testing web services over HTTP (20)

12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devices
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)
 
Talking to Web Services
Talking to Web ServicesTalking to Web Services
Talking to Web Services
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swift
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 
web2py:Web development like a boss
web2py:Web development like a bossweb2py:Web development like a boss
web2py:Web development like a boss
 
REST in ( a mobile ) peace @ WHYMCA 05-21-2011
REST in ( a mobile ) peace @ WHYMCA 05-21-2011REST in ( a mobile ) peace @ WHYMCA 05-21-2011
REST in ( a mobile ) peace @ WHYMCA 05-21-2011
 
Introduction to python scrapping
Introduction to python scrappingIntroduction to python scrapping
Introduction to python scrapping
 
支撐英雄聯盟戰績網的那條巨蟒
支撐英雄聯盟戰績網的那條巨蟒支撐英雄聯盟戰績網的那條巨蟒
支撐英雄聯盟戰績網的那條巨蟒
 
Cqrs api v2
Cqrs api v2Cqrs api v2
Cqrs api v2
 

Recently uploaded

办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleanscorenetworkseo
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书rnrncn29
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 

Recently uploaded (20)

办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleans
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 

Python tools for testing web services over HTTP

  • 1. Python tools for testing web services over HTTP Mykhailo Kolesnyk, back-end developer at Divio AG.
  • 2. Agenda area of interest libraries CLI tools involving non-developers
  • 3. Intro – What are we interested in?
  • 4. Intro – What are we interested in? – Anything that looks like an service, can fail under certain conditions and speaks HTTP.
  • 5. Intro – What are we interested in? – Anything that looks like an service, can fail under certain conditions and speaks HTTP. web service REST API document-oriented database sepecialised search engine interface remote storage interface maybe even your fridge? RTFM!
  • 6. Standing on the shoulders of the giants Low-level protocols implement most of the complexity involved in networking operations if we operate on HTTP (application) level. Communication flow in HTTP is really straightforward and easy to understand, test and debug.
  • 7. HTTP is fairly simple
  • 8. HTTP is fairly simple GET / HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate Connection: keep-alive Host: xkcd.com User-Agent: HTTPie/0.9.2 HTTP/1.1 200 OK Accept-Ranges: bytes Age: 56 Cache-Control: public, max-age=300 Connection: keep-alive Content-Encoding: gzip Content-Length: 2762 Content-Type: text/html; charset=utf-8 Date: Wed, 11 Nov 2015 22:01:41 GMT ETag: "4112135422" Expires: Wed, 11 Nov 2015 05:05:40 GMT Last-Modified: Wed, 11 Nov 2015 05:00:05 GMT Server: lighttpd/1.4.28
  • 9. Vary: Accept-Encoding HTTP librar(y/ies) in Python So, there must be some good Python library to work with this stuff, right? There should be one – and preferably only one – obvious way to do it.
  • 10. HTTP librar(y/ies) in Python So, there must be some good Python library to work with this stuff, right? There should be one – and preferably only one – obvious way to do it. httplib (http.client in Python3)
  • 11. HTTP librar(y/ies) in Python So, there must be some good Python library to work with this stuff, right? There should be one – and preferably only one – obvious way to do it. httplib (http.client in Python3) httplib2
  • 12. HTTP librar(y/ies) in Python So, there must be some good Python library to work with this stuff, right? There should be one – and preferably only one – obvious way to do it. httplib (http.client in Python3) httplib2 urllib2
  • 13. HTTP librar(y/ies) in Python So, there must be some good Python library to work with this stuff, right? There should be one – and preferably only one – obvious way to do it. httplib (http.client in Python3) httplib2 urllib2 urllib3
  • 14. HTTP librar(y/ies) in Python So, there must be some good Python library to work with this stuff, right? There should be one – and preferably only one – obvious way to do it. httplib (http.client in Python3) httplib2 urllib2 urllib3 requests!
  • 15. requests + purl + jpath = <3 Lots of utilities are being written on top of requests these days. Tools like furl/purl/jpath make parsing and manipulating data way easier.
  • 16. Before coding often comes debugging Debugging and exploring external/blackboxed/undocumented HTTP service might be unavoidable. CLI tools can be of some use during testing/debugging. auth (penetration) testing edge cases (payload size, wrong encoding)
  • 17. Required knowledge Minimal requrements: HTTP basics Cookies/sessions Auth types POST payload formats UNIX shell pipes I/O redirection JSON
  • 18. HTTPie: a CLI, cURL-like tool for humans Written in Python, modular, based on requests -> easy to extend! And here are some basic examples...
  • 20. HTTPie Basic auth $ http -a user1:password1 example.org
  • 21. HTTPie Session Refer to the session by its name, and the previously used headers will automatically be set: $ http --session=session1 example.org $ http -a user1:password1 --session=session1 example.org X-Foo:Bar
  • 22. HTTPie JSON $ http PUT api.example.com/person/1 name=John age:=29 married:=false hobbies:='["http", "pies"]' # Raw JSON description=@about-john.txt # Embed text file bookmarks:=@bookmarks.json # Embed JSON file
  • 23. HTTPie Enter multiline data $ cat | http POST example.com/todos Content-Type:text/plain - buy milk - call parents ^D
  • 24. HTTPie Check response status and override timeout #!/bin/bash if http --check-status --timeout=1.5 HEAD example.com/health-check &> /dev/null echo 'OK!' else case $? in 2) echo 'Request timed out!' ;; 3) echo 'Unexpected HTTP 3xx Redirection!' ;; 4) echo 'HTTP 4xx Client Error!' ;; 5) echo 'HTTP 5xx Server Error!' ;; *) echo 'Other Error!' ;; esac fi
  • 25. HTTPie Streamed response Send each new tweet (JSON object) mentioning "Apple" to another server as soon as it arrives from the Twitter streaming API. $ http --stream -f -a TWITTER-NAME https://stream.twitter.com/1/statuses/filter.json track=Apple | while read tweet; do echo "$tweet" | http POST example.org/tweets ;
  • 26. Responsibility – Who has to write integration (or system) tests for an API?
  • 27. Responsibility – Who has to write integration (or system) tests for an API? – Maybe, the developer himself? He'll be more capable fixing his own stuff, for example.
  • 28. Involving others What if testing requires more resources than you can afford? Сonsumer of your API migth need precise and up-to date docs sooner than you'll be able to deliver them.
  • 29. Involving others What if testing requires more resources than you can afford? Сonsumer of your API migth need precise and up-to date docs sooner than you'll be able to deliver them. – Rewrite everything in Haskel. Broader your audience and give this people tools they can use. Simple tools.
  • 30. Behaviour Driven Development What if we start writing exact specifications according to real-world requirements? What if we reuse those specs to be our test cases that run automatically? BDD definition usually includes two or three of the following buzz-words: TDD ATDD DDD
  • 31. OOAD Take parts of BDD toolkit and use them in weird way BDD here looks like a replacement or a good addition to the integration tests. But it still allows you to go through the very natural cycle: you define behaviour behaviour defines tests tests define development direction
  • 35. requirements_tester.txt {"JSON": "JavaScript Object Notation"} Gherkin language - a business readable, DSL that allows to describe software behaviour without diving into implementation details.
  • 36. Yet another API accessible through HTTP Let's imagine we are building some API. And we are minimalists - so want it to use BasicAuth. And we are purists - so we want proper HTTP status codes, content headers, etc. How can the authentication test look like?
  • 37. Authentication test example in Gherkin yet_another_api.feature Feature: Yet another API As an API client I want to be able to do some really useful fluffy awesome colorful stuff Background: Set server name, and auth headers Given I am using server "$SERVER" And I set base URL to "$URL" And I set "Accept" header to "application/json" And I set "Content-Type" header to "application/json" And I set BasicAuth username to "user@example.com" and password to "password Scenario: Ensure account exists When I make a GET request to "account" Then the response status should be 200
  • 39. Steps implementation examples @behave.given('I set BasicAuth username to "{username}" and password to "{passw @dereference_step_parameters_and_data def set_basic_auth_headers(context, username, password): context.auth = (username, password) @behave.when('I make a GET request to "{url_path_segment}"') @dereference_step_parameters_and_data def get_request(context, url_path_segment): url = append_path(context.server, url_path_segment) context.response = requests.get( url, headers=context.headers, auth=context.auth) @behave.then('the response status should be one of "{statuses}"') @dereference_step_parameters_and_data def response_status_in(context, statuses): ensure(context.response.status_code).is_in( [int(s) for s in statuses.split(',')])
  • 40. Your custom behave module code layout yourproject/ behave/ yet_another_api.feature # the only file for humans, everything else is __init__.py environment.py # setup, helpers steps/ __init__.py # steps implementation
  • 41. environment.py from behave_http.environment import before_scenario APP_ROOT = os.path.normpath( os.path.abspath(os.path.join(os.path.dirname(__file__), '..' parse_config_file(os.path.join(APP_ROOT, "settings.py")) default_env = { 'SERVER': 'http://localhost:8081', 'API': 'api', [...] } credentials = { 'password': 'featuretester', 'email': 'featuretester@example.com' } def _recreate_account(db, auth, params , [...]): [...]
  • 42. environment.py (continued) def before_all(context): for k,v in default_env.iteritems(): os.environ.setdefault(k, v) app_url = URL(os.environ['SERVER']) api_url = app_url.add_path_segment(os.environ['API']) api_auth = (credentials['email'], credentials['password']) # DB connection setup goes here _recreate_account(db, auth, params , ...) _add_account_data(api_url, api_auth) def after_tag(context, tag): """Clean up database after destructive operation""" if tag == 'modifies': before_all(context)
  • 43. Example tag usage [...] @modifies Scenario: Delete account, ensure it does not exist When I make a DELETE request to "account" Then the response status should be 200 When I make a GET request to "account" Then the response status should be 401 @wip Scenario: Create account [...]
  • 44. Running tests # behave -q -f progress3 HTTP requests # features/http.feature Test getting context variable ...... Test GET request ...... Test POST request by checking we get the same JSON payload back ....... Test JSON path expection ....... Test JSON array length calculation ....... [...] Test GET polling with checking for value that eventually succeeds ...... Test Basic Auth ....... 1 feature passed, 0 failed, 0 skipped 17 scenarios passed, 0 failed, 0 skipped 121 steps passed, 0 failed, 0 skipped, 0 undefined Took 0m0.516s
  • 45. Failing tests [...] Test JSON array length calculation ......F -------------------------------------------------------------------------------- FAILURE in step 'the JSON array length at path "array" should be 3' (features/http.feature:55): Assertion Failed: Expected [1, 2, 3, 4] to have length 3 -------------------------------------------------------------------------------- [...] Failing scenarios: features/http.feature:49 Test JSON array length calculation 0 features passed, 1 failed, 0 skipped 16 scenarios passed, 1 failed, 0 skipped 120 steps passed, 1 failed, 0 skipped, 0 undefined Took 0m0.313s
  • 46. Behave-HTTP Implements basic reusable Behave steps for testing HTTP services
  • 47. Tools Libraries and utilities requests purl, furl jpath HTTPie Behave Behave-HTTP
  • 48. Resources Specs HTTP 1.1 Gherkin Videos "Cutting Off the Internet: Testing Applications that Use Requests", Ian Cordasco "Doing BDD with Python and PyCharm", Ilya Kazakevich