jeudi 26 mai 2016

Multiple exceptions and code coverage

The Problem:

Here is an artificial example of the code under test:

from datetime import datetime

def f(s):
    try:
        date = s.split(":")[1]
        return datetime.strptime(date, "%Y%m%d")
    except (ValueError, IndexError) as e:
        # some code here
        raise

Here is a set of tests I currently have:

from datetime import datetime
import unittest

from test_module import f

class MyTestCase(unittest.TestCase):
    def test_valid_date(self):
        self.assertEqual(f("1:20130101"), datetime(2013, 1, 1))

    def test_invalid_date(self):
        self.assertRaises(ValueError, f, "1:invalid")

The test passes and, if I run the coverage with the --branch flag, I would get 100% line and branch coverage:

$ coverage run --branch -m unittest test
..
----------------------------------------------------------------------
Ran 2 tests in 0.003s

OK
$ coverage report
Name            Stmts   Miss Branch BrPart  Cover
--------------------------------------------
test_module.py      7      0      0      0   100%
--------------------------------------------
TOTAL               7      0      0      0   100%

However, note that the test currently examines only two cases - when there is no exception thrown, and there is a ValueError exception raised.

The question:

Is there a way for coverage to report that I have not tested a case when IndexError is raised?

Aucun commentaire:

Enregistrer un commentaire