Pytest Testing Idioms: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 27: Line 27:
         my_method()
         my_method()
     assert info.value.args[0] == "some message"
     assert info.value.args[0] == "some message"
     assert str(info.value.args[0]).contains("some message")
     assert "some message" in str(info.value)
</syntaxhighlight>
</syntaxhighlight>
Also see: {{Internal|Python_Language_Exceptions#Overview|Python Language &#124; Exceptions}}
Also see: {{Internal|Python_Language_Exceptions#Overview|Python Language &#124; Exceptions}}

Revision as of 21:56, 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 "some message" in str(info.value)

Also see:

Python Language | Exceptions