How do you show an error message when a test does not throw an expected exception?

前端 未结 2 914
傲寒
傲寒 2021-01-27 08:02

I am new to python. I wanted to test if my code throws an exception. I got the code from here: How do you test that a Python function throws an exception?

import         


        
相关标签:
2条回答
  • 2021-01-27 08:55

    Now, I also want to display a message if the exception is not thrown. How do I do that ?

    The general philosophy of unittest is for the tests to be silent when they succeed and only become verbose when they fail. Accordingly, the API provides a "msg" keyword argument for the unsuccessful case but does not offer an alternative for the successful case.

    That said, another part of the philosophy works in your favor. In general, test cases internally raise an exception when a testcase fails. That means that if you want to display a message when there is a success, you just add another statement after the test:

    with self.assertRaises(TypeError, msg='Oh no, I did not get a TypeError')
         somecode()
    logging.info('Yippee, we got a TypeError!')  # Runs after a successful test
    
    0 讨论(0)
  • 2021-01-27 08:57

    As of python 3.3, assertRaises can be used as a context manager with a message:

    import unittest
    
    def sayHelloTo(name):
        print("Hello " + name)
    
    class MyTestCase(unittest.TestCase):
        def test1(self):
            person = "John"
            with self.assertRaises(Exception, msg="My insightful message"):
                sayHelloTo(person)
    
    if __name__ == "__main__":
        unittest.main()
    

    Results in

    Hello John
    F
    ======================================================================
    FAIL: test1 (__main__.MyTestCase)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "r.py", line 10, in test1
        sayHelloTo(person)
    AssertionError: Exception not raised : My insightful message
    
    ----------------------------------------------------------------------
    Ran 1 test in 0.001s
    
    FAILED (failures=1)
    
    0 讨论(0)
提交回复
热议问题