Unit Testing

Install dependencies.
 
.\myenv\Scripts\Activate
(myenv) pip install pytest requests httpx
(myenv) pip freeze > requirements.txt
Test endpoint (no server needed).
 
""" Run test in quite mode (or with no bytecode cache):

    cd fastapi-service/
    ./myenv/Scripts/activate
    (myenv) pip install pytest
    (myenv) pytest -q
    (myenv) python -B -m pytest
"""

import sys
sys.dont_write_bytecode = True  # no .pyc

from fastapi.testclient import TestClient
from app.main import app  # Import your FastApi 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:
 
# D:\python-apps\fastapi-service\pytest.ini
[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)
 
""" Run test in quite mode (or with no bytecode cache):
    tests/test_hello.py
    
    cd fastapi-service/
    ./myenv/Scripts/activate
    (myenv) pip install pytest requests httpx
    (myenv) python -B -m pytest -q
    (myenv) python -B -m pytest -q -m integration
"""

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)  # verify=False
    data = response.json()
    assert response.status_code == 200
    assert data['message'] == 'Hello from FastAPI - POST'