Unit Testing
Install dependencies.
.\myenv\Scripts\Activate
(myenv) pip install pytest requests httpx
(myenv) pip freeze > requirements.txt
Test endpoint (no server needed).
import sys
sys.dont_write_bytecode = True
from fastapi.testclient import TestClient
from app.main import app
def test_hello_endpoint():
client = TestClient(app)
response = client.get("/hello/")
assert response.status_code == 200
assert response.json() == {"message": "Hello from FastAPI"}
If running from the root still gives issues, add a pytest.ini at the project root:
[pytest]
testpaths = tests
pythonpath = .
Run test in quite mode (or with no bytecode cache)
(myenv) pytest -q
(myenv) python -B -m pytest
Test the live UAT URL (like a PHP snippet)
import os
import requests
import pytest
from fastapi.testclient import TestClient
from app.main import app
from dotenv import load_dotenv
load_dotenv()
@pytest.mark.unit
def test_hello_endpoint():
client = TestClient(app)
response = client.get("/fastapi/hello_world/")
assert response.status_code == 200
assert response.json() == {"message": "Hello from FastAPI - GET"}
@pytest.mark.integration
def test_hello_endpoint_real_server():
SERVER_URL = os.getenv('SERVER_URL')
SSL_CRT = os.getenv('SSL_CRT')
SSL_KEY = os.getenv('SSL_KEY')
response = requests.post(SERVER_URL + '/fastapi/hello_world/second', timeout=8, verify=SSL_CRT)
data = response.json()
assert response.status_code == 200
assert data['message'] == 'Hello from FastAPI - POST'