147 lines
7.2 KiB
Python
147 lines
7.2 KiB
Python
import asyncio
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
from zipfile import ZipFile
|
|
|
|
import httpx
|
|
from fastapi import HTTPException
|
|
from codex_pcb import app as service, editing_projects as ep, storage
|
|
|
|
TID = 'pcb-' + '1'*24
|
|
OTHER = 'pcb-' + '2'*24
|
|
|
|
|
|
class EditingProjects(unittest.IsolatedAsyncioTestCase):
|
|
def setUp(self):
|
|
temp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(temp.cleanup)
|
|
tasks = Path(temp.name)/'tasks'
|
|
self.enterContext(patch.object(storage, 'TASKS', tasks))
|
|
self.enterContext(patch.object(service, 'CACHE', {}))
|
|
for tid in (TID, OTHER):
|
|
folder = tasks/tid/'delivery'
|
|
folder.mkdir(parents=True)
|
|
source = folder/'design.epro'
|
|
with ZipFile(source,'w') as z:
|
|
z.writestr('project.json', json.dumps({'pcbs':{'b':'PCB'},'schematics':{'s':'Schematic'}}))
|
|
(folder/'manifest.json').write_text('{}')
|
|
service.CACHE[tid] = {'id':tid, 'state':'completed', 'created_at':1, 'request':'Board',
|
|
'delivery':{'files':[{'kind':'project','name':'design.epro','sha256':hashlib.sha256(source.read_bytes()).hexdigest()}]}}
|
|
self.posts = 0
|
|
self.cloud = []
|
|
self.fail_after_create = False
|
|
self.enterContext(patch.object(ep, 'platform', self.platform))
|
|
self.owner = ep.owner_key('alice')
|
|
ep.bind(TID,self.owner)
|
|
self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=service.app),base_url='http://test')
|
|
self.addAsyncCleanup(self.client.aclose)
|
|
|
|
async def platform(self, method, path, token, **kwargs):
|
|
if path == '/users/me':
|
|
if token not in ('alice','bob'):
|
|
raise HTTPException(401,'expired')
|
|
return {'userCode':token}
|
|
self.assertEqual(token,'alice')
|
|
if method == 'POST':
|
|
self.posts += 1
|
|
item = {'pcbProjectCode':f'code-{self.posts}', **kwargs['json']}
|
|
self.cloud.append(item)
|
|
if self.fail_after_create:
|
|
raise HTTPException(503,'unknown result')
|
|
return item
|
|
self.assertEqual(method,'GET')
|
|
if path.startswith('/pcb/workspace/projects/'):
|
|
code = path.rsplit('/',1)[-1]
|
|
for item in self.cloud:
|
|
if item['pcbProjectCode'] == code:
|
|
return item
|
|
raise HTTPException(404,'deleted')
|
|
return {'page':1,'size':20,'total':len(self.cloud),'items':list(self.cloud)}
|
|
|
|
async def call(self, method, path, token=None, **kwargs):
|
|
headers = {'Authorization':'Bearer '+token} if token else {}
|
|
return await self.client.request(method,'/api/sessions'+path,headers=headers,**kwargs)
|
|
|
|
async def test_identity_comes_from_platform_and_all_task_routes_include_owner_guard(self):
|
|
self.assertEqual((await self.call('GET','')).status_code,401)
|
|
self.assertEqual((await self.call('GET','','expired')).status_code,401)
|
|
self.assertEqual((await self.call('GET','','bob')).json(),[])
|
|
alice = (await self.call('GET','','alice')).json()
|
|
self.assertEqual([t['id'] for t in alice],[TID])
|
|
self.assertEqual(alice[0]['manifest_sha256'],storage.digest(b'{}'))
|
|
self.assertEqual(alice[0]['editing_status'],'available')
|
|
self.assertNotIn('owner',alice[0])
|
|
result = await self.call('GET','/'+TID+'/files/design.epro','alice')
|
|
self.assertEqual(result.status_code,200)
|
|
for method,path in [('GET',''),('GET','/preview'),('GET','/events'),('GET','/questions'),
|
|
('GET','/files/design.epro'),('POST','/cancel'),('POST','/resume'),('POST','/questions'),
|
|
('POST','/comments'),('POST','/approve'),('POST','/feedback'),('POST','/editing-project')]:
|
|
for tid,token in [(TID,'bob'),(OTHER,'alice')]:
|
|
result=await self.call(method,'/'+tid+path,token,json={} if method=='POST' else None)
|
|
self.assertEqual(result.status_code,404,(method,path,result.text))
|
|
with self.assertRaises(ValueError):
|
|
ep.bind(TID,ep.owner_key('bob'))
|
|
ep.bind(TID,self.owner)
|
|
|
|
async def test_retry_lost_receipt_recovers_same_project_after_restart(self):
|
|
self.cloud.append({'pcbProjectCode':'unrelated','name':'Board','description':''})
|
|
self.fail_after_create=True
|
|
path='/'+TID+'/editing-project'
|
|
self.assertEqual((await self.call('POST',path,'alice')).status_code,503)
|
|
self.cloud[-1]['name']='renamed'
|
|
self.fail_after_create=False
|
|
for _ in range(2):
|
|
self.assertEqual((await self.call('POST',path,'alice')).json(),{'project_code':'code-1'})
|
|
self.assertEqual(self.posts,1)
|
|
self.assertEqual((await self.call('GET','/'+TID,'alice')).json()['project_code'],'code-1')
|
|
|
|
async def test_overlapping_creation_issues_one_platform_post(self):
|
|
started,release=asyncio.Event(),asyncio.Event()
|
|
async def delayed(method,path,token,**kwargs):
|
|
if method=='POST':
|
|
started.set()
|
|
await release.wait()
|
|
return await self.platform(method,path,token,**kwargs)
|
|
path='/'+TID+'/editing-project'
|
|
with patch.object(ep,'platform',delayed):
|
|
first=asyncio.create_task(self.call('POST',path,'alice'))
|
|
await started.wait()
|
|
second=await self.call('POST',path,'alice')
|
|
self.assertEqual(second.status_code,409)
|
|
release.set()
|
|
self.assertEqual((await first).status_code,200)
|
|
self.assertEqual((await self.call('POST',path,'alice')).status_code,200)
|
|
self.assertEqual(self.posts,1)
|
|
|
|
async def test_deleted_copy_can_be_recreated_but_platform_outage_does_not_rebind(self):
|
|
path='/'+TID+'/editing-project'
|
|
first=await self.call('POST',path,'alice')
|
|
self.assertEqual(first.json(),{'project_code':'code-1'})
|
|
async def outage(method,path,token,**kwargs):
|
|
if path.endswith('/code-1'):
|
|
raise HTTPException(503,'temporarily unavailable')
|
|
return await self.platform(method,path,token,**kwargs)
|
|
with patch.object(ep,'platform',outage):
|
|
self.assertEqual((await self.call('POST',path,'alice')).status_code,503)
|
|
self.assertEqual(self.posts,1)
|
|
self.assertEqual(ep.record(TID,self.owner)['project_code'],'code-1')
|
|
self.cloud.clear()
|
|
self.assertEqual((await self.call('POST',path,'alice')).json(),{'project_code':'code-2'})
|
|
self.assertEqual((await self.call('POST',path,'alice')).json(),{'project_code':'code-2'})
|
|
self.assertEqual(self.posts,2)
|
|
|
|
async def test_newer_format_inside_a_legacy_extension_is_download_only(self):
|
|
path=storage.task_dir(TID)/'delivery/design.epro'
|
|
with ZipFile(path,'w') as z:
|
|
z.writestr('project2.json','{}')
|
|
z.writestr('design.epru','document')
|
|
dto=(await self.call('GET','/'+TID,'alice')).json()
|
|
self.assertEqual(dto['editing_status'],'unsupported')
|
|
self.assertIn('新版',dto['editing_reason'])
|
|
self.assertEqual((await self.call('POST','/'+TID+'/editing-project','alice')).status_code,409)
|
|
self.assertEqual(self.posts,0)
|