[TIP] Mocking sys.exit() and replacing it back?
dstanek at dstanek.com
Thu Aug 5 21:56:49 PDT 2010
On Thu, Aug 5, 2010 at 11:34 PM, Jorge Vargas <jorge.vargas at gmail.com> wrote:
> 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
> 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 ?
Yes storing it in an instance variable where the tearDown can access
it is a good idea.
I also have two alternatives for you:
1. Don't mock it and just uses TestCase.assertRaises
2. Do a form of DI and have the exit function passed into the class.
The default value would be the sys.exit function, but then in your
tests you can pass in a mock. No monkey patching necessary.
More information about the testing-in-python