On Sun, Apr 01, 2018 at 10:57:15AM +0000, Simon Connah via Tutor wrote:

> I'm just wondering what the accepted way to handle unit testing 
> exceptions is? I know you are meant to use assertRaises, but my code 
> seems a little off.

Here's a modified example from the statistics library in Python 3.4 and 
above, testing that statistics.mean raises appropriate errors.

class TestMean(TestCase):
    def test_no_args(self):
        # Fail if given no arguments.
        self.assertRaises(TypeError, statistics.mean)

    def test_empty_data(self):
        # Fail when the data argument (first argument) is empty.
        for empty in ([], (), iter([])):
            self.assertRaises(statistics.StatisticsError, 
                              statistics.mean, empty)


Let's dissect how they work.

`test_no_args` calls 

    self.assertRaises(TypeError, statistics.mean)

which calls `statistics.mean` with no arguments. If it raises TypeError, 
then the test passes; otherwise the test fails.

`test_empty_data` makes the following test:

    self.assertRaises(statistics.StatisticsError,
                      statistics.mean, [])

which calls `statistics.mean` with a single argument, the empty list [], 
and fails if StatisticsError is NOT raised; then it repeats the test 
using an empty tuple (), and a third time with an empty iterable. Only 
if all three tests raise does the test pass.

Examples are heavily modified from here:

https://github.com/python/cpython/blob/3.7/Lib/test/test_statistics.py


> try:    some_func()
> except SomeException:    self.assertRaises(SomeException)

Re-write it as:

    self.assertRaises(SomeException, some_func)

Note carefully that you do NOT write some_func() with parentheses. The 
idea is to pass the function object itself to the test case, which will 
then call it for you. If your function needs arguments, you add them 
after the function:

    self.assertRaises(SomeException, some_func, 1, 2, 3, "surprise")

will call 

    some_func(1, 2, 3, "surprise")

and only pass if it raises SomeException.



-- 
Steve
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to