SlideShare a Scribd company logo
1 of 30
Download to read offline
How to Write Fast and Efficient Unit
Tests in Django
Casey Kinsey
DjangoCon 2013
Monday, September 2, 13
A REAL NEED FORTEST SPEED
Monday, September 2, 13
A REAL NEED FORTEST SPEED
• Made an initial production release of a real product for a national media company
• Test coverage was not great
• Started seeing regressions in subsequent releases
• Decided to aggressively pursue greater test coverage
• Results were successful, but one thing clear: As test coverage increased we had an
acute need for faster test suites.
Monday, September 2, 13
WHY SHOULD I BE CONCERNED WITH
UNITTEST SPEED?
• If you’re serious about testing, you’re serious about at least two things:
• Having lots of tests
• Running those tests frequently
Monday, September 2, 13
•A slow test suite gets in the way of your testing goals because:
•Developers will avoid running tests
•Preparing code for integration becomes painful
•Deployment speed is directly affected
Monday, September 2, 13
THE FIRST STEPTO FASTER UNITTESTS:
WRITE UNITTESTS
Monday, September 2, 13
UNITTESTSVS INTEGRATIONTESTS
• Many Django project test suites are comprised mostly of integration tests
• What is a UnitTest?
• UnitTests cover a small “unit” of code
• Ideally, these units include as few branches as possible
• What is an IntegrationTest?
• IntegrationTests test the contracts between your “units”
Monday, September 2, 13
UNITTESTSVS INTEGRATIONTESTS
• Django test client is an integration test
dead giveaway
• The test client covers way more than
you are interested in testing
• URL Routing, Request Middleware,
ORM,Template Rendering, Response
Middleware, etc
Monday, September 2, 13
UNITTESTSVS INTEGRATIONTESTS
• A good unit tests covers code that is
limited in functionality/scope
• Ideally, a single method with limited
external calls
Monday, September 2, 13
UNITTESTSVS INTEGRATIONTESTS
• Establish a good ratio of unit tests to integration tests. An example may be:
• for each method that contains business logic, there should exist a unit test
• for each page/view/user path of your project, there should exist an integration test
• YMMV
Monday, September 2, 13
SET UP CAUTIOUSLY
Monday, September 2, 13
SET UP CAUTIOUSLY
• Be judicious about how you use setUp/tearDown
• Think like middleware--do I need this for every test in this case?
• One inefficient computation can cripple a large test case
Monday, September 2, 13
Monday, September 2, 13
SET UP CAUTIOUSLY
• Take advantage of setUpClass /
tearDownClass
• Runs once per test case
• Effective for read-only data that
is not altered by tests
• Your data will persist
between tests!
Monday, September 2, 13
THE DATABASE IS HOT LAVA
Monday, September 2, 13
XKCD.COM/735/
Monday, September 2, 13
THE DATABASE IS HOT LAVA
• If you touch it you’ll die
• Not really, but it’s one of slowest things your application will do in a unit test
• Work with read-only, non persisted data
• use in-memory model instances
Monday, September 2, 13
THE DATABASE IS HOT LAVA
• Avoid fixtures. Fixtures add lots of database machinery to tests
• Loaded/purged between each test in a case
• Fixtures don’t adapt with your data model
• Schema changes will often result in test failures
• Not much need for django.test.TestCase
• When you do write: in-memory database (SQLite)
Monday, September 2, 13
Monday, September 2, 13
FAKE IT ‘TILYOU MAKE IT WITH MOCK
Monday, September 2, 13
FAKE IT ‘TILYOU MAKE IT WITH MOCK
• Mock is a library for creating programmable stub objects
• Mock objects can be configured to emulate other objects/structures
• Configure specific behavior for just for testing
• Gets rid of unnecessary overhead
Monday, September 2, 13
FAKE IT ‘TILYOU MAKE IT WITH MOCK
• Use mock to emulate model instances
• Set the attributes you need for testing
directly
• Use the spec argument to give
guidelines
• No Model/ORM overhead
Monday, September 2, 13
FAKE IT ‘TILYOU MAKE IT WITH MOCK
• Use mock.patch to focus your tests
• Patch in configurable mock objects to
sys.modules
• Alter the behavior of code imported
elsewhere
• Eliminate branches you are not
interested in testing
Monday, September 2, 13
FAKE IT ‘TILYOU MAKE IT WITH MOCK
Monday, September 2, 13
FAKE IT ‘TILYOU MAKE IT WITH MOCK
• Use mock in more complex situations
• mock.patch.multiple decorator lets you patch multiple module references
simultaneously
• Track the way objects are used
• Mock.assert_has_calls, Mock.assert_called_with
• many, many more: http://www.voidspace.org.uk/python/mock/
Monday, September 2, 13
IT’S OKAYTO ENGINEER WHENTESTING
Monday, September 2, 13
IT’S OKAYTO ENGINEER WHENTESTING
• Don’t be afraid to invest engineering effort into your test suite
• Your tests are Python code--take advantage of it!
• Write tools to help you test
• Leverage 3rd party tools (mock, django-nose)
• Decorators, custom test runners
• If you can’t test the code efficiently, refactor the code!
Monday, September 2, 13
HOW SLOWTESTINGYIELDED
EFFECTIVETESTING
Monday, September 2, 13
HOW SLOWTESTINGYIELDED
EFFECTIVETESTING
• Started out working towards speed
• In order to write fast tests, we had to rethink how we tested
• Developed an efficient test philosophy
• Resulted in much more effective tests, and ultimately better code
Monday, September 2, 13
THANKYOU!
Casey Kinsey
Consultant, Celerity
Slides available online:
Internets
www.caseykinsey.com
www.celerity.com
Twitter
@cordiskinsey
@CelerityITLLC
Monday, September 2, 13

More Related Content

What's hot

It Sounded Good on Paper - Lessons Learned with Puppet
It Sounded Good on Paper - Lessons Learned with PuppetIt Sounded Good on Paper - Lessons Learned with Puppet
It Sounded Good on Paper - Lessons Learned with PuppetJeffery Smith
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with CypressYong Shean Chong
 
Why you should switch to Cypress for modern web testing?
Why you should switch to Cypress for modern web testing?Why you should switch to Cypress for modern web testing?
Why you should switch to Cypress for modern web testing?Shivam Bharadwaj
 
Capybara testing
Capybara testingCapybara testing
Capybara testingFutureworkz
 
Introduction to Integration Testing With Cypress
Introduction to Integration Testing With CypressIntroduction to Integration Testing With Cypress
Introduction to Integration Testing With CypressErez Cohen
 
Test driven development_continuous_integration
Test driven development_continuous_integrationTest driven development_continuous_integration
Test driven development_continuous_integrationhaochenglee
 
Cypress vs Selenium WebDriver: Better, Or Just Different? -- by Gil Tayar
Cypress vs Selenium WebDriver: Better, Or Just Different? -- by Gil TayarCypress vs Selenium WebDriver: Better, Or Just Different? -- by Gil Tayar
Cypress vs Selenium WebDriver: Better, Or Just Different? -- by Gil TayarApplitools
 
[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScriptHazem Saleh
 
Automating Software Releases (Dallas/Ft. Worth Perl Mongers 2004)
Automating Software Releases (Dallas/Ft. Worth Perl Mongers 2004)Automating Software Releases (Dallas/Ft. Worth Perl Mongers 2004)
Automating Software Releases (Dallas/Ft. Worth Perl Mongers 2004)brian d foy
 
WordPress automation and CI
WordPress automation and CIWordPress automation and CI
WordPress automation and CIRan Bar-Zik
 
From devOps to front end Ops, test first
From devOps to front end Ops, test firstFrom devOps to front end Ops, test first
From devOps to front end Ops, test firstCaesar Chi
 
Helpful Automation Techniques - Selenium Camp 2014
Helpful Automation Techniques - Selenium Camp 2014Helpful Automation Techniques - Selenium Camp 2014
Helpful Automation Techniques - Selenium Camp 2014Justin Ison
 
Automated Infrastructure Testing
Automated Infrastructure TestingAutomated Infrastructure Testing
Automated Infrastructure TestingRanjib Dey
 
DevOps叢林裡的小隊游擊戰術 (@ iThome DevOps 2015)
DevOps叢林裡的小隊游擊戰術 (@ iThome DevOps 2015)DevOps叢林裡的小隊游擊戰術 (@ iThome DevOps 2015)
DevOps叢林裡的小隊游擊戰術 (@ iThome DevOps 2015)Chen Cheng-Wei
 
Nightwatch JS for End to End Tests
Nightwatch JS for End to End TestsNightwatch JS for End to End Tests
Nightwatch JS for End to End TestsSriram Angajala
 
[English][Test Girls] Zero to Hero: Start Test automation with Cypress
[English][Test Girls] Zero to Hero: Start Test automation with Cypress[English][Test Girls] Zero to Hero: Start Test automation with Cypress
[English][Test Girls] Zero to Hero: Start Test automation with CypressTest Girls
 

What's hot (20)

It Sounded Good on Paper - Lessons Learned with Puppet
It Sounded Good on Paper - Lessons Learned with PuppetIt Sounded Good on Paper - Lessons Learned with Puppet
It Sounded Good on Paper - Lessons Learned with Puppet
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with Cypress
 
Why you should switch to Cypress for modern web testing?
Why you should switch to Cypress for modern web testing?Why you should switch to Cypress for modern web testing?
Why you should switch to Cypress for modern web testing?
 
Capybara testing
Capybara testingCapybara testing
Capybara testing
 
Introduction to Integration Testing With Cypress
Introduction to Integration Testing With CypressIntroduction to Integration Testing With Cypress
Introduction to Integration Testing With Cypress
 
Test driven development_continuous_integration
Test driven development_continuous_integrationTest driven development_continuous_integration
Test driven development_continuous_integration
 
Speed = $$$
Speed = $$$Speed = $$$
Speed = $$$
 
Cypress vs Selenium WebDriver: Better, Or Just Different? -- by Gil Tayar
Cypress vs Selenium WebDriver: Better, Or Just Different? -- by Gil TayarCypress vs Selenium WebDriver: Better, Or Just Different? -- by Gil Tayar
Cypress vs Selenium WebDriver: Better, Or Just Different? -- by Gil Tayar
 
[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript
 
Automating Software Releases (Dallas/Ft. Worth Perl Mongers 2004)
Automating Software Releases (Dallas/Ft. Worth Perl Mongers 2004)Automating Software Releases (Dallas/Ft. Worth Perl Mongers 2004)
Automating Software Releases (Dallas/Ft. Worth Perl Mongers 2004)
 
Integration testing - A&BP CC
Integration testing - A&BP CCIntegration testing - A&BP CC
Integration testing - A&BP CC
 
WordPress automation and CI
WordPress automation and CIWordPress automation and CI
WordPress automation and CI
 
Testing In Django
Testing In DjangoTesting In Django
Testing In Django
 
From devOps to front end Ops, test first
From devOps to front end Ops, test firstFrom devOps to front end Ops, test first
From devOps to front end Ops, test first
 
Helpful Automation Techniques - Selenium Camp 2014
Helpful Automation Techniques - Selenium Camp 2014Helpful Automation Techniques - Selenium Camp 2014
Helpful Automation Techniques - Selenium Camp 2014
 
Automated Infrastructure Testing
Automated Infrastructure TestingAutomated Infrastructure Testing
Automated Infrastructure Testing
 
DevOps叢林裡的小隊游擊戰術 (@ iThome DevOps 2015)
DevOps叢林裡的小隊游擊戰術 (@ iThome DevOps 2015)DevOps叢林裡的小隊游擊戰術 (@ iThome DevOps 2015)
DevOps叢林裡的小隊游擊戰術 (@ iThome DevOps 2015)
 
Nightwatch JS for End to End Tests
Nightwatch JS for End to End TestsNightwatch JS for End to End Tests
Nightwatch JS for End to End Tests
 
[English][Test Girls] Zero to Hero: Start Test automation with Cypress
[English][Test Girls] Zero to Hero: Start Test automation with Cypress[English][Test Girls] Zero to Hero: Start Test automation with Cypress
[English][Test Girls] Zero to Hero: Start Test automation with Cypress
 
Automate Yo' Self
Automate Yo' SelfAutomate Yo' Self
Automate Yo' Self
 

Viewers also liked

12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best PracticesDavid Arcos
 
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With DjangoEric Satterwhite
 
Django: Advanced Models
Django: Advanced ModelsDjango: Advanced Models
Django: Advanced ModelsYing-An Lai
 
Dive into sentry
Dive into sentryDive into sentry
Dive into sentryLeo Zhou
 
Introduction openstack-horizon
Introduction openstack-horizonIntroduction openstack-horizon
Introduction openstack-horizonbobo52310
 
OpenStack Horizon: Controlling the Cloud using Django
OpenStack Horizon: Controlling the Cloud using DjangoOpenStack Horizon: Controlling the Cloud using Django
OpenStack Horizon: Controlling the Cloud using DjangoDavid Lapsley
 
Introduction to sentry
Introduction to sentryIntroduction to sentry
Introduction to sentrymozillazg
 
Efficient Django
Efficient DjangoEfficient Django
Efficient DjangoDavid Arcos
 
Sentry - An Introduction
Sentry - An Introduction Sentry - An Introduction
Sentry - An Introduction Alexander Alten
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of DjangoJacob Kaplan-Moss
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 

Viewers also liked (13)

12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best Practices
 
Django Best Practices
Django Best PracticesDjango Best Practices
Django Best Practices
 
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With Django
 
Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 
Django: Advanced Models
Django: Advanced ModelsDjango: Advanced Models
Django: Advanced Models
 
Dive into sentry
Dive into sentryDive into sentry
Dive into sentry
 
Introduction openstack-horizon
Introduction openstack-horizonIntroduction openstack-horizon
Introduction openstack-horizon
 
OpenStack Horizon: Controlling the Cloud using Django
OpenStack Horizon: Controlling the Cloud using DjangoOpenStack Horizon: Controlling the Cloud using Django
OpenStack Horizon: Controlling the Cloud using Django
 
Introduction to sentry
Introduction to sentryIntroduction to sentry
Introduction to sentry
 
Efficient Django
Efficient DjangoEfficient Django
Efficient Django
 
Sentry - An Introduction
Sentry - An Introduction Sentry - An Introduction
Sentry - An Introduction
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 

Similar to DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django

Continuous Automated Regression Testing to the Rescue
Continuous Automated Regression Testing to the RescueContinuous Automated Regression Testing to the Rescue
Continuous Automated Regression Testing to the RescueTechWell
 
Boston MeetUp 10.10
Boston MeetUp 10.10Boston MeetUp 10.10
Boston MeetUp 10.10Solano Labs
 
Keeping your users happy with testable apps - Greg Shackles
Keeping your users happy with testable apps - Greg ShacklesKeeping your users happy with testable apps - Greg Shackles
Keeping your users happy with testable apps - Greg ShacklesXamarin
 
[DPE Summit] How Improving the Testing Experience Goes Beyond Quality: A Deve...
[DPE Summit] How Improving the Testing Experience Goes Beyond Quality: A Deve...[DPE Summit] How Improving the Testing Experience Goes Beyond Quality: A Deve...
[DPE Summit] How Improving the Testing Experience Goes Beyond Quality: A Deve...Roberto Pérez Alcolea
 
So long, and thanks for all the tests (Scottish Developers 2014)
So long, and thanks for all the tests (Scottish Developers 2014)So long, and thanks for all the tests (Scottish Developers 2014)
So long, and thanks for all the tests (Scottish Developers 2014)Seb Rose
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Grzegorz Miejski
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildAndrei Sebastian Cîmpean
 
Implementing Continuous Integration in .NET for Cheapskates
Implementing Continuous Integration in .NET for CheapskatesImplementing Continuous Integration in .NET for Cheapskates
Implementing Continuous Integration in .NET for Cheapskatesmhenroid
 
Automated testing san francisco oct 2013
Automated testing san francisco oct 2013Automated testing san francisco oct 2013
Automated testing san francisco oct 2013Solano Labs
 
Plone Testing Tools And Techniques
Plone Testing Tools And TechniquesPlone Testing Tools And Techniques
Plone Testing Tools And TechniquesJordan Baker
 
Solano Labs presented at MassTLC's automated testing
Solano Labs presented at MassTLC's automated testingSolano Labs presented at MassTLC's automated testing
Solano Labs presented at MassTLC's automated testingMassTLC
 
Agile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayAgile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayJordi Pradel
 
jQuery Mobile Deep Dive
jQuery Mobile Deep DivejQuery Mobile Deep Dive
jQuery Mobile Deep DiveTroy Miles
 
So you-want-to-go-faster
So you-want-to-go-fasterSo you-want-to-go-faster
So you-want-to-go-fasterOoblioob
 
Load testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew SiemerLoad testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew SiemerAndrew Siemer
 
Project Onion unit test environment
Project Onion unit test environmentProject Onion unit test environment
Project Onion unit test environmentAbhinav Jha
 
Practical unit testing in c & c++
Practical unit testing in c & c++Practical unit testing in c & c++
Practical unit testing in c & c++Matt Hargett
 
Re:Inventing your Innovation Cycle by Scaling Out with Spot Instances (CPN207...
Re:Inventing your Innovation Cycle by Scaling Out with Spot Instances (CPN207...Re:Inventing your Innovation Cycle by Scaling Out with Spot Instances (CPN207...
Re:Inventing your Innovation Cycle by Scaling Out with Spot Instances (CPN207...Amazon Web Services
 

Similar to DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django (20)

NYC MeetUp 10.9
NYC MeetUp 10.9NYC MeetUp 10.9
NYC MeetUp 10.9
 
Continuous Automated Regression Testing to the Rescue
Continuous Automated Regression Testing to the RescueContinuous Automated Regression Testing to the Rescue
Continuous Automated Regression Testing to the Rescue
 
Boston MeetUp 10.10
Boston MeetUp 10.10Boston MeetUp 10.10
Boston MeetUp 10.10
 
Keeping your users happy with testable apps - Greg Shackles
Keeping your users happy with testable apps - Greg ShacklesKeeping your users happy with testable apps - Greg Shackles
Keeping your users happy with testable apps - Greg Shackles
 
[DPE Summit] How Improving the Testing Experience Goes Beyond Quality: A Deve...
[DPE Summit] How Improving the Testing Experience Goes Beyond Quality: A Deve...[DPE Summit] How Improving the Testing Experience Goes Beyond Quality: A Deve...
[DPE Summit] How Improving the Testing Experience Goes Beyond Quality: A Deve...
 
So long, and thanks for all the tests (Scottish Developers 2014)
So long, and thanks for all the tests (Scottish Developers 2014)So long, and thanks for all the tests (Scottish Developers 2014)
So long, and thanks for all the tests (Scottish Developers 2014)
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
 
Implementing Continuous Integration in .NET for Cheapskates
Implementing Continuous Integration in .NET for CheapskatesImplementing Continuous Integration in .NET for Cheapskates
Implementing Continuous Integration in .NET for Cheapskates
 
Automated testing san francisco oct 2013
Automated testing san francisco oct 2013Automated testing san francisco oct 2013
Automated testing san francisco oct 2013
 
Plone Testing Tools And Techniques
Plone Testing Tools And TechniquesPlone Testing Tools And Techniques
Plone Testing Tools And Techniques
 
Solano Labs presented at MassTLC's automated testing
Solano Labs presented at MassTLC's automated testingSolano Labs presented at MassTLC's automated testing
Solano Labs presented at MassTLC's automated testing
 
Agile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayAgile Software Testing the Agilogy Way
Agile Software Testing the Agilogy Way
 
jQuery Mobile Deep Dive
jQuery Mobile Deep DivejQuery Mobile Deep Dive
jQuery Mobile Deep Dive
 
So you-want-to-go-faster
So you-want-to-go-fasterSo you-want-to-go-faster
So you-want-to-go-faster
 
Load testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew SiemerLoad testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew Siemer
 
Project Onion unit test environment
Project Onion unit test environmentProject Onion unit test environment
Project Onion unit test environment
 
Practical unit testing in c & c++
Practical unit testing in c & c++Practical unit testing in c & c++
Practical unit testing in c & c++
 
Re:Inventing your Innovation Cycle by Scaling Out with Spot Instances (CPN207...
Re:Inventing your Innovation Cycle by Scaling Out with Spot Instances (CPN207...Re:Inventing your Innovation Cycle by Scaling Out with Spot Instances (CPN207...
Re:Inventing your Innovation Cycle by Scaling Out with Spot Instances (CPN207...
 
Unit testing in Unity
Unit testing in UnityUnit testing in Unity
Unit testing in Unity
 

Recently uploaded

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
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.pdfsudhanshuwaghmare1
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Recently uploaded (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django

  • 1. How to Write Fast and Efficient Unit Tests in Django Casey Kinsey DjangoCon 2013 Monday, September 2, 13
  • 2. A REAL NEED FORTEST SPEED Monday, September 2, 13
  • 3. A REAL NEED FORTEST SPEED • Made an initial production release of a real product for a national media company • Test coverage was not great • Started seeing regressions in subsequent releases • Decided to aggressively pursue greater test coverage • Results were successful, but one thing clear: As test coverage increased we had an acute need for faster test suites. Monday, September 2, 13
  • 4. WHY SHOULD I BE CONCERNED WITH UNITTEST SPEED? • If you’re serious about testing, you’re serious about at least two things: • Having lots of tests • Running those tests frequently Monday, September 2, 13
  • 5. •A slow test suite gets in the way of your testing goals because: •Developers will avoid running tests •Preparing code for integration becomes painful •Deployment speed is directly affected Monday, September 2, 13
  • 6. THE FIRST STEPTO FASTER UNITTESTS: WRITE UNITTESTS Monday, September 2, 13
  • 7. UNITTESTSVS INTEGRATIONTESTS • Many Django project test suites are comprised mostly of integration tests • What is a UnitTest? • UnitTests cover a small “unit” of code • Ideally, these units include as few branches as possible • What is an IntegrationTest? • IntegrationTests test the contracts between your “units” Monday, September 2, 13
  • 8. UNITTESTSVS INTEGRATIONTESTS • Django test client is an integration test dead giveaway • The test client covers way more than you are interested in testing • URL Routing, Request Middleware, ORM,Template Rendering, Response Middleware, etc Monday, September 2, 13
  • 9. UNITTESTSVS INTEGRATIONTESTS • A good unit tests covers code that is limited in functionality/scope • Ideally, a single method with limited external calls Monday, September 2, 13
  • 10. UNITTESTSVS INTEGRATIONTESTS • Establish a good ratio of unit tests to integration tests. An example may be: • for each method that contains business logic, there should exist a unit test • for each page/view/user path of your project, there should exist an integration test • YMMV Monday, September 2, 13
  • 11. SET UP CAUTIOUSLY Monday, September 2, 13
  • 12. SET UP CAUTIOUSLY • Be judicious about how you use setUp/tearDown • Think like middleware--do I need this for every test in this case? • One inefficient computation can cripple a large test case Monday, September 2, 13
  • 14. SET UP CAUTIOUSLY • Take advantage of setUpClass / tearDownClass • Runs once per test case • Effective for read-only data that is not altered by tests • Your data will persist between tests! Monday, September 2, 13
  • 15. THE DATABASE IS HOT LAVA Monday, September 2, 13
  • 17. THE DATABASE IS HOT LAVA • If you touch it you’ll die • Not really, but it’s one of slowest things your application will do in a unit test • Work with read-only, non persisted data • use in-memory model instances Monday, September 2, 13
  • 18. THE DATABASE IS HOT LAVA • Avoid fixtures. Fixtures add lots of database machinery to tests • Loaded/purged between each test in a case • Fixtures don’t adapt with your data model • Schema changes will often result in test failures • Not much need for django.test.TestCase • When you do write: in-memory database (SQLite) Monday, September 2, 13
  • 20. FAKE IT ‘TILYOU MAKE IT WITH MOCK Monday, September 2, 13
  • 21. FAKE IT ‘TILYOU MAKE IT WITH MOCK • Mock is a library for creating programmable stub objects • Mock objects can be configured to emulate other objects/structures • Configure specific behavior for just for testing • Gets rid of unnecessary overhead Monday, September 2, 13
  • 22. FAKE IT ‘TILYOU MAKE IT WITH MOCK • Use mock to emulate model instances • Set the attributes you need for testing directly • Use the spec argument to give guidelines • No Model/ORM overhead Monday, September 2, 13
  • 23. FAKE IT ‘TILYOU MAKE IT WITH MOCK • Use mock.patch to focus your tests • Patch in configurable mock objects to sys.modules • Alter the behavior of code imported elsewhere • Eliminate branches you are not interested in testing Monday, September 2, 13
  • 24. FAKE IT ‘TILYOU MAKE IT WITH MOCK Monday, September 2, 13
  • 25. FAKE IT ‘TILYOU MAKE IT WITH MOCK • Use mock in more complex situations • mock.patch.multiple decorator lets you patch multiple module references simultaneously • Track the way objects are used • Mock.assert_has_calls, Mock.assert_called_with • many, many more: http://www.voidspace.org.uk/python/mock/ Monday, September 2, 13
  • 26. IT’S OKAYTO ENGINEER WHENTESTING Monday, September 2, 13
  • 27. IT’S OKAYTO ENGINEER WHENTESTING • Don’t be afraid to invest engineering effort into your test suite • Your tests are Python code--take advantage of it! • Write tools to help you test • Leverage 3rd party tools (mock, django-nose) • Decorators, custom test runners • If you can’t test the code efficiently, refactor the code! Monday, September 2, 13
  • 29. HOW SLOWTESTINGYIELDED EFFECTIVETESTING • Started out working towards speed • In order to write fast tests, we had to rethink how we tested • Developed an efficient test philosophy • Resulted in much more effective tests, and ultimately better code Monday, September 2, 13
  • 30. THANKYOU! Casey Kinsey Consultant, Celerity Slides available online: Internets www.caseykinsey.com www.celerity.com Twitter @cordiskinsey @CelerityITLLC Monday, September 2, 13

Editor's Notes

  1. Remember, you are winding down here!
  2. Remember, you are winding down here!