From b86b6a4bf8584e0b9085023756659018361a944a Mon Sep 17 00:00:00 2001 From: Christian Kellner Date: Wed, 22 Jul 2020 15:24:47 +0200 Subject: [PATCH] test/api: add checks for the api infrastructure Add a check for `api.BaseAPI` by implementing a test API and test that receiving messages and dispatching them works as planned. --- test/mod/test_api.py | 66 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 test/mod/test_api.py diff --git a/test/mod/test_api.py b/test/mod/test_api.py new file mode 100644 index 00000000..d46e7736 --- /dev/null +++ b/test/mod/test_api.py @@ -0,0 +1,66 @@ +# +# Test for API infrastructure +# + +import os +import tempfile +import unittest + +import osbuild +from osbuild.util import jsoncomm + + +class APITester(osbuild.api.BaseAPI): + """Records the number of messages and if it got cleaned up""" + def __init__(self, sockaddr): + super().__init__(sockaddr) + self.clean = False + self.messages = 0 + + def _dispatch(self, server): + msg, _, addr = server.recv() + self.messages += 1 + + if msg["method"] == "echo": + msg["method"] = "reply" + server.send(msg, destination=addr) + + def _cleanup(self): + self.clean = True + + +class TestAPI(unittest.TestCase): + """Check API infrastructure""" + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp.cleanup() + + def test_basic(self): + # Basic API communication and cleanup checks + + socket = os.path.join(self.tmp.name, "socket") + api = APITester(socket) + with api: + with jsoncomm.Socket.new_client(socket) as client: + req = {'method': 'echo', 'data': 'Hello'} + client.send(req) + msg, _, _ = client.recv() + self.assertEqual(msg["method"], "reply") + self.assertEqual(req["data"], msg["data"]) + + self.assertEqual(api.clean, True) + self.assertEqual(api.messages, 1) + + # Assert proper cleanup + self.assertIsNone(api.thread) + self.assertIsNone(api.event_loop) + + def test_reentrancy_guard(self): + socket = os.path.join(self.tmp.name, "socket") + api = APITester(socket) + with api: + with self.assertRaises(AssertionError): + with api: + pass