From 3e12918325fcde4cd749ac4c7957fa95ecbc584b Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:30:50 +0000 Subject: [PATCH 01/28] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20sche?= =?UTF-8?q?ma=5Fextra=5Fexample=20(#13197)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../test_tutorial001.py | 18 +- .../test_tutorial001_pv1.py | 18 +- .../test_tutorial001_pv1_py310.py | 129 ------------- .../test_tutorial001_py310.py | 135 ------------- .../test_tutorial004.py | 27 ++- .../test_tutorial004_an.py | 168 ----------------- .../test_tutorial004_an_py310.py | 177 ------------------ .../test_tutorial004_an_py39.py | 177 ------------------ .../test_tutorial004_py310.py | 177 ------------------ .../test_tutorial005.py | 21 ++- .../test_tutorial005_an.py | 166 ---------------- .../test_tutorial005_an_py310.py | 170 ----------------- .../test_tutorial005_an_py39.py | 170 ----------------- .../test_tutorial005_py310.py | 170 ----------------- 14 files changed, 65 insertions(+), 1658 deletions(-) delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py index 98b187355..c21cbb4bc 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py @@ -1,14 +1,22 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv2 +from ...utils import needs_py310, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py index 3520ef61d..b79f42e64 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py @@ -1,14 +1,22 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv1 +from ...utils import needs_py310, needs_pydanticv1 -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001_pv1 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001_pv1", + pytest.param("tutorial001_pv1_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py deleted file mode 100644 index b2a4d15b1..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py +++ /dev/null @@ -1,129 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001_pv1_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@needs_pydanticv1 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - # insert_assert(response.json()) - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"type": "integer", "title": "Item Id"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": {"type": "string", "title": "Description"}, - "price": {"type": "number", "title": "Price"}, - "tax": {"type": "number", "title": "Tax"}, - }, - "type": "object", - "required": ["name", "price"], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } - ], - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py deleted file mode 100644 index e63e33cda..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py +++ /dev/null @@ -1,135 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@needs_pydanticv2 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - # insert_assert(response.json()) - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "name": "item_id", - "in": "path", - "required": True, - "schema": {"type": "integer", "title": "Item Id"}, - } - ], - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - "price": {"type": "number", "title": "Price"}, - "tax": { - "anyOf": [{"type": "number"}, {"type": "null"}], - "title": "Tax", - }, - }, - "type": "object", - "required": ["name", "price"], - "title": "Item", - "examples": [ - { - "description": "A very nice Item", - "name": "Foo", - "price": 35.4, - "tax": 3.2, - } - ], - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py index eac0d1e29..61aefd12a 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py @@ -1,13 +1,30 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.schema_extra_example.tutorial004 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial004", + pytest.param("tutorial004_py310", marks=needs_py310), + "tutorial004_an", + pytest.param("tutorial004_an_py39", marks=needs_py39), + pytest.param("tutorial004_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -# Test required and embedded body parameters with no bodies sent -def test_post_body_example(): +def test_post_body_example(client: TestClient): response = client.put( "/items/5", json={ @@ -20,7 +37,7 @@ def test_post_body_example(): assert response.status_code == 200 -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py deleted file mode 100644 index a9cecd098..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py +++ /dev/null @@ -1,168 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.schema_extra_example.tutorial004_an import app - -client = TestClient(app) - - -# Test required and embedded body parameters with no bodies sent -def test_post_body_example(): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "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"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py deleted file mode 100644 index b6a735599..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py +++ /dev/null @@ -1,177 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial004_an_py310 import app - - client = TestClient(app) - return client - - -# Test required and embedded body parameters with no bodies sent -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "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"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py deleted file mode 100644 index 2493194a0..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py +++ /dev/null @@ -1,177 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial004_an_py39 import app - - client = TestClient(app) - return client - - -# Test required and embedded body parameters with no bodies sent -@needs_py39 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "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"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py deleted file mode 100644 index 15f54bd5a..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py +++ /dev/null @@ -1,177 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial004_py310 import app - - client = TestClient(app) - return client - - -# Test required and embedded body parameters with no bodies sent -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "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"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py index 94a40ed5a..12859227b 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py @@ -1,13 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39, needs_py310 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005 import app +@pytest.fixture( + name="client", + params=[ + "tutorial005", + pytest.param("tutorial005_py310", marks=needs_py310), + "tutorial005_an", + pytest.param("tutorial005_an_py39", marks=needs_py39), + pytest.param("tutorial005_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py deleted file mode 100644 index da92f98f6..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py +++ /dev/null @@ -1,166 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_an import app - - client = TestClient(app) - return client - - -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "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"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py deleted file mode 100644 index 9109cb14e..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "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"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py deleted file mode 100644 index fd4ec0575..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py39 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "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"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py deleted file mode 100644 index 05df53422..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "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"}, - }, - }, - } - }, - } From 818eb1f365dd6daad7746499120b10a0a1e0d42d Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:31:13 +0000 Subject: [PATCH 02/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 933b7271e..f1538d6f4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for schema_extra_example. PR [#13197](https://github.com/fastapi/fastapi/pull/13197) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_model. PR [#13195](https://github.com/fastapi/fastapi/pull/13195) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_forms_and_files. PR [#13185](https://github.com/fastapi/fastapi/pull/13185) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_forms. PR [#13184](https://github.com/fastapi/fastapi/pull/13184) by [@alejsdev](https://github.com/alejsdev). From 20079934334945cf1e527a37582742e1f8d6dbb0 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:35:40 +0000 Subject: [PATCH 03/28] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20secu?= =?UTF-8?q?rity=20(#13200)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_security/test_tutorial001.py | 28 +- .../test_security/test_tutorial001_an.py | 57 --- .../test_security/test_tutorial001_an_py39.py | 68 --- .../test_security/test_tutorial003.py | 40 +- .../test_security/test_tutorial003_an.py | 207 --------- .../test_tutorial003_an_py310.py | 223 --------- .../test_security/test_tutorial003_an_py39.py | 223 --------- .../test_security/test_tutorial003_py310.py | 223 --------- .../test_security/test_tutorial005.py | 108 +++-- .../test_security/test_tutorial005_an.py | 409 ---------------- .../test_tutorial005_an_py310.py | 437 ------------------ .../test_security/test_tutorial005_an_py39.py | 437 ------------------ .../test_security/test_tutorial005_py310.py | 437 ------------------ .../test_security/test_tutorial005_py39.py | 437 ------------------ .../test_security/test_tutorial006.py | 29 +- .../test_security/test_tutorial006_an.py | 65 --- .../test_security/test_tutorial006_an_py39.py | 77 --- 17 files changed, 146 insertions(+), 3359 deletions(-) delete mode 100644 tests/test_tutorial/test_security/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial003_an.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial003_an_py310.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial003_an_py39.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial003_py310.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_an.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_an_py310.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_an_py39.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_py310.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_py39.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial006_an.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial006_an_py39.py diff --git a/tests/test_tutorial/test_security/test_tutorial001.py b/tests/test_tutorial/test_security/test_tutorial001.py index 417bed8f7..f572d6e3e 100644 --- a/tests/test_tutorial/test_security/test_tutorial001.py +++ b/tests/test_tutorial/test_security/test_tutorial001.py @@ -1,31 +1,47 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.security.tutorial001 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_no_token(): +def test_no_token(client: TestClient): response = client.get("/items") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_token(): +def test_token(client: TestClient): response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"token": "testtoken"} -def test_incorrect_token(): +def test_incorrect_token(client: TestClient): response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial001_an.py b/tests/test_tutorial/test_security/test_tutorial001_an.py deleted file mode 100644 index 59460da7f..000000000 --- a/tests/test_tutorial/test_security/test_tutorial001_an.py +++ /dev/null @@ -1,57 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.security.tutorial001_an import app - -client = TestClient(app) - - -def test_no_token(): - response = client.get("/items") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_token(): - response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) - assert response.status_code == 200, response.text - assert response.json() == {"token": "testtoken"} - - -def test_incorrect_token(): - response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "security": [{"OAuth2PasswordBearer": []}], - } - } - }, - "components": { - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - } - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial001_an_py39.py b/tests/test_tutorial/test_security/test_tutorial001_an_py39.py deleted file mode 100644 index d8e712773..000000000 --- a/tests/test_tutorial/test_security/test_tutorial001_an_py39.py +++ /dev/null @@ -1,68 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/items") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) - assert response.status_code == 200, response.text - assert response.json() == {"token": "testtoken"} - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "security": [{"OAuth2PasswordBearer": []}], - } - } - }, - "components": { - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - } - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003.py b/tests/test_tutorial/test_security/test_tutorial003.py index 18d4680f6..7a4c99401 100644 --- a/tests/test_tutorial/test_security/test_tutorial003.py +++ b/tests/test_tutorial/test_security/test_tutorial003.py @@ -1,18 +1,36 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.security.tutorial003 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py310", marks=needs_py310), + "tutorial003_an", + pytest.param("tutorial003_an_py39", marks=needs_py39), + pytest.param("tutorial003_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_login(): +def test_login(client: TestClient): response = client.post("/token", data={"username": "johndoe", "password": "secret"}) assert response.status_code == 200, response.text assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} -def test_login_incorrect_password(): +def test_login_incorrect_password(client: TestClient): response = client.post( "/token", data={"username": "johndoe", "password": "incorrect"} ) @@ -20,20 +38,20 @@ def test_login_incorrect_password(): assert response.json() == {"detail": "Incorrect username or password"} -def test_login_incorrect_username(): +def test_login_incorrect_username(client: TestClient): response = client.post("/token", data={"username": "foo", "password": "secret"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "Incorrect username or password"} -def test_no_token(): +def test_no_token(client: TestClient): 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_token(): +def test_token(client: TestClient): response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) assert response.status_code == 200, response.text assert response.json() == { @@ -45,14 +63,14 @@ def test_token(): } -def test_incorrect_token(): +def test_incorrect_token(client: TestClient): response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Invalid authentication credentials"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_incorrect_token_type(): +def test_incorrect_token_type(client: TestClient): response = client.get( "/users/me", headers={"Authorization": "Notexistent testtoken"} ) @@ -61,13 +79,13 @@ def test_incorrect_token_type(): assert response.headers["WWW-Authenticate"] == "Bearer" -def test_inactive_user(): +def test_inactive_user(client: TestClient): response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "Inactive user"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial003_an.py b/tests/test_tutorial/test_security/test_tutorial003_an.py deleted file mode 100644 index a8f64d0c6..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_an.py +++ /dev/null @@ -1,207 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.security.tutorial003_an import app - -client = TestClient(app) - - -def test_login(): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -def test_login_incorrect_password(): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_login_incorrect_username(): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_no_token(): - 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_token(): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -def test_incorrect_token(): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_incorrect_token_type(): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_inactive_user(): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "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_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "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": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003_an_py310.py b/tests/test_tutorial/test_security/test_tutorial003_an_py310.py deleted file mode 100644 index 7cbbcee2f..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_an_py310.py +++ /dev/null @@ -1,223 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial003_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_inactive_user(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "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_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "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": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003_an_py39.py b/tests/test_tutorial/test_security/test_tutorial003_an_py39.py deleted file mode 100644 index 7b21fbcc9..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_an_py39.py +++ /dev/null @@ -1,223 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial003_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -@needs_py39 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_inactive_user(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "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_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "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": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003_py310.py b/tests/test_tutorial/test_security/test_tutorial003_py310.py deleted file mode 100644 index 512504534..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_py310.py +++ /dev/null @@ -1,223 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial003_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_inactive_user(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "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_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "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": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005.py b/tests/test_tutorial/test_security/test_tutorial005.py index 2e580dbb3..c7f791b03 100644 --- a/tests/test_tutorial/test_security/test_tutorial005.py +++ b/tests/test_tutorial/test_security/test_tutorial005.py @@ -1,18 +1,33 @@ +import importlib +from types import ModuleType + +import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.security.tutorial005 import ( - app, - create_access_token, - fake_users_db, - get_password_hash, - verify_password, +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="mod", + params=[ + "tutorial005", + pytest.param("tutorial005_py310", marks=needs_py310), + "tutorial005_an", + pytest.param("tutorial005_py39", marks=needs_py39), + pytest.param("tutorial005_an_py39", marks=needs_py39), + pytest.param("tutorial005_an_py310", marks=needs_py310), + ], ) +def get_mod(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -client = TestClient(app) + return mod -def get_access_token(username="johndoe", password="secret", scope=None): +def get_access_token( + *, username="johndoe", password="secret", scope=None, client: TestClient +): data = {"username": username, "password": password} if scope: data["scope"] = scope @@ -22,7 +37,8 @@ def get_access_token(username="johndoe", password="secret", scope=None): return access_token -def test_login(): +def test_login(mod: ModuleType): + client = TestClient(mod.app) response = client.post("/token", data={"username": "johndoe", "password": "secret"}) assert response.status_code == 200, response.text content = response.json() @@ -30,7 +46,8 @@ def test_login(): assert content["token_type"] == "bearer" -def test_login_incorrect_password(): +def test_login_incorrect_password(mod: ModuleType): + client = TestClient(mod.app) response = client.post( "/token", data={"username": "johndoe", "password": "incorrect"} ) @@ -38,21 +55,24 @@ def test_login_incorrect_password(): assert response.json() == {"detail": "Incorrect username or password"} -def test_login_incorrect_username(): +def test_login_incorrect_username(mod: ModuleType): + client = TestClient(mod.app) response = client.post("/token", data={"username": "foo", "password": "secret"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "Incorrect username or password"} -def test_no_token(): +def test_no_token(mod: ModuleType): + client = TestClient(mod.app) 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_token(): - access_token = get_access_token(scope="me") +def test_token(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token(scope="me", client=client) response = client.get( "/users/me", headers={"Authorization": f"Bearer {access_token}"} ) @@ -65,14 +85,16 @@ def test_token(): } -def test_incorrect_token(): +def test_incorrect_token(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Could not validate credentials"} assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_incorrect_token_type(): +def test_incorrect_token_type(mod: ModuleType): + client = TestClient(mod.app) response = client.get( "/users/me", headers={"Authorization": "Notexistent testtoken"} ) @@ -81,20 +103,24 @@ def test_incorrect_token_type(): assert response.headers["WWW-Authenticate"] == "Bearer" -def test_verify_password(): - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) +def test_verify_password(mod: ModuleType): + assert mod.verify_password( + "secret", mod.fake_users_db["johndoe"]["hashed_password"] + ) -def test_get_password_hash(): - assert get_password_hash("secretalice") +def test_get_password_hash(mod: ModuleType): + assert mod.get_password_hash("secretalice") -def test_create_access_token(): - access_token = create_access_token(data={"data": "foo"}) +def test_create_access_token(mod: ModuleType): + access_token = mod.create_access_token(data={"data": "foo"}) assert access_token -def test_token_no_sub(): +def test_token_no_sub(mod: ModuleType): + client = TestClient(mod.app) + response = client.get( "/users/me", headers={ @@ -106,7 +132,9 @@ def test_token_no_sub(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_no_username(): +def test_token_no_username(mod: ModuleType): + client = TestClient(mod.app) + response = client.get( "/users/me", headers={ @@ -118,8 +146,10 @@ def test_token_no_username(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_no_scope(): - access_token = get_access_token() +def test_token_no_scope(mod: ModuleType): + client = TestClient(mod.app) + + access_token = get_access_token(client=client) response = client.get( "/users/me", headers={"Authorization": f"Bearer {access_token}"} ) @@ -128,7 +158,9 @@ def test_token_no_scope(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_nonexistent_user(): +def test_token_nonexistent_user(mod: ModuleType): + client = TestClient(mod.app) + response = client.get( "/users/me", headers={ @@ -140,9 +172,11 @@ def test_token_nonexistent_user(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_inactive_user(): +def test_token_inactive_user(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token( - username="alice", password="secretalice", scope="me" + username="alice", password="secretalice", scope="me", client=client ) response = client.get( "/users/me", headers={"Authorization": f"Bearer {access_token}"} @@ -151,8 +185,9 @@ def test_token_inactive_user(): assert response.json() == {"detail": "Inactive user"} -def test_read_items(): - access_token = get_access_token(scope="me items") +def test_read_items(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token(scope="me items", client=client) response = client.get( "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} ) @@ -160,8 +195,9 @@ def test_read_items(): assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] -def test_read_system_status(): - access_token = get_access_token() +def test_read_system_status(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token(client=client) response = client.get( "/status/", headers={"Authorization": f"Bearer {access_token}"} ) @@ -169,14 +205,16 @@ def test_read_system_status(): assert response.json() == {"status": "ok"} -def test_read_system_status_no_token(): +def test_read_system_status_no_token(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/status/") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_openapi_schema(): +def test_openapi_schema(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial005_an.py b/tests/test_tutorial/test_security/test_tutorial005_an.py deleted file mode 100644 index 04c7d60bc..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_an.py +++ /dev/null @@ -1,409 +0,0 @@ -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from docs_src.security.tutorial005_an import ( - app, - create_access_token, - fake_users_db, - get_password_hash, - verify_password, -) - -client = TestClient(app) - - -def get_access_token(username="johndoe", password="secret", scope=None): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -def test_login(): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -def test_login_incorrect_password(): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_login_incorrect_username(): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_no_token(): - 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_token(): - access_token = get_access_token(scope="me") - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -def test_incorrect_token(): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_incorrect_token_type(): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_verify_password(): - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -def test_get_password_hash(): - assert get_password_hash("secretalice") - - -def test_create_access_token(): - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -def test_token_no_sub(): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_no_username(): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_no_scope(): - access_token = get_access_token() - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_nonexistent_user(): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_inactive_user(): - access_token = get_access_token( - username="alice", password="secretalice", scope="me" - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -def test_read_items(): - access_token = get_access_token(scope="me items") - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -def test_read_system_status(): - access_token = get_access_token() - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -def test_read_system_status_no_token(): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "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": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py b/tests/test_tutorial/test_security/test_tutorial005_an_py310.py deleted file mode 100644 index 9c7f83ed2..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_an_py310 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_verify_password(): - from docs_src.security.tutorial005_an_py310 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py310 -def test_get_password_hash(): - from docs_src.security.tutorial005_an_py310 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py310 -def test_create_access_token(): - from docs_src.security.tutorial005_an_py310 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py310 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_nonexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py310 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py310 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "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": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py b/tests/test_tutorial/test_security/test_tutorial005_an_py39.py deleted file mode 100644 index 04cc1b014..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_an_py39 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py39 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py39 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_verify_password(): - from docs_src.security.tutorial005_an_py39 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py39 -def test_get_password_hash(): - from docs_src.security.tutorial005_an_py39 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py39 -def test_create_access_token(): - from docs_src.security.tutorial005_an_py39 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py39 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_nonexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py39 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py39 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py39 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "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": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_py310.py b/tests/test_tutorial/test_security/test_tutorial005_py310.py deleted file mode 100644 index 98c60c1c2..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_py310.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_py310 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_verify_password(): - from docs_src.security.tutorial005_py310 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py310 -def test_get_password_hash(): - from docs_src.security.tutorial005_py310 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py310 -def test_create_access_token(): - from docs_src.security.tutorial005_py310 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py310 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_nonexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py310 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py310 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "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": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_py39.py b/tests/test_tutorial/test_security/test_tutorial005_py39.py deleted file mode 100644 index cd2157d54..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_py39.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_py39 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py39 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py39 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_verify_password(): - from docs_src.security.tutorial005_py39 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py39 -def test_get_password_hash(): - from docs_src.security.tutorial005_py39 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py39 -def test_create_access_token(): - from docs_src.security.tutorial005_py39 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py39 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_nonexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py39 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py39 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py39 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "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": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial006.py b/tests/test_tutorial/test_security/test_tutorial006.py index dc459b6fd..40b413806 100644 --- a/tests/test_tutorial/test_security/test_tutorial006.py +++ b/tests/test_tutorial/test_security/test_tutorial006.py @@ -1,26 +1,41 @@ +import importlib from base64 import b64encode +import pytest from fastapi.testclient import TestClient -from docs_src.security.tutorial006 import app +from ...utils import needs_py39 -client = TestClient(app) +@pytest.fixture( + name="client", + params=[ + "tutorial006", + "tutorial006_an", + pytest.param("tutorial006_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -def test_security_http_basic(): + client = TestClient(mod.app) + return client + + +def test_security_http_basic(client: TestClient): response = client.get("/users/me", auth=("john", "secret")) assert response.status_code == 200, response.text assert response.json() == {"username": "john", "password": "secret"} -def test_security_http_basic_no_credentials(): +def test_security_http_basic_no_credentials(client: TestClient): response = client.get("/users/me") assert response.json() == {"detail": "Not authenticated"} assert response.status_code == 401, response.text assert response.headers["WWW-Authenticate"] == "Basic" -def test_security_http_basic_invalid_credentials(): +def test_security_http_basic_invalid_credentials(client: TestClient): response = client.get( "/users/me", headers={"Authorization": "Basic notabase64token"} ) @@ -29,7 +44,7 @@ def test_security_http_basic_invalid_credentials(): assert response.json() == {"detail": "Invalid authentication credentials"} -def test_security_http_basic_non_basic_credentials(): +def test_security_http_basic_non_basic_credentials(client: TestClient): payload = b64encode(b"johnsecret").decode("ascii") auth_header = f"Basic {payload}" response = client.get("/users/me", headers={"Authorization": auth_header}) @@ -38,7 +53,7 @@ def test_security_http_basic_non_basic_credentials(): assert response.json() == {"detail": "Invalid authentication credentials"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial006_an.py b/tests/test_tutorial/test_security/test_tutorial006_an.py deleted file mode 100644 index 52ddd938f..000000000 --- a/tests/test_tutorial/test_security/test_tutorial006_an.py +++ /dev/null @@ -1,65 +0,0 @@ -from base64 import b64encode - -from fastapi.testclient import TestClient - -from docs_src.security.tutorial006_an import app - -client = TestClient(app) - - -def test_security_http_basic(): - response = client.get("/users/me", auth=("john", "secret")) - assert response.status_code == 200, response.text - assert response.json() == {"username": "john", "password": "secret"} - - -def test_security_http_basic_no_credentials(): - response = client.get("/users/me") - assert response.json() == {"detail": "Not authenticated"} - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - - -def test_security_http_basic_invalid_credentials(): - response = client.get( - "/users/me", headers={"Authorization": "Basic notabase64token"} - ) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -def test_security_http_basic_non_basic_credentials(): - payload = b64encode(b"johnsecret").decode("ascii") - auth_header = f"Basic {payload}" - response = client.get("/users/me", headers={"Authorization": auth_header}) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Current User", - "operationId": "read_current_user_users_me_get", - "security": [{"HTTPBasic": []}], - } - } - }, - "components": { - "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}} - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial006_an_py39.py b/tests/test_tutorial/test_security/test_tutorial006_an_py39.py deleted file mode 100644 index 52b22e573..000000000 --- a/tests/test_tutorial/test_security/test_tutorial006_an_py39.py +++ /dev/null @@ -1,77 +0,0 @@ -from base64 import b64encode - -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial006_an import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_security_http_basic(client: TestClient): - response = client.get("/users/me", auth=("john", "secret")) - assert response.status_code == 200, response.text - assert response.json() == {"username": "john", "password": "secret"} - - -@needs_py39 -def test_security_http_basic_no_credentials(client: TestClient): - response = client.get("/users/me") - assert response.json() == {"detail": "Not authenticated"} - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - - -@needs_py39 -def test_security_http_basic_invalid_credentials(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Basic notabase64token"} - ) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -@needs_py39 -def test_security_http_basic_non_basic_credentials(client: TestClient): - payload = b64encode(b"johnsecret").decode("ascii") - auth_header = f"Basic {payload}" - response = client.get("/users/me", headers={"Authorization": auth_header}) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Current User", - "operationId": "read_current_user_users_me_get", - "security": [{"HTTPBasic": []}], - } - } - }, - "components": { - "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}} - }, - } From 6d51389f75d0e5fff17edc0e71bba604a744e440 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:36:07 +0000 Subject: [PATCH 04/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f1538d6f4..a604e5169 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for security. PR [#13200](https://github.com/fastapi/fastapi/pull/13200) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for schema_extra_example. PR [#13197](https://github.com/fastapi/fastapi/pull/13197) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_model. PR [#13195](https://github.com/fastapi/fastapi/pull/13195) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_forms_and_files. PR [#13185](https://github.com/fastapi/fastapi/pull/13185) by [@alejsdev](https://github.com/alejsdev). From 39698df8069b8cd705dd4cb2194bbf447d3eec49 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:36:49 +0000 Subject: [PATCH 05/28] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20sepa?= =?UTF-8?q?rate=5Fopenapi=5Fschemas=20(#13201)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../test_tutorial001.py | 19 ++- .../test_tutorial001_py310.py | 136 ------------------ .../test_tutorial001_py39.py | 136 ------------------ .../test_tutorial002.py | 19 ++- .../test_tutorial002_py310.py | 136 ------------------ .../test_tutorial002_py39.py | 136 ------------------ 6 files changed, 28 insertions(+), 554 deletions(-) delete mode 100644 tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py delete mode 100644 tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py delete mode 100644 tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py delete mode 100644 tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py index cdfae9f8c..059fb889b 100644 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv2 +from ...utils import needs_py39, needs_py310, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + pytest.param("tutorial001_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest) -> TestClient: + mod = importlib.import_module(f"docs_src.separate_openapi_schemas.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py deleted file mode 100644 index 3b22146f6..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py310 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py deleted file mode 100644 index 991abe811..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial001_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py39 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py index d2cf7945b..cc9afeab7 100644 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv2 +from ...utils import needs_py39, needs_py310, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial002 import app +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + pytest.param("tutorial002_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest) -> TestClient: + mod = importlib.import_module(f"docs_src.separate_openapi_schemas.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py deleted file mode 100644 index 89c9ce977..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial002_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py310 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py deleted file mode 100644 index 6ac3d8f79..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial002_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py39 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } From b5e40a6233d93e8805ba4c843bc82893d074d31a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:37:13 +0000 Subject: [PATCH 06/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a604e5169..169345509 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for separate_openapi_schemas. PR [#13201](https://github.com/fastapi/fastapi/pull/13201) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for security. PR [#13200](https://github.com/fastapi/fastapi/pull/13200) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for schema_extra_example. PR [#13197](https://github.com/fastapi/fastapi/pull/13197) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_model. PR [#13195](https://github.com/fastapi/fastapi/pull/13195) by [@alejsdev](https://github.com/alejsdev). From 182c28e57acace06f9c3e9f11fd5096be5bac781 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:39:18 +0000 Subject: [PATCH 07/28] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20requ?= =?UTF-8?q?est=5Fform=5Fmodels=20=20(#13183)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem --- .../test_tutorial001.py | 19 +- .../test_tutorial001_an.py | 232 ----------------- .../test_tutorial001_an_py39.py | 240 ------------------ .../test_tutorial002.py | 19 +- .../test_tutorial002_an.py | 196 -------------- .../test_tutorial002_an_py39.py | 203 --------------- .../test_tutorial002_pv1.py | 26 +- .../test_tutorial002_pv1_an.py | 196 -------------- .../test_tutorial002_pv1_an_p39.py | 203 --------------- 9 files changed, 50 insertions(+), 1284 deletions(-) delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_an.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001.py b/tests/test_tutorial/test_request_form_models/test_tutorial001.py index 46c130ee8..1ca3c96d3 100644 --- a/tests/test_tutorial/test_request_form_models/test_tutorial001.py +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001.py @@ -1,13 +1,24 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_form_models.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py deleted file mode 100644 index 4e14d89c8..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py +++ /dev/null @@ -1,232 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial001_an import app - - client = TestClient(app) - return client - - -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "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/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py deleted file mode 100644 index 2e6426aa7..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py +++ /dev/null @@ -1,240 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from tests.utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -@needs_py39 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "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/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002.py b/tests/test_tutorial/test_request_form_models/test_tutorial002.py index 76f480001..b3f6be63a 100644 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002.py +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from tests.utils import needs_pydanticv2 +from ...utils import needs_py39, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002 import app +@pytest.fixture( + name="client", + params=[ + "tutorial002", + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_form_models.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py deleted file mode 100644 index 179b2977d..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py +++ /dev/null @@ -1,196 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from tests.utils import needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_an import app - - client = TestClient(app) - return client - - -@needs_pydanticv2 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -@needs_pydanticv2 -def test_post_body_extra_form(client: TestClient): - response = client.post( - "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} - ) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "extra_forbidden", - "loc": ["body", "extra"], - "msg": "Extra inputs are not permitted", - "input": "extra", - } - ] - } - - -@needs_pydanticv2 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - - -@needs_pydanticv2 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - - -@needs_pydanticv2 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - - -@needs_pydanticv2 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - - -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "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/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "additionalProperties": False, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py deleted file mode 100644 index 510ad9d7c..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py +++ /dev/null @@ -1,203 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from tests.utils import needs_py39, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_an_py39 import app - - client = TestClient(app) - return client - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_extra_form(client: TestClient): - response = client.post( - "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} - ) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "extra_forbidden", - "loc": ["body", "extra"], - "msg": "Extra inputs are not permitted", - "input": "extra", - } - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "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/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "additionalProperties": False, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py index 249b9379d..b503f23a5 100644 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py @@ -1,17 +1,27 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from tests.utils import needs_pydanticv1 +from ...utils import needs_py39, needs_pydanticv1 -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_pv1 import app +@pytest.fixture( + name="client", + params=[ + "tutorial002_pv1", + "tutorial002_pv1_an", + pytest.param("tutorial002_pv1_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_form_models.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_form(client: TestClient): response = client.post("/login/", data={"username": "Foo", "password": "secret"}) @@ -19,6 +29,7 @@ def test_post_body_form(client: TestClient): assert response.json() == {"username": "Foo", "password": "secret"} +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_extra_form(client: TestClient): response = client.post( @@ -36,6 +47,7 @@ def test_post_body_extra_form(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_form_no_password(client: TestClient): response = client.post("/login/", data={"username": "Foo"}) @@ -51,6 +63,7 @@ def test_post_body_form_no_password(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_form_no_username(client: TestClient): response = client.post("/login/", data={"password": "secret"}) @@ -66,6 +79,7 @@ def test_post_body_form_no_username(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_form_no_data(client: TestClient): response = client.post("/login/") @@ -86,6 +100,7 @@ def test_post_body_form_no_data(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_json(client: TestClient): response = client.post("/login/", json={"username": "Foo", "password": "secret"}) @@ -106,6 +121,7 @@ def test_post_body_json(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py deleted file mode 100644 index 44cb3c32b..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py +++ /dev/null @@ -1,196 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from tests.utils import needs_pydanticv1 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_pv1_an import app - - client = TestClient(app) - return client - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_extra_form(client: TestClient): - response = client.post( - "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} - ) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.extra", - "loc": ["body", "extra"], - "msg": "extra fields not permitted", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - }, - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - }, - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - }, - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - }, - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "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/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "additionalProperties": False, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py deleted file mode 100644 index 899549e40..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py +++ /dev/null @@ -1,203 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from tests.utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_pv1_an_py39 import app - - client = TestClient(app) - return client - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_extra_form(client: TestClient): - response = client.post( - "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} - ) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.extra", - "loc": ["body", "extra"], - "msg": "extra fields not permitted", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - }, - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - }, - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - }, - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - }, - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "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/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "additionalProperties": False, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "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"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From 9f3edbf537deb28ed56dd983b09156b365cfec87 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:39:42 +0000 Subject: [PATCH 08/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 169345509..162d8c752 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for request_form_models . PR [#13183](https://github.com/fastapi/fastapi/pull/13183) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for separate_openapi_schemas. PR [#13201](https://github.com/fastapi/fastapi/pull/13201) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for security. PR [#13200](https://github.com/fastapi/fastapi/pull/13200) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for schema_extra_example. PR [#13197](https://github.com/fastapi/fastapi/pull/13197) by [@alejsdev](https://github.com/alejsdev). From 280fe73c0398c912a38ffbf96e3897fc9cb78a5f Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:40:39 +0000 Subject: [PATCH 09/28] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20webs?= =?UTF-8?q?ockets=20(#13202)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_websockets/test_tutorial002.py | 33 ++++-- .../test_websockets/test_tutorial002_an.py | 88 --------------- .../test_tutorial002_an_py310.py | 102 ------------------ .../test_tutorial002_an_py39.py | 102 ------------------ .../test_websockets/test_tutorial002_py310.py | 102 ------------------ 5 files changed, 26 insertions(+), 401 deletions(-) delete mode 100644 tests/test_tutorial/test_websockets/test_tutorial002_an.py delete mode 100644 tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py delete mode 100644 tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py delete mode 100644 tests/test_tutorial/test_websockets/test_tutorial002_py310.py diff --git a/tests/test_tutorial/test_websockets/test_tutorial002.py b/tests/test_tutorial/test_websockets/test_tutorial002.py index bb5ccbf8e..51aa5752a 100644 --- a/tests/test_tutorial/test_websockets/test_tutorial002.py +++ b/tests/test_tutorial/test_websockets/test_tutorial002.py @@ -1,18 +1,37 @@ +import importlib + import pytest +from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi.websockets import WebSocketDisconnect -from docs_src.websockets.tutorial002 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="app", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_app(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.websockets.{request.param}") + + return mod.app -def test_main(): +def test_main(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"" in response.content -def test_websocket_with_cookie(): +def test_websocket_with_cookie(app: FastAPI): client = TestClient(app, cookies={"session": "fakesession"}) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/foo/ws") as websocket: @@ -30,7 +49,7 @@ def test_websocket_with_cookie(): assert data == f"Message text was: {message}, for item ID: foo" -def test_websocket_with_header(): +def test_websocket_with_header(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: @@ -48,7 +67,7 @@ def test_websocket_with_header(): assert data == f"Message text was: {message}, for item ID: bar" -def test_websocket_with_header_and_query(): +def test_websocket_with_header_and_query(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: @@ -70,7 +89,7 @@ def test_websocket_with_header_and_query(): assert data == f"Message text was: {message}, for item ID: 2" -def test_websocket_no_credentials(): +def test_websocket_no_credentials(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/foo/ws"): @@ -79,7 +98,7 @@ def test_websocket_no_credentials(): ) # pragma: no cover -def test_websocket_invalid_data(): +def test_websocket_invalid_data(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_an.py b/tests/test_tutorial/test_websockets/test_tutorial002_an.py deleted file mode 100644 index ec78d70d3..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_an.py +++ /dev/null @@ -1,88 +0,0 @@ -import pytest -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from docs_src.websockets.tutorial002_an import app - - -def test_main(): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -def test_websocket_with_cookie(): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -def test_websocket_with_header(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -def test_websocket_with_header_and_query(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -def test_websocket_no_credentials(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -def test_websocket_invalid_data(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py b/tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py deleted file mode 100644 index 23b4bcb78..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from ...utils import needs_py310 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.websockets.tutorial002_an_py310 import app - - return app - - -@needs_py310 -def test_main(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -@needs_py310 -def test_websocket_with_cookie(app: FastAPI): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -@needs_py310 -def test_websocket_with_header(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -@needs_py310 -def test_websocket_with_header_and_query(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -@needs_py310 -def test_websocket_no_credentials(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -@needs_py310 -def test_websocket_invalid_data(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py b/tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py deleted file mode 100644 index 2d77f05b3..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from ...utils import needs_py39 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.websockets.tutorial002_an_py39 import app - - return app - - -@needs_py39 -def test_main(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -@needs_py39 -def test_websocket_with_cookie(app: FastAPI): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -@needs_py39 -def test_websocket_with_header(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -@needs_py39 -def test_websocket_with_header_and_query(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -@needs_py39 -def test_websocket_no_credentials(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -@needs_py39 -def test_websocket_invalid_data(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_py310.py b/tests/test_tutorial/test_websockets/test_tutorial002_py310.py deleted file mode 100644 index 03bc27bdf..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_py310.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from ...utils import needs_py310 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.websockets.tutorial002_py310 import app - - return app - - -@needs_py310 -def test_main(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -@needs_py310 -def test_websocket_with_cookie(app: FastAPI): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -@needs_py310 -def test_websocket_with_header(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -@needs_py310 -def test_websocket_with_header_and_query(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -@needs_py310 -def test_websocket_no_credentials(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -@needs_py310 -def test_websocket_invalid_data(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover From 6ba09082a0b8455a890a4877c8ab1e3f143be8d1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:41:00 +0000 Subject: [PATCH 10/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 162d8c752..a242407ea 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for websockets. PR [#13202](https://github.com/fastapi/fastapi/pull/13202) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_form_models . PR [#13183](https://github.com/fastapi/fastapi/pull/13183) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for separate_openapi_schemas. PR [#13201](https://github.com/fastapi/fastapi/pull/13201) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for security. PR [#13200](https://github.com/fastapi/fastapi/pull/13200) by [@alejsdev](https://github.com/alejsdev). From 8fa18e5e6ff5ae6bb620bf4a7bd0d1964f10f2de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro?= Date: Wed, 22 Jan 2025 10:41:56 -0300 Subject: [PATCH 11/28] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20Tran?= =?UTF-8?q?slation=20for=20`docs/pt/docs/tutorial/request-forms.md`=20(#13?= =?UTF-8?q?216)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/request-forms.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index 756ceb581..572ddf003 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -6,7 +6,11 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pod Para usar formulários, primeiro instale `python-multipart`. -Ex: `pip install python-multipart`. +Lembre-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e então instalar a dependência, por exemplo: + +```console +$ pip install python-multipart +``` /// From a215687c987ea882ef6c4f0788b6c5a8b71f75ff Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 13:42:19 +0000 Subject: [PATCH 12/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a242407ea..5f527d37b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -49,6 +49,7 @@ hide: ### Translations +* 🌐 Update Portuguese Translation for `docs/pt/docs/tutorial/request-forms.md`. PR [#13216](https://github.com/fastapi/fastapi/pull/13216) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#13209](https://github.com/fastapi/fastapi/pull/13209) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/oauth2-jwt.md`. PR [#13205](https://github.com/fastapi/fastapi/pull/13205) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Indonesian translation for `docs/id/docs/index.md`. PR [#13191](https://github.com/fastapi/fastapi/pull/13191) by [@gerry-sabar](https://github.com/gerry-sabar). From 548f67d465afff233fa1856b2d337d13595e3308 Mon Sep 17 00:00:00 2001 From: Daniel Kusy <36250676+DanielKusyDev@users.noreply.github.com> Date: Wed, 22 Jan 2025 19:02:36 +0100 Subject: [PATCH 13/28] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20`jinja2`?= =?UTF-8?q?=20to=20>=3D3.1.5=20(#13194)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index edfa81522..ae56ebb7e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,7 +60,7 @@ standard = [ # For the test client "httpx >=0.23.0", # For templates - "jinja2 >=2.11.2", + "jinja2 >=3.1.5", # For forms and file uploads "python-multipart >=0.0.7", # To validate email fields @@ -79,7 +79,7 @@ all = [ # # For the test client "httpx >=0.23.0", # For templates - "jinja2 >=2.11.2", + "jinja2 >=3.1.5", # For forms and file uploads "python-multipart >=0.0.7", # For Starlette's SessionMiddleware, not commonly used with FastAPI From 1a38cc506e5732a8a0e2d4cfec3059f670a5ef90 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 18:03:00 +0000 Subject: [PATCH 14/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5f527d37b..d982a15f2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,10 @@ hide: * ✅ Simplify tests for background_tasks. PR [#13166](https://github.com/fastapi/fastapi/pull/13166) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for additional_status_codes. PR [#13149](https://github.com/fastapi/fastapi/pull/13149) by [@tiangolo](https://github.com/tiangolo). +### Upgrades + +* ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). + ### Docs * ✏️ Update Strawberry integration docs. PR [#13155](https://github.com/fastapi/fastapi/pull/13155) by [@kinuax](https://github.com/kinuax). From 82c74789e8c2ba68f4c88b6e8c80928881578272 Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Wed, 22 Jan 2025 19:21:40 +0100 Subject: [PATCH 15/28] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Bump=20Starlette=20t?= =?UTF-8?q?o=20allow=20up=20to=200.45.0:=20`>=3D0.40.0,<0.46.0`=20(#13117)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index ae56ebb7e..9510d36c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.40.0,<0.42.0", + "starlette>=0.40.0,<0.46.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] From 91c05b9245269502ea3d28569b3cbe2fa556e465 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 18:22:02 +0000 Subject: [PATCH 16/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d982a15f2..1951d6559 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Upgrades +* ⬆️ Bump Starlette to allow up to 0.45.0: `>=0.40.0,<0.46.0`. PR [#13117](https://github.com/fastapi/fastapi/pull/13117) by [@Kludex](https://github.com/Kludex). * ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). ### Docs From 49e82ed2ac63c2aad957d01c857ee1fe597dc4ca Mon Sep 17 00:00:00 2001 From: Daniel Kusy <36250676+DanielKusyDev@users.noreply.github.com> Date: Wed, 22 Jan 2025 19:23:13 +0100 Subject: [PATCH 17/28] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20`python-mu?= =?UTF-8?q?ltipart`=20to=20>=3D0.0.18=20(#13219)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9510d36c3..6fa0f080f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -62,7 +62,7 @@ standard = [ # For templates "jinja2 >=3.1.5", # For forms and file uploads - "python-multipart >=0.0.7", + "python-multipart >=0.0.18", # To validate email fields "email-validator >=2.0.0", # Uvicorn with uvloop @@ -81,7 +81,7 @@ all = [ # For templates "jinja2 >=3.1.5", # For forms and file uploads - "python-multipart >=0.0.7", + "python-multipart >=0.0.18", # For Starlette's SessionMiddleware, not commonly used with FastAPI "itsdangerous >=1.1.0", # For Starlette's schema generation, would not be used with FastAPI From e39143d56de41f8d72a3be8847030346cb1d8adc Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 18:24:12 +0000 Subject: [PATCH 18/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1951d6559..a806930f5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Upgrades +* ⬆️ Upgrade `python-multipart` to >=0.0.18. PR [#13219](https://github.com/fastapi/fastapi/pull/13219) by [@DanielKusyDev](https://github.com/DanielKusyDev). * ⬆️ Bump Starlette to allow up to 0.45.0: `>=0.40.0,<0.46.0`. PR [#13117](https://github.com/fastapi/fastapi/pull/13117) by [@Kludex](https://github.com/Kludex). * ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). From abd05a6d30e6e4c9b1496e0b94d362a9979c9f37 Mon Sep 17 00:00:00 2001 From: johnthagen Date: Wed, 22 Jan 2025 13:24:58 -0500 Subject: [PATCH 19/28] =?UTF-8?q?=F0=9F=94=A7=20Add=20Pydantic=202=20trove?= =?UTF-8?q?=20classifier=20(#13199)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 6fa0f080f..381eb50bf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,6 +29,7 @@ classifiers = [ "Framework :: FastAPI", "Framework :: Pydantic", "Framework :: Pydantic :: 1", + "Framework :: Pydantic :: 2", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3 :: Only", From 2b6f63df712f0ab98f071f64b3f8ac215ddf43be Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 18:25:24 +0000 Subject: [PATCH 20/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a806930f5..13976b788 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -110,6 +110,7 @@ hide: ### Internal +* 🔧 Add Pydantic 2 trove classifier. PR [#13199](https://github.com/fastapi/fastapi/pull/13199) by [@johnthagen](https://github.com/johnthagen). * 👥 Update FastAPI People - Sponsors. PR [#13231](https://github.com/fastapi/fastapi/pull/13231) by [@tiangolo](https://github.com/tiangolo). * 👷 Refactor FastAPI People Sponsors to use 2 tokens. PR [#13228](https://github.com/fastapi/fastapi/pull/13228) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token for FastAPI People - Sponsors. PR [#13225](https://github.com/fastapi/fastapi/pull/13225) by [@tiangolo](https://github.com/tiangolo). From 7183f0d683558390b973af8ad708e82567d4dc7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 22 Jan 2025 22:48:57 +0000 Subject: [PATCH 21/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 13976b788..c7f01b82f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,12 @@ hide: ## Latest Changes +### Upgrades + +* ⬆️ Upgrade `python-multipart` to >=0.0.18. PR [#13219](https://github.com/fastapi/fastapi/pull/13219) by [@DanielKusyDev](https://github.com/DanielKusyDev). +* ⬆️ Bump Starlette to allow up to 0.45.0: `>=0.40.0,<0.46.0`. PR [#13117](https://github.com/fastapi/fastapi/pull/13117) by [@Kludex](https://github.com/Kludex). +* ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). + ### Refactors * ✅ Simplify tests for websockets. PR [#13202](https://github.com/fastapi/fastapi/pull/13202) by [@alejsdev](https://github.com/alejsdev). @@ -33,12 +39,6 @@ hide: * ✅ Simplify tests for background_tasks. PR [#13166](https://github.com/fastapi/fastapi/pull/13166) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for additional_status_codes. PR [#13149](https://github.com/fastapi/fastapi/pull/13149) by [@tiangolo](https://github.com/tiangolo). -### Upgrades - -* ⬆️ Upgrade `python-multipart` to >=0.0.18. PR [#13219](https://github.com/fastapi/fastapi/pull/13219) by [@DanielKusyDev](https://github.com/DanielKusyDev). -* ⬆️ Bump Starlette to allow up to 0.45.0: `>=0.40.0,<0.46.0`. PR [#13117](https://github.com/fastapi/fastapi/pull/13117) by [@Kludex](https://github.com/Kludex). -* ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). - ### Docs * ✏️ Update Strawberry integration docs. PR [#13155](https://github.com/fastapi/fastapi/pull/13155) by [@kinuax](https://github.com/kinuax). From fe513719ea98abade167d8a89e92f600d9d8f0e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 22 Jan 2025 22:50:29 +0000 Subject: [PATCH 22/28] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.115.?= =?UTF-8?q?7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c7f01b82f..c8a75756b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.7 + ### Upgrades * ⬆️ Upgrade `python-multipart` to >=0.0.18. PR [#13219](https://github.com/fastapi/fastapi/pull/13219) by [@DanielKusyDev](https://github.com/DanielKusyDev). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 823957822..c92279cfd 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.115.6" +__version__ = "0.115.7" from starlette import status as status From 4d60022c88e6ba92a89df4860ba2df3af7e8c926 Mon Sep 17 00:00:00 2001 From: alv2017 Date: Thu, 23 Jan 2025 11:46:41 +0200 Subject: [PATCH 23/28] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translatio?= =?UTF-8?q?n=20for=20`docs/ru/docs/tutorial/bigger-applications.md`=20(#13?= =?UTF-8?q?154)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/tutorial/bigger-applications.md | 556 +++++++++++++++++++ 1 file changed, 556 insertions(+) create mode 100644 docs/ru/docs/tutorial/bigger-applications.md diff --git a/docs/ru/docs/tutorial/bigger-applications.md b/docs/ru/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..7c3dc288f --- /dev/null +++ b/docs/ru/docs/tutorial/bigger-applications.md @@ -0,0 +1,556 @@ +# Большие приложения, в которых много файлов + +При построении приложения или веб-API нам редко удается поместить всё в один файл. + +**FastAPI** предоставляет удобный инструментарий, который позволяет нам структурировать приложение, сохраняя при этом всю необходимую гибкость. + +/// info | Примечание + +Если вы раньше использовали Flask, то это аналог шаблонов Flask (Flask's Blueprints). + +/// + +## Пример структуры приложения + +Давайте предположим, что наше приложение имеет следующую структуру: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +/// tip | Подсказка + +Обратите внимание, что в каждом каталоге и подкаталоге имеется файл `__init__.py` + +Это как раз то, что позволяет импортировать код из одного файла в другой. + +Например, в файле `app/main.py` может быть следующая строка: + +``` +from app.routers import items +``` + +/// + +* Всё помещается в каталоге `app`. В нём также находится пустой файл `app/__init__.py`. Таким образом, `app` является "Python-пакетом" (коллекцией модулей Python). +* Он содержит файл `app/main.py`. Данный файл является частью пакета (т.е. находится внутри каталога, содержащего файл `__init__.py`), и, соответственно, он является модулем пакета: `app.main`. +* Он также содержит файл `app/dependencies.py`, который также, как и `app/main.py`, является модулем: `app.dependencies`. +* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является суб-пакетом: `app.routers`. +* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является суб-модулем: `app.routers.items`. +* Точно также `app/routers/users.py` является ещё одним суб-модулем: `app.routers.users`. +* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним суб-пакетом: `app.internal`. +* А файл `app/internal/admin.py` является ещё одним суб-модулем: `app.internal.admin`. + + + +Та же самая файловая структура приложения, но с комментариями: + +``` +. +├── app # "app" пакет +│   ├── __init__.py # этот файл превращает "app" в "Python-пакет" +│   ├── main.py # модуль "main", напр.: import app.main +│   ├── dependencies.py # модуль "dependencies", напр.: import app.dependencies +│   └── routers # суб-пакет "routers" +│   │ ├── __init__.py # превращает "routers" в суб-пакет +│   │ ├── items.py # суб-модуль "items", напр.: import app.routers.items +│   │ └── users.py # суб-модуль "users", напр.: import app.routers.users +│   └── internal # суб-пакет "internal" +│   ├── __init__.py # превращает "internal" в суб-пакет +│   └── admin.py # суб-модуль "admin", напр.: import app.internal.admin +``` + +## `APIRouter` + +Давайте предположим, что для работы с пользователями используется отдельный файл (суб-модуль) `/app/routers/users.py`. + +Для лучшей организации приложения, вы хотите отделить операции пути, связанные с пользователями, от остального кода. + +Но так, чтобы эти операции по-прежнему оставались частью **FastAPI** приложения/веб-API (частью одного пакета) + +С помощью `APIRouter` вы можете создать *операции пути* (*эндпоинты*) для данного модуля. + + +### Импорт `APIRouter` + +Точно также, как и в случае с классом `FastAPI`, вам нужно импортировать и создать объект класса `APIRouter`. + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### Создание *эндпоинтов* с помощью `APIRouter` + +В дальнейшем используйте `APIRouter` для объявления *эндпоинтов*, точно также, как вы используете класс `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Вы можете думать об `APIRouter` как об "уменьшенной версии" класса FastAPI`. + +`APIRouter` поддерживает все те же самые опции. + +`APIRouter` поддерживает все те же самые параметры, такие как `parameters`, `responses`, `dependencies`, `tags`, и т. д. + +/// tip | Подсказка + +В данном примере, в качестве названия переменной используется `router`, но вы можете использовать любое другое имя. + +/// + +Мы собираемся подключить данный `APIRouter` к нашему основному приложению на `FastAPI`, но сначала давайте проверим зависимости и создадим ещё один модуль с `APIRouter`. + +## Зависимости + +Нам понадобятся некоторые зависимости, которые мы будем использовать в разных местах нашего приложения. + +Мы поместим их в отдельный модуль `dependencies` (`app/dependencies.py`). + +Теперь мы воспользуемся простой зависимостью, чтобы прочитать кастомизированный `X-Token` из заголовка: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Подсказка + +Мы рекомендуем использовать версию `Annotated`, когда это возможно. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | Подсказка + +Для простоты мы воспользовались неким воображаемым заголовоком. + +В реальных случаях для получения наилучших результатов используйте интегрированные утилиты обеспечения безопасности [Security utilities](security/index.md){.internal-link target=_blank}. + +/// + +## Ещё один модуль с `APIRouter` + +Давайте также предположим, что у вас есть *эндпоинты*, отвечающие за обработку "items", и они находятся в модуле `app/routers/items.py`. + +У вас определены следующие *операции пути* (*эндпоинты*): + +* `/items/` +* `/items/{item_id}` + +Тут всё точно также, как и в ситуации с `app/routers/users.py`. + +Но теперь мы хотим поступить немного умнее и слегка упростить код. + +Мы знаем, что все *эндпоинты* данного модуля имеют некоторые общие свойства: + +* Префикс пути: `/items`. +* Теги: (один единственный тег: `items`). +* Дополнительные ответы (responses) +* Зависимости: использование созданной нами зависимости `X-token` + +Таким образом, вместо того чтобы добавлять все эти свойства в функцию каждого отдельного *эндпоинта*, +мы добавим их в `APIRouter`. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Так как каждый *эндпоинт* начинается с символа `/`: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...то префикс не должен заканчиваться символом `/`. + +В нашем случае префиксом является `/items`. + +Мы также можем добавить в наш маршрутизатор (router) список `тегов` (`tags`) и дополнительных `ответов` (`responses`), которые являются общими для каждого *эндпоинта*. + +И ещё мы можем добавить в наш маршрутизатор список `зависимостей`, которые должны вызываться при каждом обращении к *эндпоинтам*. + +/// tip | Подсказка + +Обратите внимание, что также, как и в случае с зависимостями в декораторах *эндпоинтов* ([dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), никакого значения в *функцию эндпоинта* передано не будет. + +/// + +В результате мы получим следующие эндпоинты: + +* `/items/` +* `/items/{item_id}` + +...как мы и планировали. + +* Они будут помечены тегами из заданного списка, в нашем случае это `"items"`. + * Эти теги особенно полезны для системы автоматической интерактивной документации (с использованием OpenAPI). +* Каждый из них будет включать предопределенные ответы `responses`. +* Каждый *эндпоинт* будет иметь список зависимостей (`dependencies`), исполняемых перед вызовом *эндпоинта*. + * Если вы определили зависимости в самой операции пути, **то она также будет выполнена**. + * Сначала выполняются зависимости маршрутизатора, затем вызываются зависимости, определенные в декораторе *эндпоинта* ([`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), и, наконец, обычные параметрические зависимости. + * Вы также можете добавить зависимости безопасности с областями видимости (`scopes`) [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. + +/// tip | Подсказка + +Например, с помощью зависимостей в `APIRouter` мы можем потребовать аутентификации для доступа ко всей группе *эндпоинтов*, не указывая зависимости для каждой отдельной функции *эндпоинта*. + +/// + +/// check | Заметка + +Параметры `prefix`, `tags`, `responses` и `dependencies` относятся к функционалу **FastAPI**, помогающему избежать дублирования кода. + +/// + +### Импорт зависимостей + +Наш код находится в модуле `app.routers.items` (файл `app/routers/items.py`). + +И нам нужно вызвать функцию зависимости из модуля `app.dependencies` (файл `app/dependencies.py`). + +Мы используем операцию относительного импорта `..` для импорта зависимости: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Как работает относительный импорт? + +/// tip | Подсказка + +Если вы прекрасно знаете, как работает импорт в Python, то переходите к следующему разделу. + +/// + +Одна точка `.`, как в данном примере: + +```Python +from .dependencies import get_token_header +``` +означает: + +* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` расположен в каталоге `app/routers/`)... +* ... найдите модуль `dependencies` (файл `app/routers/dependencies.py`)... +* ... и импортируйте из него функцию `get_token_header`. + +К сожалению, такого файла не существует, и наши зависимости находятся в файле `app/dependencies.py`. + +Вспомните, как выглядит файловая структура нашего приложения: + + + +--- + +Две точки `..`, как в данном примере: + +```Python +from ..dependencies import get_token_header +``` + +означают: + +* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)... +* ... перейдите в родительский пакет (каталог `app/`)... +* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)... +* ... и импортируйте из него функцию `get_token_header`. + +Это работает верно! 🎉 + +--- + +Аналогично, если бы мы использовали три точки `...`, как здесь: + +```Python +from ...dependencies import get_token_header +``` + +то это бы означало: + +* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)... +* ... перейдите в родительский пакет (каталог `app/`)... +* ... затем перейдите в родительский пакет текущего пакета (такого пакета не существует, `app` находится на самом верхнем уровне 😱)... +* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)... +* ... и импортируйте из него функцию `get_token_header`. + +Это будет относиться к некоторому пакету, находящемуся на один уровень выше чем `app/` и содержащему свой собственный файл `__init__.py`. Но ничего такого у нас нет. Поэтому это приведет к ошибке в нашем примере. 🚨 + +Теперь вы знаете, как работает импорт в Python, и сможете использовать относительное импортирование в своих собственных приложениях любого уровня сложности. 🤓 + +### Добавление пользовательских тегов (`tags`), ответов (`responses`) и зависимостей (`dependencies`) + +Мы не будем добавлять префикс `/items` и список тегов `tags=["items"]` для каждого *эндпоинта*, т.к. мы уже их добавили с помощью `APIRouter`. + +Но помимо этого мы можем добавить новые теги для каждого отдельного *эндпоинта*, а также некоторые дополнительные ответы (`responses`), характерные для данного *эндпоинта*: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | Подсказка + +Последний *эндпоинт* будет иметь следующую комбинацию тегов: `["items", "custom"]`. + +А также в его документации будут содержаться оба ответа: один для `404` и другой для `403`. + +/// + +## Модуль main в `FastAPI` + +Теперь давайте посмотрим на модуль `app/main.py`. + +Именно сюда вы импортируете и именно здесь вы используете класс `FastAPI`. + +Это основной файл вашего приложения, который объединяет всё в одно целое. + +И теперь, когда большая часть логики приложения разделена на отдельные модули, основной файл `app/main.py` будет достаточно простым. + +### Импорт `FastAPI` + +Вы импортируете и создаете класс `FastAPI` как обычно. + +Мы даже можем объявить глобальные зависимости [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank}, которые будут объединены с зависимостями для каждого отдельного маршрутизатора: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Импорт `APIRouter` + +Теперь мы импортируем другие суб-модули, содержащие `APIRouter`: + +```Python hl_lines="4-5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Так как файлы `app/routers/users.py` и `app/routers/items.py` являются суб-модулями одного и того же Python-пакета `app`, то мы сможем их импортировать, воспользовавшись операцией относительного импорта `.`. + +### Как работает импорт? + +Данная строка кода: + +```Python +from .routers import items, users +``` + +означает: + +* Начните с пакета, в котором содержится данный модуль (файл `app/main.py` содержится в каталоге `app/`)... +* ... найдите суб-пакет `routers` (каталог `app/routers/`)... +* ... и из него импортируйте суб-модули `items` (файл `app/routers/items.py`) и `users` (файл `app/routers/users.py`)... + +В модуле `items` содержится переменная `router` (`items.router`), та самая, которую мы создали в файле `app/routers/items.py`, она является объектом класса `APIRouter`. + +И затем мы сделаем то же самое для модуля `users`. + +Мы также могли бы импортировать и другим методом: + +```Python +from app.routers import items, users +``` + +/// info | Примечание + +Первая версия является примером относительного импорта: + +```Python +from .routers import items, users +``` + +Вторая версия является примером абсолютного импорта: + +```Python +from app.routers import items, users +``` + +Узнать больше о пакетах и модулях в Python вы можете из официальной документации Python о модулях + +/// + +### Избегайте конфликтов имен + +Вместо того чтобы импортировать только переменную `router`, мы импортируем непосредственно суб-модуль `items`. + +Мы делаем это потому, что у нас есть ещё одна переменная `router` в суб-модуле `users`. + +Если бы мы импортировали их одну за другой, как показано в примере: + +```Python +from .routers.items import router +from .routers.users import router +``` + +то переменная `router` из `users` переписал бы переменную `router` из `items`, и у нас не было бы возможности использовать их одновременно. + +Поэтому, для того чтобы использовать обе эти переменные в одном файле, мы импортировали соответствующие суб-модули: + +```Python hl_lines="5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Подключение маршрутизаторов (`APIRouter`) для `users` и для `items` + +Давайте подключим маршрутизаторы (`router`) из суб-модулей `users` и `items`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +/// info | Примечание + +`users.router` содержит `APIRouter` из файла `app/routers/users.py`. + +А `items.router` содержит `APIRouter` из файла `app/routers/items.py`. + +/// + +С помощью `app.include_router()` мы можем добавить каждый из маршрутизаторов (`APIRouter`) в основное приложение `FastAPI`. + +Он подключит все маршруты заданного маршрутизатора к нашему приложению. + +/// note | Технические детали + +Фактически, внутри он создаст все *операции пути* для каждой операции пути объявленной в `APIRouter`. + +И под капотом всё будет работать так, как будто бы мы имеем дело с одним файлом приложения. + +/// + +/// check | Заметка + +При подключении маршрутизаторов не стоит беспокоиться о производительности. + +Операция подключения займёт микросекунды и понадобится только при запуске приложения. + +Таким образом, это не повлияет на производительность. ⚡ + +/// + +### Подключение `APIRouter` с пользовательскими префиксом (`prefix`), тегами (`tags`), ответами (`responses`), и зависимостями (`dependencies`) + +Теперь давайте представим, что ваша организация передала вам файл `app/internal/admin.py`. + +Он содержит `APIRouter` с некоторыми *эндпоитами* администрирования, которые ваша организация использует для нескольких проектов. + +В данном примере это сделать очень просто. Но давайте предположим, что поскольку файл используется для нескольких проектов, +то мы не можем модифицировать его, добавляя префиксы (`prefix`), зависимости (`dependencies`), теги (`tags`), и т.д. непосредственно в `APIRouter`: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Но, несмотря на это, мы хотим использовать кастомный префикс (`prefix`) для подключенного маршрутизатора (`APIRouter`), в результате чего, каждая *операция пути* будет начинаться с `/admin`. Также мы хотим защитить наш маршрутизатор с помощью зависимостей, созданных для нашего проекта. И ещё мы хотим включить теги (`tags`) и ответы (`responses`). + +Мы можем применить все вышеперечисленные настройки, не изменяя начальный `APIRouter`. Нам всего лишь нужно передать нужные параметры в `app.include_router()`. + +```Python hl_lines="14-17" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Таким образом, оригинальный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации. + +В результате, в нашем приложении каждый *эндпоинт* модуля `admin` будет иметь: + +* Префикс `/admin`. +* Тег `admin`. +* Зависимость `get_token_header`. +* Ответ `418`. 🍵 + +Это будет иметь место исключительно для `APIRouter` в нашем приложении, и не затронет любой другой код, использующий его. + +Например, другие проекты, могут использовать тот же самый `APIRouter` с другими методами аутентификации. + +### Подключение отдельного *эндпоинта* + +Мы также можем добавить *эндпоинт* непосредственно в основное приложение `FastAPI`. + +Здесь мы это делаем ... просто, чтобы показать, что это возможно 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +и это будет работать корректно вместе с другими *эндпоинтами*, добавленными с помощью `app.include_router()`. + +/// info | Сложные технические детали + +**Примечание**: это сложная техническая деталь, которую, скорее всего, **вы можете пропустить**. + +--- + +Маршрутизаторы (`APIRouter`) не "монтируются" по-отдельности и не изолируются от остального приложения. + +Это происходит потому, что нужно включить их *эндпоинты* в OpenAPI схему и в интерфейс пользователя. + +В силу того, что мы не можем их изолировать и "примонтировать" независимо от остальных, *эндпоинты* клонируются (пересоздаются) и не подключаются напрямую. + +/// + +## Проверка автоматической документации API + +Теперь запустите приложение: + +
+ +```console +$ fastapi dev app/main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Откройте документацию по адресу http://127.0.0.1:8000/docs. + +Вы увидите автоматическую API документацию. Она включает в себя маршруты из суб-модулей, используя верные маршруты, префиксы и теги: + + + +## Подключение существующего маршрута через новый префикс (`prefix`) + +Вы можете использовать `.include_router()` несколько раз с одним и тем же маршрутом, применив различные префиксы. + +Это может быть полезным, если нужно предоставить доступ к одному и тому же API через различные префиксы, например, `/api/v1` и `/api/latest`. + +Это продвинутый способ, который вам может и не пригодится. Мы приводим его на случай, если вдруг вам это понадобится. + +## Включение одного маршрутизатора (`APIRouter`) в другой + +Точно так же, как вы включаете `APIRouter` в приложение `FastAPI`, вы можете включить `APIRouter` в другой `APIRouter`: + +```Python +router.include_router(other_router) +``` + +Удостоверьтесь, что вы сделали это до того, как подключить маршрутизатор (`router`) к вашему `FastAPI` приложению, и *эндпоинты* маршрутизатора `other_router` были также подключены. From b6f6818d76f312fe30d798e52fff16927649db0a Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 23 Jan 2025 09:47:05 +0000 Subject: [PATCH 24/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c8a75756b..bc725fafe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`. PR [#13154](https://github.com/fastapi/fastapi/pull/13154) by [@alv2017](https://github.com/alv2017). + ## 0.115.7 ### Upgrades From 0e2d8d64a427905d673ecee9cfeaf9e74ed979e4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 24 Jan 2025 17:05:11 +0000 Subject: [PATCH 25/28] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-pu?= =?UTF-8?q?blish=20from=201.12.3=20to=201.12.4=20(#13251)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.12.3 to 1.12.4. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.12.3...v1.12.4) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 38df75928..bf88d59b1 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.12.3 + uses: pypa/gh-action-pypi-publish@v1.12.4 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 6bbd315f3e7c08893591729cfb61a19eadb73eae Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 24 Jan 2025 17:05:37 +0000 Subject: [PATCH 26/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bc725fafe..b1020d6e4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`. PR [#13154](https://github.com/fastapi/fastapi/pull/13154) by [@alv2017](https://github.com/alv2017). +### Internal + +* ⬆ Bump pypa/gh-action-pypi-publish from 1.12.3 to 1.12.4. PR [#13251](https://github.com/fastapi/fastapi/pull/13251) by [@dependabot[bot]](https://github.com/apps/dependabot). + ## 0.115.7 ### Upgrades From 998a9139d3e34100874712f5a9261cdc67f8d4ed Mon Sep 17 00:00:00 2001 From: Rishat-F <66554797+Rishat-F@users.noreply.github.com> Date: Fri, 24 Jan 2025 22:44:31 +0300 Subject: [PATCH 27/28] =?UTF-8?q?=F0=9F=8C=90=20Update=20Russian=20transla?= =?UTF-8?q?tion=20for=20`docs/ru/docs/tutorial/dependencies/dependencies-i?= =?UTF-8?q?n-path-operation-decorators.md`=20(#13252)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/dependencies-in-path-operation-decorators.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index f9b9dec25..0e4eb95be 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -18,7 +18,7 @@ Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. -/// подсказка +/// tip | Подсказка Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку. @@ -28,7 +28,7 @@ /// -/// дополнительная | информация +/// info | Примечание В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`. From 1e44825ef2143e37e51edb86ae44d408d9dbb756 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 24 Jan 2025 19:44:54 +0000 Subject: [PATCH 28/28] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b1020d6e4..f25648b9a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#13252](https://github.com/fastapi/fastapi/pull/13252) by [@Rishat-F](https://github.com/Rishat-F). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`. PR [#13154](https://github.com/fastapi/fastapi/pull/13154) by [@alv2017](https://github.com/alv2017). ### Internal