From ebecb9af9593ab639298b3f17373efa3056fb765 Mon Sep 17 00:00:00 2001 From: Tomaz Muraus Date: Mon, 31 Jul 2023 21:42:33 +0200 Subject: [PATCH] Add a comment and some in-direct test for connection re-use / making sure self.connect() is only called if connection details (scheme, host, port) change. --- libcloud/common/openstack.py | 2 ++ libcloud/test/common/test_openstack.py | 41 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/libcloud/common/openstack.py b/libcloud/common/openstack.py index d63cddb7c2..960b759af6 100644 --- a/libcloud/common/openstack.py +++ b/libcloud/common/openstack.py @@ -362,6 +362,8 @@ def _set_up_connection_info(self, url): (self.host, self.port, self.secure, self.request_path) = result new_conn = (self.host, self.port, self.secure) if new_conn != prev_conn: + # We only call connect in case connection details have changed - this way we correctly + # re-use connection in case nothing has changed self.connect() def _populate_hosts_and_request_paths(self): diff --git a/libcloud/test/common/test_openstack.py b/libcloud/test/common/test_openstack.py index e10a7a1e1e..2bfeb76401 100644 --- a/libcloud/test/common/test_openstack.py +++ b/libcloud/test/common/test_openstack.py @@ -76,6 +76,47 @@ def test_request(self, mock_request): raw=False, ) + @patch("libcloud.test.common.test_openstack.OpenStackBaseConnection.connect", Mock()) + def test_connection_is_reused_when_details_dont_change(self): + url = "https://example.com" + + self.connection._set_up_connection_info(url=url) + self.assertEqual(self.connection.connect.call_count, 1) + + for index in range(0, 10): + self.connection._set_up_connection_info(url=url) + self.assertEqual(self.connection.connect.call_count, 1) + + @patch("libcloud.test.common.test_openstack.OpenStackBaseConnection.connect", Mock()) + def test_connection_is_not_reused_when_details_change(self): + url = "https://example.com" + self.connection._set_up_connection_info(url=url) + self.assertEqual(self.connection.connect.call_count, 1) + + url = "https://example.com" + self.connection._set_up_connection_info(url=url) + self.assertEqual(self.connection.connect.call_count, 1) + + url = "https://example.com:80" + self.connection._set_up_connection_info(url=url) + self.assertEqual(self.connection.connect.call_count, 2) + + url = "http://example.com:80" + self.connection._set_up_connection_info(url=url) + self.assertEqual(self.connection.connect.call_count, 3) + + url = "http://exxample.com:80" + self.connection._set_up_connection_info(url=url) + self.assertEqual(self.connection.connect.call_count, 4) + + url = "http://exxample.com:81" + self.connection._set_up_connection_info(url=url) + self.assertEqual(self.connection.connect.call_count, 5) + + url = "http://exxample.com:81" + self.connection._set_up_connection_info(url=url) + self.assertEqual(self.connection.connect.call_count, 5) + if __name__ == "__main__": sys.exit(unittest.main())