[TIP] Mocking sys.exit() and replacing it back?

Mark Roddy markroddy at gmail.com
Thu Aug 5 21:43:27 PDT 2010

On Thu, Aug 5, 2010 at 11:34 PM, Jorge Vargas <jorge.vargas at gmail.com> wrote:
> Hello,
> Doing this seems really simple. All we need is something like
> def mock_exit(exit_status):
>     return exit_status
> class RunCommand(TestCase):
>     def setUp(self):
>         #we setup a fake sys.exit() to allow tests to continue
>         sys.exit = mock_exit
> However I have two questions.
> 1- do I need a tearDown that will replace sys.exit with the original
> function?
> 2- if so which is the best way to do this? store it in self.orig_exit ?
> Or the test collector is smart enough to know it has to wipe out and
> reimport everything on each testcase ?
> In case someone asks this is with unittest2.
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python

You have a couple options:
1) Mock sys.exit, but you're going to want this to be undone if you
monkey patch the sys name space.  Doing so in tearDown() from a saved
attribute is one way.
2) A mocking framework will take care of all of this boot strap code
for you automatically.
3) Alternatively, you could leverage the fact that sys.exit() raises SystemExit:
def test_calls_sys_exit(self):
    with self.assertRaises(SystemExit) as cm:
    self.assertEqual(cm.exception.code, my_expected_exit_code)


More information about the testing-in-python mailing list