You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何Mock paramiko.SSHClient使connect调用抛出异常?

问题原因与解决方案

你当前的测试代码没有正确设置实例方法的异常抛出——你给类的mock(ssh_client_mock)的connect属性设置了side_effect,但实际代码中调用的是实例的connect方法(也就是with语句里ssh对象的connect)。

正确的测试写法

要让实例的connect抛出异常,需要给SSHClient类mock的return_value(也就是类实例的mock)的connect方法设置side_effect:

def raiser():
    raise ValueError("test")

# 补丁paramiko.SSHClient类
ssh_client_mock = mocker.patch('paramiko.SSHClient')
# 获取类实例的mock(对应with语句中的ssh对象)
ssh_instance = ssh_client_mock.return_value
# 给实例的connect方法设置异常抛出
ssh_instance.connect.side_effect = raiser

如果待测试代码封装在函数里,完整测试用例可以写成这样:

import pytest
from unittest import mock
import paramiko

# 假设待测试代码封装在这个函数里
def ssh_connect(host_name, user_name, pk, port):
    with paramiko.SSHClient() as ssh:
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host_name, username=user_name, pkey=pk, port=port)

def test_ssh_connect_raises_error():
    def raiser():
        raise ValueError("test")
    
    with mock.patch('paramiko.SSHClient') as ssh_client_mock:
        # 给实例的connect设置异常
        ssh_client_mock.return_value.connect.side_effect = raiser
        
        # 验证调用时抛出预期异常
        with pytest.raises(ValueError, match="test"):
            ssh_connect("test_host", "test_user", None, 22)

为什么原来的写法无效?

当你mockparamiko.SSHClient类时:

  • ssh_client_mock是类的mock对象
  • with paramiko.SSHClient() as ssh中的ssh是ssh_client_mock.return_value(类实例的mock)
  • 你之前设置的ssh_client_mock.connect是类方法的mock,和实例方法无关,所以实际调用ssh.connect时不会触发异常。

内容的提问来源于stack exchange,提问作者reikje

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 16:45:06