Files
worklog/tests/test_center_records.py
T

101 lines
8.1 KiB
Python

import tempfile
from pathlib import Path
from unittest.mock import AsyncMock, patch
from sqlalchemy import insert, select, update, func
from test_api import ApiTestCase, auth, register
from test_center_export import package
class CenterRecordTests(ApiTestCase):
async def make_material(self, user):
response = await self.client.post('/api/center/materials', headers=auth(user['token']), content=package())
self.assertEqual(response.status_code, 200, response.text)
return response.json()
async def test_public_record_has_no_participation_and_legacy_rows_do_not_affect_stats(self):
m = self.m; c = self.client
owner = await register(c, 'recordowner'); other = await register(c, 'recordviewer')
oh = auth(owner['token']); vh = auth(other['token'])
normal = (await c.post('/api/activities', headers=oh, json={'title':'普通活动', 'start_at':m.now_ms()+3600000})).json()['activity']
self.assertEqual((await c.post('/api/activities/'+normal['id']+'/claim', headers=vh)).status_code, 200)
baseline = (await c.get('/api/stats/overview', headers=oh)).json()
with tempfile.TemporaryDirectory() as directory, patch.object(m, '_db_path', Path(directory)/'test.db'):
material = await self.make_material(owner)
with patch.object(m, 'DEV_MODE', False), patch.object(m, 'NOTIFY_ENABLED', True), patch.object(m, '_notify_new_activity', new_callable=AsyncMock) as notify:
response = await c.post('/api/activities', headers=oh, json={
'title':'全员可见记录', 'start_at':m.now_ms()+3600000, 'record_type':'center',
'visibility':'private', 'capacity':1, 'material_id':material['id'],
})
self.assertEqual(response.status_code, 200, response.text)
notify.assert_not_called()
activity = response.json()['activity']; aid = activity['id']
self.assertEqual(activity['visibility'], 'public'); self.assertIsNone(activity['capacity'])
self.assertEqual(activity['participants'], []); self.assertIsNone(activity['my_participation'])
self.assertEqual((await c.get('/api/activities/'+aid, headers=vh)).status_code, 200)
for method, suffix, body in [('POST','/claim',{}),('POST','/leave',{}),('PATCH','/participants/'+other['user']['id'],{'status':'attended'}),('DELETE','/participants/'+other['user']['id'],{})]:
result = await c.request(method, '/api/activities/'+aid+suffix, headers=vh, json=body)
self.assertEqual(result.status_code, 409, result.text)
edited = await c.patch('/api/activities/'+aid, headers=oh, json={'visibility':'private','capacity':2})
self.assertEqual(edited.json()['activity']['visibility'], 'public')
self.assertIsNone(edited.json()['activity']['capacity'])
# 旧版遗留的私密状态、参加记录及邮件链接也不能重新产生参加行为。
token = 'legacy-center-link'
async with self.sessions() as db:
self.assertIsNone(await m._require_participant(db, aid, owner['user']['id']))
await db.execute(insert(m.participations).values(id=m.new_id(),activity_id=aid,user_id=other['user']['id'],role='member',status='attended',note='历史备注',joined_at=m.now_ms(),updated_at=m.now_ms()))
await db.execute(update(m.activities).where(m.activities.c.id==aid).values(visibility='private'))
await db.execute(insert(m.join_links).values(id=m.new_id(),token=m.token_digest(token),activity_id=aid,user_id=owner['user']['id'],expires_at=m.now_ms()+86400000,used=0,created_at=m.now_ms()))
await db.commit()
for method in ('GET','POST'):
page = await c.request(method, '/join/'+token)
self.assertIn('仅作记录', page.text); self.assertNotIn('<form', page.text)
with patch.object(m, '_send_email', new_callable=AsyncMock) as send:
await m._notify_new_activity(aid, '记录人', 'http://localhost')
send.assert_not_awaited()
detail = (await c.get('/api/activities/'+aid, headers=vh)).json()['activity']
self.assertEqual(detail['participant_count'], 0); self.assertEqual(detail['visibility'], 'public')
self.assertEqual((await c.get('/api/center/materials/'+material['id'],headers=vh)).status_code,200)
self.assertEqual((await c.get('/api/stats/overview',headers=oh)).json(), baseline)
for person in (owner, other):
stats = (await c.get('/api/users/'+person['user']['id'],headers=oh)).json()['stats']
self.assertEqual(stats['total'], 1)
self.assertEqual(stats['organized'], 1 if person is owner else 0)
members = (await c.get('/api/users',headers=oh)).json()['items']
self.assertTrue(all(member['total']==1 for member in members))
self.assertEqual(len((await c.get('/api/activities?scope=joined',headers=vh)).json()['items']),1)
async with self.sessions() as db:
self.assertIsNotNone(await m._require_participant(db,aid,other['user']['id']))
async def test_members_append_materials_without_replacing_or_editing_record(self):
c = self.client; m = self.m
owner = await register(c,'materialrecorder'); member = await register(c,'materialmember'); viewer = await register(c,'materialviewer')
oh = auth(owner['token']); mh = auth(member['token']); vh = auth(viewer['token'])
with tempfile.TemporaryDirectory() as directory, patch.object(m,'_db_path',Path(directory)/'test.db'):
first = await self.make_material(owner)
activity = (await c.post('/api/activities',headers=oh,json={'title':'共同归档','start_at':m.now_ms(),'record_type':'center','material_id':first['id']})).json()['activity']; aid = activity['id']
extra = await self.make_material(member)
self.assertEqual((await c.get('/api/center/materials/'+extra['id'],headers=oh)).status_code,403)
path = '/api/activities/'+aid+'/materials'
self.assertEqual((await c.post(path,json={'material_id':extra['id']})).status_code,401)
self.assertEqual((await c.post(path,headers=mh,json={'material_id':first['id']})).status_code,403)
for _ in range(2):
response = await c.post(path,headers=mh,json={'material_id':extra['id']})
self.assertEqual(response.status_code,200,response.text)
self.assertEqual(len(response.json()['activity']['materials']),2)
self.assertEqual((await c.patch('/api/activities/'+aid,headers=mh,json={'title':'擅自改名'})).status_code,403)
replacement = await self.make_material(owner)
response = await c.patch('/api/activities/'+aid,headers=oh,json={'title':'共同归档更新','material_id':replacement['id']})
self.assertEqual(response.status_code,200,response.text)
detail = (await c.get('/api/activities/'+aid,headers=vh)).json()['activity']
self.assertEqual(len(detail['materials']),3); self.assertEqual(len(detail['photo_ids']),3)
uploaders = {item['uploader_id'] for item in detail['materials']}
self.assertEqual(uploaders,{owner['user']['id'],member['user']['id']})
for item in detail['materials']:
self.assertEqual((await c.get(item['download_url'],headers=vh)).status_code,200)
self.assertEqual((await c.get('/api/center/photos/'+item['photo_ids'][0],headers=vh)).status_code,200)
exported = (await c.get('/api/center/data?dataset=activities',headers=vh)).json()['data']['activities'][0]
self.assertEqual(exported['materials'],detail['materials'])
self.assertEqual(exported['photo_ids'],detail['photo_ids'])
normal = (await c.post('/api/activities',headers=oh,json={'title':'普通','start_at':m.now_ms()})).json()['activity']
self.assertEqual((await c.post('/api/activities/'+normal['id']+'/materials',headers=mh,json={'material_id':extra['id']})).status_code,409)