【问题标题】:Temporary "unpatching" functionality within mock.side_effectmock.side_effect 中的临时“取消修补”功能
【发布时间】:2011-09-05 06:39:26
【问题描述】:

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

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

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

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

    【讨论】:

    • side_effect内无法真正访问self
    • @Oleksiy:是什么让你这么认为?! Python 有闭包,因此您可以从side_effect 中直接环绕的命名空间访问所有名称。这包括self,它本身并没有什么特别之处。
    • @lunaryorn 代码不需要 self.urlpatcher.start/stop() 吗?
    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多