Skip to content

Commit 0deef03

Browse files
committed
GH-7: Add login simulation for testing the new security module
1 parent 4b3e6a6 commit 0deef03

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

tests/test_oauth2_middleware.py

+44
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,47 @@
11
import pytest
2+
from fastapi import APIRouter
3+
from fastapi import Depends
24
from fastapi import FastAPI
5+
from fastapi import Request
36
from httpx import AsyncClient
47
from social_core.backends.github import GithubOAuth2
8+
from starlette.responses import Response
59

610
from fastapi_oauth2.client import OAuth2Client
711
from fastapi_oauth2.core import OAuth2Core
812
from fastapi_oauth2.middleware import OAuth2Middleware
913
from fastapi_oauth2.router import router as oauth2_router
14+
from fastapi_oauth2.security import OAuth2
1015

1116
app = FastAPI()
17+
oauth2 = OAuth2()
18+
app_router = APIRouter()
1219

20+
21+
@app_router.get("/user")
22+
def user(request: Request, _: str = Depends(oauth2)):
23+
return request.user
24+
25+
26+
@app_router.get("/auth")
27+
def auth(request: Request):
28+
access_token = request.auth.jwt_create({
29+
"name": "test",
30+
"sub": "test",
31+
"id": "test",
32+
})
33+
response = Response()
34+
response.set_cookie(
35+
"Authorization",
36+
value=f"Bearer {access_token}",
37+
max_age=request.auth.expires,
38+
expires=request.auth.expires,
39+
httponly=request.auth.http,
40+
)
41+
return response
42+
43+
44+
app.include_router(app_router)
1345
app.include_router(oauth2_router)
1446
app.add_middleware(OAuth2Middleware, config={
1547
"allow_http": True,
@@ -30,6 +62,18 @@ async def test_auth_redirect():
3062
assert response.status_code == 303 # Redirect
3163

3264

65+
@pytest.mark.anyio
66+
async def test_authenticated_request():
67+
async with AsyncClient(app=app, base_url="http://test") as client:
68+
response = await client.get("/user")
69+
assert response.status_code == 403 # Forbidden
70+
71+
await client.get("/auth") # Simulate login
72+
73+
response = await client.get("/user")
74+
assert response.status_code == 200 # OK
75+
76+
3377
@pytest.mark.anyio
3478
async def test_core_init(backends):
3579
for backend in backends:

0 commit comments

Comments
 (0)