gpt4 book ai didi

python - 模拟socket.recv()

转载 作者:行者123 更新时间:2023-12-03 12:08:21 26 4
gpt4 key购买 nike

我想 mock 套接字的recv函数并遇到麻烦。即使我没有必要,也要获取实际上连接套接字所需的错误。

这是所有相关代码:

Class A:
def __init__.py(self):
self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def connect(self):
self.s.connect((host,port))
def data_collection(self, d):
self.send_over_socket(self.cg.get_privilege_command())
self.send_over_socket(self.status_string)
buf = ""
while 1:
buf = buf + self.s.recv(self.BUFFER_SIZE).decode()
#Removed string manipulation below
self.publish(data from string manipulation)

def send_over_socket(self,data):
return (self.s.send(bytes(data.encode())))

pytest代码;
def test_data_collection():
with mock.patch('moduleA.classA.send_over_socket') as mock_send_over_socket:
A = classA()
A.send_over_socket.return_value = 1
with mock.patch('socket.socket') as mock_socket:
mock_socket.return_value.recv.decode.return_value = "packet_string"
with mock.patch('moduleA.ClassA.publish') as mock_publish:
d = {}
A.data_collection(d)
A.publish.assert_called_with("0","500","2","1")

最佳答案

您缺少return_valuemock_socket;您需要解决socket.socket将要返回的内容。您的测试应如下所示:

def test_data_collection():
with mock.patch('socket.socket') as mock_socket:
A = classA()
mock_socket.return_value.recv.decode.return_value = "ABC123"
buf = A.data_collection()
assert "ABC123" == buf

请注意,我必须修复您的类代码中的一些语法错误,并且使 data_collection返回 buf变量,以便可以对其进行测试。

编辑:类文件:
"""receiver.py"""
import socket

IP = 'localhost'
PORT = 80


class classA:
def __init__(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self):
self.s.connect((IP, PORT))
def data_collection(self):
buf = self.s.recv.decode()
return buf

关于python - 模拟socket.recv(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52394540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com