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

Jorge Vargas jorge.vargas at gmail.com
Fri Aug 6 07:41:41 PDT 2010


On Fri, Aug 6, 2010 at 5:32 AM, Jonathan Lange <jml at mumak.net> wrote:

> 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.
>

Awesome. That looks like a great and clean solution. Thank you!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20100806/4e9f53ae/attachment.htm>


More information about the testing-in-python mailing list