mock.side_effect中的临时“取消修补”功能

6 投票
1 回答
3931 浏览
提问于 2025-04-17 01:28

有没有办法在side_effect里使用mock临时撤销补丁?我特别想让下面这样的代码能够正常工作:

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()

1 个回答

3

为什么不直接暂时用 .stop() 来停止这个补丁呢?

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

撰写回答