SlideShare a Scribd company logo
1 of 31
Download to read offline
Mock
Abstract
• Start to Write Test
• Start to Use Mock
• Tips
• You think quality is
important
the first thing
• pip install nose
• you will get a tool called nosetests
A very simple test
def add(left,right):
return left+right
!
def test_add():
assert add(4,5) == 9
Finding, Running, Report in
one shoot
nosetests sample.py
Ran 1 test in 0.001s
!
OK
if you meet problem
def add(left,right):
return left+right+1
!
def test_add():
assert add(4,5) == 9
!
trigger pdb as fail
nosetests sample_fail.py --pdb
assert add(4,5) == 9
(Pdb) p add(4,5)
10
(Pdb)
What nose do
• cooperate with doctest, unittest2
• add an additional function baed test case
• a test discover, test runner,
• plugin integration
unittest.TestCase
import unittest
!
def add(left,right):
return left+right
!
class addTestCase(unittest.TestCase):
def test_add(self):
self.assertEqual(5, add(5,5))
what else
• test fixture preparation
• setUP, tearDown
• setUp will be called before test method
• tearDown will be called after test method
what if
• if a function called erase_disk , how can I test
it?
• if a function will get a JSON from google, how
can I test it
Time to Introduce Mock
• python3.3 builtin
• pip install mock with python2.7
• it is a library
• it helps you to provide a fake object for spy
all-mighty
In : import mock
!
In : m = mock.Mock()
!
In : m.dock.dog.bark()
Out: <Mock
name='mock.dock.dog.bark()'
id='4320364368'>
obey your order
In: dog = mock.Mock(
return_value="bark")
!
In: dog()
Out: ‘bark’
!
In: dog.bark.return_value = u"WW"
!
In: dog.bark()
Out: u'WW'
!
mock tell you his story
In [9]: def reset_file(fs):
...: fs.seek(0)
...:!
In: m = mock.Mock()
!
In: reset_file(m)
!
In: m.seek.assert_called_with(0)
like python object
In : m = mock.MagicMock()
!
In : m['key']
Out: <MagicMock
name='mock.__getitem__()'
id=‘4311227728'>
!
In: m.__getitem__.return_value = 10
!
In: m[3]
Out: 10
magic mock assertion
In:
m.__getitem__.assert_called_with(3)
read spec
In : fake_str = mock.Mock(str)
!
In : fake_str.lower()
Out: <Mock name='mock.lower()'
id='4321150160'>
!
In : fake_str.LOWER
---------
AttributeError
General Usage
In : def count(fs):
...: return len(fs.read())
...:
In : fakefs = mock.Mock()
In : fakefs.read.return_value = "xx"
In : assert count(fakefs) == 2
Add Testability
• dependency should always pass from out side
• your design need to consider testability
Inversion of control
# not this
def to_be_test():
db = Database()
return db.all()
!
# write this
def to_be_test(db):
return db.all()
from mock import *
from StringIO import *
def do_print(): # hard to IoC
print "hi"
def test_print():
os = StringIO()
with patch('sys.stdout',
new=os):
do_print()
actual = os.getvalue()
expect = "hi"
assert expect in actual
Tips
• Q: How to maintain test case?
• refactor you test infrastructure often
• duplicated test code make you will feel tired
after interface changed
• Q: how much should I test?
• test the interface, not the implementation
• don’t test private method
• test public method
• Q: Test is slow, I don’t want to test
• write quick test
• mock time consuming object
• don’t execute time consuming test every time
• run failed test only while you meet error
Add test now
• My Project has no test …
• add test for new added code
• old code can add test latter
mock needs manage
• Mock is awesome, I want to mock every thing
• mock’s behavior may has error
• mock object tell you what you want to hear
• mock dependency is okay
• share mock among test modules
finding test utility
• Django mocks some service while testing
• GAE also provide mock while testing
• if you are using ORM, there a package that help
you mock ORM
After we have tests
• don’t forget to run test before you push codes
• nose can provide report
• nose can integration coverage report
Recap
• Nose is a good test driver
• unittest provide awesome test infrastructure
• any one want to share doctest?
• test and doc are combined !
• mock is used to fake a dependency, not every
thing

More Related Content

What's hot

20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksLohika_Odessa_TechTalks
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutesRay Toal
 
Py.test
Py.testPy.test
Py.testsoasme
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your DatabaseDavid Wheeler
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)Foyzul Karim
 
Effective Test Driven Database Development
Effective Test Driven Database DevelopmentEffective Test Driven Database Development
Effective Test Driven Database Developmentelliando dias
 
Wix Automation - The False Positive Paradox
Wix Automation - The False Positive ParadoxWix Automation - The False Positive Paradox
Wix Automation - The False Positive ParadoxEfrat Attas
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit testLucy Lu
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
Mozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver frameworkMozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver frameworkdavehunt82
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django ApplicationsHonza Král
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinSigma Software
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 

What's hot (20)

20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutes
 
Py.test
Py.testPy.test
Py.test
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your Database
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)
 
Effective Test Driven Database Development
Effective Test Driven Database DevelopmentEffective Test Driven Database Development
Effective Test Driven Database Development
 
Wix Automation - The False Positive Paradox
Wix Automation - The False Positive ParadoxWix Automation - The False Positive Paradox
Wix Automation - The False Positive Paradox
 
Test Driven
Test DrivenTest Driven
Test Driven
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Unit test
Unit testUnit test
Unit test
 
Mozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver frameworkMozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver framework
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita Galkin
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 

Viewers also liked

Mock Objects Presentation
Mock Objects PresentationMock Objects Presentation
Mock Objects PresentationAndriy Buday
 
[2011 04 11]mock_object 소개
[2011 04 11]mock_object 소개[2011 04 11]mock_object 소개
[2011 04 11]mock_object 소개Jong Pil Won
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsGavin Pickin
 
資料視覺化之理論、賞析與實作
資料視覺化之理論、賞析與實作資料視覺化之理論、賞析與實作
資料視覺化之理論、賞析與實作台灣資料科學年會
 
Junit in mule demo
Junit in mule demoJunit in mule demo
Junit in mule demoSudha Ch
 

Viewers also liked (6)

Monk objects
Monk objectsMonk objects
Monk objects
 
Mock Objects Presentation
Mock Objects PresentationMock Objects Presentation
Mock Objects Presentation
 
[2011 04 11]mock_object 소개
[2011 04 11]mock_object 소개[2011 04 11]mock_object 소개
[2011 04 11]mock_object 소개
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and Stubs
 
資料視覺化之理論、賞析與實作
資料視覺化之理論、賞析與實作資料視覺化之理論、賞析與實作
資料視覺化之理論、賞析與實作
 
Junit in mule demo
Junit in mule demoJunit in mule demo
Junit in mule demo
 

Similar to Mock Introduction

Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittestFariz Darari
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Fariz Darari
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitTuan Nguyen
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012Pietro Di Bello
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Dinis Cruz
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGegoodwintx
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentguestc8093a6
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWHolger Grosse-Plankermann
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionDionatan default
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)Thierry Gayet
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentSheeju Alex
 
Automated Software Testing
Automated Software TestingAutomated Software Testing
Automated Software Testingarild2
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it. Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it. Tom Crinson
 
Debug - MITX60012016-V005100
Debug - MITX60012016-V005100Debug - MITX60012016-V005100
Debug - MITX60012016-V005100Ha Nguyen
 
Multiply your Testing Effectiveness with Parameterized Testing, v1
Multiply your Testing Effectiveness with Parameterized Testing, v1Multiply your Testing Effectiveness with Parameterized Testing, v1
Multiply your Testing Effectiveness with Parameterized Testing, v1Brian Okken
 
Test Driven Development Introduction
Test Driven Development IntroductionTest Driven Development Introduction
Test Driven Development IntroductionNguyen Hai
 

Similar to Mock Introduction (20)

Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUG
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in Action
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Automated Software Testing
Automated Software TestingAutomated Software Testing
Automated Software Testing
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it. Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it.
 
Debug - MITX60012016-V005100
Debug - MITX60012016-V005100Debug - MITX60012016-V005100
Debug - MITX60012016-V005100
 
Multiply your Testing Effectiveness with Parameterized Testing, v1
Multiply your Testing Effectiveness with Parameterized Testing, v1Multiply your Testing Effectiveness with Parameterized Testing, v1
Multiply your Testing Effectiveness with Parameterized Testing, v1
 
Tdd
TddTdd
Tdd
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
Test Driven Development Introduction
Test Driven Development IntroductionTest Driven Development Introduction
Test Driven Development Introduction
 

More from Tim (文昌)

Python的50道陰影
Python的50道陰影Python的50道陰影
Python的50道陰影Tim (文昌)
 
Frontend django, Django Web 前端探索
Frontend django, Django Web 前端探索Frontend django, Django Web 前端探索
Frontend django, Django Web 前端探索Tim (文昌)
 
Introduction to protocol buffer
Introduction to protocol bufferIntroduction to protocol buffer
Introduction to protocol bufferTim (文昌)
 
Tainan.py, Experience about package
Tainan.py, Experience about packageTainan.py, Experience about package
Tainan.py, Experience about packageTim (文昌)
 
Performance Enhancement Tips
Performance Enhancement TipsPerformance Enhancement Tips
Performance Enhancement TipsTim (文昌)
 
pygame sharing pyhug
pygame sharing pyhugpygame sharing pyhug
pygame sharing pyhugTim (文昌)
 

More from Tim (文昌) (9)

Python的50道陰影
Python的50道陰影Python的50道陰影
Python的50道陰影
 
Frontend django, Django Web 前端探索
Frontend django, Django Web 前端探索Frontend django, Django Web 前端探索
Frontend django, Django Web 前端探索
 
Profile django
Profile djangoProfile django
Profile django
 
Introduction to protocol buffer
Introduction to protocol bufferIntroduction to protocol buffer
Introduction to protocol buffer
 
I18n
I18nI18n
I18n
 
Ml weka
Ml wekaMl weka
Ml weka
 
Tainan.py, Experience about package
Tainan.py, Experience about packageTainan.py, Experience about package
Tainan.py, Experience about package
 
Performance Enhancement Tips
Performance Enhancement TipsPerformance Enhancement Tips
Performance Enhancement Tips
 
pygame sharing pyhug
pygame sharing pyhugpygame sharing pyhug
pygame sharing pyhug
 

Recently uploaded

UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdfJamie (Taka) Wang
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncObject Automation
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Babel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxBabel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxYounusS2
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfAnna Loughnan Colquhoun
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataSafe Software
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum ComputingGDSC PJATK
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 

Recently uploaded (20)

UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation Inc
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
Babel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxBabel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptx
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdf
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum Computing
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 

Mock Introduction

  • 2. Abstract • Start to Write Test • Start to Use Mock • Tips
  • 3. • You think quality is important
  • 4. the first thing • pip install nose • you will get a tool called nosetests
  • 5. A very simple test def add(left,right): return left+right ! def test_add(): assert add(4,5) == 9
  • 6. Finding, Running, Report in one shoot nosetests sample.py Ran 1 test in 0.001s ! OK
  • 7. if you meet problem def add(left,right): return left+right+1 ! def test_add(): assert add(4,5) == 9 !
  • 8. trigger pdb as fail nosetests sample_fail.py --pdb assert add(4,5) == 9 (Pdb) p add(4,5) 10 (Pdb)
  • 9. What nose do • cooperate with doctest, unittest2 • add an additional function baed test case • a test discover, test runner, • plugin integration
  • 10. unittest.TestCase import unittest ! def add(left,right): return left+right ! class addTestCase(unittest.TestCase): def test_add(self): self.assertEqual(5, add(5,5))
  • 11. what else • test fixture preparation • setUP, tearDown • setUp will be called before test method • tearDown will be called after test method
  • 12. what if • if a function called erase_disk , how can I test it? • if a function will get a JSON from google, how can I test it
  • 13. Time to Introduce Mock • python3.3 builtin • pip install mock with python2.7 • it is a library • it helps you to provide a fake object for spy
  • 14. all-mighty In : import mock ! In : m = mock.Mock() ! In : m.dock.dog.bark() Out: <Mock name='mock.dock.dog.bark()' id='4320364368'>
  • 15. obey your order In: dog = mock.Mock( return_value="bark") ! In: dog() Out: ‘bark’ ! In: dog.bark.return_value = u"WW" ! In: dog.bark() Out: u'WW' !
  • 16. mock tell you his story In [9]: def reset_file(fs): ...: fs.seek(0) ...:! In: m = mock.Mock() ! In: reset_file(m) ! In: m.seek.assert_called_with(0)
  • 17. like python object In : m = mock.MagicMock() ! In : m['key'] Out: <MagicMock name='mock.__getitem__()' id=‘4311227728'> ! In: m.__getitem__.return_value = 10 ! In: m[3] Out: 10
  • 19. read spec In : fake_str = mock.Mock(str) ! In : fake_str.lower() Out: <Mock name='mock.lower()' id='4321150160'> ! In : fake_str.LOWER --------- AttributeError
  • 20. General Usage In : def count(fs): ...: return len(fs.read()) ...: In : fakefs = mock.Mock() In : fakefs.read.return_value = "xx" In : assert count(fakefs) == 2
  • 21. Add Testability • dependency should always pass from out side • your design need to consider testability
  • 22. Inversion of control # not this def to_be_test(): db = Database() return db.all() ! # write this def to_be_test(db): return db.all()
  • 23. from mock import * from StringIO import * def do_print(): # hard to IoC print "hi" def test_print(): os = StringIO() with patch('sys.stdout', new=os): do_print() actual = os.getvalue() expect = "hi" assert expect in actual
  • 24. Tips • Q: How to maintain test case? • refactor you test infrastructure often • duplicated test code make you will feel tired after interface changed
  • 25. • Q: how much should I test? • test the interface, not the implementation • don’t test private method • test public method
  • 26. • Q: Test is slow, I don’t want to test • write quick test • mock time consuming object • don’t execute time consuming test every time • run failed test only while you meet error
  • 27. Add test now • My Project has no test … • add test for new added code • old code can add test latter
  • 28. mock needs manage • Mock is awesome, I want to mock every thing • mock’s behavior may has error • mock object tell you what you want to hear • mock dependency is okay • share mock among test modules
  • 29. finding test utility • Django mocks some service while testing • GAE also provide mock while testing • if you are using ORM, there a package that help you mock ORM
  • 30. After we have tests • don’t forget to run test before you push codes • nose can provide report • nose can integration coverage report
  • 31. Recap • Nose is a good test driver • unittest provide awesome test infrastructure • any one want to share doctest? • test and doc are combined ! • mock is used to fake a dependency, not every thing