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:
Christian Kellner 2021-05-29 13:48:47 +02:00 committed by Tom Gundersen
parent a8fcda8348
commit 0447b00dfc
2 changed files with 28 additions and 0 deletions

View file

@ -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()

View file

@ -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)