Отображение сообщений об ошибках, обнаруженных функцией Assertraises() в модуле unittest Python 2.7.

Чтобы отобразить сообщения об ошибках, обнаруженные функцией assertraises()в модуле unittestPython 2.7, вы можете использовать несколько методов. Вот несколько подходов:

  1. Использование контекстного менеджера 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)
  2. Использование метода 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.")
  3. Использование метода 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()в модуле unittestPython 2.7.