gpt4 book ai didi

python - 如何模拟作为函数输入的对象?

转载 作者:行者123 更新时间:2023-11-28 20:25:47 24 4
gpt4 key购买 nike

通常当我模拟时,我有以下类型的设置

# my_script.py
import numpy as np

def my_func(x):
out = np.power(x, 2)
return out

然后在 my_script 中测试 numpy power 调用:

# test_myscript.py

import numpy as np
import unittest
import mock

from my_script import my_func


class TestMyScript(unittest.TestCase):

@mock.patch("my_script.np")
def test_my_func(self, mock_os):
"""Test that numpy.power was called"""
a = np.array([1, 2, 3])
my_func(a)
mock_os.power.assert_called_with(a, 2)


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

这很好用。

但是现在如果情况发生变化,假设我将 numpy 模块作为一个参数 放入 my_func 中;在这种情况下,我不知道如何模拟 numpy

我如何在下面的函数中模拟 numpy,就像在上面的 test_myscript 中模拟一样?

请注意,numpy 不会导入到 my_script.py 中,而是导入到运行 my_script.py 函数的单独脚本中>.

# my_script.py
# numpy NOT imported in this script!

def my_func(x, numpy):
out = numpy.power(x, 2)
return out

编辑:

根据@Daniel Roseman 的评论,我包含了更多代码以明确函数的调用方式

# main_script.py

import numpy as np

from my_script import my_func

def main():
a = np.array([1, 2, 3])
my_func(a, np) # numpy is passed into `my_func`

然后为了测试,我正在尝试下面的

# test_myscript.py

import numpy as np
import unittest
import mock

from my_script import my_func

class TestMyScript(unittest.TestCase):

@mock.patch("main_script.np") # import from main_script since numpy is imported here
def test_my_func(self, mock_os):
"""Test that numpy.power was called"""
a = np.array([1, 2, 3])
my_func(a)
mock_os.power.assert_called_with(a, 2)


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

但这失败了

Ran 1 test in 0.154s
>>> FAILED (failures=1)
>>> AssertionError: Expected 'power' to have been called.

最佳答案

我发现在这里使用 unittest.mock.Mock 对象效果最好。

所以如果我们有:

# my_script.py

def my_func(x, numpy):
out = numpy.power(x, 2)
return out

然后为了测试它我们有:

# test_myscript.py

import numpy as np
import unittest
from unittest.mock import Mock

from my_script import my_func

numpy_mock = Mock()


class TestMyScript(unittest.TestCase):

def test_my_func(self):
"""Test that numpy.power was called"""
a = np.array([1, 2, 3])
_ = my_func(a, numpy_mock) # pass the mocked object here
numpy_mock.power.assert_called_once_with(a, 2)


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

哪个通过了测试

关于python - 如何模拟作为函数输入的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58270043/

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