我正在尝试使用重写的socket.socket
和send()
方法在Python2.7中创建read()
类的子类,以便它们将通过套接字传输的数据转储到终端中。代码如下所示:
import socket
class SocketMonkey(socket.socket):
def send(self, buf):
print('BUF: {}'.format(buf))
return super(SocketMonkey, self).send(buf)
def recv(self, size=-1):
buf = super(SocketMonkey, self).recv(size)
print('BUF: {}'.format(buf))
return buf
socket.socket = SocketMonkey
这就是我实例化和使用这个类的方法:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('www.domain.com', 80))
sock.send('GET / HTTP/1.1\n\n')
我已经修补了socket模块,但是套接字功能像以前一样工作,数据没有被转储。知道我哪里错了吗?
答案 0 :(得分:0)
我也遇到了同样的问题,可以使用以下代码解决
import socket
import logging
class TestSocket:
"""
Defines a custom socket class that'll be used for testing.
"""
def __init__(self, af, sock_type):
logging.log(logging.DEBUG,
f"FAKE SOCKET CONSTRUCT [{af}] [{sock_type}]")
def sendto(self, data, address):
logging.log(logging.DEBUG,
f"SEND TO [{data}] [{address}]")
def socket_get(af, sock_type):
return TestSocket(af, sock_type)
def test_download_file(monkeypatch, submission):
with monkeypatch.context() as m:
# This replaces the socket constructor.
m.setattr(socket, "socket", socket_get)
# use socket now.
# ...