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

Tim Hatch tim at timhatch.com
Fri Aug 6 08:00:20 PDT 2010


On 8/5/10 8:34 PM, Jorge Vargas wrote:
> Hello,
> 
> Doing this seems really simple.

For sys.exit() it could actually be cleaner, since it's done as a
SystemExit exception that when it gets to the outermost frame, actually
exits.

self.assertRaises(SystemExit, my_func)


As far as monkeypatching, it's probably best to treat them as a stack of
things to replace back.  i.e.

class ...
    def do_patch(self, obj, key, value):
        self.patches.append(obj, key, obj.key)
        obj.key = value

    def tearDown(self):
        for obj, key, value in self.patches[::-1]:
            obj.key = value

This way if you have TestCase subclasses 4 levels deep (as I ended up
ith at work) and a superclass somewhere mocks file() and then a subclass
does later, it restores the superclass mock before restoring the
original.  I guess you could do the same thing with a dict.

Tim



More information about the testing-in-python mailing list