|
7 | 7 |
|
8 | 8 | import asyncio |
9 | 9 | import datetime |
| 10 | +import logging |
10 | 11 |
|
11 | 12 | import pytest |
12 | 13 | from faker import Faker |
@@ -547,6 +548,61 @@ async def test_semaphore_context_manager_lost_renewal( |
547 | 548 | raise asyncio.CancelledError |
548 | 549 |
|
549 | 550 |
|
| 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 | + |
550 | 606 | async def test_multiple_semaphores_different_keys( |
551 | 607 | redis_client_sdk: RedisClientSDK, |
552 | 608 | faker: Faker, |
|
0 commit comments