有什么办法可以使用mock中的side_effect临时撤消补丁?
我特别想做这样的事情:

from mock import patch
import urllib2
import unittest

class SimpleTest(unittest.TestCase):
    def setUp(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()

最佳答案

为什么不只是临时.stop()补丁?

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

关于python - 模仿.side_effect中的临时 "unpatching"功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7304588/

10-11 15:02