From ddfa066de1c876111c8682f2f43d93fc5326b997 Mon Sep 17 00:00:00 2001 From: Martin Raspaud Date: Mon, 8 May 2023 11:06:40 +0200 Subject: [PATCH] Add two testing utilities --- posttroll/testing.py | 24 ++++++++++++++++++++++++ posttroll/tests/test_testing.py | 11 +++++++++++ 2 files changed, 35 insertions(+) create mode 100644 posttroll/testing.py create mode 100644 posttroll/tests/test_testing.py diff --git a/posttroll/testing.py b/posttroll/testing.py new file mode 100644 index 0000000..501aa53 --- /dev/null +++ b/posttroll/testing.py @@ -0,0 +1,24 @@ +"""Testing utilities.""" +from contextlib import contextmanager + +@contextmanager +def patched_subscriber_recv(messages): + """Patch the Subscriber object to return given messages.""" + from unittest import mock + with mock.patch("posttroll.subscriber.Subscriber.recv", mock.Mock(return_value=messages)): + yield + +@contextmanager +def patched_publisher(): + """Patch the Subscriber object to return given messages.""" + from unittest import mock + published = [] + + def fake_send(self, message): + published.append(message) + + def noop(self, *args, **kwargs): + pass + + with mock.patch.multiple("posttroll.publisher.Publisher", send=fake_send, start=noop, stop=noop): + yield published diff --git a/posttroll/tests/test_testing.py b/posttroll/tests/test_testing.py new file mode 100644 index 0000000..c8909ff --- /dev/null +++ b/posttroll/tests/test_testing.py @@ -0,0 +1,11 @@ +from posttroll.testing import patched_publisher + +def test_fake_publisher(): + from posttroll.publisher import create_publisher_from_dict_config + + with patched_publisher() as messages: + pub = create_publisher_from_dict_config(dict(port=1979, nameservers=False)) + pub.start() + pub.send("bla") + pub.stop() + assert "bla" in messages