An AI-powered application can work perfectly on your laptop and still break after a small code change. A prompt gets edited, an API response has a different shape, a configuration variable is missing, or a dependency update changes how a request is handled. If you only test the application manually, these problems can reach production before anyone notices.
The solution is to combine ordinary software tests with a continuous integration (CI) workflow. Your tests should verify predictable application behavior, while CI automatically runs those checks whenever code is pushed or a pull request is opened.
In this tutorial, we will set up automated testing for a small Python LLM application using pytest and GitHub Actions. The example focuses on a useful distinction: test your own application logic without calling a real model, then keep a separate integration test for checking the actual API connection.
Table of Contents
What should you test in an AI-powered app?
Separate unit tests from real API tests
Prepare the Python project for CI
Create a GitHub Actions workflow
Add integration checks without exposing API keys
Improve the pipeline as the application grows
What Should You Test in an AI-Powered App?
Testing an AI-powered app is not the same as testing a simple calculator. Some parts of the application are deterministic, while model-generated content can vary between requests.
Start by dividing the application into three test areas:
Application logic: Input validation, data transformation, permission checks, error handling, and business rules.
LLM integration: Request construction, response parsing, model configuration, and provider error handling.
AI output quality: Whether responses follow your task requirements, contain the expected information, and avoid unacceptable outputs.
Do not use one test to answer all three questions. A unit test can confirm that your code builds the correct request, but it cannot prove that a live model will always produce the same answer. Likewise, a successful API request does not prove that your application handles malformed user input correctly.
Separate Unit Tests From Real API Tests
Consider a service that generates a short answer from a user prompt. Its business logic should reject empty input and return the text supplied by the model client.
Keep the model client injectable instead of creating it inside every function:
def generate_answer(client, model, prompt):
if not prompt or not prompt.strip():
raise ValueError("Prompt cannot be empty")
response = client.responses.create(
model=model,
input=prompt,
)
return response.output_textThis small design choice makes the function easier to test. A unit test can pass a fake client that behaves like the SDK without contacting the provider.
import pytest
from app.services.answers import generate_answer
class FakeResponse:
output_text = "Python uses indentation to define blocks."
class FakeResponses:
def create(self, **kwargs):
assert kwargs["model"] == "test-model"
assert kwargs["input"] == "Explain Python indentation."
return FakeResponse()
class FakeClient:
responses = FakeResponses()
def test_generate_answer_returns_text():
result = generate_answer(
client=FakeClient(),
model="test-model",
prompt="Explain Python indentation.",
)
assert result.startswith("Python uses")
def test_generate_answer_rejects_empty_input():
with pytest.raises(ValueError):
generate_answer(
client=FakeClient(),
model="test-model",
prompt=" ",
)These tests are fast, repeatable, and do not require an API key. They verify your application's contract with the client. They do not verify the provider's live availability, account permissions, or model behavior.
For more complex applications, add tests for timeout handling, rate-limit responses, invalid structured output, and provider failures. Use mocks or fakes to simulate these conditions instead of waiting for them to happen naturally.

Prepare the Python Project for CI
Before creating a workflow, make sure the project can install its dependencies consistently. If you followed the previous starter-template tutorial, you may already have a pyproject.toml file. Add the test tools as development dependencies:
[project.optional-dependencies]
dev = [
"pytest",
"pytest-cov",
"ruff"
]Install the project in editable mode with its development tools:
python -m pip install -e ".[dev]"Run the same checks locally that you plan to run in CI:
ruff check .
pytest -qIf these commands only work on your machine because of an undeclared dependency or a local environment variable, CI will expose the problem. That is useful: the purpose of CI is to test a clean, repeatable environment rather than reproduce undocumented details of your workstation.
Create a GitHub Actions Workflow
GitHub Actions can run your checks automatically when someone pushes a commit or opens a pull request. Create this file in your repository:
.github/workflows/tests.ymlThen add the workflow:
name: Python tests
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v6
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: "pip"
- name: Install project
run: |
python -m pip install --upgrade pip
pip install -e ".[dev]"
- name: Run lint checks
run: ruff check .
- name: Run tests
run: pytest -q --cov=app --cov-report=term-missingThis workflow checks out the repository, configures Python, installs the project, runs linting, and executes tests. GitHub recommends using the setup-python action to manage Python versions consistently across hosted runners. Its Python CI guide also demonstrates running pytest and collecting test results.
The workflow is intentionally small. You can add more jobs later, but first make sure the basic pipeline works on every pull request.

Add Integration Checks Without Exposing API Keys
Unit tests should not need a real API key. However, it is still useful to have a controlled integration test that checks whether your application can communicate with the provider.
Keep that test separate from the default test suite. For example, mark it with a pytest marker:
import os
import pytest
from openai import OpenAI
@pytest.mark.integration
def test_live_api_connection():
if not os.getenv("OPENAI_API_KEY"):
pytest.skip("API key is not configured")
client = OpenAI()
response = client.responses.create(
model=os.environ["OPENAI_MODEL"],
input="Reply with the word ready.",
)
assert response.output_text.strip()Register the marker in pyproject.toml:
[tool.pytest.ini_options]
testpaths = ["tests"]
markers = [
"integration: tests that require a live external service"
]You can run the integration test explicitly when needed:
pytest -m integration -qIf you later run it in GitHub Actions, store credentials as repository or environment secrets and expose them only to the job that needs them. Do not put API keys in workflow files, test fixtures, screenshots, or commit history. Also avoid giving untrusted pull-request code access to secrets.
Test AI Output Quality Separately
A passing unit test does not mean an AI feature is useful. For example, a customer-support assistant might return a non-empty answer that is still inaccurate, incomplete, or unrelated to the question.
Create a small evaluation dataset containing representative inputs and expected criteria. You do not always need one exact reference sentence. You can check whether the answer includes required facts, follows a format, or avoids prohibited claims.
For a document question-answering app, useful evaluation cases might include:
A question with a clear answer in the source document.
A question whose answer is missing from the document.
A question that combines information from two sections.
A question containing misleading or irrelevant context.
Record model name, prompt version, evaluation input, output, and scoring result. This makes it easier to detect quality changes after prompt edits or model changes. Because model outputs can vary, evaluate a set of cases rather than relying on one successful example.
Improve the Pipeline as the App Grows
Once the basic workflow is stable, consider adding a Python-version matrix, type checking, dependency security checks, and test-result artifacts. You can also split the pipeline into separate jobs so that a formatting failure is easier to identify than a model-integration failure.
Be careful with coverage percentages. High coverage does not automatically mean meaningful tests. A test that only checks whether a function returns a string may cover every line while missing important business rules.
For AI-powered applications, a useful CI strategy has three layers:
Fast checks on every pull request: Linting, unit tests, and deterministic validation.
Controlled integration checks: Real provider requests in a protected environment.
Quality evaluations: A representative dataset that checks whether the AI feature still meets product expectations.
Automated testing and CI will not guarantee that an AI application never fails. They make failures easier to detect, reproduce, and investigate before a change reaches users. Start with a small pipeline that runs reliably, then expand it as your application becomes more complex.
Build it. Break it. Understand it. Fix it.
