不调用模拟方法socket.accept()

时间:2019-06-13 08:08:15

标签: python sockets mocking server-side

我正在尝试模拟套接字的服务器端。这个例子不起作用,我也不知道为什么(它仍然使用原始的socket.socket.accept()方法)。 有什么想法可以正确模拟监听套接字吗?

class MySocket:
    def __init__:
        self.socket = socket.socket()
    def listen(self):
        self.socket.accept()  # original socket method

class MockConn:
    def recv(self, int):
        return b'' 
    def close(self):
        pass
    def sendall(self, str):
        pass

with mock.patch('socket.socket') as mock_socket:
    conn = MockConn()
    mock_socket.return_value.accept.return_value = (conn, 'localhost')
    s = MySocket(None)
    s.listen()  # this should call accept from the mock

2 个答案:

答案 0 :(得分:0)

不确定您想要什么,但这可以工作:

import socket
from unittest import mock

class MySocket:
    def listen(self):
        print('Accept result:', socket.socket().accept())  
        # Accept result: (<__main__.MockConn object at 0x000001E592B36B38>, 'localhost')

class MockConn:
    def recv(self, int):
        return b'' 
    def close(self):
        pass
    def sendall(self, str):
        pass

with mock.patch('socket.socket') as mock_socket:
    conn = MockConn()
    mock_socket.return_value.accept.return_value = (conn, 'localhost')
    s = MySocket()
    s.listen()  

答案 1 :(得分:0)

对您当前的代码进行一些非常小的更改,即可工作:

from unittest import mock
import socket

class MySocket:
    def __init__(self):    # init takes self
        self.socket = socket.socket()
    def listen(self):
        return self.socket.accept()  # original socket method

class MockConn:
    def recv(self, int):
        return b''
    def close(self):
        pass
    def sendall(self, str):
        pass

with mock.patch('socket.socket') as mock_socket:
    conn = MockConn()
    mock_socket.return_value.accept.return_value = (conn, 'localhost')
    s = MySocket()
    print(s.listen())  # this should call accept from the mock

输出:

(<__main__.MockConn object at 0x00000255C5A53B00>, 'localhost')