Чтобы отобразить сообщения об ошибках, обнаруженные функцией assertraises()
в модуле unittest
Python 2.7, вы можете использовать несколько методов. Вот несколько подходов:
-
Использование контекстного менеджера
assertRaises()
:import unittest class MyTestCase(unittest.TestCase): def test_my_function(self): with self.assertRaises(ValueError) as cm: # Call the function that raises the error result = my_function() # Access the caught exception and its error message exception = cm.exception error_message = str(exception) # Print or do further processing with the error message print(error_message)
-
Использование метода
assertRaises()
и явный захват исключения:import unittest class MyTestCase(unittest.TestCase): def test_my_function(self): # Call the function that raises the error try: result = my_function() except ValueError as e: error_message = str(e) # Print or do further processing with the error message print(error_message) else: self.fail("Expected ValueError was not raised.")
-
Использование метода
assertRaisesRegexp()
(не рекомендуется в Python 3, но доступно в Python 2.7):import unittest class MyTestCase(unittest.TestCase): def test_my_function(self): # Call the function that raises the error with self.assertRaisesRegexp(ValueError, "expected error message"): result = my_function()
Эти методы позволяют извлекать и отображать сообщения об ошибках, обнаруженные функцией assertraises()
в модуле unittest
Python 2.7.