Files
worklog/tests/test_center.py
T

321 lines
14 KiB
Python

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