Python 中的 with..as 子句断言
Asserting with..as clause in Python
所以,有了 unittest.mock 和代码
with pysftp.Connection(host, username, password, port) as sftp:
sftp.get("filename")
... 可以断言 Connection.assert_called_with(host, username, password, port)
。
但是断言 Connection.assert_called_with(host, username, password, port).get("filename")
失败了。
我该如何断言?
我假设你想 patch
pysftp.Connection
参考。
以下是如何进行测试的示例:
>>> import pysftp
>>> from mock import *
>>> with patch("pysftp.Connection") as mock_connection:
... with pysftp.Connection("1.2.3.4", "user", "pwd", 12345) as sftp:
... sftp.get("filename")
... mock_connection.assert_called_with("1.2.3.4", "user", "pwd", 12345)
... sftp.get.assert_called_with("filename")
...
<MagicMock name='Connection().__enter__().get()' id='139907730030992'>
因为sftp
对象是一个MagicMock
你可以直接使用它。正如您在日志中看到的 sftp
与
完全相同
mock_connection.return_value.__enter__.return_value
Connection
-> mock_connection
()
-> return_value
所以,有了 unittest.mock 和代码
with pysftp.Connection(host, username, password, port) as sftp:
sftp.get("filename")
... 可以断言 Connection.assert_called_with(host, username, password, port)
。
但是断言 Connection.assert_called_with(host, username, password, port).get("filename")
失败了。
我该如何断言?
我假设你想 patch
pysftp.Connection
参考。
以下是如何进行测试的示例:
>>> import pysftp
>>> from mock import *
>>> with patch("pysftp.Connection") as mock_connection:
... with pysftp.Connection("1.2.3.4", "user", "pwd", 12345) as sftp:
... sftp.get("filename")
... mock_connection.assert_called_with("1.2.3.4", "user", "pwd", 12345)
... sftp.get.assert_called_with("filename")
...
<MagicMock name='Connection().__enter__().get()' id='139907730030992'>
因为sftp
对象是一个MagicMock
你可以直接使用它。正如您在日志中看到的 sftp
与
mock_connection.return_value.__enter__.return_value
Connection
->mock_connection
()
->return_value