Skip to content

🔁 💯

👆 ✔️ ⏪ 👀 ❔ 💯 👆 FastAPI 🈸 ⚙️ 🚚 TestClient. 🆙 🔜, 👆 ✔️ 🕴 👀 ❔ ✍ 🔁 💯, 🍵 ⚙️ async 🔢.

➖ 💪 ⚙️ 🔁 🔢 👆 💯 💪 ⚠, 🖼, 🕐❔ 👆 🔬 👆 💽 🔁. 🌈 👆 💚 💯 📨 📨 👆 FastAPI 🈸 & ⤴️ ✔ 👈 👆 👩‍💻 ⏪ ✍ ☑ 💽 💽, ⏪ ⚙️ 🔁 💽 🗃.

➡️ 👀 ❔ 👥 💪 ⚒ 👈 👷.

pytest.mark.anyio

🚥 👥 💚 🤙 🔁 🔢 👆 💯, 👆 💯 🔢 ✔️ 🔁. AnyIO 🚚 👌 📁 👉, 👈 ✔ 👥 ✔ 👈 💯 🔢 🤙 🔁.

🇸🇲

🚥 👆 FastAPI 🈸 ⚙️ 😐 def 🔢 ↩️ async def, ⚫️ async 🈸 🔘.

TestClient 🔨 🎱 🔘 🤙 🔁 FastAPI 🈸 👆 😐 def 💯 🔢, ⚙️ 🐩 ✳. ✋️ 👈 🎱 🚫 👷 🚫🔜 🕐❔ 👥 ⚙️ ⚫️ 🔘 🔁 🔢. 🏃 👆 💯 🔁, 👥 💪 🙅‍♂ 📏 ⚙️ TestClient 🔘 👆 💯 🔢.

TestClient ⚓️ 🔛 🇸🇲, & ↩️, 👥 💪 ⚙️ ⚫️ 🔗 💯 🛠️.

🖼

🙅 🖼, ➡️ 🤔 📁 📊 🎏 1️⃣ 🔬 🦏 🈸 & 🔬:

.
├── app
│   ├── __init__.py
│   ├── main.py
│   └── test_main.py

📁 main.py 🔜 ✔️:

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Tomato"}

📁 test_main.py 🔜 ✔️ 💯 main.py, ⚫️ 💪 👀 💖 👉 🔜:

import pytest
from httpx import AsyncClient

from .main import app


@pytest.mark.anyio
async def test_root():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Tomato"}

🏃 ⚫️

👆 💪 🏃 👆 💯 🐌 📨:

$ pytest

---> 100%

📑 @pytest.mark.anyio 💬 ✳ 👈 👉 💯 🔢 🔜 🤙 🔁:

import pytest
from httpx import AsyncClient

from .main import app


@pytest.mark.anyio
async def test_root():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Tomato"}

Tip

🗒 👈 💯 🔢 🔜 async def ↩️ def ⏭ 🕐❔ ⚙️ TestClient.

⤴️ 👥 💪 ✍ AsyncClient ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ await.

import pytest
from httpx import AsyncClient

from .main import app


@pytest.mark.anyio
async def test_root():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Tomato"}

👉 🌓:

response = client.get('/')

...👈 👥 ⚙️ ⚒ 👆 📨 ⏮️ TestClient.

Tip

🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 AsyncClient - 📨 🔁.

🎏 🔁 🔢 🤙

🔬 🔢 🔜 🔁, 👆 💪 🔜 🤙 (& await) 🎏 async 🔢 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 👆 💯, ⚫️❔ 👆 🔜 🤙 👫 🙆 🙆 👆 📟.

Tip

🚥 👆 ⚔ RuntimeError: Task attached to a different loop 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ ✳ MotorClient) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ '@app.on_event("startup") ⏲.