重命名内置函数以进行测试

时间:2012-08-29 11:32:56

标签: python unit-testing testing

我正在考虑在我的测试套件中重命名一些内置函数,但是我发现这样做具有全局效果(当我预期它们只在本地产生效果时)。例如:

import time
def test():
    time.sleep = "hello" #woah there! time is mutable so this won't just apply locally!

print time.sleep #prints <built-in function sleep>
test()
print time.sleep #prints hello (!)

我必须将time.sleep恢复到test()结束之前的状态吗?

这是气馁 ...... 应该我做这种测试的方式?

2 个答案:

答案 0 :(得分:3)

如果您想要以这种方式测试对象,则应使用dependency injectionmocking。从程序的“顶部”传入一个对象(在本例中为时间)。然后你可以通过传入一个模拟版本对单个函数或对象进行单元测试。

示例:

# Function to be tested
def callSleep(timer):
    timer.sleep(5)

# Example usage
def main():
    import time
    timer = time

    callSleep(timer)

# Example test
def testFunction():


    class MockTimer:
        numCalled = 0
        withValue = 0
        def sleep(self, val):
            self.numCalled += 1
            self.withValue = val

    mockTimer = MockTimer()

    callSleep(mockTimer)

    print "Num called:", mockTimer.numCalled, "with value", mockTimer.withValue

答案 1 :(得分:1)

我会按照上面@ Joe的建议,但下面是你的问题的快速解决方法。 至于为什么会发生这种情况,对time.sleep的引用在全局范围内,因此替换它的效果不仅限于本地范围。

import time
def test():
    old_sleep = time.sleep # Save a reference to the builtin
    time.sleep = "hello" #shouldn't this just set time.sleep locally?
    print 'Inside test:', time.sleep
    time.sleep = old_sleep # replace the reference

print time.sleep #prints <built-in function sleep>
test()
print time.sleep  #prints <built-in function sleep>