際際滷

際際滷Share a Scribd company logo
Pretenders
(fake servers for testing)

 Don't GET (nor POST) me wrong




                             Carles Barrob辿s - @technomilk
Motivation
We want to test applications that rely on
external network services.

Are we sending the right stuff?
Do we deal properly with different types of
responses?
Main Use Cases
HTTP:
Applications that call external HTTP APIs
AJAX client code


SMTP:
Applications that send e-mail
Design Decisions
Preset/Replay/Verify mocking pattern
Mock at the "wire protocol" level
Simplicity of client test code
Configuration and checks via a ReST API
   Usable in polyglot environments
Preset/Replay/Verify
We pre-program our pretend server with pre-
canned responses (presets)

We let the test run, and the mock server
replays the presets

Finally, we verify what requests/data were sent
to the server
Mock at wire protocol level
Instead of "patch-style" mocking
  Usable for testing non-Python applications
  Usable in integration tests (where you
   cannot patch running code)


Just make your application point to the mock
server:port instead of the real service
How it all works together
Start the main boss server (i.e. manually)
Each time you create a Mock, it:
   Tells the boss to instantiate a new mock server
    (pretender)
   Returns the port of the new server
   Your mock acts as a proxy to the remote server for
    configuration and collection of results

The boss takes care of cleaning up stale pretenders
Sample client test code
from pretenders.http.client import HttpMock
mock = HttpMock('localhost', 8000) #boss host and port
# Define presets
mock.when('GET /hello').reply('Hello')
mock.when('(POST|PUT) /somewhere').reply(status=400)
mock.reply('{"temperature": 23}', headers={'Content-Type':
'application/json'})
# Set your app to the fake URL, and exercise it
set_service_url(mock.pretend_access_point)
 run stuff
# Verify requests your code made
r = mock.get_request(0)
assert_equal(r.method, 'GET')
assert_equal(r.url, '/weather?city=barcelona')
THANK YOU!


Pretenders was written by:
Alex Couper and Carles Barrob辿s

$ pip install pretenders
Docs: http://pretenders.readthedocs.org
Code: https://github.com/txels/pretenders
Ad

Recommended

Colin Bowern - The Not So Scary Side Of Asp.Net Model View Controller In Th...
Colin Bowern - The Not So Scary Side Of Asp.Net Model View Controller In Th...
Refresh Events
Reflection in Pharo5
Reflection in Pharo5
Marcus Denker
Create a fake REST API without writing a single line of code
Create a fake REST API without writing a single line of code
Yashobanta Bai
TDD, BDD, RSpec
TDD, BDD, RSpec
Nascenia IT
What's new in c# 8.0
What's new in c# 8.0
Moaid Hathot
Rack
Rack
Aakanksha Bhardwaj
Inside asp.net mvc framework
Inside asp.net mvc framework
Ciklum Ukraine
Inside ASP.NET MVC framework
Inside ASP.NET MVC framework
Ciklum Ukraine
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
Marcus Denker
Behaviour-Driven Development
Behaviour-Driven Development
Kerry Buckley
Karma - JS Test Runner
Karma - JS Test Runner
Sebastiano Armeli
Variables in Pharo5
Variables in Pharo5
Marcus Denker
Integration and Acceptance Testing
Integration and Acceptance Testing
Alan Hecht
Dynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection Promises
Marcus Denker
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
Roman Liubun
One does not simply "Upgrade to Rails 3"
One does not simply "Upgrade to Rails 3"
testflyjets
Conejo Architecture
Conejo Architecture
paulosuzart
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1
Mindfire Solutions
RSpec and Rails
RSpec and Rails
Alan Hecht
Javascript async / await Frontend-IL
Javascript async / await Frontend-IL
Ran Wahle
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
intuit_india
TDD, BDD and mocks
TDD, BDD and mocks
Kerry Buckley
Deploying Rails Apps with Capistrano
Deploying Rails Apps with Capistrano
Nyros Technologies
Angular Unit Testing
Angular Unit Testing
Alessandro Giorgetti
Flask & Flask-restx
Flask & Flask-restx
ammaraslam18
Patterns in JavaScript
Patterns in JavaScript
Dhananjay Kumar
PowerShell: Automation for everyone
PowerShell: Automation for everyone
Gavin Barron
Why I am hooked on the future of React
Why I am hooked on the future of React
Maurice De Beijer [MVP]
Palestra VCR
Palestra VCR
C叩ssio Marques
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
coreygoldberg

More Related Content

What's hot (20)

Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
Marcus Denker
Behaviour-Driven Development
Behaviour-Driven Development
Kerry Buckley
Karma - JS Test Runner
Karma - JS Test Runner
Sebastiano Armeli
Variables in Pharo5
Variables in Pharo5
Marcus Denker
Integration and Acceptance Testing
Integration and Acceptance Testing
Alan Hecht
Dynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection Promises
Marcus Denker
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
Roman Liubun
One does not simply "Upgrade to Rails 3"
One does not simply "Upgrade to Rails 3"
testflyjets
Conejo Architecture
Conejo Architecture
paulosuzart
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1
Mindfire Solutions
RSpec and Rails
RSpec and Rails
Alan Hecht
Javascript async / await Frontend-IL
Javascript async / await Frontend-IL
Ran Wahle
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
intuit_india
TDD, BDD and mocks
TDD, BDD and mocks
Kerry Buckley
Deploying Rails Apps with Capistrano
Deploying Rails Apps with Capistrano
Nyros Technologies
Angular Unit Testing
Angular Unit Testing
Alessandro Giorgetti
Flask & Flask-restx
Flask & Flask-restx
ammaraslam18
Patterns in JavaScript
Patterns in JavaScript
Dhananjay Kumar
PowerShell: Automation for everyone
PowerShell: Automation for everyone
Gavin Barron
Why I am hooked on the future of React
Why I am hooked on the future of React
Maurice De Beijer [MVP]
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
Marcus Denker
Behaviour-Driven Development
Behaviour-Driven Development
Kerry Buckley
Variables in Pharo5
Variables in Pharo5
Marcus Denker
Integration and Acceptance Testing
Integration and Acceptance Testing
Alan Hecht
Dynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection Promises
Marcus Denker
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
Roman Liubun
One does not simply "Upgrade to Rails 3"
One does not simply "Upgrade to Rails 3"
testflyjets
Conejo Architecture
Conejo Architecture
paulosuzart
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1
Mindfire Solutions
RSpec and Rails
RSpec and Rails
Alan Hecht
Javascript async / await Frontend-IL
Javascript async / await Frontend-IL
Ran Wahle
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
intuit_india
TDD, BDD and mocks
TDD, BDD and mocks
Kerry Buckley
Deploying Rails Apps with Capistrano
Deploying Rails Apps with Capistrano
Nyros Technologies
Flask & Flask-restx
Flask & Flask-restx
ammaraslam18
Patterns in JavaScript
Patterns in JavaScript
Dhananjay Kumar
PowerShell: Automation for everyone
PowerShell: Automation for everyone
Gavin Barron
Why I am hooked on the future of React
Why I am hooked on the future of React
Maurice De Beijer [MVP]

Similar to Pretenders talk at PyconUK 2012 (20)

Palestra VCR
Palestra VCR
C叩ssio Marques
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
coreygoldberg
A.java
A.java
JahnaviBhagat
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
Steve Wortham
Expand Your Testing with Virtual Services
Expand Your Testing with Virtual Services
Amber Race
java networking
java networking
Waheed Warraich
T2
T2
Mo Ch
Postman.ppt
Postman.ppt
ParrotBAD
Leveraging Playwright for API Testing.pdf
Leveraging Playwright for API Testing.pdf
Steve Wortham
Intro to Node
Intro to Node
Aaron Stannard
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
VannaSchrader3
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
alfredacavx97
692015 programming油assignment油1油building油a油multi足threaded油w
692015 programming油assignment油1油building油a油multi足threaded油w
smile790243
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
Viktor Todorov
API_Testing_with_Postman
API_Testing_with_Postman
Mithilesh Singh
1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel
AgripinaBeaulieuyw
Java 1
Java 1
VidyaVarshini3
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docx
randymartin91030
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
hanneloremccaffery
Exposing Salesforce REST Services Using Swagger
Exposing Salesforce REST Services Using Swagger
Salesforce Developers
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
coreygoldberg
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
Steve Wortham
Expand Your Testing with Virtual Services
Expand Your Testing with Virtual Services
Amber Race
T2
T2
Mo Ch
Postman.ppt
Postman.ppt
ParrotBAD
Leveraging Playwright for API Testing.pdf
Leveraging Playwright for API Testing.pdf
Steve Wortham
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
VannaSchrader3
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
alfredacavx97
692015 programming油assignment油1油building油a油multi足threaded油w
692015 programming油assignment油1油building油a油multi足threaded油w
smile790243
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
Viktor Todorov
API_Testing_with_Postman
API_Testing_with_Postman
Mithilesh Singh
1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel
AgripinaBeaulieuyw
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docx
randymartin91030
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
hanneloremccaffery
Exposing Salesforce REST Services Using Swagger
Exposing Salesforce REST Services Using Swagger
Salesforce Developers
Ad

Recently uploaded (20)

AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) 際際滷s
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) 際際滷s
Ravi Tamada
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
Wenn alles versagt - IBM Tape sch端tzt, was z辰hlt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape sch端tzt, was z辰hlt! Und besonders mit dem neust...
Josef Weingand
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) 際際滷s
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) 際際滷s
Ravi Tamada
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
Wenn alles versagt - IBM Tape sch端tzt, was z辰hlt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape sch端tzt, was z辰hlt! Und besonders mit dem neust...
Josef Weingand
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
Ad

Pretenders talk at PyconUK 2012

  • 1. Pretenders (fake servers for testing) Don't GET (nor POST) me wrong Carles Barrob辿s - @technomilk
  • 2. Motivation We want to test applications that rely on external network services. Are we sending the right stuff? Do we deal properly with different types of responses?
  • 3. Main Use Cases HTTP: Applications that call external HTTP APIs AJAX client code SMTP: Applications that send e-mail
  • 4. Design Decisions Preset/Replay/Verify mocking pattern Mock at the "wire protocol" level Simplicity of client test code Configuration and checks via a ReST API Usable in polyglot environments
  • 5. Preset/Replay/Verify We pre-program our pretend server with pre- canned responses (presets) We let the test run, and the mock server replays the presets Finally, we verify what requests/data were sent to the server
  • 6. Mock at wire protocol level Instead of "patch-style" mocking Usable for testing non-Python applications Usable in integration tests (where you cannot patch running code) Just make your application point to the mock server:port instead of the real service
  • 7. How it all works together Start the main boss server (i.e. manually) Each time you create a Mock, it: Tells the boss to instantiate a new mock server (pretender) Returns the port of the new server Your mock acts as a proxy to the remote server for configuration and collection of results The boss takes care of cleaning up stale pretenders
  • 8. Sample client test code from pretenders.http.client import HttpMock mock = HttpMock('localhost', 8000) #boss host and port # Define presets mock.when('GET /hello').reply('Hello') mock.when('(POST|PUT) /somewhere').reply(status=400) mock.reply('{"temperature": 23}', headers={'Content-Type': 'application/json'}) # Set your app to the fake URL, and exercise it set_service_url(mock.pretend_access_point) run stuff # Verify requests your code made r = mock.get_request(0) assert_equal(r.method, 'GET') assert_equal(r.url, '/weather?city=barcelona')
  • 9. THANK YOU! Pretenders was written by: Alex Couper and Carles Barrob辿s $ pip install pretenders Docs: http://pretenders.readthedocs.org Code: https://github.com/txels/pretenders