From 8890e67b86d876b8e100c87589bc613f0c06d93c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Thu, 5 Sep 2019 15:52:34 +0200 Subject: [PATCH] Implement test cases for PipeIOHandler --- tfw/components/pipe_io/pipe_io_handler.py | 5 ++- .../pipe_io/test_pipe_io_handler.py | 45 +++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 tfw/components/pipe_io/test_pipe_io_handler.py diff --git a/tfw/components/pipe_io/pipe_io_handler.py b/tfw/components/pipe_io/pipe_io_handler.py index d5726a1..50201ac 100644 --- a/tfw/components/pipe_io/pipe_io_handler.py +++ b/tfw/components/pipe_io/pipe_io_handler.py @@ -21,7 +21,8 @@ class PipeIOHandlerBase: def __init__(self, in_pipe_path, out_pipe_path, permissions=DEFAULT_PERMISSIONS): self.connector = None - self._in_pipe = in_pipe_path + self.in_pipe = in_pipe_path + self.out_pipe = out_pipe_path self.pipe_io = PipeIOServer( in_pipe_path, out_pipe_path, @@ -34,7 +35,7 @@ class PipeIOHandlerBase: try: self.handle_pipe_event(message) except: # pylint: disable=bare-except - LOG.exception('Failed to handle message %s from pipe %s!', message, self._in_pipe) + LOG.exception('Failed to handle message %s from pipe %s!', message, self.in_pipe) @abstractmethod def handle_pipe_event(self, message_bytes): diff --git a/tfw/components/pipe_io/test_pipe_io_handler.py b/tfw/components/pipe_io/test_pipe_io_handler.py new file mode 100644 index 0000000..b4a0aaa --- /dev/null +++ b/tfw/components/pipe_io/test_pipe_io_handler.py @@ -0,0 +1,45 @@ +# pylint: disable=redefined-outer-name +from tempfile import TemporaryDirectory +from os.path import join +from queue import Queue +from json import dumps, loads + +import pytest + +from .pipe_io_handler import PipeIOHandler + + +@pytest.fixture +def pipe_io(): + with TemporaryDirectory() as tmpdir: + pipeio = PipeIOHandler( + join(tmpdir, 'in'), + join(tmpdir, 'out'), + permissions=0o600 + ) + pipeio.connector = MockConnector() + yield pipeio + pipeio.cleanup() + + +class MockConnector: + def __init__(self): + self.messages = Queue() + + def send_message(self, msg): + self.messages.put(msg) + + +def test_pipe_io_handler_recv(pipe_io): + test_msg = {'key': 'cica'} + with open(pipe_io.in_pipe, 'w') as ofile: + ofile.write(dumps(test_msg) + '\n') + + assert pipe_io.connector.messages.get() == test_msg + + +def test_pipe_io_handler_send(pipe_io): + test_msg = {'key': 'cica'} + pipe_io.handle_event(test_msg, None) + with open(pipe_io.out_pipe, 'r') as ifile: + assert loads(ifile.readline()) == test_msg