SlideShare a Scribd company logo
1 of 20
http://www.skillbrew.com
/SkillbrewTalent brewed by the
industry itself
Unit Testing
Pavan Verma
@YinYangPavan
Founder, P3 InfoTech Solutions Pvt. Ltd.
Python Programming Essentials
© SkillBrew http://skillbrew.com
What is Unit Testing
 A software testing method by which individual
units of source code are tested to determine if
they are fit for use.
 Unit testing is a software development
process in which the smallest testable parts of
an application, called units, are individually
and independently scrutinized for proper
operation. Unit testing is often automated but
it can also be done manually.
© SkillBrew http://skillbrew.com
Unit Testing Glossary
 test fixture – A test fixture represents the
preparation needed to perform one or more
tests, and any associate cleanup actions. This
may involve, for example, creating temporary or
proxy databases, directories, or starting a server
process.
© SkillBrew http://skillbrew.com
Unit Testing Glossary (2)
 test case – A test case is the smallest unit
of testing. It checks for a specific response
to a particular set of inputs.
 Python unittest module provides a base
class, TestCase, which may be used to
create new test cases.
© SkillBrew http://skillbrew.com
Unit Testing Glossary (3)
 test suite – A test suite is a collection of
test cases, test suites, or both. It is used to
aggregate tests that should be executed
together.
© SkillBrew http://skillbrew.com
Unit Testing Glossary (4)
 test runner – A test runner is a component
which orchestrates the execution of tests
and provides the outcome to the user.
 The runner may use a graphical interface,
a textual interface, or return a special value
to indicate the results of executing the
tests.
© SkillBrew http://skillbrew.com
Unittest module
 The unittest module started life as the
third-party module PyUnit.
 PyUnit was a Python port of JUnit, the
Java unit testing framework.
© SkillBrew http://skillbrew.com
Program to test – primes.py
def is_prime(number):
"""Return True if *number* is prime.""“
for element in range(number):
if number % element == 0:
return False
return True
© SkillBrew http://skillbrew.com
Basic unit test example
import unittest
from primes import is_prime
class PrimesTestCase(unittest.TestCase):
"""Tests for `primes.py`.""“
def test_is_five_prime(self):
"""Is five successfully determined to be
prime?""“
self.assertTrue(is_prime(5))
if __name__ == '__main__':
unittest.main()
© SkillBrew http://skillbrew.com
Running a unit test
$ python test_primes.py
E ======================================================================
ERROR: test_is_five_prime (__main__.PrimesTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_primes.py", line 8, in test_is_five_prime
self.assertTrue(is_prime(5))
File "/home/jknupp/code/github_code/blug_private/primes.py", line 4, in
is_prime
if number % element == 0: 
ZeroDivisionError: integer division or modulo by zero
----------------------------------------------------------------------
Ran 1 test in 0.000s
© SkillBrew http://skillbrew.com
Assertions
Method Checks that
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a, b) a is b
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)
© SkillBrew http://skillbrew.com
Assertions (2)
Method Checks that
assertAlmostEqual(a, b) round(a-b, 7) == 0
assertNotAlmostEqual(a, b) round(a-b, 7) != 0
assertGreater(a, b) a > b
assertGreaterEqual(a, b) a >= b
assertLess(a, b) a < b
assertLessEqual(a, b) a <= b
assertRegexpMatches(s, r) r.search(s)
assertNotRegexpMatches(s, r) not r.search(s)
assertItemsEqual(a, b)
sorted(a) == sorted(b) and works with
unhashable objs
assertDictContainsSubset(a, b) all the key/value pairs in a exist in b
© SkillBrew http://skillbrew.com
setUp and tearDown
#!/usr/bin/python
import unittest
class FooTest(unittest.TestCase):
"""Sample test case"""
# preparing to test
def setUp(self):
""" Setting up for the test """
print "FooTest:setUp_:begin"
## do something...
print "FooTest:setUp_:end"
# ending the test
© SkillBrew http://skillbrew.com
setUp and tearDown (2)
def tearDown(self):
"""Cleaning up after the test"""
print "FooTest:tearDown_:begin" ## do
something...
print "FooTest:tearDown_:end" # test routine A
def testA(self):
"""Test routine A"""
print "FooTest:testA"
# test routine B
def testB(self):
"""Test routine B"""
print "FooTest:testB"
© SkillBrew http://skillbrew.com
setUp and tearDown (3)
© SkillBrew http://skillbrew.com
Unittest features
 setupClass() / tearDownClass()
 Skip tests
 Expected failures
© SkillBrew http://skillbrew.com
Testing Frameworks
 pytest
 Nose
© SkillBrew http://skillbrew.com
Code coverage
 coverage
http://nedbatchelder.com/code/coverage/
© SkillBrew http://skillbrew.com
References
 https://docs.python.org/2/library/unittest.ht
ml
 http://pytest.org/
 http://nose.readthedocs.org/
 http://nedbatchelder.com/code/coverage/
Python Programming Essentials - M39 - Unit Testing

More Related Content

What's hot

Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentalscbcunc
 
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
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
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
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to heroJeremy Cook
 
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
 
Test your code like a pro - PHPUnit in practice
Test your code like a pro - PHPUnit in practiceTest your code like a pro - PHPUnit in practice
Test your code like a pro - PHPUnit in practiceSebastian Marek
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit TestingMike Lively
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitMichelangelo van Dam
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 

What's hot (20)

Pyunit
PyunitPyunit
Pyunit
 
Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentals
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
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 unittest
Python unittestPython unittest
Python unittest
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
 
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
 
Phpunit
PhpunitPhpunit
Phpunit
 
Phpunit testing
Phpunit testingPhpunit testing
Phpunit testing
 
Test your code like a pro - PHPUnit in practice
Test your code like a pro - PHPUnit in practiceTest your code like a pro - PHPUnit in practice
Test your code like a pro - PHPUnit in practice
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit Testing
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnit
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Rc2010 tdd
Rc2010 tddRc2010 tdd
Rc2010 tdd
 

Viewers also liked

Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsP3 InfoTech Solutions Pvt. Ltd.
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To DjangoTuan Anh Tran
 
Automated hardware testing using python
Automated hardware testing using pythonAutomated hardware testing using python
Automated hardware testing using pythonYuvaraja Ravi
 
Python Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to PythonPython Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to PythonP3 InfoTech Solutions Pvt. Ltd.
 
Why I Love Python V2
Why I Love Python V2Why I Love Python V2
Why I Love Python V2gsroma
 

Viewers also liked (14)

Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdb
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External Programs
 
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8
 
Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web Development
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and Files
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List Comprehensions
 
Python Programming Essentials - M5 - Variables
Python Programming Essentials - M5 - VariablesPython Programming Essentials - M5 - Variables
Python Programming Essentials - M5 - Variables
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
 
Python Programming Essentials - M15 - References
Python Programming Essentials - M15 - ReferencesPython Programming Essentials - M15 - References
Python Programming Essentials - M15 - References
 
Automated hardware testing using python
Automated hardware testing using pythonAutomated hardware testing using python
Automated hardware testing using python
 
Learn python
Learn pythonLearn python
Learn python
 
Python Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to PythonPython Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to Python
 
Why I Love Python V2
Why I Love Python V2Why I Love Python V2
Why I Love Python V2
 

Similar to Python Programming Essentials - M39 - Unit Testing

TEST AUTOMATION: AKA QUALITY CONTROL
TEST AUTOMATION: AKA QUALITY CONTROLTEST AUTOMATION: AKA QUALITY CONTROL
TEST AUTOMATION: AKA QUALITY CONTROLNyarai Tinashe Gomiwa
 
TEST AUTOMATION: AKA QUALITY CONTROL
TEST AUTOMATION: AKA QUALITY CONTROLTEST AUTOMATION: AKA QUALITY CONTROL
TEST AUTOMATION: AKA QUALITY CONTROLSovTech
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPressHarshad Mane
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
qtp 9.2 features
qtp 9.2 featuresqtp 9.2 features
qtp 9.2 featureskrishna3032
 
Qtp 92 Tutorial
Qtp 92 TutorialQtp 92 Tutorial
Qtp 92 Tutorialsasidhar
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769subhasis100
 
Qtp 92 Tutorial Anil
Qtp 92 Tutorial AnilQtp 92 Tutorial Anil
Qtp 92 Tutorial Anilguest3373d3
 
Qtp 9.2 Tutorial
Qtp 9.2 TutorialQtp 9.2 Tutorial
Qtp 9.2 Tutorialguest37ae7f
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769subhasis100
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEnterprise PHP Center
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Comunidade NetPonto
 
Unit testingandcontinousintegrationfreenest1dot4
Unit testingandcontinousintegrationfreenest1dot4Unit testingandcontinousintegrationfreenest1dot4
Unit testingandcontinousintegrationfreenest1dot4JAMK
 

Similar to Python Programming Essentials - M39 - Unit Testing (20)

TEST AUTOMATION: AKA QUALITY CONTROL
TEST AUTOMATION: AKA QUALITY CONTROLTEST AUTOMATION: AKA QUALITY CONTROL
TEST AUTOMATION: AKA QUALITY CONTROL
 
TEST AUTOMATION: AKA QUALITY CONTROL
TEST AUTOMATION: AKA QUALITY CONTROLTEST AUTOMATION: AKA QUALITY CONTROL
TEST AUTOMATION: AKA QUALITY CONTROL
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPress
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Php unit (eng)
Php unit (eng)Php unit (eng)
Php unit (eng)
 
qtp 9.2 features
qtp 9.2 featuresqtp 9.2 features
qtp 9.2 features
 
Qtp 92 Tutorial
Qtp 92 TutorialQtp 92 Tutorial
Qtp 92 Tutorial
 
Ppt Qtp
Ppt QtpPpt Qtp
Ppt Qtp
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 
Qtp 92 Tutorial Anil
Qtp 92 Tutorial AnilQtp 92 Tutorial Anil
Qtp 92 Tutorial Anil
 
Qtp 9.2 Tutorial
Qtp 9.2 TutorialQtp 9.2 Tutorial
Qtp 9.2 Tutorial
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
 
Application Testing
Application TestingApplication Testing
Application Testing
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
 
Unit testingandcontinousintegrationfreenest1dot4
Unit testingandcontinousintegrationfreenest1dot4Unit testingandcontinousintegrationfreenest1dot4
Unit testingandcontinousintegrationfreenest1dot4
 

More from P3 InfoTech Solutions Pvt. Ltd.

Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsPython Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M10 - Numbers and Artihmetic Operators
Python Programming Essentials - M10 - Numbers and Artihmetic OperatorsPython Programming Essentials - M10 - Numbers and Artihmetic Operators
Python Programming Essentials - M10 - Numbers and Artihmetic OperatorsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationP3 InfoTech Solutions Pvt. Ltd.
 

More from P3 InfoTech Solutions Pvt. Ltd. (17)

Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math modulePython Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
 
Python Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File OperationsPython Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File Operations
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and Packages
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - DictionariesPython Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - Dictionaries
 
Python Programming Essentials - M13 - Tuples
Python Programming Essentials - M13 - TuplesPython Programming Essentials - M13 - Tuples
Python Programming Essentials - M13 - Tuples
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
 
Python Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsPython Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical Operators
 
Python Programming Essentials - M10 - Numbers and Artihmetic Operators
Python Programming Essentials - M10 - Numbers and Artihmetic OperatorsPython Programming Essentials - M10 - Numbers and Artihmetic Operators
Python Programming Essentials - M10 - Numbers and Artihmetic Operators
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String MethodsPython Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
 
Python Programming Essentials - M7 - Strings
Python Programming Essentials - M7 - StringsPython Programming Essentials - M7 - Strings
Python Programming Essentials - M7 - Strings
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and Indentation
 

Python Programming Essentials - M39 - Unit Testing

  • 1. http://www.skillbrew.com /SkillbrewTalent brewed by the industry itself Unit Testing Pavan Verma @YinYangPavan Founder, P3 InfoTech Solutions Pvt. Ltd. Python Programming Essentials
  • 2. © SkillBrew http://skillbrew.com What is Unit Testing  A software testing method by which individual units of source code are tested to determine if they are fit for use.  Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. Unit testing is often automated but it can also be done manually.
  • 3. © SkillBrew http://skillbrew.com Unit Testing Glossary  test fixture – A test fixture represents the preparation needed to perform one or more tests, and any associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process.
  • 4. © SkillBrew http://skillbrew.com Unit Testing Glossary (2)  test case – A test case is the smallest unit of testing. It checks for a specific response to a particular set of inputs.  Python unittest module provides a base class, TestCase, which may be used to create new test cases.
  • 5. © SkillBrew http://skillbrew.com Unit Testing Glossary (3)  test suite – A test suite is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.
  • 6. © SkillBrew http://skillbrew.com Unit Testing Glossary (4)  test runner – A test runner is a component which orchestrates the execution of tests and provides the outcome to the user.  The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests.
  • 7. © SkillBrew http://skillbrew.com Unittest module  The unittest module started life as the third-party module PyUnit.  PyUnit was a Python port of JUnit, the Java unit testing framework.
  • 8. © SkillBrew http://skillbrew.com Program to test – primes.py def is_prime(number): """Return True if *number* is prime.""“ for element in range(number): if number % element == 0: return False return True
  • 9. © SkillBrew http://skillbrew.com Basic unit test example import unittest from primes import is_prime class PrimesTestCase(unittest.TestCase): """Tests for `primes.py`.""“ def test_is_five_prime(self): """Is five successfully determined to be prime?""“ self.assertTrue(is_prime(5)) if __name__ == '__main__': unittest.main()
  • 10. © SkillBrew http://skillbrew.com Running a unit test $ python test_primes.py E ====================================================================== ERROR: test_is_five_prime (__main__.PrimesTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "test_primes.py", line 8, in test_is_five_prime self.assertTrue(is_prime(5)) File "/home/jknupp/code/github_code/blug_private/primes.py", line 4, in is_prime if number % element == 0: ZeroDivisionError: integer division or modulo by zero ---------------------------------------------------------------------- Ran 1 test in 0.000s
  • 11. © SkillBrew http://skillbrew.com Assertions Method Checks that assertEqual(a, b) a == b assertNotEqual(a, b) a != b assertTrue(x) bool(x) is True assertFalse(x) bool(x) is False assertIs(a, b) a is b assertIsNot(a, b) a is not b assertIsNone(x) x is None assertIsNotNone(x) x is not None assertIn(a, b) a in b assertNotIn(a, b) a not in b assertIsInstance(a, b) isinstance(a, b) assertNotIsInstance(a, b) not isinstance(a, b)
  • 12. © SkillBrew http://skillbrew.com Assertions (2) Method Checks that assertAlmostEqual(a, b) round(a-b, 7) == 0 assertNotAlmostEqual(a, b) round(a-b, 7) != 0 assertGreater(a, b) a > b assertGreaterEqual(a, b) a >= b assertLess(a, b) a < b assertLessEqual(a, b) a <= b assertRegexpMatches(s, r) r.search(s) assertNotRegexpMatches(s, r) not r.search(s) assertItemsEqual(a, b) sorted(a) == sorted(b) and works with unhashable objs assertDictContainsSubset(a, b) all the key/value pairs in a exist in b
  • 13. © SkillBrew http://skillbrew.com setUp and tearDown #!/usr/bin/python import unittest class FooTest(unittest.TestCase): """Sample test case""" # preparing to test def setUp(self): """ Setting up for the test """ print "FooTest:setUp_:begin" ## do something... print "FooTest:setUp_:end" # ending the test
  • 14. © SkillBrew http://skillbrew.com setUp and tearDown (2) def tearDown(self): """Cleaning up after the test""" print "FooTest:tearDown_:begin" ## do something... print "FooTest:tearDown_:end" # test routine A def testA(self): """Test routine A""" print "FooTest:testA" # test routine B def testB(self): """Test routine B""" print "FooTest:testB"
  • 16. © SkillBrew http://skillbrew.com Unittest features  setupClass() / tearDownClass()  Skip tests  Expected failures
  • 17. © SkillBrew http://skillbrew.com Testing Frameworks  pytest  Nose
  • 18. © SkillBrew http://skillbrew.com Code coverage  coverage http://nedbatchelder.com/code/coverage/
  • 19. © SkillBrew http://skillbrew.com References  https://docs.python.org/2/library/unittest.ht ml  http://pytest.org/  http://nose.readthedocs.org/  http://nedbatchelder.com/code/coverage/