3
是否有任何方式臨時撤銷修補使用mock
在side_effect
內? 我特別想打這樣的工作:臨時「打補丁」功能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()
無法在'side_effect'中真正地訪問'self' – Oleksiy
@Oleksiy:你是怎麼想的? Python有閉包,因此你可以從'side_effect'中的周圍命名空間訪問所有名字。這包括'自我',這本身並沒有什麼特別之處。 – lunaryorn
的確如此!謝謝! – Oleksiy