我想通过 ssh 连接执行命令来测试一些场景。我需要第二次调用 ssh 连接装置。
所以我的场景是这样的:
conftest.py 文件内部
@pytest.fixture(scope="session")
def get_ssh_connection(vars, logger):
ssh = SshClient(ip=vars["ip"],
port=vars["port"],
user=vars["username"],
passwd=vars["pw"])
ssh.connect()
yield ssh
ssh.close()
内部测试脚本:
@pytest.fixture(scope="class", autouse=True)
def setup_teardown(self, list):
self.ssh.exec_cmd(f"mv {file} {newfile}") # rename file
self.restartDevice() #ssh connection closed
yield
**self.ssh.exec_cmd**(f"mv {newfile} {file}") #restore file
self.restartDevice()
如何在重新启动设备后启用此 ssh 连接(突出显示的一个),因为 ssh 连接是作为会话的固定装置?
这是演示此场景的示例:
ssh_client
) 将通过 ssh 连接到远程主机。ssh_client
夹具。在这种情况下,我正在编写 2 个简单的测试。代码
# conftest.py
import logging
import time
import paramiko
import pytest
@pytest.fixture(scope="session")
def ssh_client():
"""
Create a ssh client and perform some prep works remotely.
"""
logging.info("First connection...")
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect("192.168.64.18", username="ubuntu")
logging.info("Connected")
logging.info("Prep the remote host")
# Perform prep works here
logging.info("Reboot the remote host")
client.exec_command("sudo shutdown -r now")
logging.info("Second connection...")
while True:
try:
client.connect("192.168.64.18", username="ubuntu")
logging.info("Connected again")
break
except (
paramiko.SSHException,
paramiko.ssh_exception.NoValidConnectionsError,
):
time.sleep(3)
yield client
logging.info("Clean up remote host")
# Do something here to clean up
# test_it.py
import paramiko
def test_user_is_not_root(ssh_client: paramiko.SSHClient):
_, stdout, _ = ssh_client.exec_command("whoami")
user = stdout.read().decode().strip()
assert user != "root"
def test_os_release_exists(ssh_client: paramiko.SSHClient):
with ssh_client.open_sftp() as sftp:
sftp.stat("/etc/os-release") # Will raise if not exist
# pyproject.toml
[tool.pytest.ini_options]
addopts = "--strict-markers"
log_cli_level = "INFO"
log_cli = true
ssh_client
有点长,但我希望能直截了当pyproject.toml
文件来控制日志记录级别。