Skip to content

Testing

Flask has a built-in test client, facilitating unit testing and integration testing of routes/business logic.

Dependencies:

bash
pip install pytest pytest-cov

Pytest Basic Structure:

project/
  app/
  tests/
    conftest.py
    test_app.py

Test Fixtures:

python
# tests/conftest.py
import pytest
from app import create_app

desired_config = {"TESTING": True}

@pytest.fixture()
def app():
    app = create_app()
    app.config.update(desired_config)
    yield app

@pytest.fixture()
def client(app):
    return app.test_client()

Example Test Cases:

python
# tests/test_app.py
def test_index(client):
    res = client.get("/")
    assert res.status_code == 200
    assert b"Hello" in res.data

Coverage: pytest --cov=app --cov-report=term-missing.

Content is for learning and research only.