Python Assertion for ValueError

Viewed 960

Is there a way to use assert in pure Python to test for a ValueError?

E.g. something like:

def try_me():
    raise ValueError("No way Jose")

assert try_me() is ValueError
2 Answers

You can use unittest.TestCase.assertRaises from the unittest module. Checking if the try_me function raises ValueError looks like this:

import unittest


def try_me():
    raise ValueError("No way Jose")


class MyTestCase(unittest.TestCase):
    def test_if_throws_exception(self):
        self.assertRaises(ValueError, try_me)

assert evaluates only expressions.

But you can do:

def catch_exception(method):
    try:
        method()
    except Exception as e:
        return e.__class__


def try_me():
    raise ValueError("No way Jose")


assert catch_exception(try_me) is ValueError  # okay
assert catch_exception(try_me) is IndexError  # fails
Related