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

Jonathan Lange jml at mumak.net
Fri Aug 6 02:32:02 PDT 2010


On Fri, Aug 6, 2010 at 4:34 AM, 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.


Better than tearDown:

  def patch(self, obj, name, value):
    current = getattr(obj, name)
    setattr(obj, name, value)
    self.addCleanup(setattr, obj, name, current)
    return current

  def setUp(self):
    self.patch(sys, 'exit', mock_exit)

That way, the code in setUp reads much closer to what you actually intend.

jml



More information about the testing-in-python mailing list