Files
vibemake-pcb-studio/project_library/tests/test_api.py
T

102 lines
5.5 KiB
Python

import os
import tempfile
import sqlite3
from unittest.mock import Mock, AsyncMock
import time
import unittest
from unittest.mock import patch
from fastapi.testclient import TestClient
from project_library import app as api
from project_library.tests.test_storage import archive
class LibraryApi(unittest.TestCase):
def test_upload_search_question_and_attachment_use_owner_and_version(self):
root = tempfile.TemporaryDirectory()
self.addCleanup(root.cleanup)
current = ['alice']
async def owner():
return current[0]
async def analyze(source, work, files, progress):
self.assertEqual((source/files[0]['path']).read_bytes(), b'ordinary content')
await progress('在读取 README')
return {'summary':'test board','groups':[{'name':'TestPart','category':'component','detail':'only a fixture',
'scope':'board','evidence':[{'path':files[0]['path'],'location':'line 1'}]}],'limitations':[]}
async def answer(source, work, files, report, question):
return {'text':'见 README','evidence':report['groups'][0]['evidence']}
api.app.dependency_overrides[api.current_owner] = owner
self.addCleanup(api.app.dependency_overrides.pop, api.current_owner)
data = archive([('v1/README.md','ordinary content')])
with patch.dict(os.environ, PCB_LIBRARY_ROOT=root.name), patch.object(api.engine,'analyze',analyze), patch.object(api.engine,'answer',answer), TestClient(api.app) as client:
response = client.post('/api/projects?name=Test.zip', content=data)
self.assertEqual(response.status_code, 201, response.text)
ident = response.json()['id']
base = '/api/projects/' + ident
for _ in range(200):
detail=client.get(base).json()
if detail['status'] in ('ready','failed'):break
time.sleep(0.01)
self.assertEqual(detail['status'],'ready',detail)
self.assertEqual(client.get('/api/projects?q=testpart').json()['projects'][0]['id'], ident)
self.assertEqual(client.get(base+'/archive').content,data)
r=client.get(base+'/files',params={'path':'v1/README.md'})
self.assertEqual(r.content,b'ordinary content')
self.assertIn('attachment',r.headers['Content-Disposition'])
self.assertEqual(client.get(base+'/files',params={'path':'work/note'}).status_code,404)
self.assertEqual(client.post(base+'/questions',json={'question':'来源?'}).json()['evidence'][0]['path'],'v1/README.md')
self.assertEqual(client.post(base+'/retry').status_code,409)
same = client.post('/api/projects', params={'name':'another.zip','project_id':detail['project_id']},
content=data).json()
self.assertEqual((same['project_id'],same['version'],same['name']), (detail['project_id'],2,'Test'))
self.assertEqual([r['version'] for r in client.get('/api/projects').json()['projects']], [2,1])
self.assertEqual(client.get(base+'/archive').content, data)
self.assertEqual(client.post('/api/projects?name=bad.zip',content=b'oops').status_code,400)
self.assertEqual(list(api.app.state.store.incoming.iterdir()),[])
current[0]='bob'
self.assertEqual(client.get('/api/projects').json(), {'projects':[]})
for suffix in ('','/files?path=v1/README.md','/archive'):
self.assertEqual(client.get(base+suffix).status_code,404)
self.assertEqual(client.post(base+'/questions',json={'question':'x'}).status_code,404)
self.assertEqual(client.post(base+'/retry').status_code,404)
self.assertEqual(client.post('/api/projects',params={'name':'B.zip','project_id':detail['project_id']},content=data).status_code,404)
def test_failed_analysis_can_be_retried_from_saved_archive(self):
async def analyze(**kwargs):
if analyze.fail:
raise TimeoutError()
return {'summary':'ok','groups':[],'limitations':[]}
def wait_for(client, base, status):
for _ in range(200):
d=client.get(base).json()
if d['status']==status:
return d
time.sleep(.01)
self.fail(str(d))
api.app.dependency_overrides[api.current_owner]=lambda:'alice'
self.addCleanup(api.app.dependency_overrides.pop,api.current_owner)
analyze.fail=True
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,PCB_LIBRARY_ROOT=root), patch.object(api.engine,'analyze',analyze), TestClient(api.app) as client:
r=client.post('/api/projects?name=Board.zip',content=archive([('README','ok')]))
base='/api/projects/'+r.json()['id']
d=wait_for(client,base,'failed')
self.assertIn('重试',d['error'])
analyze.fail=False
self.assertEqual(client.post(base+'/retry').status_code,202)
self.assertEqual(wait_for(client,base,'ready')['report']['summary'],'ok')
class WorkerRecovery(unittest.IsolatedAsyncioTestCase):
async def test_transient_storage_error_does_not_stop_consumer(self):
operation = Mock(side_effect=[sqlite3.OperationalError('database is locked'), 'job'])
operation.__name__ = 'claim'
with self.assertLogs(api.log, level='ERROR'), patch.object(api.asyncio, 'sleep', new_callable=AsyncMock):
self.assertEqual(await api.worker_db(operation), 'job')
self.assertEqual(operation.call_count, 2)