2

试图更多地理解 unittest.mock,但不知道为什么它运行程序两次。为简单起见,请考虑文件中的以下代码test.py

from unittest.mock import patch

class T():
    def __init__(self):
        self.setup()

    def setup(self):
        mock_testing = patch('test.testing').start()
        mock_testing.return_value = "new testing"

def testing():
    return "testing"

print("Hello")

t = T()

print("Setting up")

if testing() == "testing":
    print("old style")
elif testing() == "new testing":
    print("new style")

当我使用 运行脚本时python test.py,我得到:

Hello
Hello
Setting up
new style
Setting up
old style

为什么它运行代码两次?即使它确实运行了两次,“你好”怎么会被背靠背打印出来,应该像这样打印:

Hello
Setting up
new style
Hello
Setting up
old style

另外,我怎样才能使它只运行一次代码,模拟值为“新测试”?

4

1 回答 1

3

这是因为脚本首先作为模块加载__main__,但您使用 调用patchtest.testing所以patchtest.py再次作为test模块导入。由于在打印patch之前调用"Setting up",因此模块的加载test以及模块和模块的打印"Hello"都将在模块打印之前完成。__main__test"Setting up"__main__

如果添加__name__的参数print,您将更容易看到发生了什么:

from unittest.mock import patch

class T():
    def __init__(self):
        self.setup()

    def setup(self):
        mock_testing = patch('test.testing').start()
        mock_testing.return_value = "new testing"

def testing():
    return "testing"

print(__name__, "Hello")

t = T()

print(__name__, "Setting up")

if testing() == "testing":
    print(__name__, "old style")
elif testing() == "new testing":
    print(__name__, "new style")

这输出:

__main__ Hello
test Hello
test Setting up
test new style
__main__ Setting up
__main__ old style

为避免这种情况,您应该__main__.testing改为打补丁,以便修改后,上面的代码将输出:

__main__ Hello
__main__ Setting up
__main__ new style
于 2019-11-14T00:40:35.727 回答