我在测试异常时遇到了问题,这些异常将在Anwithinpython3.4中引发。我只是不能让测试运行来保证代码的安全:
import logging
...
class Foo(object):
...
def foo(self, src, dst):
try:
with pysftp.Connection(self._host, username=self._username, password=self._password) as connection:
connection.put(src, dst)
connection.close()
except (
ConnectionException,
CredentialException,
SSHException,
AuthenticationException,
HostKeysException,
PasswordRequiredException
) as e:
self._log.error(e)这就是我要测试的方法:
import logging
...
class TestFoo(TestCase):
@parameterized.expand([
('ConnectionException', ConnectionException),
('CredentialException', CredentialException),
('SSHException', SSHException),
('AuthenticationException', AuthenticationException),
('HostKeysException', HostKeysException),
('PasswordRequiredException', PasswordRequiredException),
])
@patch('pysftp.Connection', spec_set=pysftp.Connection)
def test_foo_exceptions(self, _, ex, sftp_mock):
"""
NOTE: take a look at:
http://stackoverflow.com/questions/37014904/mocking-python-class-in-unit-test-and-verifying-an-instance
to get an understanding of __enter__ and __exit__
"""
sftp_mock.return_value = Mock(
spec=pysftp.Connection,
side_effect=ex,
__enter__ = lambda self: self,
__exit__ = lambda *args: None
)
foo = Foo('host', 'user', 'pass', Mock(spec_set=logging.Logger))
foo.foo('src', 'dst')
self.assertEqual(foo._log.error.call_count, 1)但是它失败了--输出:
Failure
...
AssertionError: 0 != 1发布于 2016-08-09 16:32:45
您的sftp_mock.return_value对象从未被调用,因此不会触发side_effect,也不会引发异常。只有当pysftp.Connection(...)的返回值本身再次被调用时,才会调用它。
将副作用直接设置在模拟上。
sftp_mock.side_effect = ex请注意,现在pysftp.Connection(...)表达式会引发异常,该表达式的返回值在with语句中用作上下文管理器不再重要。
请注意,您的异常会抱怨没有获得任何参数;传入异常实例,而不是类型:
@parameterized.expand([
('ConnectionException', ConnectionException('host', 1234)),
# ... etc.
])https://stackoverflow.com/questions/38854796
复制相似问题