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