我正在寫一些使用paramiko的函數來執行命令並在遠程主機上創建文件。我想爲他們編寫一些單元測試,但我不知道最簡單的方法是什麼?這就是我設想爲我的代碼示例概要:在Python中模擬遠程主機
import os
import paramiko
import pytest
def my_function(hostname, relpath='.', **kwargs):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, **kwargs)
sftp = ssh.open_sftp()
sftp.chdir(relpath)
stdin, stdout, stderr = ssh.exec_command("echo hallo > test.txt")
@pytest.fixture("module")
def mock_remote_host():
# start a remote host here with a local test path
try:
yield hostname, testpath, {"username":"bob", "password":"1234"}
finally:
# delete the test path
# close the remote host
def test_my_function(mock_remote_host):
hostname, dirpath, kwargs = mock_remote_host
my_function(hostname, **kwargs)
filepath = os.path.join(dirpath, 'test.txt')
assert os.path.exists(filepath)
我有看paramiko test modules,但他們似乎對我的使用情況非常複雜,我不知道如何去簡化他們。
PyPi提供的第三方'mock'模塊是作爲'unittest.mock'併入到Python 3.3中的。 – chepner
我看到的唯一問題是,我將使用相當多的paramiko的功能來創建/銷燬文件/文件夾等。所以這意味着我必須爲每個人創建一個模擬功能這些功能。這感覺就像你沒有充分測試生產代碼中實際發生的情況。 –