[TIP] Mocking sys.exit() and replacing it back?
jorge.vargas at gmail.com
Fri Aug 6 07:39:26 PDT 2010
On Fri, Aug 6, 2010 at 12:43 AM, Mark Roddy <markroddy at gmail.com> wrote:
> On Thu, Aug 5, 2010 at 11:34 PM, Jorge Vargas <jorge.vargas at gmail.com>
> > 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.
ok I just wanted to know if unittest2 took care of this by reloading the
module. Seems it does not.
> 2) A mocking framework will take care of all of this boot strap code
> for you automatically.
I know that's the best option however In this particular project I have a
zero-external dependencies (imposed) policy.
> 3) Alternatively, you could leverage the fact that sys.exit() raises
> def test_calls_sys_exit(self):
> with self.assertRaises(SystemExit) as cm:
> self.assertEqual(cm.exception.code, my_expected_exit_code)
This could work, however I like the mock option a little better.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the testing-in-python