|
1 | 1 | import pytest |
2 | | -from fastapi import Depends |
3 | | -from starlette.authentication import requires |
4 | 2 | from starlette.testclient import TestClient |
5 | 3 |
|
6 | 4 |
|
7 | 5 | @pytest.mark.parametrize( |
8 | 6 | "test_server_path, test_client_path, method, status_code, user, response_body", [ |
9 | 7 | ('/dataset1/resource2', '/dataset1/resource2', 'GET', 200, 'alice', 'ok'), |
| 8 | + ('/dataset1/resource2', '/dataset1/resource2', 'GET', 403, 'notalice', 'Forbidden'), |
| 9 | + ('/dataset1/resource1', '/dataset1/resource1', 'POST', 200, 'alice', 'ok'), |
10 | 10 | ] |
11 | 11 | ) |
12 | 12 | def test_middleware_authed(app_fixture, test_server_path, test_client_path, method, status_code, user, response_body): |
13 | | - # if method == 'GET': |
14 | | - # @app_fixture.get(test_server_path) |
15 | | - # async def index(): |
16 | | - # return 'ok' |
17 | | - # elif method == 'POST': |
18 | | - # @app_fixture.post(test_server_path) |
19 | | - # async def index(): |
20 | | - # return 'ok' |
21 | | - # elif method == 'PUT': |
22 | | - # @app_fixture.put(test_server_path) |
23 | | - # async def index(): |
24 | | - # return 'ok' |
| 13 | + @getattr(app_fixture, method.lower())(test_server_path) |
| 14 | + async def index(): |
| 15 | + return 'ok' |
25 | 16 |
|
| 17 | + test_client = TestClient(app_fixture) |
| 18 | + |
| 19 | + test_response = getattr(test_client, method.lower())(test_client_path, auth=(user, 'password')) |
| 20 | + |
| 21 | + assert test_response.status_code == status_code |
| 22 | + assert test_response.json() == response_body |
| 23 | + |
| 24 | + |
| 25 | +@pytest.mark.parametrize( |
| 26 | + "test_server_path, test_client_path, method, status_code, response_body", [ |
| 27 | + ('/login', '/login', 'GET', 200, 'ok'), |
| 28 | + ('/', '/', 'GET', 200, 'ok') |
| 29 | + ] |
| 30 | +) |
| 31 | +def test_middleware_not_authed(app_fixture, test_server_path, test_client_path, method, status_code, response_body): |
26 | 32 | @getattr(app_fixture, method.lower())(test_server_path) |
27 | 33 | async def index(): |
28 | 34 | return 'ok' |
29 | 35 |
|
30 | 36 | test_client = TestClient(app_fixture) |
31 | 37 |
|
32 | | - test_response = test_client.get(test_client_path, auth=(user, 'password')) |
| 38 | + test_response = getattr(test_client, method.lower())(test_client_path) |
33 | 39 |
|
34 | 40 | assert test_response.status_code == status_code |
35 | 41 | assert test_response.json() == response_body |
|
0 commit comments