Pytest Testing Idioms: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 9: Line 9:


def test_something_that_should_throw_exception():
def test_something_that_should_throw_exception():
     with pytest.raises(Exception) as e_info:
     with pytest.raises(Exception) as info:
         my_method()
         my_method()
</syntaxhighlight>
</syntaxhighlight>
Line 16: Line 16:
<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>
def test_something_that_should_throw_exception():
def test_something_that_should_throw_exception():
     with pytest.raises(ValueError) as e_info:
     with pytest.raises(ValueError) as info:
         my_method()
         my_method()
</syntaxhighlight>
This tests the exception arguments:
<syntaxhighlight lang='python'>
def test_something_that_should_throw_exception():
    with pytest.raises(ValueError) as info:
        my_method()
    assert info.value.args[0] == "some message"
    assert str(info.value.args[0]).contains("some message")
</syntaxhighlight>
</syntaxhighlight>



Revision as of 21:45, 16 February 2022

External

Internal

Overview

Tested Code is Supposed to Throw Exception

import pytest

def test_something_that_should_throw_exception():
    with pytest.raises(Exception) as info:
        my_method()

If the tested code raises a more specific exception, you can use that instead:

def test_something_that_should_throw_exception():
    with pytest.raises(ValueError) as info:
        my_method()

This tests the exception arguments:

def test_something_that_should_throw_exception():
    with pytest.raises(ValueError) as info:
        my_method()
    assert info.value.args[0] == "some message"
    assert str(info.value.args[0]).contains("some message")

  • How to I test the exception message?

Also see:

Python Language | Exceptions