|
16 | 16 |
|
17 | 17 | import asyncio |
18 | 18 | import os |
| 19 | +from threading import Thread |
19 | 20 | from typing import Union |
20 | 21 |
|
21 | 22 | from aiohttp import ClientResponseError |
|
29 | 30 | from google.cloud.sql.connector.client import CloudSQLClient |
30 | 31 | from google.cloud.sql.connector.connection_name import ConnectionName |
31 | 32 | from google.cloud.sql.connector.exceptions import CloudSQLIPTypeError |
| 33 | +from google.cloud.sql.connector.exceptions import ConnectorLoopError |
32 | 34 | from google.cloud.sql.connector.exceptions import IncompatibleDriverError |
33 | 35 | from google.cloud.sql.connector.instance import RefreshAheadCache |
34 | 36 |
|
@@ -280,6 +282,38 @@ async def test_Connector_connect_async( |
280 | 282 | assert connection is True |
281 | 283 |
|
282 | 284 |
|
| 285 | +@pytest.mark.asyncio |
| 286 | +async def test_Connector_connect_async_multiple_event_loops( |
| 287 | + fake_credentials: Credentials, fake_client: CloudSQLClient |
| 288 | +) -> None: |
| 289 | + """Test that Connector.connect_async errors when run on wrong event loop.""" |
| 290 | + |
| 291 | + new_loop = asyncio.new_event_loop() |
| 292 | + thread = Thread(target=new_loop.run_forever, daemon=True) |
| 293 | + thread.start() |
| 294 | + |
| 295 | + async with Connector( |
| 296 | + credentials=fake_credentials, loop=asyncio.get_running_loop() |
| 297 | + ) as connector: |
| 298 | + connector._client = fake_client |
| 299 | + with pytest.raises(ConnectorLoopError) as exc_info: |
| 300 | + future = asyncio.run_coroutine_threadsafe( |
| 301 | + connector.connect_async( |
| 302 | + "test-project:test-region:test-instance", "asyncpg" |
| 303 | + ), |
| 304 | + loop=new_loop, |
| 305 | + ) |
| 306 | + future.result() |
| 307 | + assert ( |
| 308 | + exc_info.value.args[0] == "Running event loop does not match " |
| 309 | + "'connector._loop'. Connector.connect_async() must be called from " |
| 310 | + "the event loop the Connector was initialized with. If you need to " |
| 311 | + "connect across event loops, please use a new Connector object." |
| 312 | + ) |
| 313 | + new_loop.call_soon_threadsafe(new_loop.stop) |
| 314 | + thread.join() |
| 315 | + |
| 316 | + |
283 | 317 | @pytest.mark.asyncio |
284 | 318 | async def test_create_async_connector(fake_credentials: Credentials) -> None: |
285 | 319 | """Test that create_async_connector properly initializes connector |
|
0 commit comments