Files
worklog/tests/test_center.py
T

386 lines
17 KiB
Python

import io
import tempfile
import zipfile
from pathlib import Path
from unittest.mock import patch
from PIL import Image
from sqlalchemy import insert, inspect, select, text
from test_api import ApiTestCase, auth, register
class CenterTests(ApiTestCase):
async def test_record_loan_without_inventory_is_independent(self):
owner = await register(self.client, 'centerowner')
other = await register(self.client, 'othermember')
headers = auth(owner['token'])
c = self.client
payload = {'item_name': '临时借用的投影仪', 'quantity': 99, 'reason': '开展活动', 'contact': '13900000000'}
response = await c.post('/api/center/loans', headers=headers, json=payload)
self.assertEqual(response.status_code, 200, response.text)
loan = response.json()['id']
self.assertEqual(response.json()['status'], 'recorded')
self.assertEqual((await c.get('/api/center/items', headers=headers)).json()['items'], [])
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]['item_name'], payload['item_name'])
self.assertIsNone(own_rows[0]['item_id'])
self.assertEqual(own_rows[0]['status'], 'recorded')
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=headers,
)).status_code, 409)
self.assertEqual(
len((await c.get('/api/center/loans?status=recorded', headers=headers)).json()['items']),
1,
)
self.assertEqual((await c.get(
'/api/center/loans?status=pending',
headers=headers,
)).status_code, 422)
async def test_legacy_item_loan_endpoint_records_without_changing_inventory(self):
owner = await register(self.client, 'compatloanowner')
headers = auth(owner['token'])
item = (await self.client.post(
'/api/center/items',
headers=headers,
json={'name': '投影仪', 'quantity': 1},
)).json()['id']
response = await self.client.post(
f'/api/center/items/{item}/loans',
headers=headers,
json={'quantity': 5, 'reason': '兼容旧调用', 'contact': '微信'},
)
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(response.json()['status'], 'recorded')
inventory = (await self.client.get('/api/center/items', headers=headers)).json()
self.assertEqual(inventory['items'][0]['quantity'], 1)
self.assertEqual(inventory['items'][0]['borrowed'], 0)
self.assertEqual(inventory['items'][0]['available'], 1)
row = (await self.client.get('/api/center/loans?status=recorded', headers=headers)).json()['items'][0]
self.assertEqual(row['item_name'], '投影仪')
self.assertEqual(row['item_id'], item)
async def test_historical_inventory_loan_can_return_and_contacts_are_private(self):
owner = await register(self.client, 'historicalloanowner')
other = await register(self.client, 'historicalloonother')
headers = auth(owner['token'])
item = (await self.client.post(
'/api/center/items',
headers=headers,
json={'name': '历史音箱', 'quantity': 3},
)).json()['id']
async with self.sessions() as db:
await db.execute(insert(self.m.center_loans).values(
id='historical-approved',
item_id=item,
user_id=owner['user']['id'],
quantity=2,
reason='升级前借出',
contact='13900000000',
status='approved',
created_at=self.m.now_ms(),
))
await db.commit()
own_rows = (await self.client.get('/api/center/loans', headers=headers)).json()['items']
other_rows = (await self.client.get('/api/center/loans', headers=auth(other['token']))).json()['items']
self.assertEqual(own_rows[0]['contact'], '13900000000')
self.assertIsNone(other_rows[0]['contact'])
self.assertEqual((await self.client.post(
'/api/center/loans/historical-approved/return',
headers=auth(other['token']),
)).status_code, 403)
self.assertEqual((await self.client.post(
'/api/center/loans/historical-approved/return',
headers=headers,
)).status_code, 200)
self.assertEqual((await self.client.get('/api/center/items', headers=headers)).json()['items'][0]['available'], 3)
self.assertEqual((await self.client.post(
'/api/center/loans/historical-approved/return',
headers=headers,
)).status_code, 200)
self.assertEqual((await self.client.get(
'/api/center/loans?status=returned',
headers=headers,
)).json()['items'][0]['contact'], '13900000000')
async def test_stocktake_ignores_new_loan_registrations(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(
'/api/center/loans',
headers=headers,
json={'item_name': '库存外物品', 'quantity': 2, 'reason': '活动使用', 'contact': '私密联系方式'},
)
response = await self.client.post(
'/api/center/checks',
headers=headers,
json={'quantities': {item: 3}},
)
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'], 0)
self.assertEqual(data['items'][0]['available'], 3)
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_old_loan_schema_allows_only_recorded_loans(self):
owner = await register(self.client, 'oldloanschema')
async with self.engine.begin() as connection:
await connection.execute(insert(self.m.center_items).values(
id='legacy-schema-item',
name='旧版物品',
quantity=2,
created_at=1,
))
await connection.exec_driver_sql('DROP TABLE center_loans')
await connection.exec_driver_sql("""
CREATE TABLE center_loans (
id VARCHAR(32) PRIMARY KEY,
item_id VARCHAR(32) NOT NULL REFERENCES center_items(id),
user_id VARCHAR(36) NOT NULL REFERENCES users(id),
quantity INTEGER NOT NULL,
reason VARCHAR(500) NOT NULL,
contact VARCHAR(200) NOT NULL,
created_at INTEGER NOT NULL,
returned_at INTEGER,
status VARCHAR(16) NOT NULL DEFAULT 'approved',
reviewer_id VARCHAR(36) REFERENCES users(id),
reviewed_at INTEGER,
review_note VARCHAR(500) NOT NULL DEFAULT ''
)
""")
await connection.execute(text("""
INSERT INTO center_loans (
id, item_id, user_id, quantity, reason, contact,
created_at, status, review_note
) VALUES (
'old-schema-loan', 'legacy-schema-item', :user_id, 1,
'旧记录', '电话', 1, 'approved', ''
)
"""), {'user_id': owner['user']['id']})
await self.m._migrate_center_loan_schema(connection)
columns = await connection.run_sync(
lambda sync: {
column['name']: column
for column in inspect(sync).get_columns('center_loans')
}
)
self.assertIn('item_name', columns)
self.assertTrue(columns['item_id']['nullable'])
response = await self.client.post(
'/api/center/loans',
headers=auth(owner['token']),
json={'item_name': '库存外椅子', 'quantity': 2, 'reason': '会议', 'contact': '微信'},
)
self.assertEqual(response.status_code, 200, response.text)
rows = (await self.client.get('/api/center/loans', headers=auth(owner['token']))).json()['items']
by_id = {row['id']: row for row in rows}
self.assertEqual(by_id['old-schema-loan']['item_name'], '旧版物品')
self.assertEqual(by_id[response.json()['id']]['item_name'], '库存外椅子')
self.assertIsNone(by_id[response.json()['id']]['item_id'])
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())