0
0
PyTesttesting~10 mins

Testing multiple exceptions in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a function raises either a ValueError or a TypeError when given invalid inputs. It verifies that the function correctly handles multiple error cases.

Test Code - pytest
PyTest
import pytest

def process_value(value):
    if not isinstance(value, int):
        raise TypeError("Value must be an integer")
    if value < 0:
        raise ValueError("Value must be non-negative")
    return value * 2

def test_process_value_exceptions():
    with pytest.raises((ValueError, TypeError)) as exc_info:
        process_value(-1)  # Should raise ValueError
    assert isinstance(exc_info.value, ValueError)

    with pytest.raises((ValueError, TypeError)) as exc_info:
        process_value('a')  # Should raise TypeError
    assert isinstance(exc_info.value, TypeError)
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Calls process_value(-1)Function receives -1 as inputCheck if ValueError or TypeError is raisedPASS
3process_value raises ValueError("Value must be non-negative")Exception raised inside functionException type is ValueErrorPASS
4Assertion confirms exception is ValueErrorException captured in exc_infoassert isinstance(exc_info.value, ValueError)PASS
5Calls process_value('a')Function receives string 'a' as inputCheck if ValueError or TypeError is raisedPASS
6process_value raises TypeError("Value must be an integer")Exception raised inside functionException type is TypeErrorPASS
7Assertion confirms exception is TypeErrorException captured in exc_infoassert isinstance(exc_info.value, TypeError)PASS
8Test endsAll assertions passed-PASS
Failure Scenario
Failing Condition: Function does not raise the expected exceptions for invalid inputs
Execution Trace Quiz - 3 Questions
Test your understanding
What exception does process_value(-1) raise in this test?
ATypeError
BIndexError
CValueError
DNo exception
Key Result
Using pytest.raises with a tuple allows testing that a function raises any one of multiple expected exceptions, making tests concise and clear.