test_rpc.py 20.4 KB
Newer Older
1
2
import re

Kevin Morris's avatar
Kevin Morris committed
3
from http import HTTPStatus
4
from typing import Dict
Kevin Morris's avatar
Kevin Morris committed
5
6
from unittest import mock

7
import orjson
8
import pytest
9
10

from fastapi.testclient import TestClient
Kevin Morris's avatar
Kevin Morris committed
11
from redis.client import Pipeline
12

Kevin Morris's avatar
Kevin Morris committed
13
from aurweb import config, db, scripts
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from aurweb.asgi import app
from aurweb.db import begin, create, query
from aurweb.models.account_type import AccountType
from aurweb.models.dependency_type import DependencyType
from aurweb.models.license import License
from aurweb.models.package import Package
from aurweb.models.package_base import PackageBase
from aurweb.models.package_dependency import PackageDependency
from aurweb.models.package_keyword import PackageKeyword
from aurweb.models.package_license import PackageLicense
from aurweb.models.package_relation import PackageRelation
from aurweb.models.package_vote import PackageVote
from aurweb.models.relation_type import RelationType
from aurweb.models.user import User
Kevin Morris's avatar
Kevin Morris committed
28
from aurweb.redis import redis_connection
29
30


31
def make_request(path, headers: Dict[str, str] = {}):
32
    with TestClient(app) as request:
33
        return request.get(path, headers=headers)
34
35


36
@pytest.fixture(autouse=True)
37
38
def setup(db_test):
    # TODO: Rework this into organized fixtures.
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

    # Create test package details.
    with begin():
        # Get ID types.
        account_type = query(AccountType, AccountType.AccountType == "User").first()

        dependency_depends = query(DependencyType, DependencyType.Name == "depends").first()
        dependency_optdepends = query(DependencyType, DependencyType.Name == "optdepends").first()
        dependency_makedepends = query(DependencyType, DependencyType.Name == "makedepends").first()
        dependency_checkdepends = query(DependencyType, DependencyType.Name == "checkdepends").first()

        relation_conflicts = query(RelationType, RelationType.Name == "conflicts").first()
        relation_provides = query(RelationType, RelationType.Name == "provides").first()
        relation_replaces = query(RelationType, RelationType.Name == "replaces").first()

        # Create database info.
        user1 = create(User,
                       Username="user1",
                       Email="user1@example.com",
                       RealName="Test User 1",
                       Passwd="testPassword",
                       AccountType=account_type)

        user2 = create(User,
                       Username="user2",
                       Email="user2@example.com",
                       RealName="Test User 2",
                       Passwd="testPassword",
                       AccountType=account_type)

        user3 = create(User,
                       Username="user3",
                       Email="user3@example.com",
                       RealName="Test User 3",
                       Passwd="testPassword",
                       AccountType=account_type)

76
77
78
        pkgbase1 = create(PackageBase, Name="big-chungus",
                          Maintainer=user1,
                          Packager=user1)
79
80
81
82
83
84
85

        pkgname1 = create(Package,
                          PackageBase=pkgbase1,
                          Name=pkgbase1.Name,
                          Description="Bunny bunny around bunny",
                          URL="https://example.com/")

86
87
88
        pkgbase2 = create(PackageBase, Name="chungy-chungus",
                          Maintainer=user1,
                          Packager=user1)
89
90
91
92
93
94
95

        pkgname2 = create(Package,
                          PackageBase=pkgbase2,
                          Name=pkgbase2.Name,
                          Description="Wubby wubby on wobba wuubu",
                          URL="https://example.com/")

96
97
98
        pkgbase3 = create(PackageBase, Name="gluggly-chungus",
                          Maintainer=user1,
                          Packager=user1)
99

100
101
102
103
104
105
106
107
108
109
110
        pkgbase4 = create(PackageBase, Name="fugly-chungus",
                          Maintainer=user1,
                          Packager=user1)

        desc = "A Package belonging to a PackageBase with another name."
        create(Package,
               PackageBase=pkgbase4,
               Name="other-pkg",
               Description=desc,
               URL="https://example.com")

111
112
113
114
115
116
        create(Package,
               PackageBase=pkgbase3,
               Name=pkgbase3.Name,
               Description="glurrba glurrba gur globba",
               URL="https://example.com/")

117
        pkgbase4 = create(PackageBase, Name="woogly-chungus")
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

        create(Package,
               PackageBase=pkgbase4,
               Name=pkgbase4.Name,
               Description="wuggla woblabeloop shemashmoop",
               URL="https://example.com/")

        # Dependencies.
        create(PackageDependency,
               Package=pkgname1,
               DependencyType=dependency_depends,
               DepName="chungus-depends")

        create(PackageDependency,
               Package=pkgname2,
               DependencyType=dependency_depends,
               DepName="chungy-depends")

        create(PackageDependency,
               Package=pkgname1,
               DependencyType=dependency_optdepends,
               DepName="chungus-optdepends",
               DepCondition="=50")

        create(PackageDependency,
               Package=pkgname1,
               DependencyType=dependency_makedepends,
               DepName="chungus-makedepends")

        create(PackageDependency,
               Package=pkgname1,
               DependencyType=dependency_checkdepends,
               DepName="chungus-checkdepends")

        # Relations.
        create(PackageRelation,
               Package=pkgname1,
               RelationType=relation_conflicts,
               RelName="chungus-conflicts")

        create(PackageRelation,
               Package=pkgname2,
               RelationType=relation_conflicts,
               RelName="chungy-conflicts")

        create(PackageRelation,
               Package=pkgname1,
               RelationType=relation_provides,
               RelName="chungus-provides",
               RelCondition="<=200")

        create(PackageRelation,
               Package=pkgname1,
               RelationType=relation_replaces,
               RelName="chungus-replaces",
               RelCondition="<=200")

        license = create(License, Name="GPL")

        create(PackageLicense,
               Package=pkgname1,
               License=license)

        for i in ["big-chungus", "smol-chungus", "sizeable-chungus"]:
            create(PackageKeyword,
                   PackageBase=pkgbase1,
                   Keyword=i)

        for i in [user1, user2, user3]:
            create(PackageVote,
                   User=i,
                   PackageBase=pkgbase1,
                   VoteTS=5000)

192
193
194
    conn = db.ConnectionExecutor(db.get_engine().raw_connection())
    scripts.popupdate.run_single(conn, pkgbase1)

195

Kevin Morris's avatar
Kevin Morris committed
196
197
198
199
200
201
202
203
204
205
206
207
@pytest.fixture
def pipeline():
    redis = redis_connection()
    pipeline = redis.pipeline()

    pipeline.delete("ratelimit-ws:testclient")
    pipeline.delete("ratelimit:testclient")
    one, two = pipeline.execute()

    yield pipeline


208
209
210
def test_rpc_singular_info():
    # Define expected response.
    expected_data = {
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
        "version": 5,
        "results": [{
            "Name": "big-chungus",
            "Version": "",
            "Description": "Bunny bunny around bunny",
            "URL": "https://example.com/",
            "PackageBase": "big-chungus",
            "NumVotes": 3,
            "Popularity": 0.0,
            "OutOfDate": None,
            "Maintainer": "user1",
            "URLPath": "/cgit/aur.git/snapshot/big-chungus.tar.gz",
            "Depends": ["chungus-depends"],
            "OptDepends": ["chungus-optdepends=50"],
            "MakeDepends": ["chungus-makedepends"],
            "CheckDepends": ["chungus-checkdepends"],
            "Conflicts": ["chungus-conflicts"],
            "Provides": ["chungus-provides<=200"],
            "Replaces": ["chungus-replaces<=200"],
            "License": ["GPL"],
            "Keywords": [
                "big-chungus",
                "sizeable-chungus",
                "smol-chungus"
            ]
        }],
        "resultcount": 1,
        "type": "multiinfo"
    }
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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

    # Make dummy request.
    response_arg = make_request("/rpc/?v=5&type=info&arg=chungy-chungus&arg=big-chungus")

    # Load  request response into Python dictionary.
    response_info_arg = orjson.loads(response_arg.content.decode())

    # Remove the FirstSubmitted LastModified, ID and PackageBaseID keys from
    # reponse, as the key's values aren't guaranteed to match between the two
    # (the keys are already removed from 'expected_data').
    for i in ["FirstSubmitted", "LastModified", "ID", "PackageBaseID"]:
        response_info_arg["results"][0].pop(i)

    # Validate that the new dictionaries are the same.
    assert response_info_arg == expected_data


def test_rpc_nonexistent_package():
    # Make dummy request.
    response = make_request("/rpc/?v=5&type=info&arg=nonexistent-package")

    # Load request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert response_data["resultcount"] == 0


def test_rpc_multiinfo():
    # Make dummy request.
    request_packages = ["big-chungus", "chungy-chungus"]
    response = make_request("/rpc/?v=5&type=info&arg[]=big-chungus&arg[]=chungy-chungus")

    # Load request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    for i in response_data["results"]:
        request_packages.remove(i["Name"])

    assert request_packages == []


def test_rpc_mixedargs():
    # Make dummy request.
    response1_packages = ["gluggly-chungus"]
    response2_packages = ["gluggly-chungus", "chungy-chungus"]

    response1 = make_request("/rpc/?v=5&arg[]=big-chungus&arg=gluggly-chungus&type=info")
    response2 = make_request("/rpc/?v=5&arg=big-chungus&arg[]=gluggly-chungus&type=info&arg[]=chungy-chungus")

    # Load request response into Python dictionary.
    response1_data = orjson.loads(response1.content.decode())
    response2_data = orjson.loads(response2.content.decode())

    # Validate data.
    for i in response1_data["results"]:
        response1_packages.remove(i["Name"])

    for i in response2_data["results"]:
        response2_packages.remove(i["Name"])

    for i in [response1_packages, response2_packages]:
        assert i == []


def test_rpc_no_dependencies():
    """This makes sure things like 'MakeDepends' get removed from JSON strings
    when they don't have set values."""

    expected_response = {
311
312
313
314
315
316
317
        'version': 5,
        'results': [{
            'Name': 'chungy-chungus',
            'Version': '',
            'Description': 'Wubby wubby on wobba wuubu',
            'URL': 'https://example.com/',
            'PackageBase': 'chungy-chungus',
318
            'NumVotes': 0,
319
320
321
322
323
324
325
326
327
328
329
330
            'Popularity': 0.0,
            'OutOfDate': None,
            'Maintainer': 'user1',
            'URLPath': '/cgit/aur.git/snapshot/chungy-chungus.tar.gz',
            'Depends': ['chungy-depends'],
            'Conflicts': ['chungy-conflicts'],
            'License': [],
            'Keywords': []
        }],
        'resultcount': 1,
        'type': 'multiinfo'
    }
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

    # Make dummy request.
    response = make_request("/rpc/?v=5&type=info&arg=chungy-chungus")
    response_data = orjson.loads(response.content.decode())

    # Remove inconsistent keys.
    for i in ["ID", "PackageBaseID", "FirstSubmitted", "LastModified"]:
        response_data["results"][0].pop(i)

    assert response_data == expected_response


def test_rpc_bad_type():
    # Define expected response.
    expected_data = {
346
347
348
349
350
351
        'version': 5,
        'results': [],
        'resultcount': 0,
        'type': 'error',
        'error': 'Incorrect request type specified.'
    }
352
353
354
355
356
357
358
359
360
361
362
363
364

    # Make dummy request.
    response = make_request("/rpc/?v=5&type=invalid-type&arg=big-chungus")

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


def test_rpc_bad_version():
    # Define expected response.
365
366
367
368
369
370
371
    expected_data = {
        'version': 0,
        'resultcount': 0,
        'results': [],
        'type': 'error',
        'error': 'Invalid version specified.'
    }
372
373
374
375
376
377
378
379
380
381
382
383
384

    # Make dummy request.
    response = make_request("/rpc/?v=0&type=info&arg=big-chungus")

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


def test_rpc_no_version():
    # Define expected response.
385
386
387
388
389
390
391
    expected_data = {
        'version': None,
        'resultcount': 0,
        'results': [],
        'type': 'error',
        'error': 'Please specify an API version.'
    }
392
393
394
395
396
397
398
399
400
401
402
403
404
405

    # Make dummy request.
    response = make_request("/rpc/?type=info&arg=big-chungus")

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


def test_rpc_no_type():
    # Define expected response.
    expected_data = {
406
407
408
409
410
411
        'version': 5,
        'results': [],
        'resultcount': 0,
        'type': 'error',
        'error': 'No request type/data specified.'
    }
412
413
414
415
416
417
418
419
420
421
422
423
424
425

    # Make dummy request.
    response = make_request("/rpc/?v=5&arg=big-chungus")

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


def test_rpc_no_args():
    # Define expected response.
    expected_data = {
426
427
428
429
430
431
        'version': 5,
        'results': [],
        'resultcount': 0,
        'type': 'error',
        'error': 'No request type/data specified.'
    }
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451

    # Make dummy request.
    response = make_request("/rpc/?v=5&type=info")

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


def test_rpc_no_maintainer():
    # Make dummy request.
    response = make_request("/rpc/?v=5&type=info&arg=woogly-chungus")

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert response_data["results"][0]["Maintainer"] is None
452
453
454
455
456
457
458
459
460
461


def test_rpc_suggest_pkgbase():
    response = make_request("/rpc?v=5&type=suggest-pkgbase&arg=big")
    data = response.json()
    assert data == ["big-chungus"]

    response = make_request("/rpc?v=5&type=suggest-pkgbase&arg=chungy")
    data = response.json()
    assert data == ["chungy-chungus"]
462

463
464
465
466
467
    # Test no arg supplied.
    response = make_request("/rpc?v=5&type=suggest-pkgbase")
    data = response.json()
    assert data == []

468

469
470
471
472
473
474
475
476
477
478
def test_rpc_suggest():
    response = make_request("/rpc?v=5&type=suggest&arg=other")
    data = response.json()
    assert data == ["other-pkg"]

    # Test non-existent Package.
    response = make_request("/rpc?v=5&type=suggest&arg=nonexistent")
    data = response.json()
    assert data == []

479
480
481
482
483
    # Test no arg supplied.
    response = make_request("/rpc?v=5&type=suggest")
    data = response.json()
    assert data == []

484

Kevin Morris's avatar
Kevin Morris committed
485
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
def mock_config_getint(section: str, key: str):
    if key == "request_limit":
        return 4
    elif key == "window_length":
        return 100
    return config.getint(section, key)


@mock.patch("aurweb.config.getint", side_effect=mock_config_getint)
def test_rpc_ratelimit(getint: mock.MagicMock, pipeline: Pipeline):
    for i in range(4):
        # The first 4 requests should be good.
        response = make_request("/rpc?v=5&type=suggest-pkgbase&arg=big")
        assert response.status_code == int(HTTPStatus.OK)

    # The fifth request should be banned.
    response = make_request("/rpc?v=5&type=suggest-pkgbase&arg=big")
    assert response.status_code == int(HTTPStatus.TOO_MANY_REQUESTS)

    # Delete the cached records.
    pipeline.delete("ratelimit-ws:testclient")
    pipeline.delete("ratelimit:testclient")
    one, two = pipeline.execute()
    assert one and two

    # The new first request should be good.
    response = make_request("/rpc?v=5&type=suggest-pkgbase&arg=big")
    assert response.status_code == int(HTTPStatus.OK)
513
514
515
516
517
518
519
520


def test_rpc_etag():
    response1 = make_request("/rpc?v=5&type=suggest-pkgbase&arg=big")
    response2 = make_request("/rpc?v=5&type=suggest-pkgbase&arg=big")
    assert response1.headers.get("ETag") is not None
    assert response1.headers.get("ETag") != str()
    assert response1.headers.get("ETag") == response2.headers.get("ETag")
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538


def test_rpc_search_arg_too_small():
    response = make_request("/rpc?v=5&type=search&arg=b")
    assert response.status_code == int(HTTPStatus.OK)
    assert response.json().get("error") == "Query arg too small."


def test_rpc_search():
    response = make_request("/rpc?v=5&type=search&arg=big")
    assert response.status_code == int(HTTPStatus.OK)

    data = response.json()
    assert data.get("resultcount") == 1

    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"

539
540
541
542
543
544
545
    # Test the If-None-Match headers.
    etag = response.headers.get("ETag").strip('"')
    headers = {"If-None-Match": etag}
    response = make_request("/rpc?v=5&type=search&arg=big", headers=headers)
    assert response.status_code == int(HTTPStatus.NOT_MODIFIED)
    assert response.content == b''

546
547
548
549
550
    # No args on non-m by types return an error.
    response = make_request("/rpc?v=5&type=search")
    assert response.json().get("error") == "No request type/data specified."


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
def test_rpc_msearch():
    response = make_request("/rpc?v=5&type=msearch&arg=user1")
    data = response.json()

    # user1 maintains 4 packages; assert that we got them all.
    assert data.get("resultcount") == 4
    names = list(sorted(r.get("Name") for r in data.get("results")))
    expected_results = list(sorted([
        "big-chungus",
        "chungy-chungus",
        "gluggly-chungus",
        "other-pkg"
    ]))
    assert names == expected_results

    # Search for a non-existent maintainer, giving us zero packages.
    response = make_request("/rpc?v=5&type=msearch&arg=blah-blah")
    data = response.json()
    assert data.get("resultcount") == 0

    # A missing arg still succeeds, but it returns all orphans.
    # Just verify that we receive no error and the orphaned result.
    response = make_request("/rpc?v=5&type=msearch")
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "woogly-chungus"


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
def test_rpc_search_depends():
    response = make_request(
        "/rpc?v=5&type=search&by=depends&arg=chungus-depends")
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"


def test_rpc_search_makedepends():
    response = make_request(
        "/rpc?v=5&type=search&by=makedepends&arg=chungus-makedepends")
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"


def test_rpc_search_optdepends():
    response = make_request(
        "/rpc?v=5&type=search&by=optdepends&arg=chungus-optdepends")
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"


def test_rpc_search_checkdepends():
    response = make_request(
        "/rpc?v=5&type=search&by=checkdepends&arg=chungus-checkdepends")
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"


def test_rpc_incorrect_by():
    response = make_request("/rpc?v=5&type=search&by=fake&arg=big")
    assert response.json().get("error") == "Incorrect by field specified."
619
620
621
622
623
624
625
626
627
628
629
630


def test_rpc_jsonp_callback():
    """ Test the callback parameter.

    For end-to-end verification, the `examples/jsonp.html` file can be
    used to submit jsonp callback requests to the RPC.
    """
    response = make_request(
        "/rpc?v=5&type=search&arg=big&callback=jsonCallback")
    assert response.headers.get("content-type") == "text/javascript"
    assert re.search(r'^/\*\*/jsonCallback\(.*\)$', response.text) is not None
631
632
633
634
635
636

    # Test an invalid callback name; we get an application/json error.
    response = make_request(
        "/rpc?v=5&type=search&arg=big&callback=jsonCallback!")
    assert response.headers.get("content-type") == "application/json"
    assert response.json().get("error") == "Invalid callback name."