101 lines
6.4 KiB
Python
101 lines
6.4 KiB
Python
import tempfile,unittest
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from unittest.mock import Mock
|
|
from tts_test import TTSTests
|
|
from tts_runtime import TTSRuntime,REPO,REVISION
|
|
class TTSTestsValidation(unittest.TestCase):
|
|
def test_stream_chunks_and_cancellation_are_job_specific(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
t=TTSTests(d,None,None);ident='a'*32;folder=Path(d,ident);folder.mkdir()
|
|
t.job=dict(id=ident,state='running',phase='working')
|
|
(folder/'chunk-000000.pcm').write_bytes(b'\x01\x00')
|
|
stream=t.stream_audio(ident);self.assertEqual(next(stream),b'\x01\x00')
|
|
t.cancel_job('b'*32);self.assertFalse(t.cancel.is_set())
|
|
t.job.update(state='complete');self.assertEqual(list(stream),[])
|
|
t.job.update(state='running');t.cancel_job(ident);self.assertTrue(t.cancel.is_set())
|
|
for invalid in ('../outside','b'*32):
|
|
with self.assertRaises(ValueError):next(t.stream_audio(invalid))
|
|
def test_invalid_pcm_chunk_is_not_published(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
t=TTSTests(d,None,None);ident='a'*32;folder=Path(d,ident);folder.mkdir()
|
|
t.job=dict(id=ident,state='running',phase='working');(folder/'chunk-000000.pcm').write_bytes(b'odd')
|
|
with self.assertRaisesRegex(ValueError,'PCM'):next(t.stream_audio(ident))
|
|
def test_validation_and_reservation_release(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
t=TTSTests(d,SimpleNamespace(status=lambda:{'profiles':[]}),TTSRuntime(Path(d)/'runtime'));release=Mock();t.acquire=Mock(return_value=release)
|
|
for kwargs in ({'text':''},{'text':'ok','speaker':'unknown'},{'text':'ok','language':'invalid'},{'text':'ok','speed':9}):
|
|
with self.assertRaises(ValueError):t.start('p',**kwargs)
|
|
t.acquire.assert_not_called()
|
|
with self.assertRaises(ValueError):t.start('p','valid')
|
|
release.assert_called_once()
|
|
def test_audio_path_and_model_format(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
r=TTSRuntime(Path(d)/'runtime');t=TTSTests(d,None,r)
|
|
for ident in ('../secret','a'*32):
|
|
with self.assertRaises(ValueError):t.audio(ident)
|
|
self.assertTrue(t.blockers({'model':{'repo':'mlx-community/example','file':'model.safetensors'}}))
|
|
self.assertTrue(t.blockers({'model':{'repo':REPO,'revision':REVISION,'file':'speech_tokenizer/model.safetensors'}}))
|
|
self.assertFalse(r.status()['installed'])
|
|
def test_gpu_sharing_uses_free_memory_not_process_count(self):
|
|
from unittest.mock import patch
|
|
with tempfile.TemporaryDirectory() as d:
|
|
t=TTSTests(d,None,None)
|
|
shared=dict(uuid='gpu3060',name='RTX 3060',free_mib=6000,processes=3)
|
|
with patch.object(t,'_required_vram_mib',return_value=5000):
|
|
with patch('tts_test.probe',return_value=[shared]):self.assertEqual(t._available_gpu(),shared)
|
|
with patch('tts_test.probe',return_value=[dict(shared,free_mib=4999,processes=0)]):self.assertIsNone(t._available_gpu())
|
|
def test_memory_budget_tracks_the_actual_weights(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
Path(d,'model.safetensors').write_bytes(bytes(1024*1024))
|
|
t=TTSTests(d,None,SimpleNamespace(paths=lambda:(None,Path(d))))
|
|
self.assertEqual(t._required_vram_mib(),1537)
|
|
def test_library_output_cannot_corrupt_worker_protocol(self):
|
|
import io,json,sys
|
|
from unittest.mock import patch
|
|
import tts_worker
|
|
class Model:
|
|
@classmethod
|
|
def from_pretrained(cls,*args,**kwargs):print('Library startup notice');return cls()
|
|
def _warmup(self,**kwargs):print('Graph capture notice')
|
|
def generate_custom_voice(self,**kwargs):print('Library generation notice');return [[.1]*10],24000
|
|
with tempfile.TemporaryDirectory() as d:
|
|
stdout=io.StringIO();stderr=io.StringIO()
|
|
request=json.dumps(dict(output=d,text='Test',speaker='Ryan',language='German',speed=1))+'\n'
|
|
modules={'torch':SimpleNamespace(set_float32_matmul_precision=lambda x:None,bfloat16='bf16',cuda=SimpleNamespace(empty_cache=lambda:None)),'soundfile':SimpleNamespace(write=lambda *a,**k:None),'faster_qwen3_tts':SimpleNamespace(FasterQwen3TTS=Model)}
|
|
with patch.dict(sys.modules,modules),patch.object(sys,'argv',['worker','model']),patch.object(sys,'stdin',io.StringIO(request)),patch.object(sys,'stdout',stdout),patch.object(sys,'stderr',stderr):
|
|
self.assertEqual(tts_worker.main(),0)
|
|
self.assertEqual([json.loads(line) for line in stdout.getvalue().splitlines()],[{'ready':True}])
|
|
self.assertIn('Graph capture notice',stderr.getvalue());self.assertIn('startup notice',stderr.getvalue());self.assertIn('generation notice',stderr.getvalue())
|
|
self.assertTrue(json.loads(Path(d,'result.json').read_text())['ok'])
|
|
def test_existing_environment_gets_pinned_accelerator_once(self):
|
|
from unittest.mock import patch
|
|
from tts_runtime import FAST_VERSION
|
|
with tempfile.TemporaryDirectory() as d:
|
|
root=Path(d);base=root/('a'*32);(base/'python/bin').mkdir(parents=True);(base/'python/bin/python').touch();(base/'model').mkdir();(base/'model/ready').touch();(root/'active.json').write_text('{"id":"'+base.name+'"}')
|
|
runtime=TTSRuntime(root)
|
|
with patch('tts_runtime.subprocess.run',side_effect=[SimpleNamespace(returncode=1),SimpleNamespace(returncode=0),SimpleNamespace(returncode=0),SimpleNamespace(returncode=0)]) as run:
|
|
runtime.ensure_fast_backend();runtime.ensure_fast_backend()
|
|
self.assertEqual(run.call_count,4)
|
|
self.assertIn('faster-qwen3-tts=='+FAST_VERSION,run.call_args_list[1].args[0])
|
|
self.assertTrue(runtime.status()['backend_ready'])
|
|
def test_failed_upgrade_does_not_claim_fast_backend_is_ready(self):
|
|
from unittest.mock import patch
|
|
with tempfile.TemporaryDirectory() as d:
|
|
root=Path(d);base=root/('a'*32);(base/'python/bin').mkdir(parents=True);(base/'python/bin/python').touch();(base/'model').mkdir();(root/'active.json').write_text('{"id":"'+base.name+'"}')
|
|
runtime=TTSRuntime(root)
|
|
with patch('tts_runtime.subprocess.run',return_value=SimpleNamespace(returncode=1)):
|
|
with self.assertRaises(ValueError):runtime.ensure_fast_backend()
|
|
self.assertFalse(runtime.status()['backend_ready']);self.assertFalse(runtime.backend_checked)
|
|
def test_long_text_chunks_preserve_all_words(self):
|
|
from tts_worker import text_chunks
|
|
text=('Dies ist ein längerer Satz mit mehreren Wörtern. '*25).strip()
|
|
chunks=text_chunks(text)
|
|
self.assertGreater(len(chunks),1)
|
|
self.assertTrue(all(len(c)<=256 for c in chunks))
|
|
self.assertEqual(' '.join(chunks).split(),text.split())
|
|
compact='测'*1000
|
|
self.assertEqual(''.join(text_chunks(compact)),compact)
|
|
self.assertTrue(all(len(c)<=256 for c in text_chunks(compact)))
|
|
if __name__=='__main__':unittest.main()
|