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

前端 未结 2 949
傲寒
傲寒 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
    

提交回复
热议问题