You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5.2 KiB

🔬

👏 💃, 🔬 FastAPI 🈸 & 😌.

🔛 🇸🇲, 🔄 🏗 🔛 📨, 📶 😰 & 🏋️.

⏮️ ️, 👆 💪 ⚙️ 🔗 ⏮️ FastAPI.

⚙️ TestClient

!!! info ⚙️ TestClient, 🥇 httpx.

🤶 Ⓜ. `pip install httpx`.

🗄 TestClient.

TestClient 🚶‍♀️ 👆 FastAPI 🈸 ️.

🔢 ⏮️ 📛 👈 ▶️ ⏮️ test_ (👉 🐩 pytest 🏛).

⚙️ TestClient 🎚 🎏 🌌 👆 ⏮️ httpx.

🙅 assert 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 (🔄, 🐩 pytest).

{!../../../docs_src/app_testing/tutorial001.py!}

!!! tip 👀 👈 🔬 🔢 😐 def, 🚫 async def.

 & 🤙 👩‍💻 😐 🤙, 🚫 ⚙️ `await`.

👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢.

!!! note "📡 ℹ" 👆 💪 ⚙️ from starlette.testclient import TestClient.

**FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.

!!! tip 🚥 👆 💚 🤙 async 🔢 👆 💯 ↖️ ➡️ 📨 📨 👆 FastAPI 🈸 ( 🔁 💽 🔢), ✔️ 👀 🔁 💯{.internal-link target=_blank} 🏧 🔰.

🎏 💯

🎰 🈸, 👆 🎲 🔜 ✔️ 👆 💯 🎏 📁.

& 👆 FastAPI 🈸 5️⃣📆📚 📁/🕹, ️.

FastAPI 📱 📁

➡️ 💬 👆 ✔️ 📁 📊 🔬 🦏 🈸{.internal-link target=_blank}:

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

📁 main.py 👆 ✔️ 👆 FastAPI 📱:

{!../../../docs_src/app_testing/main.py!}

🔬 📁

⤴️ 👆 💪 ✔️ 📁 test_main.py ⏮️ 👆 💯. 💪 🖖 🔛 🎏 🐍 📦 (🎏 📁 ⏮️ __init__.py 📁):

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

↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 app ➡️ main 🕹 (main.py):

{!../../../docs_src/app_testing/test_main.py!}

...& ✔️ 📟 💯 💖 ⏭.

🔬: ↔ 🖼

🔜 ➡️👉 🖼 & 🚮 🌖👀 💯 🎏 🍕.

FastAPI 📱 📁

➡️ 😣 ⏮️ 🎏 📁 📊 ⏭:

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

➡️ 💬 👈 🔜 📁 main.py ⏮️ 👆 FastAPI 📱 ✔️ 🎏 🛠️.

✔️ GET 🛠️ 👈 💪 📨 .

✔️ POST 🛠️ 👈 💪 📨 📚 .

👯‍♂️ 🛠️ 🚚 X-Token 🎚.

=== "🐍 3️⃣.6️⃣ & 🔛"

```Python
{!> ../../../docs_src/app_testing/app_b/main.py!}
```

=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"

```Python
{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
```

🔬 📁

👆 💪 ⤴️test_main.py ⏮️💯:

{!> ../../../docs_src/app_testing/app_b/test_main.py!}

🕐 👆 💪 👩‍💻 🚶‍♀️📨 & 👆 🚫 💭 , 👆 💪 🔎 (🇺🇸🔍) httpx, ⚖️ ⏮️ requests, 🇸🇲 🔧 🔛 📨' 🔧.

⤴️ 👆 🎏 👆 💯.

🤶 Ⓜ.:

  • 🚶‍♀️ ⚖️ 🔢 🔢, 🚮 📛 ️.
  • 🚶‍♀️ 🎻 💪, 🚶‍♀️ 🐍 🎚 ( dict) 🔢 json.
  • 🚥 👆 💪 📨 📨 💽 ↩️ 🎻, ⚙️ data 🔢 ↩️.
  • 🚶‍♀️ 🎚, ⚙️ dict headers 🔢.
  • 🍪, dict cookies 🔢.

🌖🔃 🚶‍♀️ 💽 👩‍💻 (⚙️ httpx ⚖️ TestClient) 🇸🇲 🧾.

!!! info 🗒 👈 TestClient 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷.

🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}.

🏃

⏮️ 👈, 👆 💪 pytest:

$ pip install pytest

---> 100%

🔜 🔍 📁 & 💯 🔁, 🛠️ 👫, & 📄 🏁 🔙 👆.

🏃 💯 ⏮️:

$ pytest

================ test session starts ================
platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /home/user/code/superawesome-cli/app
plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1
collected 6 items

---> 100%

test_main.py <span style="color: green; white-space: pre;">......                            [100%]</span>

<span style="color: green;">================= 1 passed in 0.03s =================</span>