test_packages_routes.py 95.4 KB
Newer Older
1
2
import re

3
4
from datetime import datetime
from http import HTTPStatus
5
from typing import List
6
from unittest import mock
7
8
9
10

import pytest

from fastapi.testclient import TestClient
11
from sqlalchemy import and_
12

13
from aurweb import asgi, db, defaults
14
15
16
17
18
from aurweb.models.account_type import USER_ID, AccountType
from aurweb.models.dependency_type import DependencyType
from aurweb.models.official_provider import OfficialProvider
from aurweb.models.package import Package
from aurweb.models.package_base import PackageBase
19
from aurweb.models.package_comaintainer import PackageComaintainer
20
21
22
from aurweb.models.package_comment import PackageComment
from aurweb.models.package_dependency import PackageDependency
from aurweb.models.package_keyword import PackageKeyword
23
from aurweb.models.package_notification import PackageNotification
24
from aurweb.models.package_relation import PackageRelation
25
from aurweb.models.package_request import ACCEPTED_ID, REJECTED_ID, PackageRequest
26
from aurweb.models.package_vote import PackageVote
27
from aurweb.models.relation_type import PROVIDES_ID, RelationType
28
from aurweb.models.request_type import DELETION_ID, MERGE_ID, RequestType
29
30
from aurweb.models.user import User
from aurweb.testing import setup_test_db
31
from aurweb.testing.html import get_errors, get_successes, parse_root
32
33
34
35
36
37
38
from aurweb.testing.requests import Request


def package_endpoint(package: Package) -> str:
    return f"/packages/{package.Name}"


39
def create_package(pkgname: str, maintainer: User) -> Package:
40
41
    pkgbase = db.create(PackageBase,
                        Name=pkgname,
42
43
                        Maintainer=maintainer)
    return db.create(Package, Name=pkgbase.Name, PackageBase=pkgbase)
44
45
46


def create_package_dep(package: Package, depname: str,
47
                       dep_type_name: str = "depends") -> PackageDependency:
48
49
50
51
52
    dep_type = db.query(DependencyType,
                        DependencyType.Name == dep_type_name).first()
    return db.create(PackageDependency,
                     DependencyType=dep_type,
                     Package=package,
53
                     DepName=depname)
54
55
56


def create_package_rel(package: Package,
57
                       relname: str) -> PackageRelation:
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    rel_type = db.query(RelationType,
                        RelationType.ID == PROVIDES_ID).first()
    return db.create(PackageRelation,
                     RelationType=rel_type,
                     Package=package,
                     RelName=relname)


@pytest.fixture(autouse=True)
def setup():
    setup_test_db(
        User.__tablename__,
        Package.__tablename__,
        PackageBase.__tablename__,
        PackageDependency.__tablename__,
        PackageRelation.__tablename__,
        PackageKeyword.__tablename__,
75
76
77
        PackageVote.__tablename__,
        PackageNotification.__tablename__,
        PackageComaintainer.__tablename__,
78
        PackageComment.__tablename__,
79
        PackageRequest.__tablename__,
80
81
82
83
84
85
86
87
88
89
90
91
92
93
        OfficialProvider.__tablename__
    )


@pytest.fixture
def client() -> TestClient:
    """ Yield a FastAPI TestClient. """
    yield TestClient(app=asgi.app)


@pytest.fixture
def user() -> User:
    """ Yield a user. """
    account_type = db.query(AccountType, AccountType.ID == USER_ID).first()
94
95
96
97
98
99
    with db.begin():
        user = db.create(User, Username="test",
                         Email="test@example.org",
                         Passwd="testPassword",
                         AccountType=account_type)
    yield user
100
101
102
103
104
105


@pytest.fixture
def maintainer() -> User:
    """ Yield a specific User used to maintain packages. """
    account_type = db.query(AccountType, AccountType.ID == USER_ID).first()
106
107
108
109
110
111
    with db.begin():
        maintainer = db.create(User, Username="test_maintainer",
                               Email="test_maintainer@example.org",
                               Passwd="testPassword",
                               AccountType=account_type)
    yield maintainer
112
113


114
115
116
117
118
119
120
121
122
123
124
125
@pytest.fixture
def tu_user():
    tu_type = db.query(AccountType,
                       AccountType.AccountType == "Trusted User").first()
    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


126
127
128
@pytest.fixture
def package(maintainer: User) -> Package:
    """ Yield a Package created by user. """
129
    now = int(datetime.utcnow().timestamp())
130
131
132
    with db.begin():
        pkgbase = db.create(PackageBase,
                            Name="test-package",
133
134
135
136
                            Maintainer=maintainer,
                            Packager=maintainer,
                            Submitter=maintainer,
                            ModifiedTS=now)
137
138
139
140
        package = db.create(Package,
                            PackageBase=pkgbase,
                            Name=pkgbase.Name)
    yield package
141
142


143
144
145
146
147
148
149
150
151
152
153
154
155
156
@pytest.fixture
def comment(user: User, package: Package) -> PackageComment:
    pkgbase = package.PackageBase
    now = int(datetime.utcnow().timestamp())
    with db.begin():
        comment = db.create(PackageComment,
                            User=user,
                            PackageBase=pkgbase,
                            Comments="Test comment.",
                            RenderedComment=str(),
                            CommentTS=now)
    yield comment


157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
@pytest.fixture
def packages(maintainer: User) -> List[Package]:
    """ Yield 55 packages named pkg_0 .. pkg_54. """
    packages_ = []
    now = int(datetime.utcnow().timestamp())
    with db.begin():
        for i in range(55):
            pkgbase = db.create(PackageBase,
                                Name=f"pkg_{i}",
                                Maintainer=maintainer,
                                Packager=maintainer,
                                Submitter=maintainer,
                                ModifiedTS=now)
            package = db.create(Package,
                                PackageBase=pkgbase,
                                Name=f"pkg_{i}")
            packages_.append(package)

    yield packages_


178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
@pytest.fixture
def requests(user: User, packages: List[Package]) -> List[PackageRequest]:
    pkgreqs = []
    deletion_type = db.query(RequestType).filter(
        RequestType.ID == DELETION_ID
    ).first()
    with db.begin():
        for i in range(55):
            pkgreq = db.create(PackageRequest,
                               RequestType=deletion_type,
                               User=user,
                               PackageBase=packages[i].PackageBase,
                               PackageBaseName=packages[i].Name,
                               Comments=f"Deletion request for pkg_{i}",
                               ClosureComment=str())
            pkgreqs.append(pkgreq)
    yield pkgreqs


197
198
199
200
201
202
203
204
205
206
def test_package_not_found(client: TestClient):
    with client as request:
        resp = request.get("/packages/not_found")
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)


def test_package_official_not_found(client: TestClient, package: Package):
    """ When a Package has a matching OfficialProvider record, it is not
    hosted on AUR, but in the official repositories. Getting a package
    with this kind of record should return a status code 404. """
207
208
209
210
211
    with db.begin():
        db.create(OfficialProvider,
                  Name=package.Name,
                  Repo="core",
                  Provides=package.Name)
212
213
214
215
216
217
218

    with client as request:
        resp = request.get(package_endpoint(package))
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)


def test_package(client: TestClient, package: Package):
219
    """ Test a single / packages / {name} route. """
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    with client as request:

        resp = request.get(package_endpoint(package))
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    h2 = root.find('.//div[@id="pkgdetails"]/h2')

    sections = h2.text.split(":")
    assert sections[0] == "Package Details"

    name, version = sections[1].lstrip().split(" ")
    assert name == package.Name
    version == package.Version

    rows = root.findall('.//table[@id="pkginfo"]//tr')
    row = rows[1]  # Second row is our target.

    pkgbase = row.find("./td/a")
    assert pkgbase.text.strip() == package.PackageBase.Name


def test_package_comments(client: TestClient, user: User, package: Package):
    now = (datetime.utcnow().timestamp())
244
245
246
    with db.begin():
        comment = db.create(PackageComment, PackageBase=package.PackageBase,
                            User=user, Comments="Test comment", CommentTS=now)
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262

    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(package_endpoint(package), cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    expected = [
        comment.Comments
    ]
    comments = root.xpath('.//div[contains(@class, "package-comments")]'
                          '/div[@class="article-content"]/div/text()')
    for i, row in enumerate(expected):
        assert comments[i].strip() == row


263
264
265
def test_package_requests_display(client: TestClient, user: User,
                                  package: Package):
    type_ = db.query(RequestType, RequestType.ID == DELETION_ID).first()
266
267
268
269
270
271
    with db.begin():
        db.create(PackageRequest, PackageBase=package.PackageBase,
                  PackageBaseName=package.PackageBase.Name,
                  User=user, RequestType=type_,
                  Comments="Test comment.",
                  ClosureComment=str())
272
273
274
275
276
277
278
279
280
281
282
283

    # Test that a single request displays "1 pending request".
    with client as request:
        resp = request.get(package_endpoint(package))
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    selector = '//div[@id="actionlist"]/ul/li/span[@class="flagged"]'
    target = root.xpath(selector)[0]
    assert target.text.strip() == "1 pending request"

    type_ = db.query(RequestType, RequestType.ID == DELETION_ID).first()
284
285
286
287
288
289
    with db.begin():
        db.create(PackageRequest, PackageBase=package.PackageBase,
                  PackageBaseName=package.PackageBase.Name,
                  User=user, RequestType=type_,
                  Comments="Test comment2.",
                  ClosureComment=str())
290
291
292
293
294
295
296
297
298
299
300
301

    # Test that a two requests display "2 pending requests".
    with client as request:
        resp = request.get(package_endpoint(package))
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    selector = '//div[@id="actionlist"]/ul/li/span[@class="flagged"]'
    target = root.xpath(selector)[0]
    assert target.text.strip() == "2 pending requests"


302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def test_package_authenticated(client: TestClient, user: User,
                               package: Package):
    """ We get the same here for either authenticated or not
    authenticated. Form inputs are presented to maintainers.
    This process also occurs when pkgbase.html is rendered. """
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(package_endpoint(package), cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    expected = [
        "View PKGBUILD",
        "View Changes",
        "Download snapshot",
        "Search wiki",
        "Flag package out-of-date",
        "Vote for this package",
        "Enable notifications",
        "Submit Request"
    ]
    for expected_text in expected:
        assert expected_text in resp.text

325
326
327
328
329
330
    # When no requests are up, make sure we don't see the display for them.
    root = parse_root(resp.text)
    selector = '//div[@id="actionlist"]/ul/li/span[@class="flagged"]'
    target = root.xpath(selector)
    assert len(target) == 0

331
332
333
334
335
336
337
338
339

def test_package_authenticated_maintainer(client: TestClient,
                                          maintainer: User,
                                          package: Package):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(package_endpoint(package), cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
    expected = [
        "View PKGBUILD",
        "View Changes",
        "Download snapshot",
        "Search wiki",
        "Flag package out-of-date",
        "Vote for this package",
        "Enable notifications",
        "Manage Co-Maintainers",
        "Submit Request",
        "Disown Package"
    ]
    for expected_text in expected:
        assert expected_text in resp.text


def test_package_authenticated_tu(client: TestClient,
                                  tu_user: User,
                                  package: Package):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(package_endpoint(package), cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
    expected = [
        "View PKGBUILD",
        "View Changes",
        "Download snapshot",
        "Search wiki",
        "Flag package out-of-date",
        "Vote for this package",
        "Enable notifications",
        "Manage Co-Maintainers",
        "Submit Request",
        "Delete Package",
        "Merge Package",
        "Disown Package"
    ]
    for expected_text in expected:
        assert expected_text in resp.text


def test_package_dependencies(client: TestClient, maintainer: User,
                              package: Package):
    # Create a normal dependency of type depends.
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
421
    with db.begin():
        dep_pkg = create_package("test-dep-1", maintainer)
        dep = create_package_dep(package, dep_pkg.Name)
        dep.DepArch = "x86_64"

        # Also, create a makedepends.
        make_dep_pkg = create_package("test-dep-2", maintainer)
        make_dep = create_package_dep(package, make_dep_pkg.Name,
                                      dep_type_name="makedepends")

        # And... a checkdepends!
        check_dep_pkg = create_package("test-dep-3", maintainer)
        check_dep = create_package_dep(package, check_dep_pkg.Name,
                                       dep_type_name="checkdepends")

        # Geez. Just stop. This is optdepends.
        opt_dep_pkg = create_package("test-dep-4", maintainer)
        opt_dep = create_package_dep(package, opt_dep_pkg.Name,
                                     dep_type_name="optdepends")

        # Heh. Another optdepends to test one with a description.
        opt_desc_dep_pkg = create_package("test-dep-5", maintainer)
        opt_desc_dep = create_package_dep(package, opt_desc_dep_pkg.Name,
                                          dep_type_name="optdepends")
        opt_desc_dep.DepDesc = "Test description."

        broken_dep = create_package_dep(package, "test-dep-6",
                                        dep_type_name="depends")

        # Create an official provider record.
        db.create(OfficialProvider, Name="test-dep-99",
                  Repo="core", Provides="test-dep-99")
        official_dep = create_package_dep(package, "test-dep-99")

        # Also, create a provider who provides our test-dep-99.
        provider = create_package("test-provider", maintainer)
        create_package_rel(provider, dep.DepName)
422
423
424
425
426
427
428
429
430
431
432
433

    with client as request:
        resp = request.get(package_endpoint(package))
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)

    expected = [
        dep.DepName,
        make_dep.DepName,
        check_dep.DepName,
        opt_dep.DepName,
434
        opt_desc_dep.DepName,
435
436
437
438
439
440
        official_dep.DepName
    ]
    pkgdeps = root.findall('.//ul[@id="pkgdepslist"]/li/a')
    for i, expectation in enumerate(expected):
        assert pkgdeps[i].text.strip() == expectation

441
442
443
444
445
    # Let's make sure the DepArch was displayed for our first dep.
    arch = root.findall('.//ul[@id="pkgdepslist"]/li')[0]
    arch = arch.xpath('./em')[1]
    assert arch.text.strip() == "(x86_64)"

446
447
    broken_node = root.find('.//ul[@id="pkgdepslist"]/li/span')
    assert broken_node.text.strip() == broken_dep.DepName
Kevin Morris's avatar
Kevin Morris committed
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464


def test_pkgbase_not_found(client: TestClient):
    with client as request:
        resp = request.get("/pkgbase/not_found")
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)


def test_pkgbase_redirect(client: TestClient, package: Package):
    with client as request:
        resp = request.get(f"/pkgbase/{package.Name}",
                           allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == f"/packages/{package.Name}"


def test_pkgbase(client: TestClient, package: Package):
465
466
467
    with db.begin():
        second = db.create(Package, Name="second-pkg",
                           PackageBase=package.PackageBase)
Kevin Morris's avatar
Kevin Morris committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485

    expected = [package.Name, second.Name]
    with client as request:
        resp = request.get(f"/pkgbase/{package.Name}",
                           allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)

    # Check the details box title.
    title = root.find('.//div[@id="pkgdetails"]/h2')
    title, pkgname = title.text.split(": ")
    assert title == "Package Base Details"
    assert pkgname == package.Name

    pkgs = root.findall('.//div[@id="pkgs"]/ul/li/a')
    for i, name in enumerate(expected):
        assert pkgs[i].text.strip() == name
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
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
725
726
727
728
729
730
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
758
759
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
786
787
788
789
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987


def test_packages(client: TestClient, packages: List[Package]):
    """ Test the / packages route with defaults.

    Defaults:
        50 results per page
        offset of 0
    """
    with client as request:
        response = request.get("/packages", params={
            "SeB": "X"  # "X" isn't valid, defaults to "nd"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    stats = root.xpath('//div[@class="pkglist-stats"]/p')[0]
    pager_text = re.sub(r'\s+', " ", stats.text.replace("\n", "").strip())
    assert pager_text == "55 packages found. Page 1 of 2."

    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 50  # Default per-page


def test_packages_search_by_name(client: TestClient, packages: List[Package]):
    with client as request:
        response = request.get("/packages", params={
            "SeB": "n",
            "K": "pkg_"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)

    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 50  # Default per-page


def test_packages_search_by_exact_name(client: TestClient,
                                       packages: List[Package]):
    with client as request:
        response = request.get("/packages", params={
            "SeB": "N",
            "K": "pkg_"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')

    # There is no package named exactly 'pkg_', we get 0 results.
    assert len(rows) == 0

    with client as request:
        response = request.get("/packages", params={
            "SeB": "N",
            "K": "pkg_1"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')

    # There's just one package named 'pkg_1', we get 1 result.
    assert len(rows) == 1


def test_packages_search_by_pkgbase(client: TestClient,
                                    packages: List[Package]):
    with client as request:
        response = request.get("/packages", params={
            "SeB": "b",
            "K": "pkg_"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)

    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 50


def test_packages_search_by_exact_pkgbase(client: TestClient,
                                          packages: List[Package]):
    with client as request:
        response = request.get("/packages", params={
            "SeB": "B",
            "K": "pkg_"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 0

    with client as request:
        response = request.get("/packages", params={
            "SeB": "B",
            "K": "pkg_1"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 1


def test_packages_search_by_keywords(client: TestClient,
                                     packages: List[Package]):
    # None of our packages have keywords, so this query should return nothing.
    with client as request:
        response = request.get("/packages", params={
            "SeB": "k",
            "K": "testKeyword"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 0

    # But now, let's create the keyword for the first package.
    package = packages[0]
    with db.begin():
        db.create(PackageKeyword,
                  PackageBase=package.PackageBase,
                  Keyword="testKeyword")

    # And request packages with that keyword, we should get 1 result.
    with client as request:
        response = request.get("/packages", params={
            "SeB": "k",
            "K": "testKeyword"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 1


def test_packages_search_by_maintainer(client: TestClient,
                                       maintainer: User,
                                       package: Package):
    with client as request:
        response = request.get("/packages", params={
            "SeB": "m",
            "K": maintainer.Username
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 1


def test_packages_search_by_comaintainer(client: TestClient,
                                         maintainer: User,
                                         package: Package):
    # Nobody's a comaintainer yet.
    with client as request:
        response = request.get("/packages", params={
            "SeB": "c",
            "K": maintainer.Username
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 0

    # Now, we create a comaintainer.
    with db.begin():
        db.create(PackageComaintainer,
                  PackageBase=package.PackageBase,
                  User=maintainer,
                  Priority=1)

    # Then test that it's returned by our search.
    with client as request:
        response = request.get("/packages", params={
            "SeB": "c",
            "K": maintainer.Username
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 1


def test_packages_search_by_co_or_maintainer(client: TestClient,
                                             maintainer: User,
                                             package: Package):
    with client as request:
        response = request.get("/packages", params={
            "SeB": "M",
            "SB": "BLAH",  # Invalid SB; gets reset to default "n".
            "K": maintainer.Username
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 1

    with db.begin():
        user = db.create(User, Username="comaintainer",
                         Email="comaintainer@example.org",
                         Passwd="testPassword")
        db.create(PackageComaintainer,
                  PackageBase=package.PackageBase,
                  User=user,
                  Priority=1)

    with client as request:
        response = request.get("/packages", params={
            "SeB": "M",
            "K": user.Username
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 1


def test_packages_search_by_submitter(client: TestClient,
                                      maintainer: User,
                                      package: Package):
    with client as request:
        response = request.get("/packages", params={
            "SeB": "s",
            "K": maintainer.Username
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 1


def test_packages_sort_by_votes(client: TestClient,
                                maintainer: User,
                                packages: List[Package]):
    # Set the first package's NumVotes to 1.
    with db.begin():
        packages[0].PackageBase.NumVotes = 1

    # Test that, by default, the first result is what we just set above.
    with client as request:
        response = request.get("/packages", params={
            "SB": "v"  # Votes.
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    votes = rows[0].xpath('./td')[2]  # The third column of the first row.
    assert votes.text.strip() == "1"

    # Now, test that with an ascending order, the last result is
    # the one we set, since the default (above) is descending.
    with client as request:
        response = request.get("/packages", params={
            "SB": "v",  # Votes.
            "SO": "a",  # Ascending.
            "O": "50"  # Second page.
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    votes = rows[-1].xpath('./td')[2]  # The third column of the last row.
    assert votes.text.strip() == "1"


def test_packages_sort_by_popularity(client: TestClient,
                                     maintainer: User,
                                     packages: List[Package]):
    # Set the first package's Popularity to 0.50.
    with db.begin():
        packages[0].PackageBase.Popularity = "0.50"

    # Test that, by default, the first result is what we just set above.
    with client as request:
        response = request.get("/packages", params={
            "SB": "p"  # Popularity
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    pop = rows[0].xpath('./td')[3]  # The fourth column of the first row.
    assert pop.text.strip() == "0.50"


def test_packages_sort_by_voted(client: TestClient,
                                maintainer: User,
                                packages: List[Package]):
    now = int(datetime.utcnow().timestamp())
    with db.begin():
        db.create(PackageVote, PackageBase=packages[0].PackageBase,
                  User=maintainer, VoteTS=now)

    # Test that, by default, the first result is what we just set above.
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/packages", params={
            "SB": "w",  # Voted
            "SO": "d"  # Descending, Voted first.
        }, cookies=cookies)
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    voted = rows[0].xpath('./td')[5]  # The sixth column of the first row.
    assert voted.text.strip() == "Yes"

    # Conversely, everything else was not voted on.
    voted = rows[1].xpath('./td')[5]  # The sixth column of the second row.
    assert voted.text.strip() == str()  # Empty.


def test_packages_sort_by_notify(client: TestClient,
                                 maintainer: User,
                                 packages: List[Package]):
    db.create(PackageNotification,
              PackageBase=packages[0].PackageBase,
              User=maintainer)

    # Test that, by default, the first result is what we just set above.
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    with client as request:
        response = request.get("/packages", params={
            "SB": "o",  # Voted
            "SO": "d"  # Descending, Voted first.
        }, cookies=cookies)
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    notify = rows[0].xpath('./td')[6]  # The sixth column of the first row.
    assert notify.text.strip() == "Yes"

    # Conversely, everything else was not voted on.
    notify = rows[1].xpath('./td')[6]  # The sixth column of the second row.
    assert notify.text.strip() == str()  # Empty.


def test_packages_sort_by_maintainer(client: TestClient,
                                     maintainer: User,
                                     package: Package):
    """ Sort a package search by the maintainer column. """

    # Create a second package, so the two can be ordered and checked.
    with db.begin():
        maintainer2 = db.create(User, Username="maintainer2",
                                Email="maintainer2@example.org",
                                Passwd="testPassword")
        base2 = db.create(PackageBase, Name="pkg_2", Maintainer=maintainer2,
                          Submitter=maintainer2, Packager=maintainer2)
        db.create(Package, Name="pkg_2", PackageBase=base2)

    # Check the descending order route.
    with client as request:
        response = request.get("/packages", params={
            "SB": "m",
            "SO": "d"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    col = rows[0].xpath('./td')[5].xpath('./a')[0]  # Last column.

    assert col.text.strip() == maintainer.Username

    # On the other hand, with ascending, we should get reverse ordering.
    with client as request:
        response = request.get("/packages", params={
            "SB": "m",
            "SO": "a"
        })
    assert response.status_code == int(HTTPStatus.OK)

    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    col = rows[0].xpath('./td')[5].xpath('./a')[0]  # Last column.

    assert col.text.strip() == maintainer2.Username


def test_packages_sort_by_last_modified(client: TestClient,
                                        packages: List[Package]):
    now = int(datetime.utcnow().timestamp())
    # Set the first package's ModifiedTS to be 1000 seconds before now.
    package = packages[0]
    with db.begin():
        package.PackageBase.ModifiedTS = now - 1000

    with client as request:
        response = request.get("/packages", params={
            "SB": "l",
            "SO": "a"  # Ascending; oldest modification first.
        })
    assert response.status_code == int(HTTPStatus.OK)

    # We should have 50 (default per page) results.
    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 50

    # Let's assert that the first item returned was the one we modified above.
    row = rows[0]
    col = row.xpath('./td')[0].xpath('./a')[0]
    assert col.text.strip() == package.Name


def test_packages_flagged(client: TestClient, maintainer: User,
                          packages: List[Package]):
    package = packages[0]

    now = int(datetime.utcnow().timestamp())

    with db.begin():
        package.PackageBase.OutOfDateTS = now
        package.PackageBase.Flagger = maintainer

    with client as request:
        response = request.get("/packages", params={
            "outdated": "on"
        })
    assert response.status_code == int(HTTPStatus.OK)

    # We should only get one result from this query; the package we flagged.
    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 1

    with client as request:
        response = request.get("/packages", params={
            "outdated": "off"
        })
    assert response.status_code == int(HTTPStatus.OK)

    # In this case, we should get 54 results, which means that the first
    # page will have 50 results (55 packages - 1 outdated = 54 not outdated).
    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 50


def test_packages_orphans(client: TestClient, packages: List[Package]):
    package = packages[0]
    with db.begin():
        package.PackageBase.Maintainer = None

    with client as request:
        response = request.get("/packages", params={"submit": "Orphans"})
    assert response.status_code == int(HTTPStatus.OK)

    # We only have one orphan. Let's make sure that's what is returned.
    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 1


def test_packages_per_page(client: TestClient, maintainer: User):
    """ Test the ability for /packages to deal with the PP query
    argument specifications (50, 100, 250; default: 50). """
    with db.begin():
        for i in range(255):
            base = db.create(PackageBase, Name=f"pkg_{i}",
                             Maintainer=maintainer,
                             Submitter=maintainer,
                             Packager=maintainer)
            db.create(Package, PackageBase=base, Name=base.Name)

    # Test default case, PP of 50.
    with client as request:
        response = request.get("/packages", params={"PP": 50})
    assert response.status_code == int(HTTPStatus.OK)
    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 50

    # Alright, test the next case, PP of 100.
    with client as request:
        response = request.get("/packages", params={"PP": 100})
    assert response.status_code == int(HTTPStatus.OK)
    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 100

    # And finally, the last case, a PP of 250.
    with client as request:
        response = request.get("/packages", params={"PP": 250})
    assert response.status_code == int(HTTPStatus.OK)
    root = parse_root(response.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 250
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005


def test_pkgbase_voters(client: TestClient, maintainer: User, package: Package):
    pkgbase = package.PackageBase
    endpoint = f"/pkgbase/{pkgbase.Name}/voters"

    now = int(datetime.utcnow().timestamp())
    with db.begin():
        db.create(PackageVote, User=maintainer, PackageBase=pkgbase,
                  VoteTS=now)

    with client as request:
        resp = request.get(endpoint)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    rows = root.xpath('//div[@class="box"]//ul/li')
    assert len(rows) == 1
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052


def test_pkgbase_comment_not_found(client: TestClient, maintainer: User,
                                   package: Package):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    comment_id = 12345  # A non-existing comment.
    endpoint = f"/pkgbase/{package.PackageBase.Name}/comments/{comment_id}"
    with client as request:
        resp = request.post(endpoint, data={
            "comment": "Failure"
        }, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)


def test_pkgbase_comment_form_unauthorized(client: TestClient, user: User,
                                           maintainer: User, package: Package):
    now = int(datetime.utcnow().timestamp())
    with db.begin():
        comment = db.create(PackageComment, PackageBase=package.PackageBase,
                            User=maintainer, Comments="Test",
                            RenderedComment=str(), CommentTS=now)

    cookies = {"AURSID": user.login(Request(), "testPassword")}
    pkgbasename = package.PackageBase.Name
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment.ID}/form"
    with client as request:
        resp = request.get(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.UNAUTHORIZED)


def test_pkgbase_comment_form_not_found(client: TestClient, maintainer: User,
                                        package: Package):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    comment_id = 12345  # A non-existing comment.
    pkgbasename = package.PackageBase.Name
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment_id}/form"
    with client as request:
        resp = request.get(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)


def test_pkgbase_comments_missing_comment(client: TestClient, maintainer: User,
                                          package: Package):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    endpoint = f"/pkgbase/{package.PackageBase.Name}/comments"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
1053
    assert resp.status_code == int(HTTPStatus.BAD_REQUEST)
1054
1055


1056
def test_pkgbase_comments(client: TestClient, maintainer: User, user: User,
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
                          package: Package):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    pkgbasename = package.PackageBase.Name
    endpoint = f"/pkgbase/{pkgbasename}/comments"
    with client as request:
        resp = request.post(endpoint, data={
            "comment": "Test comment.",
            "enable_notifications": True
        }, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    expected_prefix = f"/pkgbase/{pkgbasename}"
    prefix_len = len(expected_prefix)
    assert resp.headers.get("location")[:prefix_len] == expected_prefix

    with client as request:
        resp = request.get(resp.headers.get("location"))
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    headers = root.xpath('//h4[@class="comment-header"]')
    bodies = root.xpath('//div[@class="article-content"]/div/p')

    assert len(headers) == 1
    assert len(bodies) == 1

    assert bodies[0].text.strip() == "Test comment."

    # Clear up the PackageNotification. This doubles as testing
    # that the notification was created and clears it up so we can
    # test enabling it during edit.
    pkgbase = package.PackageBase
    db_notif = pkgbase.notifications.filter(
        PackageNotification.UserID == maintainer.ID
    ).first()
    with db.begin():
        db.session.delete(db_notif)

    # Now, let's edit the comment we just created.
    comment_id = int(headers[0].attrib["id"].split("-")[-1])
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment_id}"
    with client as request:
        resp = request.post(endpoint, data={
            "comment": "Edited comment.",
            "enable_notifications": True
        }, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    with client as request:
        resp = request.get(resp.headers.get("location"))
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    headers = root.xpath('//h4[@class="comment-header"]')
    bodies = root.xpath('//div[@class="article-content"]/div/p')

    assert len(headers) == 1
    assert len(bodies) == 1

    assert bodies[0].text.strip() == "Edited comment."

    # Ensure that a notification was created.
    db_notif = pkgbase.notifications.filter(
        PackageNotification.UserID == maintainer.ID
    ).first()
    assert db_notif is not None

1124
    # Don't supply a comment; should return BAD_REQUEST.
1125
1126
    with client as request:
        fail_resp = request.post(endpoint, cookies=cookies)
1127
    assert fail_resp.status_code == int(HTTPStatus.BAD_REQUEST)
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137

    # Now, test the form route, which should return form markup
    # via JSON.
    endpoint = f"{endpoint}/form"
    with client as request:
        resp = request.get(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    data = resp.json()
    assert "form" in data
1138
1139
1140


def test_pkgbase_comment_delete(client: TestClient,
1141
                                maintainer: User,
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
                                user: User,
                                package: Package,
                                comment: PackageComment):
    # Test the unauthorized case of comment deletion.
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    pkgbasename = package.PackageBase.Name
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment.ID}/delete"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    expected = f"/pkgbase/{pkgbasename}"
    assert resp.headers.get("location") == expected

1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
    # Test the unauthorized case of comment undeletion.
    maint_cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment.ID}/undelete"
    with client as request:
        resp = request.post(endpoint, cookies=maint_cookies)
    assert resp.status_code == int(HTTPStatus.UNAUTHORIZED)

    # And move on to undeleting it.
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191

def test_pkgbase_comment_delete_unauthorized(client: TestClient,
                                             maintainer: User,
                                             package: Package,
                                             comment: PackageComment):
    # Test the unauthorized case of comment deletion.
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    pkgbasename = package.PackageBase.Name
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment.ID}/delete"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.UNAUTHORIZED)


def test_pkgbase_comment_delete_not_found(client: TestClient,
                                          maintainer: User,
                                          package: Package):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    comment_id = 12345  # Non-existing comment.
    pkgbasename = package.PackageBase.Name
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment_id}/delete"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203


def test_pkgbase_comment_undelete_not_found(client: TestClient,
                                            maintainer: User,
                                            package: Package):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    comment_id = 12345  # Non-existing comment.
    pkgbasename = package.PackageBase.Name
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment_id}/undelete"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)
1204
1205
1206
1207
1208
1209
1210
1211
1212


def test_pkgbase_comment_pin(client: TestClient,
                             maintainer: User,
                             package: Package,
                             comment: PackageComment):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    comment_id = comment.ID
    pkgbasename = package.PackageBase.Name
1213
1214

    # Pin the comment.
1215
1216
1217
1218
1219
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment_id}/pin"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
    # Assert that PinnedTS got set.
    assert comment.PinnedTS > 0

    # Unpin the comment we just pinned.
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment_id}/unpin"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    # Let's assert that PinnedTS was unset.
    assert comment.PinnedTS == 0

1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243

def test_pkgbase_comment_pin_unauthorized(client: TestClient,
                                          user: User,
                                          package: Package,
                                          comment: PackageComment):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    comment_id = comment.ID
    pkgbasename = package.PackageBase.Name
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment_id}/pin"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.UNAUTHORIZED)
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256


def test_pkgbase_comment_unpin_unauthorized(client: TestClient,
                                            user: User,
                                            package: Package,
                                            comment: PackageComment):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    comment_id = comment.ID
    pkgbasename = package.PackageBase.Name
    endpoint = f"/pkgbase/{pkgbasename}/comments/{comment_id}/unpin"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.UNAUTHORIZED)
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364


def test_pkgbase_comaintainers_not_found(client: TestClient, maintainer: User):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    endpoint = "/pkgbase/fake/comaintainers"
    with client as request:
        resp = request.get(endpoint, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)


def test_pkgbase_comaintainers_post_not_found(client: TestClient,
                                              maintainer: User):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    endpoint = "/pkgbase/fake/comaintainers"
    with client as request:
        resp = request.post(endpoint, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)


def test_pkgbase_comaintainers_unauthorized(client: TestClient, user: User,
                                            package: Package):
    pkgbase = package.PackageBase
    endpoint = f"/pkgbase/{pkgbase.Name}/comaintainers"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(endpoint, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == f"/pkgbase/{pkgbase.Name}"


def test_pkgbase_comaintainers_post_unauthorized(client: TestClient,
                                                 user: User,
                                                 package: Package):
    pkgbase = package.PackageBase
    endpoint = f"/pkgbase/{pkgbase.Name}/comaintainers"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == f"/pkgbase/{pkgbase.Name}"


def test_pkgbase_comaintainers_post_invalid_user(client: TestClient,
                                                 maintainer: User,
                                                 package: Package):
    pkgbase = package.PackageBase
    endpoint = f"/pkgbase/{pkgbase.Name}/comaintainers"
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, data={
            "users": "\nfake\n"
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    error = root.xpath('//ul[@class="errorlist"]/li')[0]
    assert error.text.strip() == "Invalid user name: fake"


def test_pkgbase_comaintainers(client: TestClient, user: User,
                               maintainer: User, package: Package):
    pkgbase = package.PackageBase
    endpoint = f"/pkgbase/{pkgbase.Name}/comaintainers"
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}

    # Start off by adding user as a comaintainer to package.
    # The maintainer username given should be ignored.
    with client as request:
        resp = request.post(endpoint, data={
            "users": f"\n{user.Username}\n{maintainer.Username}\n"
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == f"/pkgbase/{pkgbase.Name}"

    # Do it again to exercise the last_priority bump path.
    with client as request:
        resp = request.post(endpoint, data={
            "users": f"\n{user.Username}\n{maintainer.Username}\n"
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == f"/pkgbase/{pkgbase.Name}"

    # Now that we've added a comaintainer to the pkgbase,
    # let's perform a GET request to make sure that the backend produces
    # the user we added in the users textarea.
    with client as request:
        resp = request.get(endpoint, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    users = root.xpath('//textarea[@id="id_users"]')[0]
    assert users.text.strip() == user.Username

    # Finish off by removing all the comaintainers.
    with client as request:
        resp = request.post(endpoint, data={
            "users": str()
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == f"/pkgbase/{pkgbase.Name}"

    with client as request:
        resp = request.get(endpoint, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    users = root.xpath('//textarea[@id="id_users"]')[0]
    assert users is not None and users.text is None
1365
1366


1367
def test_requests_unauthorized(client: TestClient):
1368
    with client as request:
1369
        resp = request.get("/requests", allow_redirects=False)
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)


def test_requests(client: TestClient,
                  maintainer: User,
                  tu_user: User,
                  packages: List[Package],
                  requests: List[PackageRequest]):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get("/requests", params={
            # Pass in url query parameters O, SeB and SB to exercise
            # their paths inside of the pager_nav used in this request.
            "O": 0,  # Page 1
            "SeB": "nd",
            "SB": "n"
        }, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    assert "Next ›" in resp.text
    assert "Last »" in resp.text

    root = parse_root(resp.text)
    # We have 55 requests, our defaults.PP is 50, so expect we have 50 rows.
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == defaults.PP

    # Request page 2 of the requests page.
    with client as request:
        resp = request.get("/requests", params={
            "O": 50  # Page 2
        }, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    assert "‹ Previous" in resp.text
    assert "« First" in resp.text

    root = parse_root(resp.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == 5  # There are five records left on the second page.
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428


def test_requests_selfmade(client: TestClient, user: User,
                           requests: List[PackageRequest]):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get("/requests", cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    # As the user who creates all of the requests, we should see all of them.
    # However, we are not allowed to accept any of them ourselves.
    root = parse_root(resp.text)
    rows = root.xpath('//table[@class="results"]/tbody/tr')
    assert len(rows) == defaults.PP

    # Our first and only link in the last row should be "Close".
    for row in rows:
        last_row = row.xpath('./td')[-1].xpath('./a')[0]
        assert last_row.text.strip() == "Close"
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448


def test_pkgbase_request_not_found(client: TestClient, user: User):
    pkgbase_name = "fake"
    endpoint = f"/pkgbase/{pkgbase_name}/request"

    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)


def test_pkgbase_request(client: TestClient, user: User, package: Package):
    pkgbase = package.PackageBase
    endpoint = f"/pkgbase/{pkgbase.Name}/request"

    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609


def test_pkgbase_request_post_deletion(client: TestClient, user: User,
                                       package: Package):
    endpoint = f"/pkgbase/{package.PackageBase.Name}/request"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, data={
            "type": "deletion",
            "comments": "We want to delete this."
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    pkgreq = db.query(PackageRequest).filter(
        PackageRequest.PackageBaseID == package.PackageBase.ID
    ).first()
    assert pkgreq is not None
    assert pkgreq.RequestType.Name == "deletion"
    assert pkgreq.PackageBaseName == package.PackageBase.Name
    assert pkgreq.Comments == "We want to delete this."


def test_pkgbase_request_post_orphan(client: TestClient, user: User,
                                     package: Package):
    endpoint = f"/pkgbase/{package.PackageBase.Name}/request"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, data={
            "type": "orphan",
            "comments": "We want to disown this."
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    pkgreq = db.query(PackageRequest).filter(
        PackageRequest.PackageBaseID == package.PackageBase.ID
    ).first()
    assert pkgreq is not None
    assert pkgreq.RequestType.Name == "orphan"
    assert pkgreq.PackageBaseName == package.PackageBase.Name
    assert pkgreq.Comments == "We want to disown this."


def test_pkgbase_request_post_merge(client: TestClient, user: User,
                                    package: Package):
    with db.begin():
        pkgbase2 = db.create(PackageBase, Name="new-pkgbase",
                             Submitter=user, Maintainer=user, Packager=user)
        target = db.create(Package, PackageBase=pkgbase2,
                           Name=pkgbase2.Name, Version="1.0.0")

    endpoint = f"/pkgbase/{package.PackageBase.Name}/request"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, data={
            "type": "merge",
            "merge_into": target.PackageBase.Name,
            "comments": "We want to merge this."
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    pkgreq = db.query(PackageRequest).filter(
        PackageRequest.PackageBaseID == package.PackageBase.ID
    ).first()
    assert pkgreq is not None
    assert pkgreq.RequestType.Name == "merge"
    assert pkgreq.PackageBaseName == package.PackageBase.Name
    assert pkgreq.MergeBaseName == target.PackageBase.Name
    assert pkgreq.Comments == "We want to merge this."


def test_pkgbase_request_post_not_found(client: TestClient, user: User):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post("/pkgbase/fake/request", data={
            "type": "fake"
        }, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.NOT_FOUND)


def test_pkgbase_request_post_invalid_type(client: TestClient,
                                           user: User,
                                           package: Package):
    endpoint = f"/pkgbase/{package.PackageBase.Name}/request"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, data={"type": "fake"}, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.BAD_REQUEST)


def test_pkgbase_request_post_no_comment_error(client: TestClient,
                                               user: User,
                                               package: Package):
    endpoint = f"/pkgbase/{package.PackageBase.Name}/request"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, data={
            "type": "deletion",
            "comments": ""  # An empty comment field causes an error.
        }, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    error = root.xpath('//ul[@class="errorlist"]/li')[0]
    expected = "The comment field must not be empty."
    assert error.text.strip() == expected


def test_pkgbase_request_post_merge_not_found_error(client: TestClient,
                                                    user: User,
                                                    package: Package):
    endpoint = f"/pkgbase/{package.PackageBase.Name}/request"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, data={
            "type": "merge",
            "merge_into": "fake",  # There is no PackageBase.Name "fake"
            "comments": "We want to merge this."
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    error = root.xpath('//ul[@class="errorlist"]/li')[0]
    expected = "The package base you want to merge into does not exist."
    assert error.text.strip() == expected


def test_pkgbase_request_post_merge_no_merge_into_error(client: TestClient,
                                                        user: User,
                                                        package: Package):
    endpoint = f"/pkgbase/{package.PackageBase.Name}/request"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, data={
            "type": "merge",
            "merge_into": "",  # There is no PackageBase.Name "fake"
            "comments": "We want to merge this."
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    error = root.xpath('//ul[@class="errorlist"]/li')[0]
    expected = 'The "Merge into" field must not be empty.'
    assert error.text.strip() == expected


def test_pkgbase_request_post_merge_self_error(client: TestClient, user: User,
                                               package: Package):
    endpoint = f"/pkgbase/{package.PackageBase.Name}/request"
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, data={
            "type": "merge",
            "merge_into": package.PackageBase.Name,
            "comments": "We want to merge this."
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.OK)

    root = parse_root(resp.text)
    error = root.xpath('//ul[@class="errorlist"]/li')[0]
    expected = "You cannot merge a package base into itself."
    assert error.text.strip() == expected
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693


@pytest.fixture
def pkgreq(user: User, package: Package) -> PackageRequest:
    reqtype = db.query(RequestType).filter(
        RequestType.ID == DELETION_ID
    ).first()
    with db.begin():
        pkgreq = db.create(PackageRequest,
                           RequestType=reqtype,
                           User=user,
                           PackageBase=package.PackageBase,
                           PackageBaseName=package.PackageBase.Name,
                           Comments=str(),
                           ClosureComment=str())
    yield pkgreq


def test_requests_close(client: TestClient, user: User,
                        pkgreq: PackageRequest):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(f"/requests/{pkgreq.ID}/close", cookies=cookies,
                           allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.OK)


def test_requests_close_unauthorized(client: TestClient, maintainer: User,
                                     pkgreq: PackageRequest):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(f"/requests/{pkgreq.ID}/close", cookies=cookies,
                           allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == "/"


def test_requests_close_post_invalid_reason(client: TestClient, user: User,
                                            pkgreq: PackageRequest):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(f"/requests/{pkgreq.ID}/close", data={
            "reason": 0
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.BAD_REQUEST)


def test_requests_close_post_unauthorized(client: TestClient, maintainer: User,
                                          pkgreq: PackageRequest):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(f"/requests/{pkgreq.ID}/close", data={
            "reason": ACCEPTED_ID
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == "/"


def test_requests_close_post(client: TestClient, user: User,
                             pkgreq: PackageRequest):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(f"/requests/{pkgreq.ID}/close", data={
            "reason": REJECTED_ID
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    assert pkgreq.Status == REJECTED_ID
    assert pkgreq.Closer == user
    assert pkgreq.ClosureComment == str()


def test_requests_close_post_rejected(client: TestClient, user: User,
                                      pkgreq: PackageRequest):
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(f"/requests/{pkgreq.ID}/close", data={
            "reason": REJECTED_ID
        }, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    assert pkgreq.Status == REJECTED_ID
    assert pkgreq.Closer == user
    assert pkgreq.ClosureComment == str()
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704


def test_pkgbase_flag(client: TestClient, user: User, maintainer: User,
                      package: Package):
    pkgbase = package.PackageBase

    # We shouldn't have flagged the package yet; assert so.
    assert pkgbase.Flagger is None

    cookies = {"AURSID": user.login(Request(), "testPassword")}
    endpoint = f"/pkgbase/{pkgbase.Name}/flag"
1705
1706
1707
1708
1709
1710

    # Get the flag page.
    with client as request:
        resp = request.get(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

1711
1712
1713
1714
1715
1716
1717
1718
    # Now, let's check the /pkgbase/{name}/flag-comment route.
    flag_comment_endpoint = f"/pkgbase/{pkgbase.Name}/flag-comment"
    with client as request:
        resp = request.get(flag_comment_endpoint, cookies=cookies,
                           allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == f"/pkgbase/{pkgbase.Name}"

1719
    # Try to flag it without a comment.
1720
1721
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
1722
1723
1724
1725
    assert resp.status_code == int(HTTPStatus.BAD_REQUEST)

    # Flag it with a valid comment.
    with client as request:
1726
1727
1728
        resp = request.post(endpoint, data={
            "comments": "Test"
        }, cookies=cookies)
1729
1730
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert pkgbase.Flagger == user
1731
1732
    assert pkgbase.FlaggerComment == "Test"

1733
1734
1735
1736
1737
1738
1739
    # Now, let's check the /pkgbase/{name}/flag-comment route.
    flag_comment_endpoint = f"/pkgbase/{pkgbase.Name}/flag-comment"
    with client as request:
        resp = request.get(flag_comment_endpoint, cookies=cookies,
                           allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.OK)

1740
1741
1742
1743
1744
    # Now try to perform a get; we should be redirected because
    # it's already flagged.
    with client as request:
        resp = request.get(endpoint, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
1745

1746
1747
1748
1749
1750
1751
1752
    with db.begin():
        user2 = db.create(User, Username="test2",
                          Email="test2@example.org",
                          Passwd="testPassword",
                          AccountType=user.AccountType)

    # Now, test that the 'user2' user can't unflag it, because they
1753
    # didn't flag it to begin with.
1754
    user2_cookies = {"AURSID": user2.login(Request(), "testPassword")}
1755
1756
    endpoint = f"/pkgbase/{pkgbase.Name}/unflag"
    with client as request:
1757
        resp = request.post(endpoint, cookies=user2_cookies)
1758
1759
1760
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert pkgbase.Flagger == user

1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
    # Now, test that the 'maintainer' user can.
    maint_cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, cookies=maint_cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert pkgbase.Flagger is None

    # Flag it again.
    with client as request:
        resp = request.post(f"/pkgbase/{pkgbase.Name}/flag", data={
            "comments": "Test"
        }, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

1775
1776
1777
1778
1779
    # Now, unflag it for real.
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert pkgbase.Flagger is None
1780
1781


1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
def test_pkgbase_flag_vcs(client: TestClient, user: User, package: Package):
    # Morph our package fixture into a VCS package (-git).
    with db.begin():
        package.PackageBase.Name += "-git"
        package.Name += "-git"

    cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.get(f"/pkgbase/{package.PackageBase.Name}/flag",
                           cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    expected = ("This seems to be a VCS package. Please do "
                "<strong>not</strong> flag it out-of-date if the package "
                "version in the AUR does not match the most recent commit. "
                "Flagging this package should only be done if the sources "
                "moved or changes in the PKGBUILD are required because of "
                "recent upstream changes.")
    assert expected in resp.text


1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
def test_pkgbase_notify(client: TestClient, user: User, package: Package):
    pkgbase = package.PackageBase

    # We have no notif record yet; assert that.
    notif = pkgbase.notifications.filter(
        PackageNotification.UserID == user.ID
    ).first()
    assert notif is None

    # Enable notifications.
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    endpoint = f"/pkgbase/{pkgbase.Name}/notify"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    notif = pkgbase.notifications.filter(
        PackageNotification.UserID == user.ID
    ).first()
    assert notif is not None

    # Disable notifications.
    endpoint = f"/pkgbase/{pkgbase.Name}/unnotify"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    notif = pkgbase.notifications.filter(
        PackageNotification.UserID == user.ID
    ).first()
    assert notif is None
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851


def test_pkgbase_vote(client: TestClient, user: User, package: Package):
    pkgbase = package.PackageBase

    # We haven't voted yet.
    vote = pkgbase.package_votes.filter(PackageVote.UsersID == user.ID).first()
    assert vote is None

    # Vote for the package.
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    endpoint = f"/pkgbase/{pkgbase.Name}/vote"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    vote = pkgbase.package_votes.filter(PackageVote.UsersID == user.ID).first()
    assert vote is not None
1852
    assert pkgbase.NumVotes == 1
1853
1854
1855
1856
1857
1858
1859
1860
1861

    # Remove vote.
    endpoint = f"/pkgbase/{pkgbase.Name}/unvote"
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    vote = pkgbase.package_votes.filter(PackageVote.UsersID == user.ID).first()
    assert vote is None
1862
    assert pkgbase.NumVotes == 0
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921


def test_pkgbase_disown_as_tu(client: TestClient, tu_user: User,
                              package: Package):
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    pkgbase = package.PackageBase
    endpoint = f"/pkgbase/{pkgbase.Name}/disown"

    # But we do here.
    with client as request:
        resp = request.post(endpoint, data={"confirm": True}, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)


def test_pkgbase_disown_as_sole_maintainer(client: TestClient,
                                           maintainer: User,
                                           package: Package):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    pkgbase = package.PackageBase
    endpoint = f"/pkgbase/{pkgbase.Name}/disown"

    # But we do here.
    with client as request:
        resp = request.post(endpoint, data={"confirm": True}, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)


def test_pkgbase_disown(client: TestClient, user: User, maintainer: User,
                        package: Package):
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    user_cookies = {"AURSID": user.login(Request(), "testPassword")}
    pkgbase = package.PackageBase
    endpoint = f"/pkgbase/{pkgbase.Name}/disown"

    with db.begin():
        db.create(PackageComaintainer,
                  User=user,
                  PackageBase=pkgbase,
                  Priority=1)

    # GET as a normal user, which is rejected for lack of credentials.
    with client as request:
        resp = request.get(endpoint, cookies=user_cookies,
                           allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    # GET as the maintainer.
    with client as request:
        resp = request.get(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    # POST as a normal user, which is rejected for lack of credentials.
    with client as request:
        resp = request.post(endpoint, cookies=user_cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    # POST as the maintainer without "confirm".
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
1922
    assert resp.status_code == int(HTTPStatus.BAD_REQUEST)
1923
1924
1925
1926
1927

    # POST as the maintainer with "confirm".
    with client as request:
        resp = request.post(endpoint, data={"confirm": True}, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
1928
1929


1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
def test_pkgbase_adopt(client: TestClient, user: User, tu_user: User,
                       maintainer: User, package: Package):
    # Unset the maintainer as if package is orphaned.
    with db.begin():
        package.PackageBase.Maintainer = None

    pkgbasename = package.PackageBase.Name
    cookies = {"AURSID": maintainer.login(Request(), "testPassword")}
    endpoint = f"/pkgbase/{pkgbasename}/adopt"

    # Adopt the package base.
    with client as request:
        resp = request.post(endpoint, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert package.PackageBase.Maintainer == maintainer

    # Try to adopt it when it already has a maintainer; nothing changes.
    user_cookies = {"AURSID": user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, cookies=user_cookies,
                            allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert package.PackageBase.Maintainer == maintainer

    # Steal the package as a TU.
    tu_cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    with client as request:
        resp = request.post(endpoint, cookies=tu_cookies,
                            allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert package.PackageBase.Maintainer == tu_user


1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
def test_pkgbase_delete_unauthorized(client: TestClient, user: User,
                                     package: Package):
    pkgbase = package.PackageBase
    cookies = {"AURSID": user.login(Request(), "testPassword")}
    endpoint = f"/pkgbase/{pkgbase.Name}/delete"

    # Test GET.
    with client as request:
        resp = request.get(endpoint, cookies=cookies, allow_redirects=False)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == f"/pkgbase/{pkgbase.Name}"

    # Test POST.
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)
    assert resp.headers.get("location") == f"/pkgbase/{pkgbase.Name}"


def test_pkgbase_delete(client: TestClient, tu_user: User, package: Package):
    pkgbase = package.PackageBase

    # Test that the GET request works.
    cookies = {"AURSID": tu_user.login(Request(), "testPassword")}
    endpoint = f"/pkgbase/{pkgbase.Name}/delete"
    with client as request:
        resp = request.get(endpoint, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.OK)

    # Test that POST works and denies us because we haven't confirmed.
    with client as request:
        resp = request.post(endpoint, cookies=cookies)
1995
    assert resp.status_code == int(HTTPStatus.BAD_REQUEST)
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006

    # Test that we can actually delete the pkgbase.
    with client as request:
        resp = request.post(endpoint, data={"confirm": True}, cookies=cookies)
    assert resp.status_code == int(HTTPStatus.SEE_OTHER)

    # Let's assert that the package base record got removed.
    record = db.query(PackageBase).filter(
        PackageBase.Name == pkgbase.Name
    ).first()
    assert record is None
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036