unit testing with python

13
Python Unit Testing By MicroPyramid

Upload: micropyramid-

Post on 25-Jan-2017

240 views

Category:

Software


7 download

TRANSCRIPT

Page 1: Unit Testing with Python

Python Unit Testing

By MicroPyramid

Page 2: Unit Testing with Python

AgendaUnit Testing

Nose

Doc tests

Page 3: Unit Testing with Python

Why Software testing is important?

To point out the defects during the development phases.

To Ensure that the application works as expected.

Page 4: Unit Testing with Python

Test Driven Development.

The process of implementing code by writing your tests first, seeing them fail, then writing the code to make the tests pass.● Write Tests● Make Them fail● Write code.● Make them pass● Repeat

Page 5: Unit Testing with Python

Python Unit test

Some Important Points● Every test class must be sub class of unittest.TestCase● Every test function should start with test name.● to check for an expected result use assert functions.● The setUp() method define instructions that will be executed before test

case.● The tearDown() method define instructions that will be executed after test

case.● Run Test with python -m unittest -v test_module● Only test single part of code

Page 6: Unit Testing with Python
Page 7: Unit Testing with Python

Let’s start

# tests/mul.py

def multiply(a, b):

return a*b

def add(a, b):

return a+b

Page 8: Unit Testing with Python

Test case

import unittest

from mul import multiply

class MultiplyTestCase(unittest.TestCase):

def test_multiplication_with_correct_values(self):

self.assertEqual(multiply(5, 5), 25)

if __name__ == '__main__':

unittest.main()

Page 9: Unit Testing with Python

SetUp() and TearDown()

class MulTestCase(unittest.TestCase):

def setUp(self): # Runs before every test method

self.a = 10

self.b = 20

def test_mult_with_correct_values(self):

self.assertEqual(multiply(self.a, self.b), 200)

def tearDown(self): # runs after every test method

del self.a

del self.b

if __name__ == '__main__':

unittest.main()

Page 10: Unit Testing with Python

Assert functions

● assertEqual(a, b)● assertNotEqual(a, b)● assertTrue(x)● assertFalse(x)● assertIs(a, b)● https://docs.python.org/2/library/unittest.html#test-cases

Page 11: Unit Testing with Python

Nose:

$ pip install nose# Running tests

$ nosetests

Page 12: Unit Testing with Python

Doc Tests:

# tests/mul_dc.py

def multiply(a, b):

"""

>>> multiply(4, 3)

12

"""

return a * b

# running

$ python -m doctest -v file_name

Page 13: Unit Testing with Python

Questions?