3

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

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

这是不鼓励的事情......我应该如何进行这种测试?

4

2 回答 2

3

如果你有一个想要以这种方式测试的对象,你应该使用依赖注入模拟。从程序的“顶部”传入一个对象(在这种情况下是时间)。然后您可以通过传入模拟版本来对单个函数或对象进行单元测试。

例子:

# 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
于 2012-08-29T11:34:44.827 回答
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>
于 2012-08-29T11:41:37.697 回答