[파이썬] unittest assertWarns 메서드 활용하기

In Python, the unittest module provides a set of tools for writing and running tests. Among its various assertion methods, there is one particularly useful method called assertWarns. This method allows you to test whether a specific warning is raised during the execution of your code.

Let’s take a closer look at how you can utilize the assertWarns method in your unit tests.

Syntax

The syntax for using assertWarns is as follows:

unittest.TestCase.assertWarns(self, warning, callable, *args, **kwargs)

Example

Suppose you have a class Calculator that performs some calculations, and you want to ensure a warning is issued if the result exceeds a certain threshold. Here’s an example of how you can use assertWarns to write a test case for this scenario:

import unittest

class Calculator:
    def add(self, x, y):
        if x + y > 100:
            import warnings
            warnings.warn("Result exceeds threshold", UserWarning)
        return x + y

class TestCalculator(unittest.TestCase):
    def test_add_warning(self):
        calculator = Calculator()
        with self.assertWarns(UserWarning):
            result = calculator.add(50, 60)

        self.assertEqual(result, 110)

if __name__ == '__main__':
    unittest.main()

In the example above, the Calculator class has a method called add that checks if the sum of two numbers exceeds 100. If it does, the method raises a UserWarning. The test_add_warning method in the TestCalculator class uses assertWarns to test if the warning is raised when adding 50 and 60.

By running this test, you can verify that the warning is correctly raised when the result exceeds the threshold, ensuring the expected behavior of your code.

In conclusion, the assertWarns method in the unittest module is a valuable tool for testing warning messages in your Python code. It helps you ensure that the appropriate warnings are issued when certain conditions are met, enhancing the reliability and quality of your codebase.