Files
worklog/tests/test_center_photos.py
T

167 lines
12 KiB
Python

import asyncio
import io
import tempfile
from PIL import Image
from pathlib import Path
from unittest.mock import patch
from sqlalchemy import insert, select
from test_api import ApiTestCase, auth, register
from test_center_export import package
from test_timetables import image_bytes
from server.models import center_photos
from server import center as center_service
class DirectCenterPhotoTests(ApiTestCase):
def setUp(self):
super().setUp()
self.files=tempfile.TemporaryDirectory();self.root=Path(self.files.name)
self.path_patch=patch.object(self.m,'_db_path',self.root/'test.db');self.path_patch.start()
def tearDown(self):
self.path_patch.stop();self.files.cleanup();super().tearDown()
async def upload(self,user,count=1):
ids=[]
for _ in range(count):
result=await self.client.post('/api/center/photos',headers=auth(user['token']),content=image_bytes())
self.assertEqual(result.status_code,200,result.text);ids.append(result.json()['id'])
return ids
async def test_jpeg_variants_convert_to_unified_original_size_jpeg(self):
owner=await register(self.client,'jpegvariants');headers=auth(owner['token'])
image=Image.new('RGB',(4021,237),'white')
raw=io.BytesIO();image.save(raw,'JPEG')
result=await self.client.post('/api/center/photos',headers=headers,content=raw.getvalue())
self.assertEqual(result.status_code,200,result.text)
photo=await self.client.get('/api/center/photos/'+result.json()['id'],headers=headers)
self.assertEqual(photo.status_code,200)
self.assertEqual(photo.headers['content-type'],'image/jpeg')
with Image.open(io.BytesIO(photo.content)) as stored:
self.assertEqual(stored.format,'JPEG')
self.assertEqual(stored.size,(4021,237))
async def test_photo_only_creation_supplement_and_edit_preserve_all_members_photos(self):
owner=await register(self.client,'directowner');member=await register(self.client,'directmember')
c=self.client;oh=auth(owner['token']);mh=auth(member['token'])
photos=await self.upload(owner,7)
self.assertEqual((await c.get('/api/center/photos/'+photos[0],headers=mh)).status_code,403)
response=await c.post('/api/activities',headers=oh,json={'title':'直接上传照片','start_at':self.m.now_ms(),'record_type':'center','photo_ids':photos})
self.assertEqual(response.status_code,200,response.text);activity=response.json()['activity'];aid=activity['id']
self.assertEqual(activity['photo_ids'],photos);self.assertIsNone(activity['material_id']);self.assertEqual(activity['materials'],[])
self.assertEqual(activity['participant_count'],0)
self.assertEqual((await c.get('/api/center/photos/'+photos[0],headers=mh)).status_code,200)
self.assertEqual((await c.post('/api/activities',headers=mh,json={'title':'冒用照片','start_at':self.m.now_ms(),'record_type':'center','photo_ids':photos})).status_code,403)
extra=await self.upload(member,2)
for _ in range(2):
result=await c.post('/api/activities/'+aid+'/materials',headers=mh,json={'photo_ids':extra})
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),9)
result=await c.patch('/api/activities/'+aid,headers=oh,json={'description':'从旧页面保存','photo_ids':photos})
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),9)
exported=(await c.get('/api/center/data?dataset=activities',headers=mh)).json()['data']['activities'][0]
self.assertEqual(len(exported['photo_ids']),9);self.assertIsNone(exported['material_url']);self.assertEqual(exported['materials'],[])
self.assertEqual((await c.post('/api/activities/'+aid+'/materials',headers=mh,json={})).status_code,422)
self.assertEqual((await c.post('/api/activities/'+aid+'/materials',headers=mh,json={'photo_ids':photos})).status_code,403)
async def test_document_only_zip_and_mixed_photos_are_optional_independent_inputs(self):
owner=await register(self.client,'documentsowner');c=self.client;headers=auth(owner['token'])
uploaded=await c.post('/api/center/materials',headers=headers,content=package([('说明.txt','活动说明')]))
self.assertEqual(uploaded.status_code,200,uploaded.text);material=uploaded.json();self.assertEqual(material['photo_ids'],[])
response=await c.post('/api/activities',headers=headers,json={'title':'文档活动','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id']})
self.assertEqual(response.status_code,200,response.text);self.assertEqual(response.json()['activity']['photo_ids'],[])
photos=await self.upload(owner,2)
response=await c.post('/api/activities',headers=headers,json={'title':'照片和文档','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id'],'photo_ids':photos})
self.assertEqual(response.status_code,200,response.text);self.assertEqual(response.json()['activity']['photo_ids'],photos)
self.assertEqual(len(response.json()['activity']['materials']),1)
aid=response.json()['activity']['id']
more=await c.post('/api/center/materials',headers=headers,content=package([('补充.md','补充文档')]))
self.assertEqual((await c.post('/api/activities/'+aid+'/materials',headers=headers,json={'material_id':more.json()['id']})).status_code,200)
async def test_photo_batch_limit_and_historical_photos_are_preserved(self):
limit=center_service.MAX_PHOTOS_PER_UPLOAD
owner=await register(self.client,'batchlimit');headers=auth(owner['token']);c=self.client
photos=await self.upload(owner,limit+1)
body={'title':'照片上限','start_at':self.m.now_ms(),'record_type':'center','photo_ids':photos}
rejected=await c.post('/api/activities',headers=headers,json=body)
self.assertEqual(rejected.status_code,422,rejected.text);self.assertIn(f'{limit}张',rejected.text)
body['photo_ids']=photos[:limit]
result=await c.post('/api/activities',headers=headers,json=body)
self.assertEqual(result.status_code,200,result.text);aid=result.json()['activity']['id']
path='/api/activities/'+aid
rejected=await c.post(path+'/materials',headers=headers,json={'photo_ids':photos})
self.assertEqual(rejected.status_code,422,rejected.text)
result=await c.post(path+'/materials',headers=headers,json={'photo_ids':photos[limit:]})
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),limit+1)
# 历史记录超过单次上限,旧页面提交原照片、或只改说明都能保存。
for changes in ({'description':'只改说明'},{'photo_ids':photos}):
result=await c.patch(path,headers=headers,json=changes)
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),limit+1)
extra=await self.upload(owner,limit+1)
rejected=await c.patch(path,headers=headers,json={'photo_ids':extra})
self.assertEqual(rejected.status_code,422,rejected.text)
result=await c.patch(path,headers=headers,json={'photo_ids':extra[:limit]})
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),limit*2+1)
detail=(await c.get(path,headers=headers)).json()['activity']
self.assertEqual(set(detail['photo_ids']),set(photos+extra[:limit]))
async def test_zip_and_direct_photos_share_photo_batch_limit(self):
limit=center_service.MAX_PHOTOS_PER_UPLOAD
owner=await register(self.client,'mixedlimit');headers=auth(owner['token']);c=self.client
raw=package([(f'{i}.png',image_bytes()) for i in range(limit+1)])
rejected=await c.post('/api/center/materials',headers=headers,content=raw)
self.assertEqual(rejected.status_code,422,rejected.text);self.assertIn(f'{limit}张',rejected.text)
material=(await c.post('/api/center/materials',headers=headers,content=package())).json()
photos=await self.upload(owner,limit)
body={'title':'混合上限','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id'],'photo_ids':photos}
rejected=await c.post('/api/activities',headers=headers,json=body)
self.assertEqual(rejected.status_code,422,rejected.text)
body['photo_ids']=photos[:limit-1]
result=await c.post('/api/activities',headers=headers,json=body)
self.assertEqual(result.status_code,200,result.text);aid=result.json()['activity']['id'];path='/api/activities/'+aid
self.assertEqual(len(result.json()['activity']['photo_ids']),limit)
new_material=(await c.post('/api/center/materials',headers=headers,content=package())).json()
batch={'material_id':new_material['id'],'photo_ids':photos}
rejected=await c.post(path+'/materials',headers=headers,json=batch)
self.assertEqual(rejected.status_code,422,rejected.text)
batch['photo_ids']=await self.upload(owner,limit)
rejected=await c.patch(path,headers=headers,json=batch)
self.assertEqual(rejected.status_code,422,rejected.text)
batch['photo_ids']=batch['photo_ids'][:limit-1]
result=await c.post(path+'/materials',headers=headers,json=batch)
self.assertEqual(result.status_code,200,result.text)
self.assertEqual(len(result.json()['activity']['photo_ids']),limit*2)
async def test_zip_request_limit_uses_configured_size(self):
owner=await register(self.client,'ziplimit');headers=auth(owner['token'])
with patch.object(center_service,'MAX_ZIP_BYTES',16):
result=await self.client.post('/api/center/materials',headers=headers,content=b'x'*17)
self.assertEqual(result.status_code,413,result.text)
self.assertIn('ZIP材料包最大',result.text)
async def test_daily_allowance_allows_more_than_100_and_keeps_1000_limit(self):
owner=await register(self.client,'photolimit');uid=owner['user']['id']
async with self.sessions() as db:
await db.execute(insert(center_photos),[{'id':f'{i:032x}','owner_id':uid,'created_at':self.m.now_ms()} for i in range(100)])
await db.commit()
await self.upload(owner)
async with self.sessions() as db:
await db.execute(insert(center_photos),[{'id':f'{i:032x}','owner_id':uid,'created_at':self.m.now_ms()} for i in range(100,999)])
await db.commit()
result=await self.client.post('/api/center/photos',headers=auth(owner['token']),content=image_bytes())
self.assertEqual(result.status_code,429)
async def test_concurrent_supplements_do_not_overwrite_each_other(self):
engine=self.m.create_async_engine('sqlite+aiosqlite:///'+(self.root/'concurrent.db').as_posix())
try:
async with engine.begin() as conn:await conn.run_sync(self.m.metadata.create_all)
sessions=self.m.async_sessionmaker(engine,expire_on_commit=False)
with patch.object(self.m,'SessionLocal',sessions):
owner=await register(self.client,'concurrentphotos');photos=await self.upload(owner,3);headers=auth(owner['token'])
activity=(await self.client.post('/api/activities',headers=headers,json={'title':'并发补充','start_at':self.m.now_ms(),'record_type':'center','photo_ids':photos[:1]})).json()['activity']
path='/api/activities/'+activity['id']+'/materials'
results=await asyncio.gather(*(self.client.post(path,headers=headers,json={'photo_ids':[photo]}) for photo in photos[1:]))
self.assertTrue(all(result.status_code==200 for result in results))
detail=(await self.client.get('/api/activities/'+activity['id'],headers=headers)).json()['activity']
self.assertEqual(set(detail['photo_ids']),set(photos))
finally:await engine.dispose()