1

您好,我有以下代码;

我正在尝试测试 file_a 中的加载函数;下载是我导入的外部模块中的功能

file_a.py

from foo import download

class Bar()
    __init__(self, arg_1):
        self.var = arg_1

    def load(self):
        if self.var == "latest_lib":
            download("latest_lib")

我写了这样的测试

test.py

@patch(file_a.download)
def test_download():
    import file_a
    bar = file_a.Bar("latest_lib")
    bar.load()
    file_a.download.assert_called() 

但似乎 bar 对象没有调用模拟下载,而是调用了导入的下载。我怎样才能解决这个问题并使我的测试通过?

4

2 回答 2

3

我试着用你自己的代码来看看哪里出了问题。有一些语法错误并不重要,但主要问题是您应该传递字符串以patch使其工作。

这是我对您的代码的修改,这一切都发生了:

# file_a.py

from pprint import pprint as pp

class Bar():
    def __init__(self, arg_1):
        self.var = arg_1

    def load(self):
        if self.var == "latest_lib":
            pp("latest_lib")

和:

# test_file_a.py

import unittest
from unittest.mock import patch


class TestStringMethods(unittest.TestCase):
    @patch("file_a.pp")
    def test_download(self, pp):
        import file_a
        bar = file_a.Bar("latest_lib")
        bar.load()
        pp.assert_called()


if __name__ == "__main__":
    unittest.main()

笔记:

  1. 您需要传递一个字符串以patch使其在运行时模拟对象。
  2. 您必须在测试函数中接收模拟对象。
  3. 我在这里使用了基于类的测试,因为我想使用unittest标准库,但如果你使用pytest.

还有来自官方文档的最后一条说明:

基本原则是您在查找对象的位置进行修补,该位置不一定与定义对象的位置相同。

于 2021-05-15T09:10:59.863 回答
0

我认为您缺少模拟设置:

@patch("foo.download")
def test_download(mock_download):
    from file_a import Bar

    Bar("latest_lib").load()
    mock_download.assert_called()
于 2021-05-15T04:53:37.123 回答