Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: stop event loop on Connector.close #410

Merged
merged 5 commits into from
Jul 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions google/cloud/sql/connector/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,12 @@ def close(self) -> None:
)
# Will attempt to safely shut down tasks for 5s
close_future.result(timeout=5)
# if background thread exists for Connector, clean it up
if self._thread:
# stop event loop running in background thread
self._loop.call_soon_threadsafe(self._loop.stop)
# wait for thread to finish closing (i.e. loop to stop)
self._thread.join()

async def close_async(self) -> None:
"""Helper function to cancel Instances' tasks
Expand Down
12 changes: 11 additions & 1 deletion tests/unit/test_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ def test_connect_with_unsupported_driver(connector: Connector) -> None:
)
# assert custom error message for unsupported driver is present
assert exc_info.value.args[0] == "Driver 'bad_driver' is not supported."
connector.close()


@pytest.mark.asyncio
Expand Down Expand Up @@ -157,3 +156,14 @@ async def test_create_async_connector() -> None:
connector = await create_async_connector()
assert connector._loop == asyncio.get_running_loop()
await connector.close_async()


def test_Connector_close_kills_thread() -> None:
"""Test that Connector.close kills background threads."""
# open and close Connector object
connector = Connector()
# verify background thread exists
assert connector._thread
connector.close()
# check that connector thread is no longer running
assert connector._thread.is_alive() is False