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
 
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 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 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

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

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!