[英]testing paramiko in python3
I have a method thus:我有一个方法:
def ftp_fetch(self, hostname=None, username=None, password=None, file_name=None):
source_data = ''
if hostname and username and password and file_name:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname, username=username, password=password)
except paramiko.SSHException:
print("Connection Error")
sftp = ssh.open_sftp()
source_data = json.loads(
sftp.file(file_name).read()
)
ssh.close()
return source_data
return False
... and a test thus: ...和一个测试:
@patch('paramiko.SSHClient')
def test_ftp_fetch(mock_ssh):
test_content = '{"date": "06/02/2020", "time": "07:55", "floors":[{"floor": "地面", "capacity": 149, "occupancy": "20"},{"floor": "قبو", "capacity": 184, "occupancy": "20"}]}'
mock_ssh.open_sftp().file().read().return_string = test_content
foo = PreProcessor(code="foo")
response = foo.ftp_fetch()
assert response == False
response = foo.ftp_fetch(hostname='http://foo/', username='foo', password = 'bar', file_name = 'baz')
assert response == json.loads(test_content)
No matter what I've tried to do with the mock I get the same error:无论我试图用模拟做什么,我都会得到同样的错误:
___________________________________________________________________________ test_ftp_fetch ___________________________________________________________________________
mock_ssh = <MagicMock name='SSHClient' id='139650132358312'>
@patch('paramiko.SSHClient')
def test_ftp_fetch(mock_ssh):
test_content = '{"date": "06/02/2020", "time": "07:55", "floors":[{"floor": "地面", "capacity": 149, "occupancy": "20"},{"floor": "قبو", "capacity": 184, "occupancy": "20"}]}'
mock_ssh.open_sftp().file().read().return_string = test_content
foo = PreProcessor(code="foo")
response = foo.ftp_fetch()
assert response == False
> response = foo.ftp_fetch(hostname='http://foo/', username='foo', password = 'bar', file_name = 'baz')
preprocessors/test_preprocessors.py:339:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
preprocessors/preprocessors.py:229: in ftp_fetch
sftp.file(file_name).read()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
s = <MagicMock name='SSHClient().open_sftp().file().read()' id='139650131723376'>, encoding = None, cls = None, object_hook = None, parse_float = None
parse_int = None, parse_constant = None, object_pairs_hook = None, kw = {}
<< snip lots of doc text >>
if isinstance(s, str):
if s.startswith('\ufeff'):
raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
s, 0)
else:
if not isinstance(s, (bytes, bytearray)):
raise TypeError('the JSON object must be str, bytes or bytearray, '
> 'not {!r}'.format(s.__class__.__name__))
E TypeError: the JSON object must be str, bytes or bytearray, not 'MagicMock'
/usr/lib/python3.6/json/__init__.py:348: TypeError
So my question is simple:所以我的问题很简单:
How do I set up the mock so that the sftp read returns the text defined?如何设置模拟以便 sftp 读取返回定义的文本? (I'm using python 3.6 & pytest) (我正在使用 python 3.6 和 pytest)
((and yes, I always try to test with high-order unicode text, even if I don't expect it in normal use)) ((是的,我总是尝试使用高阶 unicode 文本进行测试,即使我不希望在正常使用中使用它))
MonkeyPatch
for better mocking.使用MonkeyPatch
进行更好的MonkeyPatch
。def test_user_details(monkeypatch):
mommy.make('Hallpass', user=user)
return_data =
{
'user_created':'done'
}
monkeypatch.setattr(
'user.create_user', lambda *args, **kwargs: return_data)
user_1 = create_user(user="+123456789")
assert user_1.return_data == return_data
Pass monkeypatch as argument to the test and pass the desired method you want o mock on monkeypatch function on test with required return data as you need.将monkeypatch 作为参数传递给测试,并根据需要通过所需的返回数据在测试中模拟monkeypatch 函数的所需方法。
Make sure you install monkey patch pip install monkeypatch
确保你安装了monkey patch pip install monkeypatch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.