SlideShare uma empresa Scribd logo
1 de 13
unittest
in five minutes



Ray Toal   2011-10-22
How to unit test

• Not manually, that's for sure
• You write code that exercises your code
• Perform assertions that record
  o that you get the results you expect for various inputs
  o that exceptions are raised when they should be
• Pay attention to edge cases
Test-driven development
• Write some tests (yes, first)
• Run them
  o They will fail because the code isn't written yet. That
    is supposed to happen. Good news is you will know
    the tests run.
• Write some code
• Now run the tests again
• Work until the tests pass
• Iterate!
Unit testing in Python

• The module unittest is already there
• Docs
• Python 2.7
• Python 3
• Also see
• The unit testing chapter from Dive Into
     Python
•   Are there alternatives to unittest? See what
    they say on StackOverflow
A first example

• Let's write a function to interleave two lists
• It will be okay if one list is longer than the
    other
•   Before we start writing the code, we should
    know what the function should produce for all
    types of inputs:
     interleave([], []) ☞ []
     interleave([1,5,3], ["hello"]) ☞
     [1,"hello",5,3]
     interleave([True], [[], 8]) ☞ [True, [],
     8]
Write the test first(interleavetest.py)

from interleave import interleave
import unittest


class TestGettingStartedFunctions(unittest.TestCase):
 def test_interleave(self):
       cases = [
           ([], [], []),
           ([1, 4, 6], [], [1, 4, 6]),
           ([], [2, 3], [2, 3]),
           ([1], [9], [1, 9]),
           ([8, 8, 3, 9], [1], [8, 1, 8, 3, 9]),
           ([2], [7, 8, 9], [2, 7, 8, 9]),
       ]
       for a, b, expected in cases:
           self.assertEqual(interleave(a, b), expected)
Write a stub (interleave.py)

def interleave(a, b):
    return None
Run the test

$ python interleavetest.py
F
======================================================================
FAIL: test_interleave (__main__.TestGettingStartedFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
    File "interleavetest.py", line 15, in test_interleave
     self.assertEqual(interleave(a, b), expected)
AssertionError: None != []


----------------------------------------------------------------------
Ran 1 test in 0.000s


FAILED (failures=1)
Now write the code
def interleave(a, b):
   """Return the interleaving of two sequences as a list."""
   return [y for x in izip_longest(a, b) for y in x if y is not None]
Test again

$ python interleavetest.py
E
======================================================================
ERROR: test_interleave (__main__.TestGettingStartedFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
    File "interleavetest.py", line 15, in test_interleave
      self.assertEqual(interleave(a, b), expected)
    File "/Users/raytoal/scratch/interleave.py", line 3, in interleave
      return [y for x in izip_longest(a, b) for y in x if y is not None]
NameError: global name 'izip_longest' is not defined


----------------------------------------------------------------------
Ran 1 test in 0.000s


FAILED (errors=1)
Fix the code
from itertools import izip_longest


def interleave(a, b):
   """Return the interleaving of two sequences as a list."""
   return [y for x in izip_longest(a, b) for y in x if y is not None]
Rerun the test
$ python interleavetest.py
.
-------------------------------------------------------------
Ran 1 test in 0.000s


OK
kthx

Mais conteúdo relacionado

Mais procurados

Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
Testes pythonicos com pytest
Testes pythonicos com pytestTestes pythonicos com pytest
Testes pythonicos com pytestviniciusban
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyonddn
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 
Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Andrea Francia
 
Py.test
Py.testPy.test
Py.testsoasme
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHPRadu Murzea
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingRam Awadh Prasad, PMP
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo cleanHector Canto
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkHumberto Marchezi
 
Automated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationAutomated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationBarbara Jones
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksLohika_Odessa_TechTalks
 

Mais procurados (20)

Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit TestingPython Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit Testing
 
Testes pythonicos com pytest
Testes pythonicos com pytestTestes pythonicos com pytest
Testes pythonicos com pytest
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008
 
Py.test
Py.testPy.test
Py.test
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHP
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo clean
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing Framework
 
Automated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationAutomated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and Validation
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Phpunit testing
Phpunit testingPhpunit testing
Phpunit testing
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 

Destaque

Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with PythonMicroPyramid .
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With PytestEddy Reyes
 
2014/07/07 Software Testing - Truong Anh Hoang
2014/07/07 Software Testing - Truong Anh Hoang 2014/07/07 Software Testing - Truong Anh Hoang
2014/07/07 Software Testing - Truong Anh Hoang Vu Hung Nguyen
 
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...Ho Chi Minh City Software Testing Club
 
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...Ho Chi Minh City Software Testing Club
 
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...Ho Chi Minh City Software Testing Club
 
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...Ho Chi Minh City Software Testing Club
 
Introduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang Phi
Introduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang PhiIntroduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang Phi
Introduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang PhiHo Chi Minh City Software Testing Club
 

Destaque (20)

Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
2014/07/07 Software Testing - Truong Anh Hoang
2014/07/07 Software Testing - Truong Anh Hoang 2014/07/07 Software Testing - Truong Anh Hoang
2014/07/07 Software Testing - Truong Anh Hoang
 
Web API Test Automation Using Frisby & Node.js
Web API Test Automation Using Frisby  & Node.jsWeb API Test Automation Using Frisby  & Node.js
Web API Test Automation Using Frisby & Node.js
 
Common Web UI Problems Transforming Manual to Automation
Common Web UI Problems Transforming Manual to Automation Common Web UI Problems Transforming Manual to Automation
Common Web UI Problems Transforming Manual to Automation
 
Security testing-What can we do - Trinh Minh Hien
Security testing-What can we do - Trinh Minh HienSecurity testing-What can we do - Trinh Minh Hien
Security testing-What can we do - Trinh Minh Hien
 
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
 
[HCMC STC Jan 2015] Practical Experiences In Test Automation
[HCMC STC Jan 2015] Practical Experiences In Test Automation[HCMC STC Jan 2015] Practical Experiences In Test Automation
[HCMC STC Jan 2015] Practical Experiences In Test Automation
 
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
 
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
 
[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios
[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios
[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios
 
Building an effective mobile testing strategy
Building an effective mobile testing strategyBuilding an effective mobile testing strategy
Building an effective mobile testing strategy
 
Agile Testing - Not Just Tester’s Story _ Dang Thanh Long
Agile Testing - Not Just Tester’s Story _ Dang Thanh LongAgile Testing - Not Just Tester’s Story _ Dang Thanh Long
Agile Testing - Not Just Tester’s Story _ Dang Thanh Long
 
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
 
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
 
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang MinhTest Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
 
Analytical Risk-based and Specification-based Testing - Bui Duy Tam
Analytical Risk-based and Specification-based Testing - Bui Duy TamAnalytical Risk-based and Specification-based Testing - Bui Duy Tam
Analytical Risk-based and Specification-based Testing - Bui Duy Tam
 
[HCMC STC Jan 2015] Risk-Based Software Testing Approaches
[HCMC STC Jan 2015] Risk-Based Software Testing Approaches[HCMC STC Jan 2015] Risk-Based Software Testing Approaches
[HCMC STC Jan 2015] Risk-Based Software Testing Approaches
 
Introduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang Phi
Introduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang PhiIntroduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang Phi
Introduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang Phi
 

Semelhante a unittest in 5 minutes

Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittestFariz Darari
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Fariz Darari
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slidesericholscher
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovyTed Leung
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
DSR Testing (Part 1)
DSR Testing (Part 1)DSR Testing (Part 1)
DSR Testing (Part 1)Steve Upton
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드ksain
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patternsTomasz Kowal
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanWei-Yuan Chang
 
Automated Testing in Django
Automated Testing in DjangoAutomated Testing in Django
Automated Testing in DjangoLoek van Gent
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring QualityKent Cowgill
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaRobot Media
 

Semelhante a unittest in 5 minutes (20)

Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
 
Writing tests
Writing testsWriting tests
Writing tests
 
Auto testing!
Auto testing!Auto testing!
Auto testing!
 
UPC Testing talk 2
UPC Testing talk 2UPC Testing talk 2
UPC Testing talk 2
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Unit Testing with Foq
Unit Testing with FoqUnit Testing with Foq
Unit Testing with Foq
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - Groovy
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
DSR Testing (Part 1)
DSR Testing (Part 1)DSR Testing (Part 1)
DSR Testing (Part 1)
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Automated Testing in Django
Automated Testing in DjangoAutomated Testing in Django
Automated Testing in Django
 
Testing in Django
Testing in DjangoTesting in Django
Testing in Django
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
 

Mais de Ray Toal

Git workshop
Git workshopGit workshop
Git workshopRay Toal
 
Learning and Modern Programming Languages
Learning and Modern Programming LanguagesLearning and Modern Programming Languages
Learning and Modern Programming LanguagesRay Toal
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
Convention-Based Syntactic Descriptions
Convention-Based Syntactic DescriptionsConvention-Based Syntactic Descriptions
Convention-Based Syntactic DescriptionsRay Toal
 
An Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesAn Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesRay Toal
 
Economics of Open Source Software
Economics of Open Source SoftwareEconomics of Open Source Software
Economics of Open Source SoftwareRay Toal
 
Modeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesModeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesRay Toal
 

Mais de Ray Toal (7)

Git workshop
Git workshopGit workshop
Git workshop
 
Learning and Modern Programming Languages
Learning and Modern Programming LanguagesLearning and Modern Programming Languages
Learning and Modern Programming Languages
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Convention-Based Syntactic Descriptions
Convention-Based Syntactic DescriptionsConvention-Based Syntactic Descriptions
Convention-Based Syntactic Descriptions
 
An Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesAn Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax Trees
 
Economics of Open Source Software
Economics of Open Source SoftwareEconomics of Open Source Software
Economics of Open Source Software
 
Modeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesModeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based Games
 

Último

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

unittest in 5 minutes

  • 2. How to unit test • Not manually, that's for sure • You write code that exercises your code • Perform assertions that record o that you get the results you expect for various inputs o that exceptions are raised when they should be • Pay attention to edge cases
  • 3. Test-driven development • Write some tests (yes, first) • Run them o They will fail because the code isn't written yet. That is supposed to happen. Good news is you will know the tests run. • Write some code • Now run the tests again • Work until the tests pass • Iterate!
  • 4. Unit testing in Python • The module unittest is already there • Docs • Python 2.7 • Python 3 • Also see • The unit testing chapter from Dive Into Python • Are there alternatives to unittest? See what they say on StackOverflow
  • 5. A first example • Let's write a function to interleave two lists • It will be okay if one list is longer than the other • Before we start writing the code, we should know what the function should produce for all types of inputs: interleave([], []) ☞ [] interleave([1,5,3], ["hello"]) ☞ [1,"hello",5,3] interleave([True], [[], 8]) ☞ [True, [], 8]
  • 6. Write the test first(interleavetest.py) from interleave import interleave import unittest class TestGettingStartedFunctions(unittest.TestCase): def test_interleave(self): cases = [ ([], [], []), ([1, 4, 6], [], [1, 4, 6]), ([], [2, 3], [2, 3]), ([1], [9], [1, 9]), ([8, 8, 3, 9], [1], [8, 1, 8, 3, 9]), ([2], [7, 8, 9], [2, 7, 8, 9]), ] for a, b, expected in cases: self.assertEqual(interleave(a, b), expected)
  • 7. Write a stub (interleave.py) def interleave(a, b): return None
  • 8. Run the test $ python interleavetest.py F ====================================================================== FAIL: test_interleave (__main__.TestGettingStartedFunctions) ---------------------------------------------------------------------- Traceback (most recent call last): File "interleavetest.py", line 15, in test_interleave self.assertEqual(interleave(a, b), expected) AssertionError: None != [] ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (failures=1)
  • 9. Now write the code def interleave(a, b): """Return the interleaving of two sequences as a list.""" return [y for x in izip_longest(a, b) for y in x if y is not None]
  • 10. Test again $ python interleavetest.py E ====================================================================== ERROR: test_interleave (__main__.TestGettingStartedFunctions) ---------------------------------------------------------------------- Traceback (most recent call last): File "interleavetest.py", line 15, in test_interleave self.assertEqual(interleave(a, b), expected) File "/Users/raytoal/scratch/interleave.py", line 3, in interleave return [y for x in izip_longest(a, b) for y in x if y is not None] NameError: global name 'izip_longest' is not defined ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1)
  • 11. Fix the code from itertools import izip_longest def interleave(a, b): """Return the interleaving of two sequences as a list.""" return [y for x in izip_longest(a, b) for y in x if y is not None]
  • 12. Rerun the test $ python interleavetest.py . ------------------------------------------------------------- Ran 1 test in 0.000s OK
  • 13. kthx