|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +import astrbot.api # noqa: F401 |
| 7 | +from astrbot.core.provider.sources.azure_tts_source import ( |
| 8 | + AzureNativeProvider, |
| 9 | + AzureTTSProvider, |
| 10 | + OTTSProvider, |
| 11 | +) |
| 12 | + |
| 13 | + |
| 14 | +@pytest.mark.asyncio |
| 15 | +@pytest.mark.parametrize("backend", ["native", "otts"]) |
| 16 | +@pytest.mark.parametrize("outcome", ["success", "error", "cancel"]) |
| 17 | +async def test_overlapping_synthesis_keeps_clients_alive_and_closes_them( |
| 18 | + monkeypatch, backend, outcome |
| 19 | +): |
| 20 | + key = "A" * 32 |
| 21 | + if backend == "otts": |
| 22 | + key = ( |
| 23 | + "other[" |
| 24 | + + json.dumps( |
| 25 | + { |
| 26 | + "OTTS_SKEY": "dummy", |
| 27 | + "OTTS_URL": "https://example.com/tts", |
| 28 | + "OTTS_AUTH_TIME": "https://example.com/time", |
| 29 | + } |
| 30 | + ) |
| 31 | + + "]" |
| 32 | + ) |
| 33 | + provider = AzureTTSProvider({"azure_tts_subscription_key": key}, {}) |
| 34 | + first_started = asyncio.Event() |
| 35 | + release_first = asyncio.Event() |
| 36 | + clients = [] |
| 37 | + |
| 38 | + async def synthesize(instance, text, *args): |
| 39 | + client = instance.client |
| 40 | + clients.append(client) |
| 41 | + if text == "first": |
| 42 | + first_started.set() |
| 43 | + await release_first.wait() |
| 44 | + if outcome == "error": |
| 45 | + raise ValueError("synthesis failed") |
| 46 | + assert instance.client is client |
| 47 | + assert not client.is_closed |
| 48 | + return text |
| 49 | + |
| 50 | + monkeypatch.setattr( |
| 51 | + AzureNativeProvider if backend == "native" else OTTSProvider, |
| 52 | + "get_audio", |
| 53 | + synthesize, |
| 54 | + ) |
| 55 | + first = asyncio.create_task(provider.get_audio("first")) |
| 56 | + await asyncio.wait_for(first_started.wait(), timeout=5) |
| 57 | + second = asyncio.create_task(provider.get_audio("second")) |
| 58 | + await asyncio.sleep(0) |
| 59 | + if outcome == "cancel": |
| 60 | + first.cancel() |
| 61 | + release_first.set() |
| 62 | + try: |
| 63 | + results = await asyncio.wait_for( |
| 64 | + asyncio.gather(first, second, return_exceptions=True), timeout=5 |
| 65 | + ) |
| 66 | + assert results[1] == "second" |
| 67 | + if outcome == "success": |
| 68 | + assert results[0] == "first" |
| 69 | + elif outcome == "error": |
| 70 | + assert isinstance(results[0], ValueError) |
| 71 | + else: |
| 72 | + assert isinstance(results[0], asyncio.CancelledError) |
| 73 | + assert len(clients) == 2 |
| 74 | + assert clients[0] is not clients[1] |
| 75 | + assert all(client.is_closed for client in clients) |
| 76 | + finally: |
| 77 | + for client in clients: |
| 78 | + await client.aclose() |
0 commit comments