Author: | Kushal Das |
---|---|
Contact: | kushaldas@gmail.com |
Date: | 2012-08-01 |
If possible everything in our codebase.
A method by which individual units of source code.
For now you can think like each function.
In python we have unittest module to help us.
As you can see fact(n) is function which is doing all calculations, so we should test that at least.
factorial_test.py contains our first test.
Run the test:
$ python factorial_test.py . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK
We are importing unittest module first and then the required functions which we want to test.
A testcase is created by subclassing unittest.TestCase.
Now open the test file and change 120 to 121 and see what happens :)
Method Checks that New in 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 2.7 assertIsNot(a, b) a is not b 2.7
Method Checks that New in assertIsNone(x) x is None 2.7 assertIsNotNone(x) x is not None 2.7 assertIn(a, b) a in b 2.7 assertNotIn(a, b) a not in b 2.7 assertIsInstance(a, b) isinstance(a, b) 2.7 assertNotIsInstance(a, b) not isinstance(a, b) 2.7
If we call div(0) in factorial.py , we can see if raises an exception.
We can also test these exceptions, like:
self.assertRaises(ZeroDivisionError, div, 0)
Here we have only one function mount_details() doing the parsing and printing mount details.
Now we refactored the code and have one new function parse_mount which we can test easily.
After refactoring and the test code
$ python mounttest.py .. ---------------------------------------------------------------------- Ran 2 tests in 0.001s OK
Test coverage is a simple way to find untested parts of a codebase. It does not tell you how good your tests are.
In Python we already have a nice coverage tool to help us. You can install it in Fedora
# yum install python-coverage
$ coverage -x mounttest.py <OUTPUT snipped> $ coverage -rm Name Stmts Miss Cover Missing ----------------------------------------- mounttab2 21 7 67% 16, 24-29, 33 mounttest 14 0 100% ----------------------------------------- TOTAL 35 7 80%