ycdemo / fastapi / tests/ test_security_oauth2.py

import pytest
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel

app = FastAPI()

reusable_oauth2 = OAuth2(
    flows={
        "password": {
            "tokenUrl": "token",
            "scopes": {"read:users": "Read the users", "write:users": "Create users"},
        }
    }
)


class User(BaseModel):
    username: str


# Here we use string annotations to test them
def get_current_user(oauth_header: "str" = Security(reusable_oauth2)):
    user = User(username=oauth_header)
    return user


@app.post("/login")
# Here we use string annotations to test them
def login(form_data: "OAuth2PasswordRequestFormStrict" = Depends()):
    return form_data


@app.get("/users/me")
# Here we use string annotations to test them
def read_current_user(current_user: "User" = Depends(get_current_user)):
    return current_user


client = TestClient(app)


def test_security_oauth2():
    response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
    assert response.status_code == 200, response.text
    assert response.json() == {"username": "Bearer footokenbar"}


def test_security_oauth2_password_other_header():
    response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
    assert response.status_code == 200, response.text
    assert response.json() == {"username": "Other footokenbar"}


def test_security_oauth2_password_bearer_no_header():
    response = client.get("/users/me")
    assert response.status_code == 401, response.text
    assert response.json() == {"detail": "Not authenticated"}
    assert response.headers["WWW-Authenticate"] == "Bearer"


def test_strict_login_no_data():
    response = client.post("/login")
    assert response.status_code == 422
    assert response.json() == {
        "detail": [
            {
                "type": "missing",
                "loc": ["body", "grant_type"],
                "msg": "Field required",
                "input": None,
            },
            {
                "type": "missing",
                "loc": ["body", "username"],
                "msg": "Field required",
                "input": None,
            },
            {
                "type": "missing",
                "loc": ["body", "password"],
                "msg": "Field required",
                "input": None,
            },
        ]
    }


def test_strict_login_no_grant_type():
    response = client.post("/login", data={"username": "johndoe", "password": "secret"})
    assert response.status_code == 422
    assert response.json() == {
        "detail": [
            {
                "type": "missing",
                "loc": ["body", "grant_type"],
                "msg": "Field required",
                "input": None,
            }
        ]
    }


@pytest.mark.parametrize(
    argnames=["grant_type"],
    argvalues=[
        pytest.param("incorrect", id="incorrect value"),
        pytest.param("passwordblah", id="password with suffix"),
        pytest.param("blahpassword", id="password with prefix"),
    ],
)
def test_strict_login_incorrect_grant_type(grant_type: str):
    response = client.post(
        "/login",
        data={"username": "johndoe", "password": "secret", "grant_type": grant_type},
    )
    assert response.status_code == 422
    assert response.json() == {
        "detail": [
            {
                "type": "string_pattern_mismatch",
                "loc": ["body", "grant_type"],
                "msg": "String should match pattern '^password
		
		
		
		
	

",
                "input": grant_type,
                "ctx": {"pattern": "^password$"},
            }
        ]
    }


def test_strict_login_correct_grant_type():
    response = client.post(
        "/login",
        data={"username": "johndoe", "password": "secret", "grant_type": "password"},
    )
    assert response.status_code == 200
    assert response.json() == {
        "grant_type": "password",
        "username": "johndoe",
        "password": "secret",
        "scopes": [],
        "client_id": None,
        "client_secret": None,
    }


def test_openapi_schema():
    response = client.get("/openapi.json")
    assert response.status_code == 200, response.text
    assert response.json() == snapshot(
        {
            "openapi": "3.1.0",
            "info": {"title": "FastAPI", "version": "0.1.0"},
            "paths": {
                "/login": {
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Successful Response",
                                "content": {"application/json": {"schema": {}}},
                            },
                            "422": {
                                "description": "Validation Error",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "$ref": "#/components/schemas/HTTPValidationError"
                                        }
                                    }
                                },
                            },
                        },
                        "summary": "Login",
                        "operationId": "login_login_post",
                        "requestBody": {
                            "content": {
                                "application/x-www-form-urlencoded": {
                                    "schema": {
                                        "$ref": "#/components/schemas/Body_login_login_post"
                                    }
                                }
                            },
                            "required": True,
                        },
                    }
                },
                "/users/me": {
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Successful Response",
                                "content": {"application/json": {"schema": {}}},
                            }
                        },
                        "summary": "Read Current User",
                        "operationId": "read_current_user_users_me_get",
                        "security": [{"OAuth2": []}],
                    }
                },
            },
            "components": {
                "schemas": {
                    "Body_login_login_post": {
                        "title": "Body_login_login_post",
                        "required": ["grant_type", "username", "password"],
                        "type": "object",
                        "properties": {
                            "grant_type": {
                                "title": "Grant Type",
                                "pattern": "^password$",
                                "type": "string",
                            },
                            "username": {"title": "Username", "type": "string"},
                            "password": {"title": "Password", "type": "string"},
                            "scope": {
                                "title": "Scope",
                                "type": "string",
                                "default": "",
                            },
                            "client_id": {
                                "title": "Client Id",
                                "anyOf": [{"type": "string"}, {"type": "null"}],
                            },
                            "client_secret": {
                                "title": "Client Secret",
                                "anyOf": [{"type": "string"}, {"type": "null"}],
                            },
                        },
                    },
                    "ValidationError": {
                        "title": "ValidationError",
                        "required": ["loc", "msg", "type"],
                        "type": "object",
                        "properties": {
                            "loc": {
                                "title": "Location",
                                "type": "array",
                                "items": {
                                    "anyOf": [{"type": "string"}, {"type": "integer"}]
                                },
                            },
                            "msg": {"title": "Message", "type": "string"},
                            "type": {"title": "Error Type", "type": "string"},
                            "input": {"title": "Input"},
                            "ctx": {"title": "Context", "type": "object"},
                        },
                    },
                    "HTTPValidationError": {
                        "title": "HTTPValidationError",
                        "type": "object",
                        "properties": {
                            "detail": {
                                "title": "Detail",
                                "type": "array",
                                "items": {
                                    "$ref": "#/components/schemas/ValidationError"
                                },
                            }
                        },
                    },
                },
                "securitySchemes": {
                    "OAuth2": {
                        "type": "oauth2",
                        "flows": {
                            "password": {
                                "scopes": {
                                    "read:users": "Read the users",
                                    "write:users": "Create users",
                                },
                                "tokenUrl": "token",
                            }
                        },
                    }
                },
            },
        }
    )
\",\n \"input\": grant_type,\n \"ctx\": {\"pattern\": \"^password$\"},\n }\n ]\n }\n\n\ndef test_strict_login_correct_grant_type():\n response = client.post(\n \"/login\",\n data={\"username\": \"johndoe\", \"password\": \"secret\", \"grant_type\": \"password\"},\n )\n assert response.status_code == 200\n assert response.json() == {\n \"grant_type\": \"password\",\n \"username\": \"johndoe\",\n \"password\": \"secret\",\n \"scopes\": [],\n \"client_id\": None,\n \"client_secret\": None,\n }\n\n\ndef test_openapi_schema():\n response = client.get(\"/openapi.json\")\n assert response.status_code == 200, response.text\n assert response.json() == snapshot(\n {\n \"openapi\": \"3.1.0\",\n \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n \"paths\": {\n \"/login\": {\n \"post\": {\n \"responses\": {\n \"200\": {\n \"description\": \"Successful Response\",\n \"content\": {\"application/json\": {\"schema\": {}}},\n },\n \"422\": {\n \"description\": \"Validation Error\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"$ref\": \"#/components/schemas/HTTPValidationError\"\n }\n }\n },\n },\n },\n \"summary\": \"Login\",\n \"operationId\": \"login_login_post\",\n \"requestBody\": {\n \"content\": {\n \"application/x-www-form-urlencoded\": {\n \"schema\": {\n \"$ref\": \"#/components/schemas/Body_login_login_post\"\n }\n }\n },\n \"required\": True,\n },\n }\n },\n \"/users/me\": {\n \"get\": {\n \"responses\": {\n \"200\": {\n \"description\": \"Successful Response\",\n \"content\": {\"application/json\": {\"schema\": {}}},\n }\n },\n \"summary\": \"Read Current User\",\n \"operationId\": \"read_current_user_users_me_get\",\n \"security\": [{\"OAuth2\": []}],\n }\n },\n },\n \"components\": {\n \"schemas\": {\n \"Body_login_login_post\": {\n \"title\": \"Body_login_login_post\",\n \"required\": [\"grant_type\", \"username\", \"password\"],\n \"type\": \"object\",\n \"properties\": {\n \"grant_type\": {\n \"title\": \"Grant Type\",\n \"pattern\": \"^password$\",\n \"type\": \"string\",\n },\n \"username\": {\"title\": \"Username\", \"type\": \"string\"},\n \"password\": {\"title\": \"Password\", \"type\": \"string\"},\n \"scope\": {\n \"title\": \"Scope\",\n \"type\": \"string\",\n \"default\": \"\",\n },\n \"client_id\": {\n \"title\": \"Client Id\",\n \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}],\n },\n \"client_secret\": {\n \"title\": \"Client Secret\",\n \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}],\n },\n },\n },\n \"ValidationError\": {\n \"title\": \"ValidationError\",\n \"required\": [\"loc\", \"msg\", \"type\"],\n \"type\": \"object\",\n \"properties\": {\n \"loc\": {\n \"title\": \"Location\",\n \"type\": \"array\",\n \"items\": {\n \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n },\n },\n \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n \"type\": {\"title\": \"Error Type\", \"type\": \"string\"},\n \"input\": {\"title\": \"Input\"},\n \"ctx\": {\"title\": \"Context\", \"type\": \"object\"},\n },\n },\n \"HTTPValidationError\": {\n \"title\": \"HTTPValidationError\",\n \"type\": \"object\",\n \"properties\": {\n \"detail\": {\n \"title\": \"Detail\",\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/components/schemas/ValidationError\"\n },\n }\n },\n },\n },\n \"securitySchemes\": {\n \"OAuth2\": {\n \"type\": \"oauth2\",\n \"flows\": {\n \"password\": {\n \"scopes\": {\n \"read:users\": \"Read the users\",\n \"write:users\": \"Create users\",\n },\n \"tokenUrl\": \"token\",\n }\n },\n }\n },\n },\n }\n )\n","preview":null,"history":null,"version":"1c216e95d838819e58f6a0b46e1c7ce10801eb53"},"/_session?shell=1":null}