SlideShare uma empresa Scribd logo
1 de 70
Mocking Strategies
Please don’t mock me after this
presentation…
Daniel Davis
• Daniel Davis
• Software Developer for 8 years
• Fun Fact:
– I ran the “Jingle All The Way” 5k dressed as a
Giant Gingerbread man
Who Am I?
3
Really though, who are you?
• Came from Java world
• Python developer for 2 years
• DevOps
– Lots of work with automation and quality
• Passionate about quality!
– Doesn’t happen overnight…
Testing Journey
• Became a Certified Scrum Developer
(CSD) about 2 years ago
• Finally learned about craftsmanship and
writing better tests
– Basically black magic
• Learned in Java…
I want to be a better developer
• Switching to Python was jarring
• Kept wondering about writing unit tests
• Dealing with complicated frameworks like
Django
Finding Python
7
• Asked colleagues
– Many had the same questions
• Decided to learn…
• Wanted to share with the community
Unit testing? Mocks?
8
Let’s Talk About
Unit Tests…
Unit – 70%
Integration
– 20%
UI
10%
Testing Types
• “They’re good when the problem is easy”
– A rabbit hole of testing
• “I spend too much time writing lots of code
to test, so I give up”
• “There’s just some stuff you can’t unit test”
Great Unit Testing Myths
Mocking makes unit
testing easier!
12
What Are Mocks?
13
Test Double
Dummy
Object
Test Stub Test Spy
Mock
Object
Fake
Object
Commonly referred to as “Mocks”
• Stubs
– Provide a canned response to method calls
• Spy
– Real objects that behave like normal except
when a specific condition is met
• Mocks
– Verifies behavior (calls) to a method
What Are Mocks?
14
Blah Blah Blah professor Dan…
15
• Eliminates dependencies in the CUT
(class under test)
– Isolated Unit Tests
Problems Mocks Solve
16
foo(x) bar(x)
• Tests methods that have no return value
Problems Mocks Solve
17
How do we know that bar(x) has been called?
• Tests error handling
Problems Mocks Solve
18
How do we generate this exception???
• Eliminate dependency on database calls
– Speed up testing!
• Reduce test complexity
– Don’t have to write complex logic to handle
behavior of methods not under test
• Don’t have to wait to implement other
methods
Other Reasons Mocks Are Important
19
Ok, I’m sold…
Show me how to actually do this…
20
• Mock (MagicMock)
– Most robust, popular
– Built-in as of Python 3.3!
• flexmock
– Based on Ruby’s flexmock
• mox
– Similar to Java’s EasyMock
• Mocker
• dingus
– “record then assert” mocking library
• fudge
– Similar to Mockito
• MiniMock
– Simple mocking with DocTest
What Are The Python Options?
21
Sample Problem
22
Valentine’s Day Edition
Problem:
Tinder Competitor
23
Get yo’ container on…
• Create a method to return a new, random
victim candidate
– Must not show the same person
– Must not show someone the user has already
“swiped” on
Problem: “Docker” dating app
Easy enough…
25
“Surely no one could
have seen EVERYONE
in the database!!!”
- The Intern
get_next_person() get_random_person()
Write a Unit Test…
26
It works!!!
27
29
Easy enough…
30
What if knew the result of get_random_person()???
31
Patching
Module.attribute
Mock method
It works EVERY SINGLE TIME!!!
33
Variations on a theme
34
Variations on a theme
35
Variations on a theme
36
Variations on a theme
37
OMG, ContextManagers! WHAT???
But what if we call it
multiple times???
38
• What if I want to test the while loop?
Different results on multiple calls
Uh…umm…
40
UMM…
Use side_effect
41
• Use patching / mocks to bring certainty to
method calls
• Eliminates dependencies on other code
– Even unfinished code!!!
• Lots of ways to do it, pick your favorite
Recap: What did we learn?
42
Mocking to Verify Behavior
43
Problem:
Matching in “Docker”
• When a user swipes right…
• If the other user “likes” them:
– Send them both a message with contact info
• If the other user “dislikes” them:
– Let the user down gently…
• If the other user hasn’t evaluated yet:
– Display the “give it time” message
Problem: “Docker” matches
Implementation
46
How do we test this??? No return values!!!
Behavior Verification
47
What about checking
parameters???
48
Verifying Parameters
49
Shouldn’t we check the other
methods too?
50
We’d need to have multiple mocks to do that!!!
Multiple Mocks
51
Patch Multiple
52
Testing Multiple Calls…
53
Multiple calls
54
Whew!!!
Almost Done!
There will be beer soon!
Sweet, delicious beer!
55
Mocking built-ins
and Exceptions
56
Simple JSON reader
How do we test something like this???
• Test parsing a valid file
• Test an IOError (i.e. file missing)
• Test a ValueError (i.e invalid json)
Testing JSON reader
58
• Let’s just create a sample file!
How do I test open()
59
Can you even mock a builtin?
60
• open() returns a File object
• open(filename).read()
• So we really need to mock File.read()
– But it’s an instance!!! Oh no!
What? Why Not???
61
Have you tried solving it with Mocks???
Mocks returning Mocks? WAT???
62
What about error
handling?
63
What about error handling?
64
What about ValueError?
Wrap Up:
Key Take-Aways
66
• Mocking makes writing unit tests simpler
– Eliminates dependencies
– Verifies behavior
– Tests error handling
• You just need some practice!
Remember This!
• http://mock.readthedocs.org/en/latest/
• Pip Install Mock
• Create a simple class, then write tests!
Try It On Your Own
68
Let’s Go Write
Some Tests!!!
69
Questions?
70

Mais conteúdo relacionado

Mais procurados

Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
nickokiss
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
Richard Paul
 

Mais procurados (20)

Exploratory Testing
Exploratory TestingExploratory Testing
Exploratory Testing
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Lecture: Advanced Reflection. MetaLinks
Lecture: Advanced Reflection. MetaLinksLecture: Advanced Reflection. MetaLinks
Lecture: Advanced Reflection. MetaLinks
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Test unitaire
Test unitaireTest unitaire
Test unitaire
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
What is Agile Testing? Edureka
What is Agile Testing? EdurekaWhat is Agile Testing? Edureka
What is Agile Testing? Edureka
 
API Testing: The heart of functional testing" with Bj Rollison
API Testing: The heart of functional testing" with Bj RollisonAPI Testing: The heart of functional testing" with Bj Rollison
API Testing: The heart of functional testing" with Bj Rollison
 
Introduction & Manual Testing
Introduction & Manual TestingIntroduction & Manual Testing
Introduction & Manual Testing
 
Clean Code
Clean CodeClean Code
Clean Code
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User Group
 
Testes pythonicos com pytest
Testes pythonicos com pytestTestes pythonicos com pytest
Testes pythonicos com pytest
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Mutation testing
Mutation testingMutation testing
Mutation testing
 
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
 

Destaque

Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
PatchSpace Ltd
 

Destaque (11)

All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
[PyCon2016]To mock or not to mock, that is the questions
[PyCon2016]To mock or not to mock, that is the questions[PyCon2016]To mock or not to mock, that is the questions
[PyCon2016]To mock or not to mock, that is the questions
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
Py.test
Py.testPy.test
Py.test
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
 
Учим автотесты человеческому языку с помощью Allure и PyTest
Учим автотесты человеческому языку с помощью Allure и PyTestУчим автотесты человеческому языку с помощью Allure и PyTest
Учим автотесты человеческому языку с помощью Allure и PyTest
 
Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentals
 
Нескучное тестирование с pytest
Нескучное тестирование с pytestНескучное тестирование с pytest
Нескучное тестирование с pytest
 
AUTOMATED TESTING USING PYTHON (ATE)
AUTOMATED TESTING USING PYTHON (ATE)AUTOMATED TESTING USING PYTHON (ATE)
AUTOMATED TESTING USING PYTHON (ATE)
 
Robot Framework Dos And Don'ts
Robot Framework Dos And Don'tsRobot Framework Dos And Don'ts
Robot Framework Dos And Don'ts
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework Introduction
 

Semelhante a Mocking in python

Reviewing CPAN modules
Reviewing CPAN modulesReviewing CPAN modules
Reviewing CPAN modules
neilbowers
 
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cppQuickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
Clare Macrae
 

Semelhante a Mocking in python (20)

Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015
 
Reviewing CPAN modules
Reviewing CPAN modulesReviewing CPAN modules
Reviewing CPAN modules
 
Summit 16: Stop Writing Legacy Code!
Summit 16: Stop Writing Legacy Code!Summit 16: Stop Writing Legacy Code!
Summit 16: Stop Writing Legacy Code!
 
PuppetConf 2016: How Not to Freak Out When You Start Writing Puppet Modules f...
PuppetConf 2016: How Not to Freak Out When You Start Writing Puppet Modules f...PuppetConf 2016: How Not to Freak Out When You Start Writing Puppet Modules f...
PuppetConf 2016: How Not to Freak Out When You Start Writing Puppet Modules f...
 
Tdd
TddTdd
Tdd
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To Testing
 
It's Not Just About Code
It's Not Just About CodeIt's Not Just About Code
It's Not Just About Code
 
Agile Software Development in practice: Experience, Tips and Tools from the T...
Agile Software Development in practice: Experience, Tips and Tools from the T...Agile Software Development in practice: Experience, Tips and Tools from the T...
Agile Software Development in practice: Experience, Tips and Tools from the T...
 
Don't get blamed for your choices - Techorama 2019
Don't get blamed for your choices - Techorama 2019Don't get blamed for your choices - Techorama 2019
Don't get blamed for your choices - Techorama 2019
 
TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)
TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)
TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)
 
TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)
TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)
TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)
 
Lrug
LrugLrug
Lrug
 
Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)
 
TDD - Seriously, try it! (updated '22)
TDD - Seriously, try it! (updated '22)TDD - Seriously, try it! (updated '22)
TDD - Seriously, try it! (updated '22)
 
Test-Driven Sitecore
Test-Driven SitecoreTest-Driven Sitecore
Test-Driven Sitecore
 
Automated Acceptance Testing from Scratch
Automated Acceptance Testing from ScratchAutomated Acceptance Testing from Scratch
Automated Acceptance Testing from Scratch
 
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cppQuickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
 
TDD - Seriously, try it! - Bucarest Tech Week
TDD - Seriously, try it! - Bucarest Tech WeekTDD - Seriously, try it! - Bucarest Tech Week
TDD - Seriously, try it! - Bucarest Tech Week
 
Teaching Kids Programming Using the Intentional Method
Teaching Kids Programming Using the Intentional MethodTeaching Kids Programming Using the Intentional Method
Teaching Kids Programming Using the Intentional Method
 
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Mocking in python