coverage.py
is an amazing library for determining how much of your code is covered by your tests and how much still needs to be tested.
We’re going to use coverage on our previously written test tests.py
.
import unittest
import dice
class DieTests(unittest.TestCase):
def setUp(self):
self.d6 = dice.Die(6)
self.d8 = dice.Die(8)
def test_creation(self):
self.assertEqual(self.d6.sides, 6)
self.assertIn(self.d6.value, range(1, 6))
def test_add(self):
self.assertIsInstance(self.d6+self.d8, int)
def test_bad_sides(self):
with self.assertRaises(ValueError):
dice.Die(1)
class RollTests(unittest.TestCase):
def setUp(self):
self.hand1 = dice.Roll('1d2')
self.hand3 = dice.Roll('3d6')
def test_lower(self):
self.assertGreaterEqual(int(self.hand3), 3)
def test_upper(self):
self.assertLessEqual(int(self.hand3), 18)
def test_membership(self):
test_die = dice.Die(2)
test_die.value = self.hand1.results[0].value
self.assertIn(test_die, self.hand1.results)
def test_bad_description(self):
with self.assertRaises(ValueError):
dice.Roll('2b6')
if __name__ == '__main__':
unittest.main()
Testing with Coverage
1. Install
pip install coverage
2. Use
This is how you’d run the tests in tests.py
along with the tests of coverage
.
coverage run test.py
Output
......
-------------------------------------
Ran 6 tests in 0.003s
3. Report
Generate a report of the tests conducted by coverage.
coverage report
If you want to view which lines you’ve missed, run the following command instead.
coverage report or coverage report -m
Generally, you want to aim for about 90% or better in your coverage.
A lot of these lines that aren’t covered are ones that are aimed at Python’s internals, like the repper
line.
Testing these are fine, you can right test for these. But you don’t have to.
It’s never a bad thing though to hit 100%.
Documentation
For more information, check the coverage.py
documentation.
http://nedbatchelder.com/code/coverage/