我需要在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?