gpt4 book ai didi

python - mock.side_effect 中的临时 "unpatching"功能

转载 作者:太空宇宙 更新时间:2023-11-03 11:10:00 25 4
gpt4 key购买 nike

有没有办法在 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()

最佳答案

为什么不暂时 .stop() 补丁?

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com