Reputation: 3794
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
Upvotes: 2
Views: 3913
Reputation: 21
pytest
is a good module to learn for unit testing your code and is very simple for this type of testing. Try this instead:
import pytest
with pytest.raises(ValueError):
try_me()
Upvotes: 0
Reputation: 135
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)
Upvotes: 1
Reputation: 3115
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
Upvotes: 0