test_trusted_user_routes.py 31.7 KB
Newer Older
Kevin Morris's avatar
Kevin Morris committed
1
2
3
4
import re

from http import HTTPStatus
from io import StringIO
5
from typing import Tuple
Kevin Morris's avatar
Kevin Morris committed
6
7
8
9
10
11

import lxml.etree
import pytest

from fastapi.testclient import TestClient

12
from aurweb import config, db, filters, time
13
from aurweb.models.account_type import DEVELOPER_ID, TRUSTED_USER_ID, AccountType
Kevin Morris's avatar
Kevin Morris committed
14
15
16
17
18
from aurweb.models.tu_vote import TUVote
from aurweb.models.tu_voteinfo import TUVoteInfo
from aurweb.models.user import User
from aurweb.testing.requests import Request

19
DATETIME_REGEX = r'^[0-9]{4}-[0-9]{2}-[0-9]{2} \(.+\)$'
20
PARTICIPATION_REGEX = r'^1?[0-9]{2}[%]$'  # 0% - 100%
Kevin Morris's avatar
Kevin Morris committed
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


def parse_root(html):
    parser = lxml.etree.HTMLParser(recover=True)
    tree = lxml.etree.parse(StringIO(html), parser)
    return tree.getroot()


def get_table(root, class_name):
    table = root.xpath(f'//table[contains(@class, "{class_name}")]')[0]
    return table


def get_table_rows(table):
    tbody = table.xpath("./tbody")[0]
    return tbody.xpath("./tr")


def get_pkglist_directions(table):
    stats = table.getparent().xpath("./div[@class='pkglist-stats']")[0]
    nav = stats.xpath("./p[@class='pkglist-nav']")[0]
    return nav.xpath("./a")


def get_a(node):
    return node.xpath('./a')[0].text.strip()


def get_span(node):
    return node.xpath('./span')[0].text.strip()


def assert_current_vote_html(row, expected):
    columns = row.xpath("./td")
    proposal, start, end, user, voted = columns
    p, s, e, u, v = expected  # Column expectations.
    assert re.match(p, get_a(proposal)) is not None
    assert re.match(s, start.text) is not None
    assert re.match(e, end.text) is not None
    assert re.match(u, get_a(user)) is not None
    assert re.match(v, get_span(voted)) is not None


def assert_past_vote_html(row, expected):
    columns = row.xpath("./td")
    proposal, start, end, user, yes, no, voted = columns  # Real columns.
    p, s, e, u, y, n, v = expected  # Column expectations.
    assert re.match(p, get_a(proposal)) is not None
    assert re.match(s, start.text) is not None
    assert re.match(e, end.text) is not None
    assert re.match(u, get_a(user)) is not None
    assert re.match(y, yes.text) is not None
    assert re.match(n, no.text) is not None
    assert re.match(v, get_span(voted)) is not None


@pytest.fixture(autouse=True)
78
79
def setup(db_test):
    return
Kevin Morris's avatar
Kevin Morris committed
80
81
82
83
84
85
86
87
88
89
90
91


@pytest.fixture
def client():
    from aurweb.asgi import app
    yield TestClient(app=app)


@pytest.fixture
def tu_user():
    tu_type = db.query(AccountType,
                       AccountType.AccountType == "Trusted User").first()
92
93
94
95
96
97
    with db.begin():
        tu_user = db.create(User, Username="test_tu",
                            Email="test_tu@example.org",
                            RealName="Test TU", Passwd="testPassword",
                            AccountType=tu_type)
    yield tu_user
Kevin Morris's avatar
Kevin Morris committed
98
99


100
101
102
103
104
105
106
107
108
109
@pytest.fixture
def tu_user2():
    with db.begin():
        tu_user2 = db.create(User, Username="test_tu2",
                             Email="test_tu2@example.org",
                             RealName="Test TU 2", Passwd="testPassword",
                             AccountTypeID=TRUSTED_USER_ID)
    yield tu_user2


Kevin Morris's avatar
Kevin Morris committed
110
111
112
113
@pytest.fixture
def user():
    user_type = db.query(AccountType,
                         AccountType.AccountType == "User").first()
114
115
116
117
118
    with db.begin():
        user = db.create(User, Username="test", Email="test@example.org",
                         RealName="Test User", Passwd="testPassword",
                         AccountType=user_type)
    yield user
Kevin Morris's avatar
Kevin Morris committed
119
120


121
@pytest.fixture
122
def proposal(user, tu_user):
123
    ts = time.utcnow()
124
125
126
127
    agenda = "Test proposal."
    start = ts - 5
    end = ts + 1000

128
129
130
131
132
    with db.begin():
        voteinfo = db.create(TUVoteInfo,
                             Agenda=agenda, Quorum=0.0,
                             User=user.Username, Submitter=tu_user,
                             Submitted=start, End=end)
133
134
135
    yield (tu_user, user, voteinfo)


Kevin Morris's avatar
Kevin Morris committed
136
def test_tu_index_guest(client):
137
    headers = {"referer": config.get("options", "aur_location") + "/tu"}
Kevin Morris's avatar
Kevin Morris committed
138
    with client as request:
139
        response = request.get("/tu", allow_redirects=False, headers=headers)
Kevin Morris's avatar
Kevin Morris committed
140
    assert response.status_code == int(HTTPStatus.SEE_OTHER)
141

142
    params = filters.urlencode({"next": "/tu"})
143
    assert response.headers.get("location") == f"/login?{params}"
Kevin Morris's avatar
Kevin Morris committed
144
145


146
def test_tu_index_unauthorized(client: TestClient, user: User):
Kevin Morris's avatar
Kevin Morris committed
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
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        # Login as a normal user, not a TU.
        response = request.get("/tu", cookies=cookies, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.SEE_OTHER)
    assert response.headers.get("location") == "/"


def test_tu_empty_index(client, tu_user):
    """ Check an empty index when we don't create any records. """

    # Make a default get request to /tu.
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/tu", cookies=cookies, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.OK)

    # Parse lxml root.
    root = parse_root(response.text)

    # Check that .current-votes does not exist.
    tables = root.xpath('//table[contains(@class, "current-votes")]')
    assert len(tables) == 0

    # Check that .past-votes has does not exist.
    tables = root.xpath('//table[contains(@class, "current-votes")]')
    assert len(tables) == 0


def test_tu_index(client, tu_user):
177
    ts = time.utcnow()
Kevin Morris's avatar
Kevin Morris committed
178
179
180
181
182
183
184

    # Create some test votes: (Agenda, Start, End).
    votes = [
        ("Test agenda 1", ts - 5, ts + 1000),  # Still running.
        ("Test agenda 2", ts - 1000, ts - 5)  # Not running anymore.
    ]
    vote_records = []
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    with db.begin():
        for vote in votes:
            agenda, start, end = vote
            vote_records.append(
                db.create(TUVoteInfo, Agenda=agenda,
                          User=tu_user.Username,
                          Submitted=start, End=end,
                          Quorum=0.0,
                          Submitter=tu_user))

    with db.begin():
        # Vote on an ended proposal.
        vote_record = vote_records[1]
        vote_record.Yes += 1
        vote_record.ActiveTUs += 1
        db.create(TUVote, VoteInfo=vote_record, User=tu_user)
Kevin Morris's avatar
Kevin Morris committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263

    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        # Pass an invalid cby and pby; let them default to "desc".
        response = request.get("/tu", cookies=cookies, params={
            "cby": "BAD!",
            "pby": "blah"
        }, allow_redirects=False)

    assert response.status_code == int(HTTPStatus.OK)

    # Rows we expect to exist in HTML produced by /tu for current votes.
    expected_rows = [
        (
            r'Test agenda 1',
            DATETIME_REGEX,
            DATETIME_REGEX,
            tu_user.Username,
            r'^(Yes|No)$'
        )
    ]

    # Assert that we are matching the number of current votes.
    current_votes = [c for c in votes if c[2] > ts]
    assert len(current_votes) == len(expected_rows)

    # Parse lxml.etree root.
    root = parse_root(response.text)

    table = get_table(root, "current-votes")
    rows = get_table_rows(table)
    for i, row in enumerate(rows):
        assert_current_vote_html(row, expected_rows[i])

    # Assert that we are matching the number of past votes.
    past_votes = [c for c in votes if c[2] <= ts]
    assert len(past_votes) == len(expected_rows)

    # Rows we expect to exist in HTML produced by /tu for past votes.
    expected_rows = [
        (
            r'Test agenda 2',
            DATETIME_REGEX,
            DATETIME_REGEX,
            tu_user.Username,
            r'^\d+$',
            r'^\d+$',
            r'^(Yes|No)$'
        )
    ]

    table = get_table(root, "past-votes")
    rows = get_table_rows(table)
    for i, row in enumerate(rows):
        assert_past_vote_html(row, expected_rows[i])

    # Get the .last-votes table and check that our vote shows up.
    table = get_table(root, "last-votes")
    rows = get_table_rows(table)
    assert len(rows) == 1

    # Check to see the rows match up to our user and related vote.
    username, vote_id = rows[0]
264
    username = username.xpath("./a")[0]
Kevin Morris's avatar
Kevin Morris committed
265
266
267
268
269
    vote_id = vote_id.xpath("./a")[0]
    assert username.text.strip() == tu_user.Username
    assert int(vote_id.text.strip()) == vote_records[1].ID


270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def test_tu_stats(client: TestClient, tu_user: User):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/tu", cookies=cookies, allow_redirects=False)
    assert response.status_code == HTTPStatus.OK

    root = parse_root(response.text)
    stats = root.xpath('//table[@class="no-width"]')[0]
    rows = stats.xpath("./tbody/tr")

    # We have one trusted user.
    total = rows[0]
    label, count = total.xpath("./td")
    assert int(count.text.strip()) == 1

    # And we have one active TU.
    active = rows[1]
    label, count = active.xpath("./td")
    assert int(count.text.strip()) == 1

    with db.begin():
        tu_user.InactivityTS = time.utcnow()

    with client as request:
        response = request.get("/tu", cookies=cookies, allow_redirects=False)
    assert response.status_code == HTTPStatus.OK

    root = parse_root(response.text)
    stats = root.xpath('//table[@class="no-width"]')[0]
    rows = stats.xpath("./tbody/tr")

    # We have one trusted user.
    total = rows[0]
    label, count = total.xpath("./td")
    assert int(count.text.strip()) == 1

    # But we have no more active TUs.
    active = rows[1]
    label, count = active.xpath("./td")
    assert int(count.text.strip()) == 0


Kevin Morris's avatar
Kevin Morris committed
312
def test_tu_index_table_paging(client, tu_user):
313
    ts = time.utcnow()
Kevin Morris's avatar
Kevin Morris committed
314

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
    with db.begin():
        for i in range(25):
            # Create 25 current votes.
            db.create(TUVoteInfo, Agenda=f"Agenda #{i}",
                      User=tu_user.Username,
                      Submitted=(ts - 5), End=(ts + 1000),
                      Quorum=0.0,
                      Submitter=tu_user)

        for i in range(25):
            # Create 25 past votes.
            db.create(TUVoteInfo, Agenda=f"Agenda #{25 + i}",
                      User=tu_user.Username,
                      Submitted=(ts - 1000), End=(ts - 5),
                      Quorum=0.0,
                      Submitter=tu_user)
Kevin Morris's avatar
Kevin Morris committed
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420

    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/tu", cookies=cookies, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.OK)

    # Parse lxml.etree root.
    root = parse_root(response.text)

    table = get_table(root, "current-votes")
    rows = get_table_rows(table)
    assert len(rows) == 10

    def make_expectation(offset, i):
        return [
            f"Agenda #{offset + i}",
            DATETIME_REGEX,
            DATETIME_REGEX,
            tu_user.Username,
            r'^(Yes|No)$'
        ]

    for i, row in enumerate(rows):
        assert_current_vote_html(row, make_expectation(0, i))

    # Parse out Back/Next buttons.
    directions = get_pkglist_directions(table)
    assert len(directions) == 1
    assert "Next" in directions[0].text

    # Now, get the next page of current votes.
    offset = 10  # Specify coff=10
    with client as request:
        response = request.get("/tu", cookies=cookies, params={
            "coff": offset
        }, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.OK)

    old_rows = rows
    root = parse_root(response.text)

    table = get_table(root, "current-votes")
    rows = get_table_rows(table)
    assert rows != old_rows

    for i, row in enumerate(rows):
        assert_current_vote_html(row, make_expectation(offset, i))

    # Parse out Back/Next buttons.
    directions = get_pkglist_directions(table)
    assert len(directions) == 2
    assert "Back" in directions[0].text
    assert "Next" in directions[1].text

    # Make sure past-votes' Back/Next were not affected.
    past_votes = get_table(root, "past-votes")
    past_directions = get_pkglist_directions(past_votes)
    assert len(past_directions) == 1
    assert "Next" in past_directions[0].text

    offset = 20  # Specify coff=10
    with client as request:
        response = request.get("/tu", cookies=cookies, params={
            "coff": offset
        }, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.OK)

    # Do it again, we only have five left.
    old_rows = rows
    root = parse_root(response.text)

    table = get_table(root, "current-votes")
    rows = get_table_rows(table)
    assert rows != old_rows
    for i, row in enumerate(rows):
        assert_current_vote_html(row, make_expectation(offset, i))

    # Parse out Back/Next buttons.
    directions = get_pkglist_directions(table)
    assert len(directions) == 1
    assert "Back" in directions[0].text

    # Make sure past-votes' Back/Next were not affected.
    past_votes = get_table(root, "past-votes")
    past_directions = get_pkglist_directions(past_votes)
    assert len(past_directions) == 1
    assert "Next" in past_directions[0].text


def test_tu_index_sorting(client, tu_user):
421
    ts = time.utcnow()
Kevin Morris's avatar
Kevin Morris committed
422

423
424
425
426
427
428
429
430
    with db.begin():
        for i in range(2):
            # Create 'Agenda #1' and 'Agenda #2'.
            db.create(TUVoteInfo, Agenda=f"Agenda #{i + 1}",
                      User=tu_user.Username,
                      Submitted=(ts + 5), End=(ts + 1000),
                      Quorum=0.0,
                      Submitter=tu_user)
Kevin Morris's avatar
Kevin Morris committed
431

432
433
434
435
            # Let's order each vote one day after the other.
            # This will allow us to test the sorting nature
            # of the tables.
            ts += 86405
Kevin Morris's avatar
Kevin Morris committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489

    # Make a default request to /tu.
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/tu", cookies=cookies, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.OK)

    # Get lxml handles of the document.
    root = parse_root(response.text)
    table = get_table(root, "current-votes")
    rows = get_table_rows(table)

    # The latest Agenda is at the top by default.
    expected = [
        "Agenda #2",
        "Agenda #1"
    ]

    assert len(rows) == len(expected)
    for i, row in enumerate(rows):
        assert_current_vote_html(row, [
            expected[i],
            DATETIME_REGEX,
            DATETIME_REGEX,
            tu_user.Username,
            r'^(Yes|No)$'
        ])

    # Make another request; one that sorts the current votes
    # in ascending order instead of the default descending order.
    with client as request:
        response = request.get("/tu", cookies=cookies, params={
            "cby": "asc"
        }, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.OK)

    # Get lxml handles of the document.
    root = parse_root(response.text)
    table = get_table(root, "current-votes")
    rows = get_table_rows(table)

    # Reverse our expectations and assert that the proposals got flipped.
    rev_expected = list(reversed(expected))
    assert len(rows) == len(rev_expected)
    for i, row in enumerate(rows):
        assert_current_vote_html(row, [
            rev_expected[i],
            DATETIME_REGEX,
            DATETIME_REGEX,
            tu_user.Username,
            r'^(Yes|No)$'
        ])


490
491
def test_tu_index_last_votes(client: TestClient, tu_user: User, tu_user2: User,
                             user: User):
492
    ts = time.utcnow()
Kevin Morris's avatar
Kevin Morris committed
493

494
495
496
497
498
499
500
    with db.begin():
        # Create a proposal which has ended.
        voteinfo = db.create(TUVoteInfo, Agenda="Test agenda",
                             User=user.Username,
                             Submitted=(ts - 1000),
                             End=(ts - 5),
                             Yes=1,
501
                             No=1,
502
503
504
                             ActiveTUs=1,
                             Quorum=0.0,
                             Submitter=tu_user)
Kevin Morris's avatar
Kevin Morris committed
505

506
507
        # Create a vote on it from tu_user.
        db.create(TUVote, VoteInfo=voteinfo, User=tu_user)
508
        db.create(TUVote, VoteInfo=voteinfo, User=tu_user2)
Kevin Morris's avatar
Kevin Morris committed
509
510
511
512
513
514
515
516
517
518

    # Now, check that tu_user got populated in the .last-votes table.
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/tu", cookies=cookies)
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    table = get_table(root, "last-votes")
    rows = get_table_rows(table)
519
    assert len(rows) == 2
Kevin Morris's avatar
Kevin Morris committed
520
521

    last_vote = rows[0]
522
    user, vote_id = last_vote.xpath("./td/a")
Kevin Morris's avatar
Kevin Morris committed
523
524
    assert user.text.strip() == tu_user.Username
    assert int(vote_id.text.strip()) == voteinfo.ID
525

526
527
528
529
530
    last_vote = rows[1]
    user, vote_id = last_vote.xpath("./td/a")
    assert int(vote_id.text.strip()) == voteinfo.ID
    assert user.text.strip() == tu_user2.Username

531
532
533
534
535
536
537
538

def test_tu_proposal_not_found(client, tu_user):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/tu", params={"id": 1}, cookies=cookies)
    assert response.status_code == int(HTTPStatus.NOT_FOUND)


539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def test_tu_proposal_unauthorized(client: TestClient, user: User,
                                  proposal: Tuple[User, User, TUVoteInfo]):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    endpoint = f"/tu/{proposal[2].ID}"
    with client as request:
        response = request.get(endpoint, cookies=cookies,
                               allow_redirects=False)
    assert response.status_code == int(HTTPStatus.SEE_OTHER)
    assert response.headers.get("location") == "/tu"

    with client as request:
        response = request.post(endpoint, cookies=cookies,
                                data={"decision": False},
                                allow_redirects=False)
    assert response.status_code == int(HTTPStatus.SEE_OTHER)
    assert response.headers.get("location") == "/tu"


557
558
def test_tu_running_proposal(client: TestClient,
                             proposal: Tuple[User, User, TUVoteInfo]):
559
    tu_user, user, voteinfo = proposal
560
561
    with db.begin():
        voteinfo.ActiveTUs = 1
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582

    # Initiate an authenticated GET request to /tu/{proposal_id}.
    proposal_id = voteinfo.ID
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get(f"/tu/{proposal_id}", cookies=cookies)
    assert response.status_code == int(HTTPStatus.OK)

    # Alright, now let's continue on to verifying some markup.
    # First, let's verify that the proposal details match.
    root = parse_root(response.text)
    details = root.xpath('//div[@class="proposal details"]')[0]

    vote_running = root.xpath('//p[contains(@class, "vote-running")]')[0]
    assert vote_running.text.strip() == "This vote is still running."

    # Verify User field.
    username = details.xpath(
        './div[contains(@class, "user")]/strong/a/text()')[0]
    assert username.strip() == user.Username

583
584
585
586
587
    active = details.xpath('./div[contains(@class, "field")]')[1]
    content = active.text.strip()
    assert "Active Trusted Users assigned:" in content
    assert "1" in content

588
589
    submitted = details.xpath(
        './div[contains(@class, "submitted")]/text()')[0]
590
    assert re.match(r'^Submitted: \d{4}-\d{2}-\d{2} \d{2}:\d{2} \(.+\) by$',
591
                    submitted.strip()) is not None
592
593
594
    submitter = details.xpath('./div[contains(@class, "submitted")]/a')[0]
    assert submitter.text.strip() == tu_user.Username
    assert submitter.attrib["href"] == f"/account/{tu_user.Username}"
595
596
597
598
599
600

    end = details.xpath('./div[contains(@class, "end")]')[0]
    end_label = end.xpath("./text()")[0]
    assert end_label.strip() == "End:"

    end_datetime = end.xpath("./strong/text()")[0]
601
    assert re.match(r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2} \(.+\)$',
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
                    end_datetime.strip()) is not None

    # We have not voted yet. Assert that our voting form is shown.
    form = root.xpath('//form[contains(@class, "action-form")]')[0]
    fields = form.xpath("./fieldset")[0]
    buttons = fields.xpath('./button[@name="decision"]')
    assert len(buttons) == 3

    # Check the button names and values.
    yes, no, abstain = buttons

    # Yes
    assert yes.attrib["name"] == "decision"
    assert yes.attrib["value"] == "Yes"

    # No
    assert no.attrib["name"] == "decision"
    assert no.attrib["value"] == "No"

    # Abstain
    assert abstain.attrib["name"] == "decision"
    assert abstain.attrib["value"] == "Abstain"

    # Create a vote.
626
627
628
629
    with db.begin():
        db.create(TUVote, VoteInfo=voteinfo, User=tu_user)
        voteinfo.ActiveTUs += 1
        voteinfo.Yes += 1
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651

    # Make another request now that we've voted.
    with client as request:
        response = request.get(
            "/tu", params={"id": voteinfo.ID}, cookies=cookies)
    assert response.status_code == int(HTTPStatus.OK)

    # Parse our new root.
    root = parse_root(response.text)

    # Check that we no longer have a voting form.
    form = root.xpath('//form[contains(@class, "action-form")]')
    assert not form

    # Check that we're told we've voted.
    status = root.xpath('//span[contains(@class, "status")]/text()')[0]
    assert status == "You've already voted for this proposal."


def test_tu_ended_proposal(client, proposal):
    tu_user, user, voteinfo = proposal

652
    ts = time.utcnow()
653
654
    with db.begin():
        voteinfo.End = ts - 5  # 5 seconds ago.
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724

    # Initiate an authenticated GET request to /tu/{proposal_id}.
    proposal_id = voteinfo.ID
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get(f"/tu/{proposal_id}", cookies=cookies)
    assert response.status_code == int(HTTPStatus.OK)

    # Alright, now let's continue on to verifying some markup.
    # First, let's verify that the proposal details match.
    root = parse_root(response.text)
    details = root.xpath('//div[@class="proposal details"]')[0]

    vote_running = root.xpath('//p[contains(@class, "vote-running")]')
    assert not vote_running

    result_node = details.xpath('./div[contains(@class, "result")]')[0]
    result_label = result_node.xpath("./text()")[0]
    assert result_label.strip() == "Result:"

    result = result_node.xpath("./span/text()")[0]
    assert result.strip() == "unknown"

    # Check that voting has ended.
    form = root.xpath('//form[contains(@class, "action-form")]')
    assert not form

    # We should see a status about it.
    status = root.xpath('//span[contains(@class, "status")]/text()')[0]
    assert status == "Voting is closed for this proposal."


def test_tu_proposal_vote_not_found(client, tu_user):
    """ Test POST request to a missing vote. """
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        data = {"decision": "Yes"}
        response = request.post("/tu/1", cookies=cookies,
                                data=data, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.NOT_FOUND)


def test_tu_proposal_vote(client, proposal):
    tu_user, user, voteinfo = proposal

    # Store the current related values.
    yes = voteinfo.Yes

    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        data = {"decision": "Yes"}
        response = request.post(f"/tu/{voteinfo.ID}", cookies=cookies,
                                data=data)
    assert response.status_code == int(HTTPStatus.OK)

    # Check that the proposal record got updated.
    assert voteinfo.Yes == yes + 1

    # Check that the new TUVote exists.
    vote = db.query(TUVote, TUVote.VoteInfo == voteinfo,
                    TUVote.User == tu_user).first()
    assert vote is not None

    root = parse_root(response.text)

    # Check that we're told we've voted.
    status = root.xpath('//span[contains(@class, "status")]/text()')[0]
    assert status == "You've already voted for this proposal."


725
726
def test_tu_proposal_vote_unauthorized(
        client: TestClient, proposal: Tuple[User, User, TUVoteInfo]):
727
728
    tu_user, user, voteinfo = proposal

729
    with db.begin():
730
        tu_user.AccountTypeID = DEVELOPER_ID
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757

    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        data = {"decision": "Yes"}
        response = request.post(f"/tu/{voteinfo.ID}", cookies=cookies,
                                data=data, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.UNAUTHORIZED)

    root = parse_root(response.text)
    status = root.xpath('//span[contains(@class, "status")]/text()')[0]
    assert status == "Only Trusted Users are allowed to vote."

    with client as request:
        data = {"decision": "Yes"}
        response = request.get(f"/tu/{voteinfo.ID}", cookies=cookies,
                               data=data, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    status = root.xpath('//span[contains(@class, "status")]/text()')[0]
    assert status == "Only Trusted Users are allowed to vote."


def test_tu_proposal_vote_cant_self_vote(client, proposal):
    tu_user, user, voteinfo = proposal

    # Update voteinfo.User.
758
759
    with db.begin():
        voteinfo.User = tu_user.Username
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785

    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        data = {"decision": "Yes"}
        response = request.post(f"/tu/{voteinfo.ID}", cookies=cookies,
                                data=data, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.BAD_REQUEST)

    root = parse_root(response.text)
    status = root.xpath('//span[contains(@class, "status")]/text()')[0]
    assert status == "You cannot vote in an proposal about you."

    with client as request:
        data = {"decision": "Yes"}
        response = request.get(f"/tu/{voteinfo.ID}", cookies=cookies,
                               data=data, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    status = root.xpath('//span[contains(@class, "status")]/text()')[0]
    assert status == "You cannot vote in an proposal about you."


def test_tu_proposal_vote_already_voted(client, proposal):
    tu_user, user, voteinfo = proposal

786
787
788
789
    with db.begin():
        db.create(TUVote, VoteInfo=voteinfo, User=tu_user)
        voteinfo.Yes += 1
        voteinfo.ActiveTUs += 1
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822

    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        data = {"decision": "Yes"}
        response = request.post(f"/tu/{voteinfo.ID}", cookies=cookies,
                                data=data, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.BAD_REQUEST)

    root = parse_root(response.text)
    status = root.xpath('//span[contains(@class, "status")]/text()')[0]
    assert status == "You've already voted for this proposal."

    with client as request:
        data = {"decision": "Yes"}
        response = request.get(f"/tu/{voteinfo.ID}", cookies=cookies,
                               data=data, allow_redirects=False)
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    status = root.xpath('//span[contains(@class, "status")]/text()')[0]
    assert status == "You've already voted for this proposal."


def test_tu_proposal_vote_invalid_decision(client, proposal):
    tu_user, user, voteinfo = proposal

    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        data = {"decision": "EVIL"}
        response = request.post(f"/tu/{voteinfo.ID}", cookies=cookies,
                                data=data)
    assert response.status_code == int(HTTPStatus.BAD_REQUEST)
    assert response.text == "Invalid 'decision' value."
823
824
825
826
827
828
829
830
831


def test_tu_addvote(client: TestClient, tu_user: User):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/addvote", cookies=cookies)
    assert response.status_code == int(HTTPStatus.OK)


832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
def test_tu_addvote_unauthorized(client: TestClient, user: User,
                                 proposal: Tuple[User, User, TUVoteInfo]):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/addvote", cookies=cookies,
                               allow_redirects=False)
    assert response.status_code == int(HTTPStatus.SEE_OTHER)
    assert response.headers.get("location") == "/tu"

    with client as request:
        response = request.post("/addvote", cookies=cookies,
                                allow_redirects=False)
    assert response.status_code == int(HTTPStatus.SEE_OTHER)
    assert response.headers.get("location") == "/tu"


848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
def test_tu_addvote_invalid_type(client: TestClient, tu_user: User):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/addvote", params={"type": "faketype"},
                               cookies=cookies)
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    error = root.xpath('//*[contains(@class, "error")]/text()')[0]
    assert error.strip() == "Invalid type."


def test_tu_addvote_post(client: TestClient, tu_user: User, user: User):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}

    data = {
        "user": user.Username,
        "type": "add_tu",
        "agenda": "Blah"
    }

    with client as request:
        response = request.post("/addvote", cookies=cookies, data=data)
    assert response.status_code == int(HTTPStatus.SEE_OTHER)

    voteinfo = db.query(TUVoteInfo, TUVoteInfo.Agenda == "Blah").first()
    assert voteinfo is not None


def test_tu_addvote_post_cant_duplicate_username(client: TestClient,
                                                 tu_user: User, user: User):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}

    data = {
        "user": user.Username,
        "type": "add_tu",
        "agenda": "Blah"
    }

    with client as request:
        response = request.post("/addvote", cookies=cookies, data=data)
    assert response.status_code == int(HTTPStatus.SEE_OTHER)

    voteinfo = db.query(TUVoteInfo, TUVoteInfo.Agenda == "Blah").first()
    assert voteinfo is not None

    with client as request:
        response = request.post("/addvote", cookies=cookies, data=data)
    assert response.status_code == int(HTTPStatus.BAD_REQUEST)


def test_tu_addvote_post_invalid_username(client: TestClient, tu_user: User):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    data = {"user": "fakeusername"}
    with client as request:
        response = request.post("/addvote", cookies=cookies, data=data)
    assert response.status_code == int(HTTPStatus.NOT_FOUND)


def test_tu_addvote_post_invalid_type(client: TestClient, tu_user: User,
                                      user: User):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    data = {"user": user.Username}
    with client as request:
        response = request.post("/addvote", cookies=cookies, data=data)
    assert response.status_code == int(HTTPStatus.BAD_REQUEST)


def test_tu_addvote_post_invalid_agenda(client: TestClient,
                                        tu_user: User, user: User):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    data = {"user": user.Username, "type": "add_tu"}
    with client as request:
        response = request.post("/addvote", cookies=cookies, data=data)
    assert response.status_code == int(HTTPStatus.BAD_REQUEST)


def test_tu_addvote_post_bylaws(client: TestClient, tu_user: User):
    # Bylaws votes do not need a user specified.
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    data = {"type": "bylaws", "agenda": "Blah blah!"}
    with client as request:
        response = request.post("/addvote", cookies=cookies, data=data)
    assert response.status_code == int(HTTPStatus.SEE_OTHER)