我需要在client.py中测试这个类:

import socket

class Client:
    def execute(self, url: str):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(('localhost', 9999))
            sock.send(url.encode())
            data = sock.recv(1024)
            sock.close()
            print(f"{url}: {data.decode('utf-8')}")
        except Exception as e:
            print("Error sending request to", url, ":", str(e))

tests中,我模拟了socket.socket,并试图模拟sock.connect,以便它将返回异常:

import client

    def test_1(self, mocker, capsys):
        mock_socket = mocker.patch("socket.socket")
        mock_socket.return_value.connect.return_value = ConnectionRefusedError
        client1 = client.Client()
        client1.execute("https://example.com")
        captured = capsys.readouterr()
        assert captured.out == "Error sending request to https://example.com : [WinError 10061]"

But this Exception didn't triggered and I got this result in captured.out:
"https://example.com: <MagicMock name='socket().recv().decode()' id='1874290459152'>\n"
instead of
'Error sending request to https://example.com : [WinError 10061]'
which shows that I didn't hit except Exception as e: block. How to pass this Exception properly?

推荐答案

要使模拟函数在调用时引发异常,请改为设置side_effect属性:

mock_socket.return_value.connect.side_effect = ConnectionRefusedError('[WinError 10061]')

Python相关问答推荐

Django:如何将一个模型的唯一实例创建为另一个模型中的字段

按日期和组增量计算总价值

FastAPI:使用APIRouter路由子模块功能

是否有方法将现有的X-Y图转换为X-Y-Y1图(以重新填充)?

使用Python C API重新启动Python解释器

避免循环的最佳方法

模型序列化器中未调用现场验证器

在Pandas框架中截短至固定数量的列

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

抓取rotowire MLB球员新闻并使用Python形成表格

查找两极rame中组之间的所有差异

使用setuptools pyproject.toml和自定义目录树构建PyPi包

删除字符串中第一次出现单词后的所有内容

如何在Python数据框架中加速序列的符号化

如何在Raspberry Pi上检测USB并使用Python访问它?

根据列值添加时区

如何根据一列的值有条件地 Select 前N组?

计算天数

如何在Python中使用另一个数据框更改列值(列表)

搜索按钮不工作,Python tkinter