Sunday, September 7, 2014

Python Unit-Testing

The standard workflow of Python Unit-test is:

1. We define your own class derived from unittest.TestCase.
2. Then you fill it with functions that start with ‘test_’.
3. You run the tests by placing unittest.main() in your file, usually at the bottom.


Example 1
import unittestfrom unnecessary_math import multiply
class TestUM(unittest.TestCase):
    def setUp(self):        pass
    def test_numbers_3_4(self):        self.assertEqual( multiply(3,4), 12)
    def test_strings_a_3(self):        self.assertEqual( multiply('a',3), 'aaa')
if __name__ == '__main__':    unittest.main()
In this example,  assertEqual()method is used
This method is used to compare the actual and expected values of partcular class execution.

Running Unit Tests
At the bottom of the code we have "if __name__ == '__main__':    unittest.main()" .
This allows us to run all of the test code just by running the file.
Running it with no options is the most terse, and running with a ‘-v’ is more verbose, showing which tests

Output-
> python -m unittest discover simple_example
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
 
OK
> python -m unittest discover -v simple_example
test_numbers_3_4 (test_um_unittest.TestUM) ... ok
test_strings_a_3 (test_um_unittest.TestUM) ... ok
 
----------------------------------------------------------------------
Ran 2 tests in 0.000s
 
OK

No comments:

Post a Comment