Py-Test Assert Exception Message

I’ve been using PyTest for a while now. And apart from writing simple assert statement for my code there is not much I’ve explored so far in PyTest. Recently I’ve been looking into Hypothesis as well which is a property based testing tool.

PyTest is awesome to be honest and mind you guys! this is my personal view. It’s easy, fast and Pythonic (haha..).

Moreover, this blog post is going to be a simple one. It’s more about writing sample PyTest Assert Exception Message.

Scenario : Suppose you want to test a function, the best you can do is write a function asserting certain set of values. One of the examples is :

[code language=”python” wraplines=”false” collapse=”false”]

def add_two_number(a,b):
c = a + b
return c

[/code]

And it’s equivalent test :

[code language=”python” wraplines=”false” collapse=”false”]

def test_add_two_numbers():
output = add_two_numbers(4,5)
assert output == 9

[/code]

Now suppose you want to write a simple and basic test to catch the assert message in a function all you need to do is use

[code language=”python” wraplines=”false” collapse=”false”]

pytest.raises

[/code]

Suppose you have a function which checks for e-mail validation

[code language=”python” wraplines=”false” collapse=”false”]

def email_validation(self, email):
if not email:
raise ValueError(‘No Email Found’)
else:
print "Your Email id is {}".format(email)

[/code]

Now if you want to write the test whether this exception gets invoked correctly or not. All you need to do is write it as :

[code language=”python” wraplines=”false” collapse=”false”]

def test_email_validation(email):
with pytest.raises(ValueError, message="No Email Found"):
email_validation("")

[/code]

And voila! it’ll work like a charm. As you can see pytest.raises can catch certain known exceptions and for that you don’t need to define “message” part explicitly. But if you have a custom message for that error in your function then in your test function you have to pass that.

For more examples you can check the following link

Till next time. Adios!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *