SlideShare a Scribd company logo
Test Driven Development in Python




      Siddharta Govindaraj
  siddharta@silverstripesoftware.com
What is Test Driven Development (TDD)?




http://www.flickr.com/photos/johnsyweb/3051647719/
Red, Green, Refactor

●   First write a test
●   Write code to pass the
    test
●   Clean up the code
●   Repeat
TDD Example




Write a function to check whether a given input
             string is a palindrome
code.py
def is_palindrome(input_str):
    pass
tests.py
from code import is_palindrome


def test_function_should_accept_palindromic_words():
    input = "noon"
    assert is_palindrome(input) == True
Result
code.py
def is_palindrome(input_str):
    return input_str == input_str[::-1]
Result
tests.py
def test_function_should_ignore_case():
    input = "Noon"
    assert is_palindrome(input) == True
Result
code.py
def is_palindrome(input_str):
    input_clean = input_str.lower()
    return input_clean == input_clean[::-1]
Result
tests.py
def test_function_should_ignore_trailing_space():
    input = "Noon   "
    assert is_palindrome(input) == True
code.py
def is_palindrome(input_str):
    input_clean = input_str.strip().lower()
    return input_clean == input_clean[::-1]
tests.py
def test_function_should_ignore_spaces_in_text():
    input = "ab raca carba"
    assert is_palindrome(input) == True
code.py
def is_palindrome(input_str):
    input_stripped = input_str.replace(" ", "")
    input_clean = input_stripped.lower()
    return input_clean == input_clean[::-1]
tests.py
def test_function_should_handle_combined_characters():
    input = u"u0bb4u0bbfuu0b95u0bb4u0bbf"
    assert is_palindrome(input) == True



                 (Input is ழ கழ )
Reversing unicode strings

The String: ழ கழ
Characters: ழ + ி + க + ழ + ி
Wrong: ி + ழ + க + ி + ழ
Right: ழ + ி + க + ழ + ி
# naïve implementation to pass the test



def is_palindrome(input_str):

   def reverse_string(input_str):

       def is_combining_char(char):

           chars = [u"u0bcd"]

           return char in chars

       reversed_chars = []

       for char in input_str:

           if is_combining_char(char): reversed_chars.insert(1, char)

           else: reversed_chars.insert(0, char)

       return "".join(reversed_chars)

   input_stripped = input_str.replace(" ", "")

   input_clean = input_stripped.lower()

   reversed_string = reverse_string(input_clean)

   return input_clean == reversed_string
And so it continues...

●   Turns out reversing a string is quite complex
    when unicode scripts come into the picture
●   Many different cases to consider
●   Unit tests can validate the complex code logic
    and check for regression errors
Why is unit testing important?

●   Quality
●   Regression
●   Safety Net
●   Integration with build
    and CI tools
●   Documentation
Attributes of good tests

●   Fast
●   Clear
●   Isolated
●   Reliable
Unit Testing in Python

●   We will look at three test frameworks
    ●   unittest
    ●   py.test
    ●   nose
What are we looking for?

●   Ease of writing tests    ●   xUnit output support
●   Ease of running tests    ●   Test →Doc
●   Test autodiscovery       ●   Code coverage
●   Running specific tests   ●   Code profiling
●   Running failed tests     ●   Parallel testing
●   Setup & teardown         ●   Interactive debug
unittest
import unittest


class TestPalindrome(unittest.TestCase):
    def test_function_should_accept_palindromes(self):
        input = “noon”
        self.assertTrue(is_palindrome(input))
unittest features

+ Similar to standard unit testing frameworks in
other languages (jUnit, Nunit...)
+ Included in base python standard library
+ Best IDE support
+ Maximum adoption
unittest features

– Inflexible, cumbersome, unpythonic
– Requires lots of boilerplate code to write code
– No test autodiscovery
– No support for running specific tests
– Limited support for setup and teardown
– No support for advanced test features
py.test
def test_function_should_accept_palindromic_words():
    input = "noon"
    assert is_palindrome(input) == True
py.test features

+ Test autodiscovery
+ Easy to write and run tests
+ Supports most of the advanced features –
parallel testing, parametrized tests, compatibility
with unittest, coverage, interactive debug
+ Good support for extensions
py.test features

– Not standard
– Lack of IDE support
nose
def test_function_should_accept_palindromic_words():
    input = "noon"
    assert is_palindrome(input) == True
nose features

+ Compatible with unittest
+ Supports all advanced features
+ Works well with Django, Pylons, Turbogears
+ Excellent plugin support
+ Supported by some IDEs
+ Most popular among alternative test frameworks
nose features

– Not standard
Some interesting plugins

●   Code coverage – Shows you how well your unit
    tests covers the code
●   Profiling – Measures the time taken by
    functions when running the tests
●   Parallel testing – Runs tests in parallel to speed
    things up
Other Interesting Features

●   Generative tests – Runs the same test sequence
    with different combinations of input data
●   Interactive debug – Drops into the python
    debugger on test failure
How we use nose
..Scriptspaver.exe test_django
---> test_django
.............
Ran 1302 tests in 262.391s


OK
Destroying test database...
How we use nose
..Scriptspaver.exe test_django --database=sqlite3
--exclude=south
---> test_django
.............
Ran 1274 tests in 128.359s


OK
Destroying test database...
How we use nose
..Scriptspaver.exe test_django metrics --with-coverage
--cover-package=metrics
Name                            Stmts   Exec   Cover
----------------------------------------------------------
metrics                             0      0    100%
metrics.cumulative_calculator      34     34    100%
metrics.models                     39     37     94%   48-49
metrics.throughput                 13     13    100%
metrics.views                     100     91     91%   20-
22, 33-35, 46-48
TOTAL                             186    175     94%
Nose Plugins - Spec
Test → Doc


class TestIsPalindrome(self)
    def test_should_accept_palindromic_words
    def test_function_should_ignore_case
    def test_function_should_ignore_trailing_space


IsPalindrome
 - Should accept palindromic words
 - Should ignore case
 - Should ignore trailing space
Nose Plugins - Xunit

●   Provides test result output in the standard xUnit
    xml format
●   This format can be read and integrated into
    standard continuous integration systems
Summary

Not much to choose between py.test and nose
nose is currently more popular
Use unittest if standardisation is important

More Related Content

What's hot

Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022
Sam Brannen
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Md. Enamul Haque Chowdhury
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
St. Petersburg College
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
Angel Garcia Olloqui
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
Richard Paul
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
Suraj Deshmukh
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
Hector Canto
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
David Berliner
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
Sugantha T
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
Fredrik Wendt
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
Francesco Garavaglia
 
Robot framework Gowthami Goli
Robot framework Gowthami GoliRobot framework Gowthami Goli
Robot framework Gowthami Goli
Gowthami Buddi
 
Fake It Outside-In TDD @XP2017
Fake It Outside-In TDD @XP2017Fake It Outside-In TDD @XP2017
Fake It Outside-In TDD @XP2017
David Völkel
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
Derek Smith
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
Arulalan T
 
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
Jacob Kaplan-Moss
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Kamal Acharya
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
NexThoughts Technologies
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
Maurice De Beijer [MVP]
 

What's hot (20)

Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Robot framework Gowthami Goli
Robot framework Gowthami GoliRobot framework Gowthami Goli
Robot framework Gowthami Goli
 
Fake It Outside-In TDD @XP2017
Fake It Outside-In TDD @XP2017Fake It Outside-In TDD @XP2017
Fake It Outside-In TDD @XP2017
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
 

Viewers also liked

Mock testing mit Python
Mock testing mit PythonMock testing mit Python
Mock testing mit Python
Timo Stollenwerk
 
Softwarequalitätssicherung mit Continuous Integration Tools
Softwarequalitätssicherung mit Continuous Integration ToolsSoftwarequalitätssicherung mit Continuous Integration Tools
Softwarequalitätssicherung mit Continuous Integration Tools
GFU Cyrus AG
 
Python in Test automation
Python in Test automationPython in Test automation
Python in Test automation
Krishnana Sreeraman
 
Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...
Timo Stollenwerk
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
David Xie
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutes
Ray Toal
 
Presentation TDD in Python
Presentation TDD in PythonPresentation TDD in Python
Presentation TDD in Python
Roberto Bettazzoni
 
Cómo aplicar TDD. Almería 13/05/2014
Cómo aplicar TDD. Almería 13/05/2014Cómo aplicar TDD. Almería 13/05/2014
Cómo aplicar TDD. Almería 13/05/2014
Javier_J
 
Las Claves del Desarrollo Dirigido por Pruebas (o TDD)
Las Claves del Desarrollo Dirigido por Pruebas (o TDD)Las Claves del Desarrollo Dirigido por Pruebas (o TDD)
Las Claves del Desarrollo Dirigido por Pruebas (o TDD)
Javier_J
 
TDD y Python
TDD y PythonTDD y Python
TDD y Python
Javier_J
 
Java EE 5
Java EE 5Java EE 5
Java EE 5
GFU Cyrus AG
 
Kata Tenis. Enunciados y soluciones alternativas. Python Sevilla 30/11/2012
Kata Tenis. Enunciados y soluciones alternativas. Python Sevilla 30/11/2012Kata Tenis. Enunciados y soluciones alternativas. Python Sevilla 30/11/2012
Kata Tenis. Enunciados y soluciones alternativas. Python Sevilla 30/11/2012
Javier_J
 
Kata Tenis Completa Paso a Paso. Python Sevilla 30/11/2012
Kata Tenis Completa Paso a Paso. Python Sevilla 30/11/2012Kata Tenis Completa Paso a Paso. Python Sevilla 30/11/2012
Kata Tenis Completa Paso a Paso. Python Sevilla 30/11/2012
Javier_J
 
Python unittest
Python unittestPython unittest
Python unittest
Felipe Ruhland
 
Clean Code Developer
Clean Code DeveloperClean Code Developer
Clean Code Developer
GFU Cyrus AG
 
TDD com Python (Completo)
TDD com Python (Completo)TDD com Python (Completo)
TDD com Python (Completo)
Osvaldo Santana Neto
 
Integration Testing in Python
Integration Testing in PythonIntegration Testing in Python
Integration Testing in Python
Panoptic Development, Inc.
 
Easy selenium test automation on python
Easy selenium test automation on pythonEasy selenium test automation on python
Easy selenium test automation on python
Mykhailo Poliarush
 
bubble sorting of an array in 8086 assembly language
bubble sorting of an array in 8086 assembly languagebubble sorting of an array in 8086 assembly language
bubble sorting of an array in 8086 assembly language
Bilal Amjad
 
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
Python Ireland
 

Viewers also liked (20)

Mock testing mit Python
Mock testing mit PythonMock testing mit Python
Mock testing mit Python
 
Softwarequalitätssicherung mit Continuous Integration Tools
Softwarequalitätssicherung mit Continuous Integration ToolsSoftwarequalitätssicherung mit Continuous Integration Tools
Softwarequalitätssicherung mit Continuous Integration Tools
 
Python in Test automation
Python in Test automationPython in Test automation
Python in Test automation
 
Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutes
 
Presentation TDD in Python
Presentation TDD in PythonPresentation TDD in Python
Presentation TDD in Python
 
Cómo aplicar TDD. Almería 13/05/2014
Cómo aplicar TDD. Almería 13/05/2014Cómo aplicar TDD. Almería 13/05/2014
Cómo aplicar TDD. Almería 13/05/2014
 
Las Claves del Desarrollo Dirigido por Pruebas (o TDD)
Las Claves del Desarrollo Dirigido por Pruebas (o TDD)Las Claves del Desarrollo Dirigido por Pruebas (o TDD)
Las Claves del Desarrollo Dirigido por Pruebas (o TDD)
 
TDD y Python
TDD y PythonTDD y Python
TDD y Python
 
Java EE 5
Java EE 5Java EE 5
Java EE 5
 
Kata Tenis. Enunciados y soluciones alternativas. Python Sevilla 30/11/2012
Kata Tenis. Enunciados y soluciones alternativas. Python Sevilla 30/11/2012Kata Tenis. Enunciados y soluciones alternativas. Python Sevilla 30/11/2012
Kata Tenis. Enunciados y soluciones alternativas. Python Sevilla 30/11/2012
 
Kata Tenis Completa Paso a Paso. Python Sevilla 30/11/2012
Kata Tenis Completa Paso a Paso. Python Sevilla 30/11/2012Kata Tenis Completa Paso a Paso. Python Sevilla 30/11/2012
Kata Tenis Completa Paso a Paso. Python Sevilla 30/11/2012
 
Python unittest
Python unittestPython unittest
Python unittest
 
Clean Code Developer
Clean Code DeveloperClean Code Developer
Clean Code Developer
 
TDD com Python (Completo)
TDD com Python (Completo)TDD com Python (Completo)
TDD com Python (Completo)
 
Integration Testing in Python
Integration Testing in PythonIntegration Testing in Python
Integration Testing in Python
 
Easy selenium test automation on python
Easy selenium test automation on pythonEasy selenium test automation on python
Easy selenium test automation on python
 
bubble sorting of an array in 8086 assembly language
bubble sorting of an array in 8086 assembly languagebubble sorting of an array in 8086 assembly language
bubble sorting of an array in 8086 assembly language
 
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
 

Similar to Test Driven Development With Python

Plone testingdzug tagung2010
Plone testingdzug tagung2010Plone testingdzug tagung2010
Plone testingdzug tagung2010
Timo Stollenwerk
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded c
Benux Wei
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
Hans Jones
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passage
Erik Rose
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Ukraine
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
ericholscher
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
Richárd Kovács
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
Mark Niebergall
 
report
reportreport
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
Fariz Darari
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
Honza Král
 
How to write maintainable code without tests
How to write maintainable code without testsHow to write maintainable code without tests
How to write maintainable code without tests
Juti Noppornpitak
 
Python ppt
Python pptPython ppt
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suite
ericholscher
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 
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
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
NileshBorkar12
 
ppopoff
ppopoffppopoff
ppopoff
Paul Popoff
 

Similar to Test Driven Development With Python (20)

Plone testingdzug tagung2010
Plone testingdzug tagung2010Plone testingdzug tagung2010
Plone testingdzug tagung2010
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded c
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passage
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
 
report
reportreport
report
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
How to write maintainable code without tests
How to write maintainable code without testsHow to write maintainable code without tests
How to write maintainable code without tests
 
Python ppt
Python pptPython ppt
Python ppt
 
Python basic
Python basicPython basic
Python basic
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suite
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
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)
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
 
ppopoff
ppopoffppopoff
ppopoff
 

More from Siddhi

Not all features are equal
Not all features are equalNot all features are equal
Not all features are equal
Siddhi
 
The end of the backlog?
The end of the backlog?The end of the backlog?
The end of the backlog?
Siddhi
 
Growth hacks
Growth hacksGrowth hacks
Growth hacks
Siddhi
 
Kanban for Startups
Kanban for StartupsKanban for Startups
Kanban for Startups
Siddhi
 
Venture lab tech entrepreneurship market survey
Venture lab tech entrepreneurship market surveyVenture lab tech entrepreneurship market survey
Venture lab tech entrepreneurship market survey
Siddhi
 
Technology Entrepreneurship: Assignment 2
Technology Entrepreneurship: Assignment 2Technology Entrepreneurship: Assignment 2
Technology Entrepreneurship: Assignment 2
Siddhi
 
5 steps to better user engagement
5 steps to better user engagement5 steps to better user engagement
5 steps to better user engagement
Siddhi
 
Bridging the gap between your Agile project organisation and the traditional ...
Bridging the gap between your Agile project organisation and the traditional ...Bridging the gap between your Agile project organisation and the traditional ...
Bridging the gap between your Agile project organisation and the traditional ...
Siddhi
 
So you wanna build something? Now what?
So you wanna build something? Now what?So you wanna build something? Now what?
So you wanna build something? Now what?
Siddhi
 
Agile in short projects
Agile in short projectsAgile in short projects
Agile in short projects
Siddhi
 
Continuous feedback
Continuous feedbackContinuous feedback
Continuous feedback
Siddhi
 
Organizational Dysfunctions - Agile to the Rescue
Organizational Dysfunctions - Agile to the RescueOrganizational Dysfunctions - Agile to the Rescue
Organizational Dysfunctions - Agile to the Rescue
Siddhi
 
Agile is not the easy way out
Agile is not the easy way outAgile is not the easy way out
Agile is not the easy way out
Siddhi
 
The Three Amigos
The Three AmigosThe Three Amigos
The Three Amigos
Siddhi
 
Visualisation & Self Organisation
Visualisation & Self OrganisationVisualisation & Self Organisation
Visualisation & Self Organisation
Siddhi
 
Portfolio Management - Figuring Out How to Say When and Why
Portfolio Management - Figuring Out How to Say When and WhyPortfolio Management - Figuring Out How to Say When and Why
Portfolio Management - Figuring Out How to Say When and Why
Siddhi
 
Attention Middle Management Chickens
Attention Middle Management ChickensAttention Middle Management Chickens
Attention Middle Management Chickens
Siddhi
 
Agile Project Outsourcing - Dealing with RFP and RFI
Agile Project Outsourcing - Dealing with RFP and RFIAgile Project Outsourcing - Dealing with RFP and RFI
Agile Project Outsourcing - Dealing with RFP and RFI
Siddhi
 
Migrating Legacy Code
Migrating Legacy CodeMigrating Legacy Code
Migrating Legacy Code
Siddhi
 
Big Bang Agile Roll-out
Big Bang Agile Roll-outBig Bang Agile Roll-out
Big Bang Agile Roll-out
Siddhi
 

More from Siddhi (20)

Not all features are equal
Not all features are equalNot all features are equal
Not all features are equal
 
The end of the backlog?
The end of the backlog?The end of the backlog?
The end of the backlog?
 
Growth hacks
Growth hacksGrowth hacks
Growth hacks
 
Kanban for Startups
Kanban for StartupsKanban for Startups
Kanban for Startups
 
Venture lab tech entrepreneurship market survey
Venture lab tech entrepreneurship market surveyVenture lab tech entrepreneurship market survey
Venture lab tech entrepreneurship market survey
 
Technology Entrepreneurship: Assignment 2
Technology Entrepreneurship: Assignment 2Technology Entrepreneurship: Assignment 2
Technology Entrepreneurship: Assignment 2
 
5 steps to better user engagement
5 steps to better user engagement5 steps to better user engagement
5 steps to better user engagement
 
Bridging the gap between your Agile project organisation and the traditional ...
Bridging the gap between your Agile project organisation and the traditional ...Bridging the gap between your Agile project organisation and the traditional ...
Bridging the gap between your Agile project organisation and the traditional ...
 
So you wanna build something? Now what?
So you wanna build something? Now what?So you wanna build something? Now what?
So you wanna build something? Now what?
 
Agile in short projects
Agile in short projectsAgile in short projects
Agile in short projects
 
Continuous feedback
Continuous feedbackContinuous feedback
Continuous feedback
 
Organizational Dysfunctions - Agile to the Rescue
Organizational Dysfunctions - Agile to the RescueOrganizational Dysfunctions - Agile to the Rescue
Organizational Dysfunctions - Agile to the Rescue
 
Agile is not the easy way out
Agile is not the easy way outAgile is not the easy way out
Agile is not the easy way out
 
The Three Amigos
The Three AmigosThe Three Amigos
The Three Amigos
 
Visualisation & Self Organisation
Visualisation & Self OrganisationVisualisation & Self Organisation
Visualisation & Self Organisation
 
Portfolio Management - Figuring Out How to Say When and Why
Portfolio Management - Figuring Out How to Say When and WhyPortfolio Management - Figuring Out How to Say When and Why
Portfolio Management - Figuring Out How to Say When and Why
 
Attention Middle Management Chickens
Attention Middle Management ChickensAttention Middle Management Chickens
Attention Middle Management Chickens
 
Agile Project Outsourcing - Dealing with RFP and RFI
Agile Project Outsourcing - Dealing with RFP and RFIAgile Project Outsourcing - Dealing with RFP and RFI
Agile Project Outsourcing - Dealing with RFP and RFI
 
Migrating Legacy Code
Migrating Legacy CodeMigrating Legacy Code
Migrating Legacy Code
 
Big Bang Agile Roll-out
Big Bang Agile Roll-outBig Bang Agile Roll-out
Big Bang Agile Roll-out
 

Recently uploaded

Opencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of MünsterOpencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of Münster
Matthias Neugebauer
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
HackersList
 
Tirana Tech Meetup - Agentic RAG with Milvus, Llama3 and Ollama
Tirana Tech Meetup - Agentic RAG with Milvus, Llama3 and OllamaTirana Tech Meetup - Agentic RAG with Milvus, Llama3 and Ollama
Tirana Tech Meetup - Agentic RAG with Milvus, Llama3 and Ollama
Zilliz
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
Priyanka Aash
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Torry Harris
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
SAI KAILASH R
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
alexjohnson7307
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
SynapseIndia
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSECHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
kumarjarun2010
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
SynapseIndia
 
Figma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdfFigma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdf
Management Institute of Skills Development
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
bhumivarma35300
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Networks
 
Pigging Unit Lubricant Oil Blending Plant
Pigging Unit Lubricant Oil Blending PlantPigging Unit Lubricant Oil Blending Plant
Pigging Unit Lubricant Oil Blending Plant
LINUS PROJECTS (INDIA)
 

Recently uploaded (20)

Opencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of MünsterOpencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of Münster
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
 
Tirana Tech Meetup - Agentic RAG with Milvus, Llama3 and Ollama
Tirana Tech Meetup - Agentic RAG with Milvus, Llama3 and OllamaTirana Tech Meetup - Agentic RAG with Milvus, Llama3 and Ollama
Tirana Tech Meetup - Agentic RAG with Milvus, Llama3 and Ollama
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSECHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
 
Figma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdfFigma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdf
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
 
Pigging Unit Lubricant Oil Blending Plant
Pigging Unit Lubricant Oil Blending PlantPigging Unit Lubricant Oil Blending Plant
Pigging Unit Lubricant Oil Blending Plant
 

Test Driven Development With Python

  • 1. Test Driven Development in Python Siddharta Govindaraj siddharta@silverstripesoftware.com
  • 2. What is Test Driven Development (TDD)? http://www.flickr.com/photos/johnsyweb/3051647719/
  • 3. Red, Green, Refactor ● First write a test ● Write code to pass the test ● Clean up the code ● Repeat
  • 4. TDD Example Write a function to check whether a given input string is a palindrome
  • 6. tests.py from code import is_palindrome def test_function_should_accept_palindromic_words(): input = "noon" assert is_palindrome(input) == True
  • 8. code.py def is_palindrome(input_str): return input_str == input_str[::-1]
  • 10. tests.py def test_function_should_ignore_case(): input = "Noon" assert is_palindrome(input) == True
  • 12. code.py def is_palindrome(input_str): input_clean = input_str.lower() return input_clean == input_clean[::-1]
  • 14. tests.py def test_function_should_ignore_trailing_space(): input = "Noon " assert is_palindrome(input) == True
  • 15. code.py def is_palindrome(input_str): input_clean = input_str.strip().lower() return input_clean == input_clean[::-1]
  • 16. tests.py def test_function_should_ignore_spaces_in_text(): input = "ab raca carba" assert is_palindrome(input) == True
  • 17. code.py def is_palindrome(input_str): input_stripped = input_str.replace(" ", "") input_clean = input_stripped.lower() return input_clean == input_clean[::-1]
  • 18. tests.py def test_function_should_handle_combined_characters(): input = u"u0bb4u0bbfuu0b95u0bb4u0bbf" assert is_palindrome(input) == True (Input is ழ கழ )
  • 19. Reversing unicode strings The String: ழ கழ Characters: ழ + ி + க + ழ + ி Wrong: ி + ழ + க + ி + ழ Right: ழ + ி + க + ழ + ி
  • 20. # naïve implementation to pass the test def is_palindrome(input_str): def reverse_string(input_str): def is_combining_char(char): chars = [u"u0bcd"] return char in chars reversed_chars = [] for char in input_str: if is_combining_char(char): reversed_chars.insert(1, char) else: reversed_chars.insert(0, char) return "".join(reversed_chars) input_stripped = input_str.replace(" ", "") input_clean = input_stripped.lower() reversed_string = reverse_string(input_clean) return input_clean == reversed_string
  • 21. And so it continues... ● Turns out reversing a string is quite complex when unicode scripts come into the picture ● Many different cases to consider ● Unit tests can validate the complex code logic and check for regression errors
  • 22. Why is unit testing important? ● Quality ● Regression ● Safety Net ● Integration with build and CI tools ● Documentation
  • 23. Attributes of good tests ● Fast ● Clear ● Isolated ● Reliable
  • 24. Unit Testing in Python ● We will look at three test frameworks ● unittest ● py.test ● nose
  • 25. What are we looking for? ● Ease of writing tests ● xUnit output support ● Ease of running tests ● Test →Doc ● Test autodiscovery ● Code coverage ● Running specific tests ● Code profiling ● Running failed tests ● Parallel testing ● Setup & teardown ● Interactive debug
  • 26. unittest import unittest class TestPalindrome(unittest.TestCase): def test_function_should_accept_palindromes(self): input = “noon” self.assertTrue(is_palindrome(input))
  • 27. unittest features + Similar to standard unit testing frameworks in other languages (jUnit, Nunit...) + Included in base python standard library + Best IDE support + Maximum adoption
  • 28. unittest features – Inflexible, cumbersome, unpythonic – Requires lots of boilerplate code to write code – No test autodiscovery – No support for running specific tests – Limited support for setup and teardown – No support for advanced test features
  • 29. py.test def test_function_should_accept_palindromic_words(): input = "noon" assert is_palindrome(input) == True
  • 30. py.test features + Test autodiscovery + Easy to write and run tests + Supports most of the advanced features – parallel testing, parametrized tests, compatibility with unittest, coverage, interactive debug + Good support for extensions
  • 31. py.test features – Not standard – Lack of IDE support
  • 32. nose def test_function_should_accept_palindromic_words(): input = "noon" assert is_palindrome(input) == True
  • 33. nose features + Compatible with unittest + Supports all advanced features + Works well with Django, Pylons, Turbogears + Excellent plugin support + Supported by some IDEs + Most popular among alternative test frameworks
  • 35. Some interesting plugins ● Code coverage – Shows you how well your unit tests covers the code ● Profiling – Measures the time taken by functions when running the tests ● Parallel testing – Runs tests in parallel to speed things up
  • 36. Other Interesting Features ● Generative tests – Runs the same test sequence with different combinations of input data ● Interactive debug – Drops into the python debugger on test failure
  • 37. How we use nose ..Scriptspaver.exe test_django ---> test_django ............. Ran 1302 tests in 262.391s OK Destroying test database...
  • 38. How we use nose ..Scriptspaver.exe test_django --database=sqlite3 --exclude=south ---> test_django ............. Ran 1274 tests in 128.359s OK Destroying test database...
  • 39. How we use nose ..Scriptspaver.exe test_django metrics --with-coverage --cover-package=metrics Name Stmts Exec Cover ---------------------------------------------------------- metrics 0 0 100% metrics.cumulative_calculator 34 34 100% metrics.models 39 37 94% 48-49 metrics.throughput 13 13 100% metrics.views 100 91 91% 20- 22, 33-35, 46-48 TOTAL 186 175 94%
  • 40. Nose Plugins - Spec Test → Doc class TestIsPalindrome(self) def test_should_accept_palindromic_words def test_function_should_ignore_case def test_function_should_ignore_trailing_space IsPalindrome - Should accept palindromic words - Should ignore case - Should ignore trailing space
  • 41. Nose Plugins - Xunit ● Provides test result output in the standard xUnit xml format ● This format can be read and integrated into standard continuous integration systems
  • 42. Summary Not much to choose between py.test and nose nose is currently more popular Use unittest if standardisation is important