物品借出免审批并扩大上传限制
This commit is contained in:
+302
-104
@@ -1,122 +1,320 @@
|
||||
import asyncio
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from PIL import Image
|
||||
from sqlalchemy import insert, select
|
||||
from test_api import ApiTestCase, auth, register
|
||||
|
||||
|
||||
class CenterTests(ApiTestCase):
|
||||
async def test_concurrent_approval_cannot_overdraw_file_database(self):
|
||||
import asyncio
|
||||
file_engine=self.m.create_async_engine(f"sqlite+aiosqlite:///{(self.directory/'center-concurrency.db').as_posix()}")
|
||||
sessions=self.m.async_sessionmaker(file_engine,expire_on_commit=False)
|
||||
async def test_concurrent_borrows_cannot_overdraw_file_database(self):
|
||||
file_engine = self.m.create_async_engine(
|
||||
f"sqlite+aiosqlite:///{(self.directory / 'center-concurrency.db').as_posix()}"
|
||||
)
|
||||
sessions = self.m.async_sessionmaker(file_engine, expire_on_commit=False)
|
||||
try:
|
||||
async with file_engine.begin() as connection:await connection.run_sync(self.m.metadata.create_all)
|
||||
with patch.object(self.m,'SessionLocal',sessions):
|
||||
owner,manager=await self.setup_people(); c=self.client
|
||||
with patch.dict(os.environ,WORKLOG_CENTER_APPROVERS=manager['user']['email']):
|
||||
item=(await c.post('/api/center/items',headers=auth(owner['token']),json={'name':'并发音箱','quantity':1})).json()['id']
|
||||
loans=[(await c.post(f'/api/center/items/{item}/loans',headers=auth(owner['token']),json={'quantity':1,'reason':'活动使用','contact':'电话'})).json()['id'] for _ in range(2)]
|
||||
replies=await asyncio.gather(*[c.post(f'/api/center/loans/{loan}/review',headers=auth(manager['token']),json={'action':'approve'}) for loan in loans])
|
||||
self.assertEqual(sorted(r.status_code for r in replies),[200,409])
|
||||
data=(await c.get('/api/center/items',headers=auth(owner['token']))).json()
|
||||
self.assertEqual(data['items'][0]['available'],0)
|
||||
finally:await file_engine.dispose()
|
||||
async with file_engine.begin() as connection:
|
||||
await connection.run_sync(self.m.metadata.create_all)
|
||||
with patch.object(self.m, 'SessionLocal', sessions):
|
||||
owner = await register(self.client, 'centerowner')
|
||||
item = (await self.client.post(
|
||||
'/api/center/items',
|
||||
headers=auth(owner['token']),
|
||||
json={'name': '并发音箱', 'quantity': 1},
|
||||
)).json()['id']
|
||||
replies = await asyncio.gather(*[
|
||||
self.client.post(
|
||||
f'/api/center/items/{item}/loans',
|
||||
headers=auth(owner['token']),
|
||||
json={'quantity': 1, 'reason': '活动使用', 'contact': '电话'},
|
||||
)
|
||||
for _ in range(2)
|
||||
])
|
||||
self.assertCountEqual([response.status_code for response in replies], [200, 409])
|
||||
data = (await self.client.get('/api/center/items', headers=auth(owner['token']))).json()
|
||||
self.assertEqual(data['items'][0]['available'], 0)
|
||||
finally:
|
||||
await file_engine.dispose()
|
||||
|
||||
async def test_stocktake_excludes_approved_loans_and_contacts_are_restricted(self):
|
||||
owner,manager=await self.setup_people(); third=await register(self.client,'othermember'); c=self.client
|
||||
with patch.dict(os.environ,WORKLOG_CENTER_APPROVERS=manager['user']['email']):
|
||||
item=(await c.post('/api/center/items',headers=auth(owner['token']),json={'name':'清点音箱','quantity':3})).json()['id']
|
||||
loan=(await c.post(f'/api/center/items/{item}/loans',headers=auth(owner['token']),json={'quantity':2,'reason':'活动使用','contact':'私密联系方式'})).json()['id']
|
||||
await c.post(f'/api/center/loans/{loan}/review',headers=auth(manager['token']),json={'action':'approve'})
|
||||
response=await c.post('/api/center/checks',headers=auth(owner['token']),json={'quantities':{item:1}})
|
||||
self.assertEqual(response.status_code,200,response.text)
|
||||
self.assertEqual((await c.get('/api/center/items',headers=auth(owner['token']))).json()['items'][0]['quantity'],3)
|
||||
self.assertIsNone((await c.get('/api/center/loans',headers=auth(third['token']))).json()['items'][0]['contact'])
|
||||
async def setup_people(self):
|
||||
owner=await register(self.client,'centerowner')
|
||||
manager=await register(self.client,'centermanager')
|
||||
return owner,manager
|
||||
async def test_borrow_is_immediate_return_and_contacts_are_private(self):
|
||||
owner = await register(self.client, 'centerowner')
|
||||
other = await register(self.client, 'othermember')
|
||||
headers = auth(owner['token'])
|
||||
c = self.client
|
||||
item = (await c.post(
|
||||
'/api/center/items',
|
||||
headers=headers,
|
||||
json={'name': '投影仪', 'quantity': 3},
|
||||
)).json()['id']
|
||||
payload = {'quantity': 2, 'reason': '开展活动', 'contact': '13900000000'}
|
||||
response = await c.post(f'/api/center/items/{item}/loans', headers=headers, json=payload)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
loan = response.json()['id']
|
||||
self.assertEqual(response.json()['status'], 'approved')
|
||||
|
||||
async def test_approval_inventory_return_and_private_contacts(self):
|
||||
owner,manager=await self.setup_people(); c=self.client
|
||||
with patch.dict(os.environ,WORKLOG_CENTER_APPROVERS=manager['user']['email']):
|
||||
item=(await c.post('/api/center/items',headers=auth(owner['token']),json={'name':'投影仪','quantity':3})).json()['id']
|
||||
payload={'quantity':2,'reason':'开展活动','contact':'13900000000'}
|
||||
loan=(await c.post(f'/api/center/items/{item}/loans',headers=auth(owner['token']),json=payload)).json()['id']
|
||||
self.assertEqual((await c.get('/api/center/items',headers=auth(owner['token']))).json()['items'][0]['available'],3)
|
||||
self.assertEqual((await c.post(f'/api/center/loans/{loan}/review',headers=auth(owner['token']),json={'action':'approve'})).status_code,403)
|
||||
response=await c.post(f'/api/center/loans/{loan}/review',headers=auth(manager['token']),json={'action':'approve'})
|
||||
self.assertEqual(response.status_code,200,response.text)
|
||||
self.assertEqual((await c.get('/api/center/items',headers=auth(owner['token']))).json()['items'][0]['available'],1)
|
||||
self.assertEqual((await c.post(f'/api/center/items/{item}/loans',headers=auth(owner['token']),json=payload)).status_code,409)
|
||||
self.assertEqual((await c.post(f'/api/center/loans/{loan}/return',headers=auth(manager['token']))).status_code,403)
|
||||
self.assertEqual((await c.post(f'/api/center/loans/{loan}/return',headers=auth(owner['token']))).status_code,200)
|
||||
self.assertEqual((await c.get('/api/center/items',headers=auth(owner['token']))).json()['items'][0]['available'],3)
|
||||
self.assertEqual((await c.post(f'/api/center/loans/{loan}/return',headers=auth(owner['token']))).status_code,200)
|
||||
self.assertEqual((await c.get('/api/center/loans?status=returned',headers=auth(manager['token']))).json()['items'][0]['contact'],payload['contact'])
|
||||
inventory = (await c.get('/api/center/items', headers=headers)).json()
|
||||
self.assertEqual(inventory['items'][0]['borrowed'], 2)
|
||||
self.assertEqual(inventory['items'][0]['available'], 1)
|
||||
self.assertNotIn('can_review', inventory)
|
||||
self.assertNotIn('approval_configured', inventory)
|
||||
self.assertEqual((await c.post(
|
||||
f'/api/center/items/{item}/loans',
|
||||
headers=headers,
|
||||
json={**payload, 'quantity': 2},
|
||||
)).status_code, 409)
|
||||
|
||||
async def test_pending_requests_cannot_overdraw_when_approved(self):
|
||||
owner,manager=await self.setup_people(); c=self.client
|
||||
with patch.dict(os.environ,WORKLOG_CENTER_APPROVERS=manager['user']['email']):
|
||||
item=(await c.post('/api/center/items',headers=auth(owner['token']),json={'name':'音箱','quantity':1})).json()['id']
|
||||
payload={'quantity':1,'reason':'测试','contact':'微信test'}
|
||||
loans=[(await c.post(f'/api/center/items/{item}/loans',headers=auth(owner['token']),json=payload)).json()['id'] for _ in range(2)]
|
||||
self.assertEqual((await c.post(f'/api/center/loans/{loans[0]}/review',headers=auth(manager['token']),json={'action':'approve'})).status_code,200)
|
||||
self.assertEqual((await c.post(f'/api/center/loans/{loans[1]}/review',headers=auth(manager['token']),json={'action':'approve'})).status_code,409)
|
||||
self.assertEqual((await c.post(f'/api/center/loans/{loans[1]}/review',headers=auth(manager['token']),json={'action':'reject','note':'无库存'})).status_code,200)
|
||||
self.assertIn((await c.post(
|
||||
f'/api/center/loans/{loan}/review',
|
||||
headers=headers,
|
||||
json={'action': 'approve'},
|
||||
)).status_code, (404, 405))
|
||||
own_rows = (await c.get('/api/center/loans', headers=headers)).json()['items']
|
||||
other_rows = (await c.get('/api/center/loans', headers=auth(other['token']))).json()['items']
|
||||
self.assertEqual(own_rows[0]['contact'], payload['contact'])
|
||||
self.assertIsNone(other_rows[0]['contact'])
|
||||
self.assertEqual(other_rows[0]['reason'], payload['reason'])
|
||||
|
||||
self.assertEqual((await c.post(
|
||||
f'/api/center/loans/{loan}/return',
|
||||
headers=auth(other['token']),
|
||||
)).status_code, 403)
|
||||
self.assertEqual((await c.post(
|
||||
f'/api/center/loans/{loan}/return',
|
||||
headers=headers,
|
||||
)).status_code, 200)
|
||||
self.assertEqual((await c.get('/api/center/items', headers=headers)).json()['items'][0]['available'], 3)
|
||||
self.assertEqual((await c.post(
|
||||
f'/api/center/loans/{loan}/return',
|
||||
headers=headers,
|
||||
)).status_code, 200)
|
||||
self.assertEqual((await c.get(
|
||||
'/api/center/loans?status=returned',
|
||||
headers=headers,
|
||||
)).json()['items'][0]['contact'], payload['contact'])
|
||||
self.assertEqual((await c.get(
|
||||
'/api/center/loans?status=pending',
|
||||
headers=headers,
|
||||
)).status_code, 422)
|
||||
|
||||
async def test_stocktake_excludes_active_loans(self):
|
||||
owner = await register(self.client, 'stocktakeowner')
|
||||
other = await register(self.client, 'stocktakeother')
|
||||
headers = auth(owner['token'])
|
||||
item = (await self.client.post(
|
||||
'/api/center/items',
|
||||
headers=headers,
|
||||
json={'name': '清点音箱', 'quantity': 3},
|
||||
)).json()['id']
|
||||
await self.client.post(
|
||||
f'/api/center/items/{item}/loans',
|
||||
headers=headers,
|
||||
json={'quantity': 2, 'reason': '活动使用', 'contact': '私密联系方式'},
|
||||
)
|
||||
response = await self.client.post(
|
||||
'/api/center/checks',
|
||||
headers=headers,
|
||||
json={'quantities': {item: 1}},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
data = (await self.client.get('/api/center/items', headers=headers)).json()
|
||||
self.assertEqual(data['items'][0]['quantity'], 3)
|
||||
self.assertEqual(data['items'][0]['borrowed'], 2)
|
||||
self.assertEqual(data['items'][0]['available'], 1)
|
||||
self.assertIsNone((
|
||||
await self.client.get('/api/center/loans', headers=auth(other['token']))
|
||||
).json()['items'][0]['contact'])
|
||||
|
||||
async def test_legacy_pending_loans_migrate_without_negative_inventory(self):
|
||||
owner = await register(self.client, 'legacyloans')
|
||||
async with self.sessions() as db:
|
||||
await db.execute(insert(self.m.center_items).values(
|
||||
id='migration-item',
|
||||
name='历史物品',
|
||||
quantity=2,
|
||||
created_at=self.m.now_ms(),
|
||||
))
|
||||
await db.execute(insert(self.m.center_loans), [
|
||||
{
|
||||
'id': 'approved-before-migration',
|
||||
'item_id': 'migration-item',
|
||||
'user_id': owner['user']['id'],
|
||||
'quantity': 1,
|
||||
'reason': '已在借',
|
||||
'contact': '电话',
|
||||
'status': 'approved',
|
||||
'created_at': 1,
|
||||
'returned_at': None,
|
||||
},
|
||||
{
|
||||
'id': 'pending-fits',
|
||||
'item_id': 'migration-item',
|
||||
'user_id': owner['user']['id'],
|
||||
'quantity': 1,
|
||||
'reason': '库存足够',
|
||||
'contact': '电话',
|
||||
'status': 'pending',
|
||||
'created_at': 2,
|
||||
'returned_at': None,
|
||||
},
|
||||
{
|
||||
'id': 'pending-overflow',
|
||||
'item_id': 'migration-item',
|
||||
'user_id': owner['user']['id'],
|
||||
'quantity': 1,
|
||||
'reason': '库存不足',
|
||||
'contact': '电话',
|
||||
'status': 'pending',
|
||||
'created_at': 3,
|
||||
'returned_at': None,
|
||||
},
|
||||
{
|
||||
'id': 'pending-returned',
|
||||
'item_id': 'migration-item',
|
||||
'user_id': owner['user']['id'],
|
||||
'quantity': 1,
|
||||
'reason': '历史已归还',
|
||||
'contact': '电话',
|
||||
'status': 'pending',
|
||||
'created_at': 4,
|
||||
'returned_at': 5,
|
||||
},
|
||||
])
|
||||
await db.commit()
|
||||
async with self.engine.begin() as connection:
|
||||
await self.m._migrate_legacy(connection)
|
||||
async with self.sessions() as db:
|
||||
rows = {
|
||||
row['id']: row
|
||||
for row in (await db.execute(select(self.m.center_loans))).mappings()
|
||||
}
|
||||
self.assertEqual(rows['pending-fits']['status'], 'approved')
|
||||
self.assertEqual(rows['pending-overflow']['status'], 'rejected')
|
||||
self.assertIn('库存不足', rows['pending-overflow']['review_note'])
|
||||
self.assertEqual(rows['pending-returned']['status'], 'returned')
|
||||
inventory = (await self.client.get('/api/center/items', headers=auth(owner['token']))).json()
|
||||
self.assertEqual(inventory['items'][0]['available'], 0)
|
||||
|
||||
async def test_daily_check_once_and_discrepancy_explanation(self):
|
||||
owner,manager=await self.setup_people(); c=self.client
|
||||
item=(await c.post('/api/center/items',headers=auth(owner['token']),json={'name':'桌子','quantity':5})).json()['id']
|
||||
self.assertEqual((await c.post('/api/center/checks',headers=auth(owner['token']),json={'quantities':{}})).status_code,422)
|
||||
payload={'quantities':{item:4}}
|
||||
self.assertEqual((await c.post('/api/center/checks',headers=auth(owner['token']),json=payload)).status_code,422)
|
||||
response=await c.post('/api/center/checks',headers=auth(owner['token']),json={**payload,'note':'发现1张损坏,移出在库'})
|
||||
self.assertEqual(response.status_code,200,response.text)
|
||||
self.assertEqual((await c.post('/api/center/checks',headers=auth(manager['token']),json=payload)).status_code,409)
|
||||
data=(await c.get('/api/center/items',headers=auth(owner['token']))).json()
|
||||
self.assertTrue(data['checked_today']);self.assertEqual(data['items'][0]['quantity'],4)
|
||||
record=(await c.get('/api/center/checks',headers=auth(owner['token']))).json()['items'][0]
|
||||
self.assertEqual(record['details'][0]['expected'],5);self.assertEqual(record['details'][0]['actual'],4)
|
||||
owner = await register(self.client, 'checkowner')
|
||||
other = await register(self.client, 'checkother')
|
||||
headers = auth(owner['token'])
|
||||
item = (await self.client.post(
|
||||
'/api/center/items',
|
||||
headers=headers,
|
||||
json={'name': '桌子', 'quantity': 5},
|
||||
)).json()['id']
|
||||
self.assertEqual((await self.client.post(
|
||||
'/api/center/checks',
|
||||
headers=headers,
|
||||
json={'quantities': {}},
|
||||
)).status_code, 422)
|
||||
payload = {'quantities': {item: 4}}
|
||||
self.assertEqual((await self.client.post(
|
||||
'/api/center/checks',
|
||||
headers=headers,
|
||||
json=payload,
|
||||
)).status_code, 422)
|
||||
response = await self.client.post(
|
||||
'/api/center/checks',
|
||||
headers=headers,
|
||||
json={**payload, 'note': '发现1张损坏,移出在库'},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
self.assertEqual((await self.client.post(
|
||||
'/api/center/checks',
|
||||
headers=auth(other['token']),
|
||||
json=payload,
|
||||
)).status_code, 409)
|
||||
data = (await self.client.get('/api/center/items', headers=headers)).json()
|
||||
self.assertTrue(data['checked_today'])
|
||||
self.assertEqual(data['items'][0]['quantity'], 4)
|
||||
record = (await self.client.get('/api/center/checks', headers=headers)).json()['items'][0]
|
||||
self.assertEqual(record['details'][0]['expected'], 5)
|
||||
self.assertEqual(record['details'][0]['actual'], 4)
|
||||
|
||||
async def test_photos_required_all_members_visible_and_category_filter(self):
|
||||
owner,other=await self.setup_people(); c=self.client
|
||||
raw=io.BytesIO();Image.new('RGB',(10,10),'red').save(raw,'PNG')
|
||||
with tempfile.TemporaryDirectory() as directory, patch.object(self.m,'_db_path',Path(directory)/'test.db'):
|
||||
self.assertEqual((await c.post('/api/center/photos',headers=auth(owner['token']),content=b'<script>bad</script>')).status_code,422)
|
||||
package=io.BytesIO()
|
||||
with zipfile.ZipFile(package,'w') as archive:archive.writestr('活动照片.png',raw.getvalue());archive.writestr('材料说明.txt','活动材料')
|
||||
material=(await c.post('/api/center/materials',headers=auth(owner['token']),content=package.getvalue())).json()
|
||||
photo=material['photo_ids'][0]
|
||||
self.assertEqual((await c.get('/api/center/materials/'+material['id'],headers=auth(other['token']))).status_code,403)
|
||||
payload={'title':'一楼活动','start_at':self.m.now_ms(),'record_type':'center','visibility':'private'}
|
||||
self.assertEqual((await c.post('/api/activities',headers=auth(owner['token']),json=payload)).status_code,422)
|
||||
response=await c.post('/api/activities',headers=auth(owner['token']),json={**payload,'material_id':material['id']})
|
||||
self.assertEqual(response.status_code,200,response.text); activity=response.json()['activity']
|
||||
self.assertEqual(activity['record_type'],'center')
|
||||
self.assertEqual(activity['location'],'赋能中心一楼')
|
||||
self.assertEqual(activity['visibility'],'public')
|
||||
self.assertEqual((await c.get('/api/center/materials/'+material['id'],headers=auth(other['token']))).status_code,200)
|
||||
self.assertEqual((await c.get(f'/api/center/photos/{photo}')).status_code,401)
|
||||
self.assertEqual((await c.get(f'/api/center/photos/{photo}',headers=auth(other['token']))).status_code,200)
|
||||
self.assertEqual((await c.get(f'/api/center/photos/{photo}',headers=auth(owner['token']))).status_code,200)
|
||||
self.assertEqual(len((await c.get('/api/activities?record_type=center',headers=auth(owner['token']))).json()['items']),1)
|
||||
self.assertEqual(len((await c.get('/api/activities?record_type=normal',headers=auth(owner['token']))).json()['items']),0)
|
||||
await c.patch('/api/activities/'+activity['id'],headers=auth(owner['token']),json={'visibility':'public'})
|
||||
self.assertEqual((await c.get(f'/api/center/photos/{photo}',headers=auth(other['token']))).status_code,200)
|
||||
self.assertEqual((await c.get('/api/center/materials/'+material['id'],headers=auth(other['token']))).content,package.getvalue())
|
||||
|
||||
async def test_missing_manager_keeps_requests_pending_and_cannot_approve(self):
|
||||
self.assertEqual((await self.client.get('/api/center/items')).status_code,401)
|
||||
owner=await register(self.client,'nomanager')
|
||||
with patch.dict(os.environ,WORKLOG_CENTER_APPROVERS=''):
|
||||
item=(await self.client.post('/api/center/items',headers=auth(owner['token']),json={'name':'纸笔','quantity':1})).json()['id']
|
||||
response=await self.client.post(f'/api/center/items/{item}/loans',headers=auth(owner['token']),json={'quantity':1,'reason':'借用','contact':'电话'})
|
||||
self.assertEqual(response.status_code,200,response.text)
|
||||
loan=response.json()['id']
|
||||
self.assertEqual((await self.client.post(f'/api/center/loans/{loan}/review',headers=auth(owner['token']),json={'action':'approve'})).status_code,403)
|
||||
self.assertEqual((await self.client.get('/api/center/items',headers=auth(owner['token']))).json()['items'][0]['available'],1)
|
||||
owner = await register(self.client, 'photoowner')
|
||||
other = await register(self.client, 'photoother')
|
||||
c = self.client
|
||||
headers = auth(owner['token'])
|
||||
raw = io.BytesIO()
|
||||
Image.new('RGB', (10, 10), 'red').save(raw, 'PNG')
|
||||
with tempfile.TemporaryDirectory() as directory, patch.object(
|
||||
self.m,
|
||||
'_db_path',
|
||||
Path(directory) / 'test.db',
|
||||
):
|
||||
self.assertEqual((await c.post(
|
||||
'/api/center/photos',
|
||||
headers=headers,
|
||||
content=b'<script>bad</script>',
|
||||
)).status_code, 422)
|
||||
package = io.BytesIO()
|
||||
with zipfile.ZipFile(package, 'w') as archive:
|
||||
archive.writestr('活动照片.png', raw.getvalue())
|
||||
archive.writestr('材料说明.txt', '活动材料')
|
||||
material = (await c.post(
|
||||
'/api/center/materials',
|
||||
headers=headers,
|
||||
content=package.getvalue(),
|
||||
)).json()
|
||||
photo = material['photo_ids'][0]
|
||||
self.assertEqual((await c.get(
|
||||
'/api/center/materials/' + material['id'],
|
||||
headers=auth(other['token']),
|
||||
)).status_code, 403)
|
||||
payload = {
|
||||
'title': '一楼活动',
|
||||
'start_at': self.m.now_ms(),
|
||||
'record_type': 'center',
|
||||
'visibility': 'private',
|
||||
}
|
||||
self.assertEqual((await c.post(
|
||||
'/api/activities',
|
||||
headers=headers,
|
||||
json=payload,
|
||||
)).status_code, 422)
|
||||
response = await c.post(
|
||||
'/api/activities',
|
||||
headers=headers,
|
||||
json={**payload, 'material_id': material['id']},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
activity = response.json()['activity']
|
||||
self.assertEqual(activity['record_type'], 'center')
|
||||
self.assertEqual(activity['location'], '赋能中心一楼')
|
||||
self.assertEqual(activity['visibility'], 'public')
|
||||
self.assertEqual((await c.get(
|
||||
'/api/center/materials/' + material['id'],
|
||||
headers=auth(other['token']),
|
||||
)).status_code, 200)
|
||||
self.assertEqual((await c.get(f'/api/center/photos/{photo}')).status_code, 401)
|
||||
self.assertEqual((await c.get(
|
||||
f'/api/center/photos/{photo}',
|
||||
headers=auth(other['token']),
|
||||
)).status_code, 200)
|
||||
self.assertEqual(len((await c.get(
|
||||
'/api/activities?record_type=center',
|
||||
headers=headers,
|
||||
)).json()['items']), 1)
|
||||
self.assertEqual(len((await c.get(
|
||||
'/api/activities?record_type=normal',
|
||||
headers=headers,
|
||||
)).json()['items']), 0)
|
||||
await c.patch(
|
||||
'/api/activities/' + activity['id'],
|
||||
headers=headers,
|
||||
json={'visibility': 'public'},
|
||||
)
|
||||
self.assertEqual((await c.get(
|
||||
f'/api/center/photos/{photo}',
|
||||
headers=auth(other['token']),
|
||||
)).status_code, 200)
|
||||
self.assertEqual((await c.get(
|
||||
'/api/center/materials/' + material['id'],
|
||||
headers=auth(other['token']),
|
||||
)).content, package.getvalue())
|
||||
|
||||
@@ -9,6 +9,7 @@ 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
|
||||
from server import center as center_service
|
||||
|
||||
|
||||
def package(entries=None):
|
||||
@@ -20,20 +21,21 @@ def package(entries=None):
|
||||
|
||||
|
||||
class CenterExportTests(ApiTestCase):
|
||||
async def test_material_with_20_photos_can_be_created_edited_and_downloaded(self):
|
||||
async def test_material_with_photo_batch_limit_can_be_created_edited_and_downloaded(self):
|
||||
limit=center_service.MAX_PHOTOS_PER_UPLOAD
|
||||
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)])
|
||||
raw=package([(f'照片/{i}.png',image.getvalue()) for i in range(limit)])
|
||||
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)
|
||||
material=response.json();self.assertEqual(len(material['photo_ids']),limit)
|
||||
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)
|
||||
activity=response.json()['activity'];self.assertEqual(len(activity['photo_ids']),limit)
|
||||
edited=await self.client.patch('/api/activities/'+activity['id'],headers=headers,json={
|
||||
'description':'更新说明','photo_ids':material['photo_ids'],
|
||||
})
|
||||
@@ -43,7 +45,7 @@ class CenterExportTests(ApiTestCase):
|
||||
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)
|
||||
|
||||
|
||||
+31
-21
@@ -8,6 +8,7 @@ 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):
|
||||
@@ -62,57 +63,66 @@ class DirectCenterPhotoTests(ApiTestCase):
|
||||
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_twenty_photo_batch_limit_and_historical_photos_are_preserved(self):
|
||||
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,21)
|
||||
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('20张',rejected.text)
|
||||
body['photo_ids']=photos[:20]
|
||||
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[20:]})
|
||||
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),21)
|
||||
# 历史记录超过20张,旧页面提交原照片、或只改说明都能保存。
|
||||
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']),21)
|
||||
extra=await self.upload(owner,21)
|
||||
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[:20]})
|
||||
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),41)
|
||||
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[:20]))
|
||||
self.assertEqual(set(detail['photo_ids']),set(photos+extra[:limit]))
|
||||
|
||||
async def test_zip_and_direct_photos_share_twenty_photo_batch_limit(self):
|
||||
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(21)])
|
||||
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('20张',rejected.text)
|
||||
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,20)
|
||||
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[:19]
|
||||
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']),20)
|
||||
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,20)
|
||||
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'][:19]
|
||||
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']),40)
|
||||
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']
|
||||
|
||||
Reference in New Issue
Block a user