Skip to content

Commit 976b7cb

Browse files
committed
test: close the gaps from the whole-PR review
Unit tests now pin the reader-failover refresh and the switch back to the writer through the plugin service's host list provider, check the probe the replacement provider gets, and cover the failover helper's writer window and DNS wait against its deadline. The outage classifier gets cases for MySQL's "Too many connections", a cause cycle, and the asyncio and psycopg connect-timeout causes, and its flow is plainer. The conftest's report hook no longer ends the session if the classifier raises: the failure is then not rerun.
1 parent f6707f6 commit 976b7cb

8 files changed

Lines changed: 119 additions & 16 deletions

File tree

‎aws_advanced_python_wrapper/aio/failover_plugin.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,8 @@ def _determine_mode(props: Properties) -> FailoverMode:
136136
@property
137137
def _host_list_provider(self) -> AsyncHostListProvider:
138138
# The service replaces its provider once the dialect is confirmed
139-
# (_update_host_list_provider), so read it at call time, as sync does.
139+
# (_update_host_list_provider), so read it at call time. Sync reads
140+
# the topology through the plugin service too.
140141
# The factory's provider only serves a service that has none.
141142
current = self._plugin_service.host_list_provider
142143
return current if current is not None else self._factory_host_list_provider

‎aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ def __init__(
104104
@property
105105
def _host_list_provider(self) -> AsyncHostListProvider:
106106
# The service replaces its provider once the dialect is confirmed
107-
# (_update_host_list_provider), so read it at call time, as sync does.
107+
# (_update_host_list_provider), so read it at call time. Sync reads
108+
# the topology through the plugin service too.
108109
# The factory's provider only serves a service that has none.
109110
current = self._plugin_service.host_list_provider
110111
return current if current is not None else self._factory_host_list_provider

‎tests/integration/container/conftest.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,12 @@ def _set_timeout_timer(item):
312312
def pytest_runtest_makereport(item, call):
313313
report = yield
314314
if report.failed:
315-
if not _phase_failed_on_cluster_outage(call.excinfo.value if call.excinfo is not None else None):
315+
try:
316+
outage = _phase_failed_on_cluster_outage(call.excinfo.value if call.excinfo is not None else None)
317+
except Exception as e: # noqa: BLE001 -- an error here would end the whole session
318+
logger.warning(f"Could not classify the failure, so the test is not rerun: {e}")
319+
outage = False
320+
if not outage:
316321
_Attempt.failed_other_than_outage = True
317322
if report.when in ("setup", "call"):
318323
_attach_recent_rds_events(item, report)

‎tests/integration/container/utils/rds_test_utility.py‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616

1717
from contextlib import closing
1818
from threading import Thread
19-
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, cast
19+
from typing import (TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Tuple,
20+
cast)
2021

2122
import botocore.exceptions
2223

@@ -212,11 +213,11 @@ def is_cluster_outage(error: Optional[BaseException], after_failover: bool = Fal
212213
:param error: the exception the test failed with, or None.
213214
:param after_failover: whether the test requested a failover before it failed. A connect
214215
timeout is then not an outage, because the wrapper may have connected to the old writer.
215-
:return: True if both of these hold. First, the exception itself is one of the helper's
216+
:return: True if all of these hold. First, the exception itself is one of the helper's
216217
outage failures (the failover did not finish in time, or an instance did not reach the
217218
RDS status available or accept a connection) or, before any failover, a connect that
218-
timed out. Second, every exception it was raised from or while handling is part of a
219-
connect timeout.
219+
timed out. Second, its text doesn't say the server is full. Third, every exception it
220+
was raised from or while handling is part of a connect timeout.
220221
"""
221222
if error is None:
222223
return False
@@ -225,12 +226,12 @@ def is_cluster_outage(error: Optional[BaseException], after_failover: bool = Fal
225226
if _NOT_CLUSTER_OUTAGE_PATTERN.search(message):
226227
return False
227228
if isinstance(error, pytest.fail.Exception):
228-
outage = any(pattern.search(message) for pattern in _HELPER_OUTAGE_PATTERNS)
229-
elif after_failover or not isinstance(error, _CONNECT_TIMEOUT_ERRORS):
230-
outage = False
229+
patterns: Tuple[re.Pattern, ...] = _HELPER_OUTAGE_PATTERNS
230+
elif not after_failover and isinstance(error, _CONNECT_TIMEOUT_ERRORS):
231+
patterns = _CONNECT_TIMEOUT_PATTERNS
231232
else:
232-
outage = any(pattern.search(message) for pattern in _CONNECT_TIMEOUT_PATTERNS)
233-
if not outage:
233+
return False
234+
if not any(pattern.search(message) for pattern in patterns):
234235
return False
235236

236237
chain: List[BaseException] = []

‎tests/unit/test_aio_failover_plugin.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,22 @@ async def _body() -> None:
267267
assert bound_host.host == r.host
268268

269269

270+
def test_reader_failover_uses_service_host_list_provider():
271+
w = HostInfo(host="writer.example.com", port=5432, role=HostRole.WRITER)
272+
r = HostInfo(host="reader.example.com", port=5432, role=HostRole.READER)
273+
# The factory's provider knows only the seed host, as a static one does.
274+
plugin, svc, _static, driver_dialect = _build_plugin(mode="strict_reader", topology=(w,))
275+
aurora = MagicMock()
276+
aurora.force_refresh = AsyncMock(return_value=(w, r))
277+
svc.host_list_provider = aurora
278+
plugin._failover_reader = AsyncMock() # type: ignore[method-assign]
279+
280+
asyncio.run(plugin._do_failover(driver_dialect=driver_dialect))
281+
282+
topology = plugin._failover_reader.call_args.args[0]
283+
assert topology == (w, r)
284+
285+
270286
def test_enabled_failover_picks_reader_in_strict_reader_mode():
271287
async def _body() -> None:
272288
plugin, svc, _hlp, driver_dialect = _build_plugin(mode="strict_reader")

‎tests/unit/test_aio_plugin_service_extras.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import asyncio
44
from typing import Optional
5-
from unittest.mock import AsyncMock, MagicMock
5+
from unittest.mock import AsyncMock, MagicMock, patch
66

77
import pytest
88

@@ -1409,13 +1409,16 @@ async def _refresh(_conn):
14091409
probe_at_refresh.append(provider._probe_host)
14101410

14111411
svc.force_refresh_host_list = AsyncMock(side_effect=_refresh)
1412+
probe = MagicMock(name="probe")
14121413

14131414
async def _run():
14141415
await svc._update_host_list_provider(MagicMock(name="conn"))
14151416

1416-
asyncio.run(_run())
1417-
assert len(probe_at_refresh) == 1
1418-
assert probe_at_refresh[0] is not None
1417+
with patch("aws_advanced_python_wrapper.aio.cluster_topology_monitor.build_probe_host",
1418+
return_value=probe) as build_probe_host:
1419+
asyncio.run(_run())
1420+
build_probe_host.assert_called_once_with(svc, props)
1421+
assert probe_at_refresh == [probe]
14191422

14201423

14211424
def test_is_static_host_list_provider_reflects_provider_type():

‎tests/unit/test_aio_read_write_splitting.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,34 @@ async def _work() -> None:
157157
asyncio.run(_body())
158158

159159

160+
def test_set_read_only_false_uses_service_host_list_provider():
161+
# After a failover the service's provider names the new writer, while the
162+
# factory's provider still names the old one.
163+
async def _body() -> None:
164+
old_writer = HostInfo(host="writer.example", port=5432, role=HostRole.WRITER)
165+
reader = HostInfo(host="reader.example", port=5432, role=HostRole.READER)
166+
new_writer = HostInfo(host="new-writer.example", port=5432, role=HostRole.WRITER)
167+
plugin, svc, *_ = _build(topology=(old_writer, reader))
168+
replacement = MagicMock()
169+
replacement.refresh = AsyncMock(return_value=(new_writer, reader))
170+
svc.host_list_provider = replacement
171+
172+
async def _work() -> None:
173+
return None
174+
175+
for read_only in (True, False):
176+
await plugin.execute(
177+
object(),
178+
DbApiMethod.CONNECTION_SET_READ_ONLY.method_name,
179+
_work,
180+
read_only,
181+
)
182+
assert svc.current_host_info is not None
183+
assert svc.current_host_info.host == "new-writer.example"
184+
185+
asyncio.run(_body())
186+
187+
160188
def test_set_read_only_false_switches_back_to_writer():
161189
async def _body() -> None:
162190
plugin, svc, hlp, dd, writer_conn = _build()

‎tests/unit/test_rds_test_utility.py‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
from __future__ import annotations
1616

17+
import asyncio
1718
import datetime
1819
import socket
1920

@@ -202,6 +203,34 @@ def _slow_new_writer(initial_writer_id, cluster_id, timeout_sec):
202203
assert target.failover_cluster.call_count == 1
203204

204205

206+
def test_failover_writer_window_bounded_by_deadline(utility, clock):
207+
target, _ = utility
208+
209+
def _no_new_writer_until_late(initial_writer_id, cluster_id, timeout_sec):
210+
# The first check uses up all but 30 s of the deadline
211+
clock[0] = _START_SEC + FAILOVER_DEADLINE_SEC - 30
212+
return False
213+
214+
target.writer_changed.side_effect = _no_new_writer_until_late
215+
target.query_host_role.return_value = HostRole.WRITER
216+
217+
with pytest.raises(pytest.fail.Exception, match="did not finish within"):
218+
target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster")
219+
220+
assert clock[0] - _START_SEC <= FAILOVER_DEADLINE_SEC + 2
221+
222+
223+
def test_failover_dns_wait_bounded_by_deadline(utility, clock):
224+
target, _ = utility
225+
rds_test_utility.socket.gethostbyname.side_effect = None
226+
rds_test_utility.socket.gethostbyname.return_value = "10.0.0.1"
227+
target.query_host_role.return_value = HostRole.READER
228+
229+
target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster")
230+
231+
assert clock[0] - _START_SEC <= FAILOVER_DEADLINE_SEC + 1
232+
233+
205234
def test_make_sure_instances_up_tries_once_after_deadline(utility, clock):
206235
target, _ = utility
207236
target._open_connection.side_effect = ConnectionRefusedError("starting up")
@@ -403,6 +432,12 @@ def _raised_while_handling(error, context):
403432
return error
404433

405434

435+
def _cause_cycle(error, cause):
436+
error.__cause__ = cause
437+
cause.__cause__ = error
438+
return error
439+
440+
406441
_MYSQL_CONNECT_TIMEOUT = "2003: Can't connect to MySQL server on 'instance-1:3306' (timed out)"
407442
_PG_CONNECT_TIMEOUT = "connection timeout expired"
408443

@@ -425,6 +460,19 @@ def _raised_while_handling(error, context):
425460
pytest.param(
426461
pytest.fail.Exception("Instances not in cluster 'cluster': instance-3"),
427462
False, False, id="instance_not_in_cluster"),
463+
pytest.param(
464+
pytest.fail.Exception(
465+
"Instance instance-2 did not accept a connection: DatabaseError: 1040 (08004): Too many connections"),
466+
True, False, id="instance_full_mysql"),
467+
pytest.param(
468+
_cause_cycle(MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), socket.timeout("timed out")),
469+
False, True, id="connect_timeout_cause_cycle"),
470+
pytest.param(
471+
_raised_from(MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), asyncio.TimeoutError()),
472+
False, True, id="connect_timeout_from_asyncio_timeout"),
473+
pytest.param(
474+
_raised_from(psycopg.OperationalError(_PG_CONNECT_TIMEOUT), psycopg.errors.ConnectionTimeout(_PG_CONNECT_TIMEOUT)),
475+
False, True, id="pg_connect_timeout_from_connection_timeout"),
428476
pytest.param(
429477
pytest.fail.Exception(
430478
"The test setup step timed out while waiting for the test custom endpoint to become available: 'ep'."),

0 commit comments

Comments
 (0)