[파이썬] pytest assert 문 활용

In software development, it is crucial to have reliable and robust testing mechanisms to ensure the quality and functionality of our code. One popular testing framework in Python is pytest. Among its many features, one that stands out is the powerful assert statements it provides.

Using assert statements in pytest can significantly enhance the readability and effectiveness of your test cases. Let’s explore some ways to leverage this feature for better testing.

Basic Usage

The basic usage of assert statements in pytest is similar to regular assert statements in Python. Here’s an example:

def multiply(a, b):
    return a * b

def test_multiply():
    assert multiply(2, 3) == 6
    assert multiply(0, 10) == 0
    assert multiply(-5, 7) == -35

In this example, we define a function multiply that multiplies two numbers. The test_multiply function is a pytest test case where we use assert statements to verify the expected results. If any of these assertions fail, pytest will raise an assertion error and provide detailed information about the failure.

Custom Error Messages

One advantage of using assert statements in pytest is the ability to provide custom error messages. This can be useful for understanding failures in complex test cases.

def divide(a, b):
    assert b != 0, "Cannot divide by zero"
    return a / b

def test_divide():
    assert divide(10, 2) == 5
    assert divide(7, 0) == 5, "Expected division by zero"

In this example, the divide function performs division but includes a custom error message for the assert statement that checks for division by zero. In the test_divide test case, we validate the correctness of the division operation and also ensure that the appropriate error message is displayed.

Checking Exceptions

Sometimes, we need to test code that raises exceptions under certain conditions. pytest assert statements can handle this scenario too.

def square_root(x):
    assert x >= 0, "Cannot calculate square root of a negative number"
    return x ** 0.5

def test_square_root():
    assert square_root(25) == 5
    with pytest.raises(AssertionError):
        square_root(-9)

In this example, the square_root function calculates the square root of a number, but it only accepts non-negative numbers. The test_square_root test case verifies that the square root is correctly calculated for a positive number. Additionally, it uses the pytest.raises context manager to assert that an exception is raised when calculating the square root of a negative number.

Conclusion

Using assert statements in pytest can greatly improve your testing workflow. It provides a concise yet powerful way to validate expected results, handle exceptions, and provide custom error messages. By leveraging this feature, you can write more effective and maintainable tests, leading to a robust and reliable software product.