File size: 10,944 Bytes
5e16fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
from datetime import date, timedelta
from io import BytesIO
from pathlib import Path
import shutil
import sqlite3
import secrets
import pytest
from openpyxl import load_workbook
from werkzeug.security import check_password_hash
from app import create_app

PASSWORD='MyTestPassword@456'

@pytest.fixture(scope='session')
def seeded(tmp_path_factory):
    path=tmp_path_factory.mktemp('seed')/'base.sqlite3'
    create_app({'TESTING':True,'DATABASE':str(path),'SECRET_KEY':'test-secret'})
    return path

@pytest.fixture
def app(tmp_path,seeded):
    path=tmp_path/'mom.sqlite3'
    shutil.copy2(seeded,path)
    return create_app({'TESTING':True,'DATABASE':str(path),'SECRET_KEY':'test-secret','REQUIRE_SETUP':False})

@pytest.fixture
def client(app):
    return app.test_client()

def query(app,sql,args=()):
    with sqlite3.connect(app.config['DATABASE']) as db:
        db.row_factory=sqlite3.Row
        return db.execute(sql,args).fetchall()

def csrf(client):
    with client.session_transaction() as session:
        return session['csrf']

def post(client,path,data=None):
    return client.post(path,data={'csrf_token':csrf(client),**(data or {})})

def login(client,name='kishan',change=True):
    client.get('/login')
    result=post(client,'/login',{'username':name,'password':'Password@123'})
    assert result.status_code==302
    client.get('/password')
    if change:
        result=post(client,'/password',{'current_password':'Password@123','new_password':PASSWORD,'confirm_password':PASSWORD})
        assert result.status_code==302
        client.get('/')
    return result

def active(app):
    return query(app,"SELECT * FROM meetings WHERE status='active'")[0]

def review(client,app,completed=None):
    return post(client,'/entry/1',{'meeting_id':active(app)['id'],'completed':completed or []})

def add(client,app,step,body='Saved test item',**kwargs):
    return post(client,f'/entry/{step}',{'meeting_id':active(app)['id'],'entry_token':secrets.token_hex(20),'body':body,**kwargs})

def test_seed_and_rotation(app):
    users=query(app,'SELECT * FROM users ORDER BY id')
    assert len(users)==14
    assert [u['username'] for u in users if u['rotation_order']] == ['kishan','harshitha','gokul','manish','madhan','honey','madhav']
    assert all(u['must_change'] and u['password_hash']!='Password@123' for u in users)
    assert check_password_hash(users[0]['password_hash'],'Password@123')
    assert query(app,'SELECT COUNT(*) n FROM updates')[0]['n']==182
    assert query(app,'SELECT COUNT(*) n FROM reviews')[0]['n']==40
    assert date.fromisoformat(active(app)['meeting_date']).weekday()==0
    assert active(app)['minutes_by']=='Harshitha P'
    assert query(app,"SELECT meeting_date FROM meetings WHERE source_file LIKE '%15-09%'")[0]['meeting_date']=='2026-09-21'
    assert query(app,"SELECT COUNT(*) n FROM actions WHERE due_note='Daily'")[0]['n']>0

def test_forced_password_change_and_csrf(client,app):
    assert client.get('/reports').status_code==302
    client.get('/login')
    assert client.post('/login',data={'username':'kishan','password':'Password@123'}).status_code==400
    login(client,change=False)
    for path in ['/','/reports','/admin/backup','/entry/1','/coordinator']:
        assert client.get(path).location.endswith('/password')
    r=post(client,'/password',{'current_password':'Password@123','new_password':'Password@123','confirm_password':'Password@123'})
    assert b'Choose a password different' in r.data
    post(client,'/password',{'current_password':'Password@123','new_password':PASSWORD,'confirm_password':PASSWORD})
    assert client.get('/').status_code==200
    assert query(app,"SELECT must_change FROM users WHERE username='kishan'")[0]['must_change']==0

def test_full_workflow_validation_and_persistence(client,app):
    login(client)
    assert client.get('/entry/2').location.endswith('/entry/1')
    previous=query(app,"SELECT a.id FROM actions a JOIN users u ON u.id=a.user_id JOIN reviews r ON a.id=r.action_id WHERE u.username='kishan'")
    chosen=previous[0]['id']
    assert review(client,app,[str(chosen)]).status_code==302
    assert add(client,app,2,'First update').status_code==302
    assert add(client,app,2,'Second update').status_code==302
    assert b'Choose a due date' in add(client,app,3,due_date='').data
    assert b'Choose a due date' in add(client,app,3,due_date='2020-01-01').data
    due=(date.fromisoformat(active(app)['meeting_date'])+timedelta(days=2)).isoformat()
    assert add(client,app,3,'New dated action',due_date=due).status_code==302
    for path in ['/entry/1','/entry/2','/entry/3','/entry/4','/reports','/admin','/coordinator']:
        assert client.get(path).status_code==200
    mid=active(app)['id']
    assert post(client,'/entry/4',{'meeting_id':mid}).status_code==302
    assert add(client,app,2,'Must be blocked').status_code==409
    # Restarting the application retains saved rows and the submission.
    restarted=create_app({'TESTING':True,'DATABASE':app.config['DATABASE'],'SECRET_KEY':'test-secret'})
    assert query(restarted,'SELECT COUNT(*) n FROM updates WHERE meeting_id=?',(mid,))[0]['n']==2
    assert query(restarted,'SELECT completed FROM actions WHERE id=?',(chosen,))[0]['completed']==1
    assert post(client,'/reopen',{'meeting_id':mid}).status_code==302
    assert client.get('/entry/1').status_code==200

def test_users_cannot_edit_others_or_admin(client,app):
    login(client,'gokul')
    assert client.get('/admin').status_code==403
    assert client.get('/admin/backup').status_code==403
    assert client.get('/coordinator').status_code==403
    foreign=query(app,"SELECT a.id FROM actions a JOIN users u ON a.user_id=u.id JOIN reviews r ON r.action_id=a.id WHERE u.username='kishan'")[0]['id']
    assert review(client,app,[str(foreign)]).status_code==403
    review(client,app)
    foreign_update=query(app,"SELECT id FROM updates LIMIT 1")[0]['id']
    assert post(client,'/entry/2',{'meeting_id':active(app)['id'],'operation':'delete','item_id':foreign_update}).status_code==404

def test_duplicate_posts_and_edit_delete(client,app):
    login(client)
    review(client,app)
    mid=active(app)['id']
    data={'meeting_id':mid,'entry_token':secrets.token_hex(20),'body':'Only once'}
    post(client,'/entry/2',data)
    post(client,'/entry/2',data)
    rows=query(app,'SELECT * FROM updates WHERE meeting_id=?',(mid,))
    assert len(rows)==1
    post(client,'/entry/2',{'meeting_id':mid,'operation':'edit','item_id':rows[0]['id'],'body':'Edited'})
    assert query(app,'SELECT body FROM updates WHERE id=?',(rows[0]['id'],))[0]['body']=='Edited'
    post(client,'/entry/2',{'meeting_id':mid,'operation':'delete','item_id':rows[0]['id']})
    assert not query(app,'SELECT * FROM updates WHERE meeting_id=?',(mid,))

def test_coordinator_rotation_and_snapshot(client,app):
    login(client,'harshitha')
    old=active(app)
    own=query(app,"SELECT a.id FROM actions a JOIN users u ON u.id=a.user_id JOIN reviews r ON r.action_id=a.id WHERE u.username='harshitha'")
    completed=own[0]['id']
    review(client,app,[str(completed)])
    due=(date.fromisoformat(old['meeting_date'])+timedelta(days=3)).isoformat()
    add(client,app,3,'Carry me next week',due_date=due)
    new_action=query(app,"SELECT id FROM actions WHERE body='Carry me next week'")[0]['id']
    assert client.get('/coordinator').status_code==200
    assert post(client,'/coordinator',{'meeting_id':old['id'],'operation':'next'}).status_code==302
    new=active(app)
    assert date.fromisoformat(new['meeting_date'])-date.fromisoformat(old['meeting_date'])==timedelta(days=7)
    assert new['minutes_by']=='Gokul M'
    assert client.get('/coordinator').status_code==403
    assert not query(app,'SELECT * FROM reviews WHERE meeting_id=? AND action_id=?',(new['id'],completed))
    assert query(app,'SELECT * FROM reviews WHERE meeting_id=? AND action_id=?',(new['id'],new_action))
    assert query(app,'SELECT completed FROM reviews WHERE meeting_id=? AND action_id=?',(old['id'],completed))[0]['completed']==1
    assert post(client,'/entry/1',{'meeting_id':old['id']}).status_code==409
    assert client.get(f"/reports/{old['id']}").status_code==200

def test_excel_literal_text_dates_and_backup(client,app):
    login(client)
    review(client,app)
    mid=active(app)['id']
    add(client,app,2,'=HYPERLINK("https://example.invalid", "text")')
    add(client,app,3,'<script>alert(1)</script>',due_date=active(app)['meeting_date'])
    response=client.get(f'/reports/{mid}')
    assert b'&lt;script&gt;' in response.data
    assert b'<script>alert(1)' not in response.data
    response=client.get(f'/reports/{mid}/excel')
    assert response.status_code==200
    workbook=load_workbook(BytesIO(response.data),read_only=True)
    cells=[c for row in workbook.active.iter_rows(max_col=5) for c in row]
    literal=next(c for c in cells if str(c.value).startswith('=HYPERLINK'))
    assert literal.data_type=='s'
    assert any(getattr(c,'is_date',False) for c in cells)
    workbook.close()
    assert client.get('/admin/backup').data.startswith(b'SQLite format 3')
    assert client.get('/reports/1/original').data.startswith(b'PK')

def test_password_reset_revokes_existing_session(client,app):
    login(client)
    member=app.test_client()
    login(member,'gokul')
    uid=query(app,"SELECT id FROM users WHERE username='gokul'")[0]['id']
    assert post(client,'/admin',{'operation':'reset','user_id':uid}).status_code==302
    assert member.get('/').location.endswith('/login')
    login(member,'gokul',change=False)
    assert member.get('/').location.endswith('/password')

def test_lockout(client,app):
    client.get('/login')
    for _ in range(5):
        post(client,'/login',{'username':'kishan','password':'wrong'})
    r=post(client,'/login',{'username':'kishan','password':'Password@123'})
    assert b'Too many attempts' in r.data

def test_rotation_validation_and_monday_only(client,app):
    login(client)
    mid=active(app)['id']
    r=post(client,'/admin',{'operation':'rotation','order_1':'1','order_2':'1'})
    assert b'unique' in r.data
    next_tuesday=date.fromisoformat(active(app)['meeting_date'])+timedelta(days=8)
    r=post(client,'/admin',{'operation':'meeting','meeting_date':next_tuesday.isoformat(),'title':'Weekly','location':'Office'})
    assert b'must be scheduled on a Monday' in r.data
    assert active(app)['id']==mid

def test_rollback_on_invalid_action_does_not_overwrite(client,app):
    login(client)
    review(client,app)
    mid=active(app)['id']
    add(client,app,3,'Original',due_date=active(app)['meeting_date'])
    item=query(app,'SELECT id FROM actions WHERE meeting_id=?',(mid,))[0]['id']
    r=post(client,'/entry/3',{'meeting_id':mid,'operation':'edit','item_id':item,'body':'Changed','due_date':'invalid'})
    assert b'Choose a valid date' in r.data
    assert query(app,'SELECT body FROM actions WHERE id=?',(item,))[0]['body']=='Original'