python - 你如何将异常参数传递给 python unittest 模拟副作用?

标签 python unit-testing mocking boto

如何将需要参数的异常作为模拟副作用传递?

我正在尝试测试 boto.exception.EC2ResponsError 的 assertRaises,但在 _mock_call 中得到“TypeError:init() takes at least 3 arguments (1 given)”。

@mock_ec2
@patch.object(Ec2Region, 'connect')
def test_ec2_get_raises(self, mock_connect):
    conn = boto.connect_ec2()
    mock_connect.return_value = conn
    reservation = conn.run_instances('ami-1234abcd')
    instance = reservation.instances[0]
    Ec2Instance.objects.create(region=self.region, account=self.account,
                               instance_id=instance.id)
    mock_connect.side_effect = boto.exception.EC2ResponseError
    self.assertRaises(
        boto.exception.EC2ResponseError,
        Ec2Instance.ec2_get, self.account, self.region)

我得到的错误是这样的:

======================================================================
ERROR: test_ec2_get_raises (session_ec2.tests.test_instance.Ec2InstanceTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/bschott/.virtualenvs/session-ec2/lib/python2.7/site-packages/moto/core/models.py", line 70, in wrapper
    result = func(*args, **kwargs)
  File "/Users/bschott/.virtualenvs/session-ec2/lib/python2.7/site-packages/mock.py", line 1201, in patched
    return func(*args, **keywargs)
  File "/Users/bschott/Source/session-ec2/session_ec2/tests/test_instance.py", line 84, in test_ec2_get_raises
    Ec2Instance.ec2_get, self.account, self.region)
  File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 475, in assertRaises
    callableObj(*args, **kwargs)
  File "/Users/bschott/Source/session-ec2/session_ec2/models/instance.py", line 110, in ec2_get
    connection = region.connect(account)
  File "/Users/bschott/.virtualenvs/session-ec2/lib/python2.7/site-packages/mock.py", line 955, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "/Users/bschott/.virtualenvs/session-ec2/lib/python2.7/site-packages/mock.py", line 1010, in _mock_call
    raise effect
TypeError: __init__() takes at least 3 arguments (1 given)

最佳答案

Calling 中所述部分您可以在 side_effect 初始化中同时使用实例或类。此外,您可以使用引发所需异常的可调用对象。

当类用于定义 side_effect 并且所需的异常没有普通的空构造函数时,您将得到一个与您拥有的异常相同的异常,因为 mock 框架没有知道如何构建该异常。

在你的情况下你可以使用类似的东西

mock_connect.side_effect = boto.exception.EC2ResponseError(400, "My reason", "my body")

关于python - 你如何将异常参数传递给 python unittest 模拟副作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677100/

相关文章:

scala - 是否可以在游戏功能测试中模拟数据库连接以及如何?

python 类方法模拟失败

python - 超时无法使用 urllib2、socks5 代理和 socksipy

python - 使用子进程调用从 python 函数重新启动 Linux 服务器

wpf - 寻找一些关于使用 MVVM 创建最佳实践单元测试的良好引用

java - gwt java 测试中的火灾事件不改变复选框的值

python - 强制其危险的 URLSafeTimedSerializer 提供旧签名

python - 如何下载位于 Web 服务器 CGI-bin 文件夹中的文件?

python - 需要 **kwargs 的 Callable 的类型注释

c++ - 如何使用签名 `object ()` 模拟函数