Spaces:
Running on T4
Running on T4
Download tests/test_sam_batting_api.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 7.47 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_sam_batting_api.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/tests/test_sam_batting_api.py
-
curl -L -o test_sam_batting_api.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_sam_batting_api.py
7.47 kB
| """Separate upload queue, public contract, auth/cancellation and media integrity.""" | |
| import json | |
| from pathlib import Path | |
| import pytest | |
| pytest.importorskip('fastapi') | |
| from fastapi.testclient import TestClient | |
| from baseball_batting.api import create_app | |
| from baseball_batting.sam_batting_contract import SamBattingResult,GROUPS | |
| from baseball_batting.storage import atomic_json,sha256_file | |
| from test_api import settings,fake_service,wait_until,AUTH | |
| def test_new_api_configuration_and_upload_kind_without_touching_old_routes(tmp_path,video,monkeypatch): | |
| import baseball_batting.sam_api as module | |
| service=fake_service(settings(tmp_path),delay=30) | |
| monkeypatch.setattr(module,'configured_record',lambda:None) | |
| with TestClient(create_app(service.settings,service)) as client: | |
| wait_until(lambda:service.ready) | |
| assert client.get('/sam-batting').status_code==200 | |
| assert client.get('/v1/sam-batting/input-schema').status_code==401 | |
| assert client.get('/v1/sam-batting/output-schema',headers=AUTH).json()==SamBattingResult.model_json_schema() | |
| files={'video':('swing.mp4',video.read_bytes(),'video/mp4')} | |
| assert client.post('/v1/sam-batting/analyses',files=files,headers=AUTH).status_code==503 | |
| monkeypatch.setattr(module,'configured_record',lambda:{'worker_python':'server_only'}) | |
| bad=client.post('/v1/sam-batting/analyses',files=files,headers=AUTH,data={'options':'{"sam_repo":"/tmp"}'}) | |
| assert bad.status_code==422 | |
| r=client.post('/v1/sam-batting/analyses',files=files,headers=AUTH) | |
| assert r.status_code==202 | |
| identifier=r.json()['job_id'];row=service.store.get(identifier) | |
| assert row['kind']=='sam_batting' | |
| directory=service.job_directory(identifier) | |
| assert json.loads((directory/'request.json').read_text())['coaching'] is True | |
| assert client.get(r.json()['result_url'],headers=AUTH).status_code==409 | |
| assert client.get(r.json()['status_url'],headers=AUTH).json()['job_id']==identifier | |
| assert client.delete(r.json()['status_url'],headers=AUTH).status_code==202 | |
| wait_until(lambda:service.store.get(identifier)['status']=='cancelled') | |
| assert not directory.exists() | |
| assert client.get(r.json()['status_url'],headers=AUTH).json()['status']=='cancelled' | |
| def stored_result(service): | |
| identifier=service.store.create(8,kind='sam_batting');job=service.job_directory(identifier);job.mkdir() | |
| folder=job/'group-videos';folder.mkdir() | |
| groups=[] | |
| for key,label in GROUPS.items(): | |
| path=folder/(key+'.mp4');path.write_bytes(b'fixture-media-not-a-real-movie') | |
| groups.append({'key':key,'label':label,'swings':[],'annotated_video':{ | |
| 'status':'available','url':f'/v1/sam-batting/analyses/{identifier}/videos/{key}', | |
| 'duration_s':1,'frame_count':30,'width':100,'height':100,'size_bytes':path.stat().st_size, | |
| 'sha256':sha256_file(path),'overlay':True}}) | |
| payload=SamBattingResult(session_id=identifier,model={'name':'test fixture'},correction={},coordinates={},capture={},quality_flags=[],groups=groups) | |
| atomic_json(job/'result.json',payload.model_dump(mode='json')) | |
| service.store.update(identifier,'completed',result_hash=sha256_file(job/'result.json')) | |
| return identifier,job,payload | |
| def test_result_and_four_video_routes_are_protected_and_verified(tmp_path): | |
| service=fake_service(settings(tmp_path));identifier,job,payload=stored_result(service) | |
| root=f'/v1/sam-batting/analyses/{identifier}' | |
| (job/'sam-raw-private.npz').write_bytes(b'secret internal pose data') | |
| with TestClient(create_app(service.settings,service)) as client: | |
| wait_until(lambda:service.ready) | |
| assert client.get(root+'/result').status_code==401 | |
| r=client.get(root+'/result',headers=AUTH) | |
| assert r.status_code==200 and r.json()==payload.model_dump(mode='json') | |
| for key in GROUPS: | |
| url=root+'/videos/'+key | |
| assert client.get(url).status_code==401 | |
| assert client.get(url,headers=AUTH).content==b'fixture-media-not-a-real-movie' | |
| partial=client.get(url,headers={**AUTH,'Range':'bytes=0-6'}) | |
| assert partial.status_code==206 and partial.content==b'fixture' | |
| assert client.head(url,headers=AUTH).status_code==200 | |
| assert client.get(root+'/videos/../../sam-raw-private.npz',headers=AUTH).status_code==404 | |
| assert client.get(root+'/sam-raw-private.npz',headers=AUTH).status_code==404 | |
| path=job/'group-videos/rotation.mp4';path.write_bytes(b'tampered') | |
| assert client.get(root+'/videos/rotation',headers=AUTH).status_code==500 | |
| (job/'result.json').write_text('{}') | |
| assert client.get(root+'/result',headers=AUTH).status_code==500 | |
| def test_new_worker_is_selected_only_for_new_jobs(tmp_path): | |
| from baseball_batting.api_jobs import JobService | |
| service=JobService(settings(tmp_path)) | |
| for kind,module in [('legacy','baseball_batting.api_worker'),('sam_batting','baseball_batting.sam_measurement_worker')]: | |
| identifier=service.store.create(8,kind=kind) | |
| assert module in service.job_command(service.job_directory(identifier)) | |
| def test_group_reviews_auth_limits_and_without_gpu_or_repeat_sam(tmp_path,monkeypatch): | |
| from ai_coach.service import CoachService | |
| from ai_coach.group_review import available_facts,build_reviews,RatingBatch | |
| from test_sam_group_scoring import group_fixture,provider_response | |
| seen=[] | |
| def review(self,groups): | |
| seen.append(groups) | |
| data=build_reviews(RatingBatch.model_validate(provider_response(groups)),*available_facts(groups),'fixture-model') | |
| for g in groups:g.score=data[g.key]['score'];g.coaching=data[g.key]['coaching'] | |
| monkeypatch.setattr(CoachService,'review_groups',review) | |
| service=fake_service(settings(tmp_path));groups=group_fixture() | |
| payload={'groups':[g.model_dump(mode='json') for g in groups]} | |
| with TestClient(create_app(service.settings,service)) as client: | |
| wait_until(lambda:service.ready);service.ready=False | |
| path='/v1/sam-batting/group-reviews' | |
| assert client.post(path,json=payload).status_code==401 | |
| response=client.post(path,json=payload,headers=AUTH) | |
| assert response.status_code==200 | |
| assert len(response.json()['groups'])==4 and all(g['score']['value']==7.5 for g in response.json()['groups']) | |
| assert len(seen)==1 | |
| assert client.post(path,content=b'x'*(4*1024*1024+1),headers=AUTH).status_code==413 | |
| bad=json.loads(json.dumps(payload));bad['groups'][0]['swings'][0]['measurements'][0]['unit']='mph' | |
| assert client.post(path,json=bad,headers=AUTH).status_code==422 | |
| assert client.get('/v1/sam-batting/group-review-schema',headers=AUTH).status_code==200 | |
| def test_input_reference_errors_are_not_silently_defaulted(value): | |
| from baseball_batting.sam_batting_contract import SamBattingInput | |
| from pydantic import ValidationError | |
| with pytest.raises(ValidationError):SamBattingInput.model_validate(value) | |