Testing your Inspira application

If you are new to Inspira, please start by reading the Getting Started with Inspira guide.

Getting started

Execute the following commands to install Inspira and create the project directories:

$ mkdir testing_app
$ cd testing_app
$ python -m venv .venv
$ source .venv/bin/activate
$ pip install inspira
$ inspira init && inspira new controller greeting

Install Dependencies

Use the command below to install the required packages pytest and pytest-asyncio:

$ pip install pytest pytest-asyncio

Test Directory Setup

In the tests directory, create a new file named test_controller.py and include the following content:

import pytest
from inspira.testclient import TestClient

from main import app

client = TestClient(app)


@pytest.mark.asyncio
async def test_index_returns_valid_json_response():
    response = await client.get("/greetings")
    expected = {"variable": "value"}

    assert response.json() == expected


@pytest.mark.asyncio
async def test_index_returns_200_status_code():
    response = await client.get("/greetings")

    assert response.status_code == 200


@pytest.mark.asyncio
async def test_nonexistent_endpoint_returns_404():
    response = await client.get("/nonexistent")

    assert response.status_code == 404

Here, a TestClient is initialized with the Inspira application, and test functions follow the pytest convention by starting with test_.

Summary

Congratulations! You have successfully navigated through the Inspira test tutorial, learning how to leverage the powerful testing capabilities provided by the TestClient.

The code is available on GitHub

Happy coding and testing!