Is it possible for a unit test to assert that a method calls sys.exit()?

后端 未结 4 1575
旧巷少年郎
旧巷少年郎 2020-12-02 14:02

I have a Python 2.7 method that sometimes calls

sys.exit(1)

Is it possible to make a unit test that verifies this line of code is called when

4条回答
  •  感情败类
    2020-12-02 14:34

    Yes. sys.exit raises SystemExit, so you can check it with assertRaises:

    with self.assertRaises(SystemExit):
        your_method()
    

    Instances of SystemExit have an attribute code which is set to the proposed exit status, and the context manager returned by assertRaises has the caught exception instance as exception, so checking the exit status is easy:

    with self.assertRaises(SystemExit) as cm:
        your_method()
    
    self.assertEqual(cm.exception.code, 1)
    

     

    sys.exit Documentation:

    Exit from Python. This is implemented by raising the SystemExit exception ... it is possible to intercept the exit attempt at an outer level.

提交回复
热议问题