Skip to content

Commit cc5c9f3

Browse files
committed
improve coverage
1 parent 7af5e29 commit cc5c9f3

File tree

2 files changed

+33
-16
lines changed

2 files changed

+33
-16
lines changed

packages/service-library/src/servicelib/redis/_semaphore.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
computed_field,
1717
field_validator,
1818
)
19-
from servicelib.logging_errors import create_troubleshootting_log_kwargs
2019

2120
from ..background_task import periodic
21+
from ..logging_errors import create_troubleshootting_log_kwargs
2222
from ..logging_utils import log_catch
2323
from ._client import RedisClientSDK
2424
from ._constants import (
@@ -32,7 +32,7 @@
3232
_logger = logging.getLogger(__name__)
3333

3434

35-
async def renew_semaphore_entry(semaphore: "DistributedSemaphore") -> None:
35+
async def _renew_semaphore_entry(semaphore: "DistributedSemaphore") -> None:
3636
"""
3737
Manually renew a semaphore entry by updating its timestamp and TTL.
3838
@@ -44,8 +44,6 @@ async def renew_semaphore_entry(semaphore: "DistributedSemaphore") -> None:
4444
Raises:
4545
Exception: If the renewal operation fails
4646
"""
47-
if not semaphore.is_acquired():
48-
return # Nothing to renew if not acquired
4947

5048
current_time = asyncio.get_event_loop().time()
5149
ttl_seconds = semaphore.ttl.total_seconds()
@@ -99,7 +97,7 @@ class DistributedSemaphore(BaseModel):
9997
blocking: Annotated[
10098
bool, Field(description="Whether acquire() should block until available")
10199
] = True
102-
timeout: Annotated[
100+
blocking_timeout: Annotated[
103101
datetime.timedelta | None,
104102
Field(description="Maximum time to wait when blocking"),
105103
] = DEFAULT_SOCKET_TIMEOUT
@@ -161,7 +159,9 @@ async def acquire(self) -> bool:
161159
return True
162160

163161
start_time = asyncio.get_event_loop().time()
164-
timeout_seconds = self.timeout.total_seconds() if self.timeout else None
162+
timeout_seconds = (
163+
self.blocking_timeout.total_seconds() if self.blocking_timeout else None
164+
)
165165

166166
while True:
167167
# Try to acquire using Redis sorted set for atomic operations
@@ -361,7 +361,7 @@ async def _wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
361361
capacity=semaphore_capacity,
362362
ttl=ttl,
363363
blocking=blocking,
364-
timeout=blocking_timeout,
364+
blocking_timeout=blocking_timeout,
365365
)
366366

367367
# Acquire the semaphore
@@ -379,7 +379,7 @@ async def _wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
379379
# Create auto-renewal task
380380
@periodic(interval=ttl / 3, raise_on_error=True)
381381
async def _periodic_renewer() -> None:
382-
await renew_semaphore_entry(semaphore)
382+
await _renew_semaphore_entry(semaphore)
383383
started_event.set()
384384

385385
# Start the renewal task

packages/service-library/tests/redis/test_semaphore.py

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ async def test_semaphore_initialization(
8181
)
8282

8383

84-
async def test_semaphore_invalid_capacity_raises(
84+
async def test_invalid_semaphore_initialization(
8585
redis_client_sdk: RedisClientSDK,
8686
semaphore_name: str,
8787
):
@@ -95,6 +95,23 @@ async def test_semaphore_invalid_capacity_raises(
9595
redis_client=redis_client_sdk, key=semaphore_name, capacity=-1
9696
)
9797

98+
with pytest.raises(ValueError, match="TTL must be positive"):
99+
DistributedSemaphore(
100+
redis_client=redis_client_sdk,
101+
key=semaphore_name,
102+
capacity=1,
103+
ttl=datetime.timedelta(seconds=0),
104+
)
105+
with pytest.raises(ValueError, match="Timeout must be positive"):
106+
DistributedSemaphore(
107+
redis_client=redis_client_sdk,
108+
key=semaphore_name,
109+
capacity=1,
110+
ttl=datetime.timedelta(seconds=10),
111+
blocking=True,
112+
blocking_timeout=datetime.timedelta(seconds=0),
113+
)
114+
98115

99116
async def test_semaphore_acquire_release_single(
100117
redis_client_sdk: RedisClientSDK,
@@ -216,7 +233,7 @@ async def test_semaphore_blocking_timeout(
216233
redis_client=redis_client_sdk,
217234
key=semaphore_name,
218235
capacity=capacity,
219-
timeout=timeout,
236+
blocking_timeout=timeout,
220237
)
221238

222239
with pytest.raises(
@@ -340,7 +357,7 @@ async def test_decorator_auto_renewal_failure_propagation(
340357
monkeypatch: pytest.MonkeyPatch,
341358
):
342359
"""Test that auto-renewal failures properly propagate as exceptions in the decorator"""
343-
from servicelib.redis._semaphore import renew_semaphore_entry
360+
from servicelib.redis._semaphore import _renew_semaphore_entry
344361

345362
class RenewalFailureError(Exception):
346363
"""Custom exception for testing renewal failures"""
@@ -349,7 +366,7 @@ class RenewalFailureError(Exception):
349366

350367
# Mock the renewal function to fail after first call
351368
call_count = 0
352-
original_renew = renew_semaphore_entry
369+
original_renew = _renew_semaphore_entry
353370

354371
async def failing_renew_semaphore_entry(semaphore):
355372
nonlocal call_count
@@ -362,7 +379,7 @@ async def failing_renew_semaphore_entry(semaphore):
362379
raise RenewalFailureError("Simulated renewal failure")
363380

364381
monkeypatch.setattr(
365-
"servicelib.redis._semaphore.renew_semaphore_entry",
382+
"servicelib.redis._semaphore._renew_semaphore_entry",
366383
failing_renew_semaphore_entry,
367384
)
368385

@@ -646,16 +663,16 @@ class UserFunctionError(Exception):
646663

647664
# Track that auto-renewal is actually happening
648665
original_renew = __import__(
649-
"servicelib.redis._semaphore", fromlist=["renew_semaphore_entry"]
650-
).renew_semaphore_entry
666+
"servicelib.redis._semaphore", fromlist=["_renew_semaphore_entry"]
667+
)._renew_semaphore_entry
651668

652669
async def tracking_renew_semaphore_entry(semaphore):
653670
nonlocal renewal_count
654671
renewal_count += 1
655672
await original_renew(semaphore)
656673

657674
with mock.patch(
658-
"servicelib.redis._semaphore.renew_semaphore_entry",
675+
"servicelib.redis._semaphore._renew_semaphore_entry",
659676
side_effect=tracking_renew_semaphore_entry,
660677
):
661678

0 commit comments

Comments
 (0)