How to Assert Expected Exceptions in pytest

作者:半吊子全栈工匠2024.01.17 23:43浏览量:3

简介:Learn how to test for expected exceptions using pytest by following a step-by-step guide with code examples.

Testing for expected exceptions is a common practice in单元测试, as it helps ensure the robustness of your code. In this article, we will explore how to assert expected exceptions in pytest, a popular Python testing framework.
To demonstrate the usage of pytest for asserting expected exceptions, let’s consider a simple example where we have a function that raises an exception when an invalid input is provided.
Here’s the code for the example:

  1. def divide(dividend, divisor):
  2. if divisor == 0:
  3. raise ValueError('Divisor cannot be zero')
  4. return dividend / divisor
  5. # Example usage
  6. result = divide(10, 0)

In this example, the divide() function raises a ValueError when the divisor is zero. We want to test this behavior using pytest.
To assert an expected exception in pytest, you need to use the pytest.raises() context manager. Here’s how you can write a test for the divide() function:

  1. import pytest
  2. from your_module import divide # replace 'your_module' with the actual module name
  3. def test_divide():
  4. with pytest.raises(ValueError) as exc_info:
  5. divide(10, 0)
  6. assert 'Divisor cannot be zero' in str(exc_info.value)

In this test, we use the pytest.raises() context manager to wrap the code that might raise an exception. If the exception is raised, it is caught by pytest.raises() and stored in the exc_info variable. We then use the assert statement to check if the raised exception contains the expected message.
By following this pattern, you can test for any type of exception and verify its properties or message.
Remember to replace 'your_module' with the actual module name where your code is located.
This article provided a basic introduction to asserting expected exceptions in pytest. You can explore further by reading the pytest documentation and checking out its extensive collection of examples.
Feel free to ask any questions or share your experiences with pytest in the comments section below.