Skip to content

Commit 5717798

Browse files
committed
ensure we test it all
1 parent 8268b44 commit 5717798

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

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

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import asyncio
99
import datetime
10+
import logging
1011

1112
import pytest
1213
from faker import Faker
@@ -547,6 +548,61 @@ async def test_semaphore_context_manager_lost_renewal(
547548
raise asyncio.CancelledError
548549

549550

551+
async def test_semaphore_context_manager_auto_renewal(
552+
redis_client_sdk: RedisClientSDK,
553+
semaphore_name: str,
554+
with_short_default_semaphore_ttl: datetime.timedelta,
555+
):
556+
async with distributed_semaphore(
557+
redis_client=redis_client_sdk,
558+
key=semaphore_name,
559+
capacity=1,
560+
ttl=with_short_default_semaphore_ttl,
561+
) as semaphore:
562+
assert await semaphore.is_acquired() is True
563+
assert await semaphore.current_count() == 1
564+
assert await semaphore.available_tokens() == 0
565+
await _assert_semaphore_redis_state(
566+
redis_client_sdk,
567+
semaphore,
568+
expected_count=1,
569+
expected_free_tokens=0,
570+
)
571+
572+
# wait for a few TTLs to ensure auto-renewal is working
573+
total_wait = with_short_default_semaphore_ttl.total_seconds() * 3
574+
await asyncio.sleep(total_wait)
575+
576+
# should still be acquired
577+
assert await semaphore.is_acquired() is True
578+
assert await semaphore.current_count() == 1
579+
assert await semaphore.available_tokens() == 0
580+
await _assert_semaphore_redis_state(
581+
redis_client_sdk,
582+
semaphore,
583+
expected_count=1,
584+
expected_free_tokens=0,
585+
)
586+
587+
588+
async def test_semaphore_context_manager_logs_warning_when_hold_too_long(
589+
redis_client_sdk: RedisClientSDK,
590+
semaphore_name: str,
591+
caplog: pytest.LogCaptureFixture,
592+
):
593+
"""Test that a warning is logged when holding the semaphore for too long"""
594+
with caplog.at_level(logging.WARNING):
595+
async with distributed_semaphore(
596+
redis_client=redis_client_sdk,
597+
key=semaphore_name,
598+
capacity=1,
599+
expected_lock_overall_time=datetime.timedelta(milliseconds=200),
600+
):
601+
await asyncio.sleep(0.3)
602+
assert caplog.records
603+
assert "longer than expected" in caplog.messages[-1]
604+
605+
550606
async def test_multiple_semaphores_different_keys(
551607
redis_client_sdk: RedisClientSDK,
552608
faker: Faker,

0 commit comments

Comments
 (0)