util/jsoncomm: add pair constructor method
Add a new constructor method, `Socket.new_pair`, to create a pair of connected sockets (via `socketpair`) and wrap both sides via `jsoncomm.Socket`. Add a simple test to check it.
This commit is contained in:
parent
a8fcda8348
commit
0447b00dfc
2 changed files with 28 additions and 0 deletions
|
|
@ -254,6 +254,24 @@ class Socket(contextlib.AbstractContextManager):
|
|||
|
||||
return cls(sock, (unlink, path[1]))
|
||||
|
||||
@classmethod
|
||||
def new_pair(cls, *, blocking=True):
|
||||
"""Create a connected socket pair
|
||||
|
||||
Create a pair of connected sockets and return both as a tuple.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
blocking
|
||||
The blocking mode for the socket pair.
|
||||
"""
|
||||
a, b = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET)
|
||||
|
||||
a.setblocking(blocking)
|
||||
b.setblocking(blocking)
|
||||
|
||||
return cls(a, None), cls(b, None)
|
||||
|
||||
def fileno(self) -> int:
|
||||
assert self._socket is not None
|
||||
return self._socket.fileno()
|
||||
|
|
|
|||
|
|
@ -176,3 +176,13 @@ class TestUtilJsonComm(unittest.TestCase):
|
|||
|
||||
conn = listener.accept()
|
||||
self.assertIsNone(conn)
|
||||
|
||||
def test_socket_pair(self):
|
||||
#
|
||||
# Test creating a socket pair and sending, receiving of a simple message
|
||||
a, b = jsoncomm.Socket.new_pair()
|
||||
|
||||
ping = {"osbuild": "yes"}
|
||||
a.send(ping)
|
||||
pong, _, _ = b.recv()
|
||||
self.assertEqual(ping, pong)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue