import asyncio import io import tempfile 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 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_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_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()