107 lines
8.2 KiB
Python
107 lines
8.2 KiB
Python
import io
|
|
import json
|
|
import csv
|
|
import zipfile
|
|
import tempfile
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
from PIL import Image
|
|
from sqlalchemy import insert
|
|
from test_api import ApiTestCase, auth, register
|
|
from server.models import center_items, center_loans, center_checks
|
|
|
|
|
|
def package(entries=None):
|
|
image=io.BytesIO();Image.new('RGB',(20,20),'blue').save(image,'PNG')
|
|
output=io.BytesIO()
|
|
with zipfile.ZipFile(output,'w') as archive:
|
|
for name,data in (entries if entries is not None else [('照片.png',image.getvalue()),('材料.txt','材料说明')]):archive.writestr(name,data)
|
|
return output.getvalue()
|
|
|
|
|
|
class CenterExportTests(ApiTestCase):
|
|
async def test_material_with_20_photos_can_be_created_edited_and_downloaded(self):
|
|
owner=await register(self.client,'manyphotos');headers=auth(owner['token'])
|
|
image=io.BytesIO();Image.new('RGB',(20,20),'blue').save(image,'PNG')
|
|
raw=package([(f'照片/{i}.png',image.getvalue()) for i in range(20)])
|
|
with tempfile.TemporaryDirectory() as directory,patch.object(self.m,'_db_path',Path(directory)/'test.db'):
|
|
response=await self.client.post('/api/center/materials',headers=headers,content=raw)
|
|
self.assertEqual(response.status_code,200,response.text)
|
|
material=response.json();self.assertEqual(len(material['photo_ids']),20)
|
|
response=await self.client.post('/api/activities',headers=headers,json={
|
|
'title':'多照片一楼活动','start_at':self.m.now_ms(),'record_type':'center',
|
|
'material_id':material['id'],'photo_ids':material['photo_ids'],
|
|
})
|
|
self.assertEqual(response.status_code,200,response.text)
|
|
activity=response.json()['activity'];self.assertEqual(len(activity['photo_ids']),20)
|
|
edited=await self.client.patch('/api/activities/'+activity['id'],headers=headers,json={
|
|
'description':'更新说明','photo_ids':material['photo_ids'],
|
|
})
|
|
self.assertEqual(edited.status_code,200,edited.text)
|
|
self.assertEqual(edited.json()['activity']['photo_ids'],material['photo_ids'])
|
|
downloaded=await self.client.get('/api/center/materials/'+material['id'],headers=headers)
|
|
self.assertEqual(downloaded.status_code,200);self.assertEqual(downloaded.content,raw)
|
|
last_photo=await self.client.get('/api/center/photos/'+material['photo_ids'][-1],headers=headers)
|
|
self.assertEqual(last_photo.status_code,200)
|
|
# 单次20张后仍可继续补充其他材料。
|
|
second=await self.client.post('/api/center/materials',headers=headers,content=package())
|
|
self.assertEqual(second.status_code,200,second.text)
|
|
|
|
async def test_api_auth_export_all_and_contact_redaction(self):
|
|
for path in ['/api/center/data','/api/center/schema','/api/center/export']:
|
|
self.assertEqual((await self.client.get(path)).status_code,401)
|
|
user=await register(self.client,'exportowner')
|
|
async with self.sessions() as db:
|
|
await db.execute(insert(center_items).values(id='item1',name='=测试物品',quantity=5,created_at=self.m.now_ms()))
|
|
await db.execute(insert(center_loans).values(id='loan1',item_id='item1',user_id=user['user']['id'],quantity=2,reason='活动使用',contact='secret@example.test',status='approved',created_at=self.m.now_ms()))
|
|
await db.execute(insert(center_checks).values(day='2026-11-11',user_id=user['user']['id'],details=json.dumps([{'name':'物品','expected':3,'actual':3,'borrowed':2}]),note='核对无误',created_at=self.m.now_ms()))
|
|
await db.commit()
|
|
headers=auth(user['token'])
|
|
response=await self.client.get('/api/center/data',headers=headers)
|
|
self.assertEqual(response.status_code,200,response.text)
|
|
data=response.json();self.assertEqual(data['data']['items'][0]['available'],3)
|
|
self.assertEqual(data['data']['checks'][0]['details'][0]['actual'],3)
|
|
self.assertNotIn('secret@example.test',response.text);self.assertNotIn(user['user']['email'],response.text)
|
|
self.assertFalse(data['contacts_included'])
|
|
exported=await self.client.get('/api/center/export?format=csv',headers=headers)
|
|
self.assertEqual(exported.status_code,200)
|
|
self.assertIn('.zip',exported.headers['Content-Disposition'])
|
|
with zipfile.ZipFile(io.BytesIO(exported.content)) as archive:
|
|
self.assertEqual(set(archive.namelist()),{'activities.csv','items.csv','loans.csv','checks.csv','metadata.json'})
|
|
rows=list(csv.DictReader(io.StringIO(archive.read('items.csv').decode('utf-8-sig'))))
|
|
self.assertEqual(rows[0]['name'],"'=测试物品")
|
|
self.assertNotIn('secret@example.test',archive.read('loans.csv').decode('utf-8-sig'))
|
|
self.assertEqual((await self.client.get('/api/center/schema',headers=headers)).json()['schema_version'],1)
|
|
|
|
async def test_pagination_and_export_are_not_silently_truncated(self):
|
|
user=await register(self.client,'exportpagination');headers=auth(user['token'])
|
|
async with self.sessions() as db:
|
|
await db.execute(insert(center_items),[dict(id=str(i),name=f'物品{i:03d}',quantity=1,created_at=self.m.now_ms()) for i in range(205)])
|
|
await db.commit()
|
|
first=(await self.client.get('/api/center/data?dataset=items&limit=100',headers=headers)).json()
|
|
self.assertEqual(len(first['data']['items']),100);self.assertEqual(first['pagination']['items']['next_offset'],100)
|
|
last=(await self.client.get('/api/center/data?dataset=items&limit=100&offset=200',headers=headers)).json()
|
|
self.assertEqual(len(last['data']['items']),5);self.assertIsNone(last['pagination']['items']['next_offset'])
|
|
exported=(await self.client.get('/api/center/export?dataset=items',headers=headers)).json()
|
|
self.assertEqual(len(exported['data']['items']),205)
|
|
self.assertEqual((await self.client.get('/api/center/data?date_from=2026-11-12&date_to=2026-11-11',headers=headers)).status_code,422)
|
|
|
|
async def test_material_zip_validation_and_export_visible_activities_only(self):
|
|
owner=await register(self.client,'materialsowner');other=await register(self.client,'materialsother');c=self.client
|
|
with tempfile.TemporaryDirectory() as directory,patch.object(self.m,'_db_path',Path(directory)/'test.db'):
|
|
for raw in [b'not zip',package([('../bad.txt','bad')]),package([]),package([('script.exe','bad')])]:
|
|
self.assertEqual((await c.post('/api/center/materials',headers=auth(owner['token']),content=raw)).status_code,422)
|
|
response=await c.post('/api/center/materials',headers=auth(owner['token']),content=package())
|
|
self.assertEqual(response.status_code,200,response.text);material=response.json()
|
|
self.assertEqual((await c.get('/api/center/materials/'+material['id'],headers=auth(other['token']))).status_code,403)
|
|
self.assertEqual((await c.post('/api/activities',headers=auth(other['token']),json={'title':'冒用','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id']})).status_code,403)
|
|
created=await c.post('/api/activities',headers=auth(owner['token']),json={'title':'私密一楼活动','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id'],'visibility':'private'})
|
|
self.assertEqual(created.status_code,200,created.text);activity=created.json()['activity']
|
|
result=(await c.get('/api/center/data?dataset=activities',headers=auth(owner['token']))).json()
|
|
self.assertEqual(result['data']['activities'][0]['material_id'],material['id'])
|
|
self.assertEqual(activity['visibility'],'public')
|
|
self.assertEqual(len((await c.get('/api/center/data?dataset=activities',headers=auth(other['token']))).json()['data']['activities']),1)
|
|
self.assertEqual((await c.get('/api/center/materials/'+material['id'],headers=auth(other['token']))).status_code,200)
|
|
await c.patch('/api/activities/'+activity['id'],headers=auth(owner['token']),json={'visibility':'public'})
|
|
self.assertEqual(len((await c.get('/api/center/data?dataset=activities&q=私密',headers=auth(other['token']))).json()['data']['activities']),1)
|