Spaces:
Sleeping
Sleeping
Download tests/test_generation.py from xstard/decision-model: direct link, hf CLI and curl.
- Browser
- Download file 9.67 kB
-
https://huggingface.co/spaces/xstard/decision-model/resolve/main/tests/test_generation.py
- Command line
-
hf download hf://spaces/xstard/decision-model/tests/test_generation.py
-
curl -L -o test_generation.py https://huggingface.co/spaces/xstard/decision-model/resolve/main/tests/test_generation.py
9.67 kB
| import httpx | |
| import pytest | |
| from decision_model.budget import BudgetLedger | |
| from decision_model.generation import Generator | |
| def test_generator_rejects_uncapped_key_before_any_paid_call(tmp_path): | |
| posts = [] | |
| def handle(request): | |
| if request.method == "GET": | |
| return httpx.Response(200, json={"data": {"limit": None, "limit_remaining": None}}) | |
| posts.append(request) | |
| return httpx.Response(500) | |
| generator = Generator("fake-test-key", BudgetLedger(tmp_path / "b.db"), httpx.Client(transport=httpx.MockTransport(handle))) | |
| with pytest.raises(ValueError, match="ліміт"): | |
| generator.verify_key() | |
| assert not posts | |
| def test_generation_resumes_from_persisted_response_without_http(tmp_path): | |
| calls = [] | |
| pair = {"source_id": "s1", "english": "Please refund the extra payment.", | |
| "ukrainian": "Поверніть зайву оплату, будь ласка.", "department": "billing", "wants_refund": True, "frustration": 0} | |
| def handle(request): | |
| if request.method == "GET": | |
| return httpx.Response(200, json={"data": {"limit": 5, "limit_remaining": 5}}) | |
| calls.append(request.method) | |
| return httpx.Response(200, json={"choices": [{"finish_reason": "stop", "message": {"content": __import__('json').dumps({"pairs": [pair]})}}], "usage": {"cost": 0.001}}) | |
| ledger = BudgetLedger(tmp_path / "b.db") | |
| client = httpx.Client(transport=httpx.MockTransport(handle)) | |
| generator = Generator("fake", ledger, client) | |
| seeds = [{"id": "s1", "text": "refund", "department": "billing", "wants_refund": True, "frustration": 0}] | |
| first = generator.generate(seeds) | |
| second = Generator("fake", BudgetLedger(tmp_path / "b.db"), client).generate(seeds) | |
| assert first == second and len(first) == 2 | |
| assert calls == ["POST"] | |
| assert first[0].group_id == first[1].group_id | |
| assert not first[0].reviewed | |
| assert ledger.committed == pytest.approx(0.001) | |
| def test_timeout_keeps_reservation_and_cannot_replay(tmp_path): | |
| def handle(request): | |
| if request.method == "GET": | |
| return httpx.Response(200, json={"data": {"limit": 5, "limit_remaining": 5}}) | |
| raise httpx.ReadTimeout("timeout") | |
| generator = Generator("fake", BudgetLedger(tmp_path / "b.db"), httpx.Client(transport=httpx.MockTransport(handle))) | |
| seeds = [{"id": "s1", "text": "x"}] | |
| with pytest.raises(httpx.ReadTimeout): | |
| generator.generate(seeds) | |
| assert generator.ledger.committed > 0 | |
| with pytest.raises(RuntimeError, match="невідом"): | |
| generator.generate(seeds) | |
| def test_dataset_download_uses_short_local_path_on_windows(tmp_path, monkeypatch): | |
| import huggingface_hub | |
| from decision_model.generation import download_seeds | |
| path = tmp_path / 'source.csv' | |
| path.write_text('instruction,intent\nHow do I pay?,payment\nWhere is it?,delivery\nNew account?,account\nRefund please?,refund\n', encoding='utf-8') | |
| calls = [] | |
| def download(*args, **kwargs): | |
| calls.append(kwargs) | |
| return str(path) | |
| monkeypatch.setattr(huggingface_hub, 'hf_hub_download', download) | |
| assert len(download_seeds(4)) == 4 | |
| assert 'local_dir' in calls[0] | |
| def test_periodic_provider_cap_is_combined_with_nonresetting_project_budget(tmp_path): | |
| client = httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={ | |
| 'data': {'limit': 5, 'limit_remaining': 4.9, 'limit_reset': 'monthly'}}))) | |
| generator = Generator('fake', BudgetLedger(tmp_path / 'b.db'), client) | |
| assert generator.verify_key()['limit'] == 5 | |
| def test_source_pool_filters_duplicates_before_selecting_paid_seeds(tmp_path, monkeypatch): | |
| import huggingface_hub | |
| import random | |
| from types import SimpleNamespace | |
| from decision_model.generation import download_seeds | |
| path = tmp_path / 'source.csv' | |
| path.write_text('instruction,intent\nRefund now,support\nFind parcel,support\nChange address,support\nNew plan,support\nPay please,support\nPay please,support\n') | |
| monkeypatch.setattr(huggingface_hub, 'hf_hub_download', lambda *a, **kw: str(path)) | |
| monkeypatch.setattr(random, 'Random', lambda seed: SimpleNamespace(shuffle=lambda rows: None)) | |
| assert len({s['id'] for s in download_seeds(5)}) == 5 | |
| def test_parallel_generation_stops_scheduling_after_a_failure(tmp_path): | |
| from decision_model.generation import run_batches | |
| from types import SimpleNamespace | |
| from threading import Event | |
| event = Event() | |
| calls = [] | |
| def generate(batch): | |
| calls.append(batch[0]['id']) | |
| if batch[0]['id'] == '0': | |
| event.set() | |
| raise RuntimeError('upstream failed') | |
| event.wait(2) | |
| return [] | |
| fake = SimpleNamespace(generate=generate, ledger=SimpleNamespace(committed=0)) | |
| with pytest.raises(RuntimeError, match='зупинено'): | |
| run_batches([{'id': str(i)} for i in range(100)], fake, tmp_path, [], workers=2) | |
| assert len(calls) <= 2 | |
| def test_known_billed_incomplete_response_has_one_budgeted_retry_and_resumes(tmp_path): | |
| import json | |
| posts = [] | |
| pair = {'source_id':'s1','english':'Please refund the duplicate payment.', 'ukrainian':'Поверніть зайву оплату.', | |
| 'department':'billing','wants_refund':True,'frustration':0} | |
| def handle(request): | |
| if request.method == 'GET': | |
| return httpx.Response(200,json={'data':{'limit':5,'limit_remaining':5}}) | |
| posts.append(request) | |
| finish = 'length' if len(posts) == 1 else 'stop' | |
| return httpx.Response(200,json={'choices':[{'finish_reason':finish,'message':{'content':json.dumps({'pairs':[pair]})}}], 'usage':{'cost':.001}}) | |
| ledger=BudgetLedger(tmp_path/'retry.db') | |
| generator=Generator('fake',ledger,httpx.Client(transport=httpx.MockTransport(handle))) | |
| seeds=[{'id':'s1','text':'refund'}] | |
| assert len(generator.generate(seeds)) == 2 | |
| assert len(generator.generate(seeds)) == 2 | |
| assert len(posts) == 2 and ledger.committed == pytest.approx(.002) | |
| def test_target_drift_is_flagged_for_review_without_repaying_valid_json(tmp_path): | |
| import json | |
| pair={'source_id':'s1','english':'Please explain the invoice payment terms.', 'ukrainian':'Поясніть умови оплати рахунку.', | |
| 'department':'billing','wants_refund':False,'frustration':0} | |
| def handle(r): | |
| if r.method=='GET':return httpx.Response(200,json={'data':{'limit':5,'limit_remaining':5}}) | |
| return httpx.Response(200,json={'choices':[{'finish_reason':'stop','message':{'content':json.dumps({'pairs':[pair]})}}], 'usage':{'cost':.001}}) | |
| generator=Generator('fake',BudgetLedger(tmp_path/'drift.db'),httpx.Client(transport=httpx.MockTransport(handle))) | |
| rows=generator.generate([{'id':'s1','text':'x','department':'technical'}]) | |
| assert rows[0].department=='billing' and not rows[0].reviewed | |
| assert 'target_drift=department' in rows[0].source | |
| def test_generation_schema_binds_required_source_keys_and_accepts_map_response(tmp_path): | |
| import json | |
| pair={'english':'Please refund the payment.','ukrainian':'Поверніть оплату.', | |
| 'department':'billing','wants_refund':True,'frustration':0} | |
| def handle(r): | |
| if r.method=='GET':return httpx.Response(200,json={'data':{'limit':5,'limit_remaining':5}}) | |
| schema=json.loads(r.content)['response_format']['json_schema']['schema'] | |
| assert schema['properties']['pairs']['type']=='object' | |
| assert schema['properties']['pairs']['required']==['s1'] | |
| return httpx.Response(200,json={'choices':[{'finish_reason':'stop','message':{'content':json.dumps({'pairs':{'s1':pair}})}}], 'usage':{'cost':.001}}) | |
| generator=Generator('fake',BudgetLedger(tmp_path/'map.db'),httpx.Client(transport=httpx.MockTransport(handle))) | |
| assert generator.generate([{'id':'s1','text':'refund'}])[0].id=='s1:en' | |
| def test_known_billed_invalid_source_ids_get_one_reserved_retry(tmp_path): | |
| import json | |
| posts=[] | |
| pair={'english':'Please refund the payment.','ukrainian':'Поверніть оплату.', | |
| 'department':'billing','wants_refund':True,'frustration':0} | |
| def handle(r): | |
| if r.method=='GET':return httpx.Response(200,json={'data':{'limit':5,'limit_remaining':5}}) | |
| posts.append(r) | |
| pairs={'wrong':pair} if len(posts)==1 else {'s1':pair} | |
| return httpx.Response(200,json={'choices':[{'finish_reason':'stop','message':{'content':json.dumps({'pairs':pairs})}}], 'usage':{'cost':.001}}) | |
| ledger=BudgetLedger(tmp_path/'map-retry.db') | |
| generator=Generator('fake',ledger,httpx.Client(transport=httpx.MockTransport(handle))) | |
| assert len(generator.generate([{'id':'s1','text':'refund'}]))==2 | |
| assert len(generator.generate([{'id':'s1','text':'refund'}]))==2 | |
| assert len(posts)==2 and ledger.committed==pytest.approx(.002) | |
| def test_stop_signal_blocks_a_new_paid_retry(tmp_path): | |
| from threading import Event | |
| from concurrent.futures import CancelledError | |
| stopped=Event(); posts=[] | |
| def handle(r): | |
| if r.method=='GET':return httpx.Response(200,json={'data':{'limit':5,'limit_remaining':5}}) | |
| posts.append(r);stopped.set() | |
| return httpx.Response(200,json={'choices':[{'finish_reason':'length','message':{'content':'{}'}}],'usage':{'cost':.001}}) | |
| generator=Generator('fake',BudgetLedger(tmp_path/'stopped.db'),httpx.Client(transport=httpx.MockTransport(handle))) | |
| generator.stop_event=stopped | |
| with pytest.raises(CancelledError):generator.generate([{'id':'s1','text':'refund'}]) | |
| assert len(posts)==1 and generator.ledger.committed==pytest.approx(.001) | |