KEMBAR78
Python Programming Essentials - M39 - Unit Testing | PPTX
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

Python Programming Essentials - M39 - Unit Testing

  • 1.
    http://www.skillbrew.com /SkillbrewTalent brewed bythe industry itself Unit Testing Pavan Verma @YinYangPavan Founder, P3 InfoTech Solutions Pvt. Ltd. Python Programming Essentials
  • 2.
    © SkillBrew http://skillbrew.com Whatis 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 UnitTesting 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 UnitTesting 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 UnitTesting 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 UnitTesting 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 Unittestmodule  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 Programto 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 Basicunit 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 Runninga 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 MethodChecks 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 setUpand 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 setUpand 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"
  • 15.
  • 16.
    © SkillBrew http://skillbrew.com Unittestfeatures  setupClass() / tearDownClass()  Skip tests  Expected failures
  • 17.
    © SkillBrew http://skillbrew.com TestingFrameworks  pytest  Nose
  • 18.
    © SkillBrew http://skillbrew.com Codecoverage  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/