SlideShare une entreprise Scribd logo
1  sur  22
Unit testing and mocking in
Python
Erick M’bwana
labofcoding.com
Software testing
• Software testing is any activity taken to verify that a given software
system is working as expected
• Types of software testing
• Integration Testing – test how components of a system work together
• System Testing – test the completely integrated system
• Regression testing – test the effects of code changes
• Unit testing – test units of code in isolation
• Security testing – test how data is protected from unauthorized access.
• Acceptance Testing - determine whether a piece of software satisfies all
of the requirements from the business or user's perspective
Unit Testing
• Unit Testing is a testing method in which individual units of
code are tested to assert that they are working as expected.
• The goal of unit testing is to isolate each part of the program
and show that the individual parts are correct.
• The functionality of individual functions and classes are
tested on their own.
• Embraced by the open source community.
• unittest module in Python
Common concepts
• Test coverage – A measurement of the effectiveness of unit
tests.Test coverage tools instrospect the code when the tests are
running and determines which parts have been executed and
which not. Coverage.py by Ned Batchelder is a common tool in
pyland.
• Test fixtures - A test fixture is a fixed state of a set of objects used
as a baseline for running tests. The purpose of a test fixture is to
ensure that there is a well known and fixed environment in which
tests are run so that results are repeatable. An example is
preparation of input data – can be defined in code, as separate
fixture files(json, yaml etc) or you can use a fixture generating
library such as factoryboy, mixer etc.
Mocking
• Mocking is the process of replacing real objects
defined in code with mock/fake objects for the
purposes of unit testing.
• This is achieved by creating objects that emulate
the behavior of real objects.
• The mock objects are used to emulate the
behavior of the real objects that the code under
test depends on.
The need for testing
•Find problems early in development
•Deploy with confidence
•Good tests forces good design in code
•Improves software reliabilty.
•Provides a sort of living documentation of
the system.
•Makes integration easier
•Helps in debugging
AAA Testing Pattern
• A - Arrange
• A - Act
• A - Assert
Testing Outcomes
•Success – the code runs as expected
•Failure – code does not work as expected.
•Error – an error either in the code or the
tests which was not anticipated
Elements of a good unit test
• Single responsibility
• Does not depend on other tests
• Simple set up
• Readable, preferably by mortals
• DRY does not apply in tests.
Hindrances to writing tests
•A waste of time
•Brittle tests
•Slow tests
•My seniors don't see the need.
•Tight timelines
Mitigating slow tests
• Keep database access to the minimum, access
only when absolutely necessary
• Replace expensive operations with less expensive
dummy ones, eg hashing algorithms
• Authenticate only where its necessary
• Mock it!
1.2 Mocking
• Mocking is the process of replacing real objects
defined in code with mock/fake objects for the
purposes of unit testing.
• This is achieved by creating objects that emulate
the behavior of real objects.
• The mock objects are used to emulate the
behavior of the real objects that the code under
test depends on.
What to mock
•Any interaction with external APIs
•Any unnecessary database calls
•Code that has external side effects, eg
sending mails
•Non trivial object creation
The unittest.mock module
• Python 3.3 and later have the mock module inbuilt.
• For python 2, there is need to install the mock module
separately.
• Mocking allows you to replace parts of your system
under test with the mock objects and make assertions
about how they have been used
The mock objects
• Mock and MagicMock – When you mock an
object, a Mock or MagicMock class is created
replacing the mocked object. It then will
create all attributes and methods as you
access them and store details of how they
have been used.
• from unittest.mock import Mock, MagicMock
How to mock objects
• The most common method is to use the patch object accessible
from the mock module
• from unittest.mock import patch
• The patch object can be used as a decorator or a context manager.
• When the patch object is used as a decorator it will automatically
send a positional argument to the decorated function. The
argument sent is by default a MagicMock class and you can use it
to make assertions about which methods / attributes were used
and arguments they were called with.
Example: using patch as a decorator
Assertion methods and attributes
• assert_any_call
• assert_called
• assert_called_once
• assert_called_once_with
• assert_called_with
• assert_not_called
• call_args
• call_args_list
• call_count
• called
• return_value
• side_effect
Setting return values for mocked objects
• The return value attribute on the MagicMock instance
passed into your test function allows you to choose
what the patched callable returns.
Using side effects in mocks
• Sometimes you'll want to test that your function correctly handles
an exception, or that multiple calls of the function you're patching
are handled correctly. You can do that using side_effect.
Setting side_effect to an exception raises that exception
immediately when the patched function is called.
• Setting side_effect to an iterable will return the next item from
the iterable each time the patched function is called.
Setting side_effect to any other value will return that value.
• You can also use it in cases where you are testing non-
deterministic values
Useful tools and libraries
• Testing libraries: pytest, nose
• Fixture generation: factory_boy, mixer
• Test coverage: coverage.py
• Test automation: tox
• Reference: https://docs.python-guide.org/writing/tests/
Thanks!
The end

Contenu connexe

Tendances

Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
Richard Paul
 
Qtp Basics
Qtp BasicsQtp Basics
Qtp Basics
mehramit
 
Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & Programming
Allan Mangune
 
upload ppt by browse button
upload ppt by browse buttonupload ppt by browse button
upload ppt by browse button
techweb08
 

Tendances (20)

Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Qtp Basics
Qtp BasicsQtp Basics
Qtp Basics
 
Ppt Qtp
Ppt QtpPpt Qtp
Ppt Qtp
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & Programming
 
Refactoring
RefactoringRefactoring
Refactoring
 
Angular Unit Test
Angular Unit TestAngular Unit Test
Angular Unit Test
 
Unit test
Unit testUnit test
Unit test
 
Mocking
MockingMocking
Mocking
 
TDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 editionTDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 edition
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
Unit testing
Unit testingUnit testing
Unit testing
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
NUnit Features Presentation
NUnit Features PresentationNUnit Features Presentation
NUnit Features Presentation
 
Gherkin model BDD
Gherkin model BDDGherkin model BDD
Gherkin model BDD
 
Gherkin model1
Gherkin model1Gherkin model1
Gherkin model1
 
QTP Automation Testing Tutorial 6
QTP Automation Testing Tutorial 6QTP Automation Testing Tutorial 6
QTP Automation Testing Tutorial 6
 
Paper CS
Paper CSPaper CS
Paper CS
 
upload ppt by browse button
upload ppt by browse buttonupload ppt by browse button
upload ppt by browse button
 

Similaire à Unit testing and mocking in Python - PyCon 2018 - Kenya

Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
TO THE NEW | Technology
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
Alex Borsuk
 

Similaire à Unit testing and mocking in Python - PyCon 2018 - Kenya (20)

Unit testing
Unit testingUnit testing
Unit testing
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Agile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayAgile Software Testing the Agilogy Way
Agile Software Testing the Agilogy Way
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
 
Beginners overview of automated testing with Rspec
Beginners overview of automated testing with RspecBeginners overview of automated testing with Rspec
Beginners overview of automated testing with Rspec
 
Ch11lect1 ud
Ch11lect1 udCh11lect1 ud
Ch11lect1 ud
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
Software testing: an introduction - 2017
Software testing: an introduction - 2017Software testing: an introduction - 2017
Software testing: an introduction - 2017
 
The Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeThe Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your Code
 
Unit Testing in Swift
Unit Testing in SwiftUnit Testing in Swift
Unit Testing in Swift
 
Mockito
MockitoMockito
Mockito
 
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubsIntegration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
 
Unit Testing and role of Test doubles
Unit Testing and role of Test doublesUnit Testing and role of Test doubles
Unit Testing and role of Test doubles
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with Pester
 

Dernier

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Dernier (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

Unit testing and mocking in Python - PyCon 2018 - Kenya

  • 1. Unit testing and mocking in Python Erick M’bwana labofcoding.com
  • 2. Software testing • Software testing is any activity taken to verify that a given software system is working as expected • Types of software testing • Integration Testing – test how components of a system work together • System Testing – test the completely integrated system • Regression testing – test the effects of code changes • Unit testing – test units of code in isolation • Security testing – test how data is protected from unauthorized access. • Acceptance Testing - determine whether a piece of software satisfies all of the requirements from the business or user's perspective
  • 3. Unit Testing • Unit Testing is a testing method in which individual units of code are tested to assert that they are working as expected. • The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. • The functionality of individual functions and classes are tested on their own. • Embraced by the open source community. • unittest module in Python
  • 4. Common concepts • Test coverage – A measurement of the effectiveness of unit tests.Test coverage tools instrospect the code when the tests are running and determines which parts have been executed and which not. Coverage.py by Ned Batchelder is a common tool in pyland. • Test fixtures - A test fixture is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. An example is preparation of input data – can be defined in code, as separate fixture files(json, yaml etc) or you can use a fixture generating library such as factoryboy, mixer etc.
  • 5. Mocking • Mocking is the process of replacing real objects defined in code with mock/fake objects for the purposes of unit testing. • This is achieved by creating objects that emulate the behavior of real objects. • The mock objects are used to emulate the behavior of the real objects that the code under test depends on.
  • 6. The need for testing •Find problems early in development •Deploy with confidence •Good tests forces good design in code •Improves software reliabilty. •Provides a sort of living documentation of the system. •Makes integration easier •Helps in debugging
  • 7. AAA Testing Pattern • A - Arrange • A - Act • A - Assert
  • 8. Testing Outcomes •Success – the code runs as expected •Failure – code does not work as expected. •Error – an error either in the code or the tests which was not anticipated
  • 9. Elements of a good unit test • Single responsibility • Does not depend on other tests • Simple set up • Readable, preferably by mortals • DRY does not apply in tests.
  • 10. Hindrances to writing tests •A waste of time •Brittle tests •Slow tests •My seniors don't see the need. •Tight timelines
  • 11. Mitigating slow tests • Keep database access to the minimum, access only when absolutely necessary • Replace expensive operations with less expensive dummy ones, eg hashing algorithms • Authenticate only where its necessary • Mock it!
  • 12. 1.2 Mocking • Mocking is the process of replacing real objects defined in code with mock/fake objects for the purposes of unit testing. • This is achieved by creating objects that emulate the behavior of real objects. • The mock objects are used to emulate the behavior of the real objects that the code under test depends on.
  • 13. What to mock •Any interaction with external APIs •Any unnecessary database calls •Code that has external side effects, eg sending mails •Non trivial object creation
  • 14. The unittest.mock module • Python 3.3 and later have the mock module inbuilt. • For python 2, there is need to install the mock module separately. • Mocking allows you to replace parts of your system under test with the mock objects and make assertions about how they have been used
  • 15. The mock objects • Mock and MagicMock – When you mock an object, a Mock or MagicMock class is created replacing the mocked object. It then will create all attributes and methods as you access them and store details of how they have been used. • from unittest.mock import Mock, MagicMock
  • 16. How to mock objects • The most common method is to use the patch object accessible from the mock module • from unittest.mock import patch • The patch object can be used as a decorator or a context manager. • When the patch object is used as a decorator it will automatically send a positional argument to the decorated function. The argument sent is by default a MagicMock class and you can use it to make assertions about which methods / attributes were used and arguments they were called with.
  • 17. Example: using patch as a decorator
  • 18. Assertion methods and attributes • assert_any_call • assert_called • assert_called_once • assert_called_once_with • assert_called_with • assert_not_called • call_args • call_args_list • call_count • called • return_value • side_effect
  • 19. Setting return values for mocked objects • The return value attribute on the MagicMock instance passed into your test function allows you to choose what the patched callable returns.
  • 20. Using side effects in mocks • Sometimes you'll want to test that your function correctly handles an exception, or that multiple calls of the function you're patching are handled correctly. You can do that using side_effect. Setting side_effect to an exception raises that exception immediately when the patched function is called. • Setting side_effect to an iterable will return the next item from the iterable each time the patched function is called. Setting side_effect to any other value will return that value. • You can also use it in cases where you are testing non- deterministic values
  • 21. Useful tools and libraries • Testing libraries: pytest, nose • Fixture generation: factory_boy, mixer • Test coverage: coverage.py • Test automation: tox • Reference: https://docs.python-guide.org/writing/tests/