Skip to content

Commit

Permalink
Add a comment and some in-direct test for connection re-use / making
Browse files Browse the repository at this point in the history
sure self.connect() is only called if connection details (scheme, host,
port) change.
  • Loading branch information
Kami committed Jul 31, 2023
1 parent 587242c commit ebecb9a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions libcloud/common/openstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
41 changes: 41 additions & 0 deletions libcloud/test/common/test_openstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())

0 comments on commit ebecb9a

Please sign in to comment.