开发者

Temporary "unpatching" functionality within mock.side_effect

Is there any way to temporary undo patching using mock within side_effect? In particular I'd like to make something like this work:

from mock import patch
import urllib2
import unittest

class SimpleTest(unittest.TestCase):
    def setU开发者_运维技巧p(self):
        self.urlpatcher = patch('urllib2.urlopen')
        self.urlopen = self.urlpatcher.start()

        def side_effect(url):
            #do some interesting stuff first

            #... temporary unpatch urllib2.urlopen so that we can call a real one here
            r = urllib2.urlopen(url) #this ought to be the real deal now
            #... patch it again

            return r

        self.urlopen.side_effect = side_effect

    def test_feature(self):
        #almost real urllib2.urlopen usage goes here
        p = urllib2.urlopen("www.google.com").read()


if __name__ == '__main__':
    unittest.main()


Why not just temporarily .stop() the patch?

self.urlopen.stop()
# points to the real `urlopen()` now
urllib2.urlopen()
# put the patch in place again
self.urlopen.start()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜