gpt4 book ai didi

python - 如何在 Python 3.5 中使用 unittest.mock 模拟导入的库方法?

转载 作者:行者123 更新时间:2023-11-28 18:33:42 25 4
gpt4 key购买 nike

是否可以在 Python 3.5 中使用 unittest.mock 模拟导入模块的方法?

# file my_function.py
import os
my_function():
# do something with os, e.g call os.listdir
return os.listdir(os.getcwd())

# file test_my_function.py
test_my_function():
os = MagickMock()
os.listdir = MagickMock(side_effect=["a", "b"])
self.assertEqual("a", my_function())

我预计 os.listdir 方法会在第一次调用时返回指定的副作用“a”,但在 my_function 内部调用了未修补的 os.listdir。

最佳答案

unittest.mock有两个主要职责:

  • 定义 Mock 对象:旨在跟随您的剧本并记录对您的模拟对象的每次访问的对象
  • 修补引用并恢复原始状态

在您的示例中,您需要两种功能:通过模拟修补生产代码中使用的 os.listdir 引用,您可以完全控制模拟的响应方式。有很多方法可以使用patch , 一些 details to take care on how use itcavelets to know .

在您的情况下,您需要测试 my_function() 行为,并且需要修补 os.listdir()os.getcwd()。此外,您需要控制 return_value(查看有关 return_valueside_effect 差异的指向文档)。

我稍微重写了您的示例以使其更加完整和清晰:

my_function(nr=0):
l = os.listdir(os.getcwd())
l.sort()
return l[nr]

@patch("os.getcwd")
@patch("os.listdir", return_value=["a","b"])
def test_my_function(mock_ld, mock_g):
self.assertEqual("a", my_function(0))
mock_ld.assert_called_with(mock_g.return_value)
self.assertEqual("a", my_function())
self.assertEqual("b", my_function(1))
with self.assertRaises(IndexError):
my_function(3)

我使用装饰器语法是因为我认为它是一种更简洁的方式;此外,为了避免引入太多细节,我没有使用 autospecing我认为这是最佳实践。

最后一点:mocking 是一个强大的工具,但要使用它而不是滥用它,只需要打补丁就可以打补丁,仅此而已。

关于python - 如何在 Python 3.5 中使用 unittest.mock 模拟导入的库方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34417521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com