Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

Practice, Testing and Review

Test Streamlit apps with pytest and the AppTest framework, separate logic from the UI, and practice with ten graded exercises that review state, caching, data and deployment.

You now know the whole stack: reruns, state, caching, data sources, models and deployment. This final lesson does two things. First it shows how to test a Streamlit app, so changes do not break it silently. Then it gives you ten exercises, from small to large, that revisit every chapter.

Testing a UI that reruns itself sounds awkward, but Streamlit has good tools, and the biggest win is a design habit you have already seen in the projects: keep logic in plain functions.

Streamlit does not run on this site. The testing framework code is read-only. The runnable examples test the plain-Python logic with assert statements, which is exactly how your pytest tests for the data layer would look.

Level 1: test the logic, not the framework

Most bugs live in the logic: a filter that drops a row, a validation that accepts a negative amount, a cache key that ignores the user. Functions that take data and return data need no browser and no Streamlit. Look at a test for the validation code from the expense tracker:

Python Tests for a pure function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The boolean test catches a classic Python surprise: True is an integer, so True > 0 passes a naive check. Edge cases like this are exactly what small unit tests are for.

Good habits for this layer:

  • One behavior per test, with a name that reads like a sentence.
  • Use an in-memory SQLite database for database functions, built fresh for each test.
  • Test failure paths (bad input) as carefully as success paths.
  • Keep tests fast, so you actually run them.

Level 2: AppTest, running the whole script headlessly

Streamlit includes streamlit.testing.v1.AppTest, which runs your script without a browser, lets you set widget values, trigger a rerun and inspect what was drawn. It is synchronous and works inside pytest.

Python
# tests/test_app.py
from streamlit.testing.v1 import AppTest

def test_counter_increments():
    at = AppTest.from_file("app.py").run()
    assert at.session_state["count"] == 0

    at.button[0].click().run()
    at.button[0].click().run()
    assert at.session_state["count"] == 2
    assert at.text[0].value == "Count: 2"

def test_filter_reduces_rows():
    at = AppTest.from_file("app.py").run()
    at.selectbox(key="category").select("Food").run()
    assert not at.exception
    assert len(at.dataframe[0].value) < 100

def test_form_shows_error_for_empty_name():
    at = AppTest.from_file("app.py").run()
    at.text_input(key="name").input("").run()
    at.button[0].click().run()
    assert at.error[0].value == "Please enter a name."

How it works:

  • AppTest.from_file("app.py") (or from_string, from_function) builds a test harness; .run() executes the script once.
  • Widgets are found by type and index (at.button[0]) or by key (at.text_input(key="name")). Giving widgets keys makes tests stable, one more reason for the habit from Session State.
  • Interact with .click(), .input("text"), .select("x"), .set_value(...), then call .run() to trigger the rerun, just like a user.
  • Inspect results with at.markdown, at.dataframe, at.metric, at.error, at.session_state and others.
  • at.exception lists unhandled exceptions, so assert not at.exception is a cheap smoke test for every page.
  • Secrets can be set with at.secrets["key"] = "value" so tests never need real credentials.

Limits to know: AppTest does not render visuals (charts are present as elements but not drawn), supports most but not every element (check the documentation for your version), and cannot test browser-side behavior such as layout and JavaScript. For that, use a browser test tool (Playwright) on a few key flows. A healthy mix is many logic tests, a moderate number of AppTests and a handful of browser tests.

Testing caches and state

Two bugs are especially common in Streamlit apps and deserve tests:

  1. A cache that returns stale or shared data. Test the function with a fake clock, or call function.clear() in a test fixture so tests do not influence each other.
  2. State that leaks. AppTest gives each test a fresh session, so you can assert that a first run starts from the initial values.
Python
import pytest
import streamlit as st

@pytest.fixture(autouse=True)
def clear_caches():
    st.cache_data.clear()
    st.cache_resource.clear()
    yield

This fixture runs before every test, so an earlier test cannot make a later one pass or fail by what it left in the cache.

Continuous integration

Run the tests on every push. A minimal GitHub Actions workflow:

YAML
name: tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip
      - run: pip install -r requirements.txt pytest
      - run: pytest -q

Because this installs from requirements.txt in a clean environment, it also proves the file is complete, which catches the most frequent cloud deployment failure (Deploying to Streamlit Community Cloud).

Level 3: ten exercises

Work through them in order. Each one lists the skills used and a hint. Try without the hint first.

1. Reset button (state)

Build a counter with Add, Subtract and Reset buttons. The counter must never go below zero. Skills: session state, callbacks. Hint: put the arithmetic in callbacks and clamp with max(0, ...).

2. Slow function (caching)

Write a function that sleeps for two seconds and returns a table. Show how many seconds the page takes with and without @st.cache_data, using time.perf_counter(). Add a "Refresh" button that clears the cache. Hint: show the elapsed time with st.caption.

3. Wizard (state)

Make a three-step form (personal info, preferences, review). Steps keep their values when the user goes back. Hint: copy widget values into plain keys in the callback that changes the step.

4. CSV cleaner (files)

Upload a CSV, show missing values per column, let the user choose to drop or fill them (with 0, mean or a custom value) and download the cleaned file. Hint: build the result in a function and test it on small frames.

5. SQL notebook (databases)

A text area where the user types a SELECT against a SQLite sample database. Reject anything that is not a single SELECT, show the result and the number of rows, and limit the output to 1,000 rows. Hint: open the connection read-only and parse conservatively; a text area accepting SQL is dangerous, so also give the database user no write permission.

6. API dashboard (APIs and secrets)

Call any public JSON API of your choice with a timeout, cache the call for ten minutes, show errors with st.error and put an API key (if needed) in secrets.toml. Hint: use a fake API function while developing and swap in requests last.

7. Spreadsheet (data editor)

Edit a small product table with st.data_editor, validate the changes and save them to SQLite. Show the saved version after a rerun. Hint: use the edit-state dictionary only to detect changes; save the returned DataFrame.

8. Classifier (machine learning)

Train a classifier on any scikit-learn toy dataset offline, save it with joblib, load it in the app and show a prediction with probabilities, a threshold slider and a confusion matrix. Hint: save the whole pipeline.

9. Chatbot (chat)

Build a chat app with a rule-based assistant that remembers the user's name, has a message limit, and a Clear button. Hint: the history is a list in session state that you replay on every run.

10. Ship it (deployment)

Take your best app, write requirements.txt with pinned versions, add .gitignore and a Dockerfile with a health check, and run it from a clean virtual environment. Add at least five pytest tests and one AppTest smoke test. Hint: a fresh environment finds missing requirements immediately.

Self-review checklist

Use this list on every app before you share it:

  • Does each widget have a clear label, a sensible default and, where needed, a key?
  • Is anything slow cached, with a ttl or max_entries where it matters?
  • Is per-user data in session state and shared data in caches, never mixed up?
  • Are all queries parameterized and all uploads validated?
  • Are secrets out of the repository?
  • Do error messages help the user without revealing internals?
  • Is there a test for the logic and a smoke test for each page?
  • Does it start from a clean environment using only requirements.txt?

Where to go next

You can now build, test and ship a Streamlit app. Extend your skills in the directions your apps need: the pandas and scikit-learn tutorials for deeper data work, the SQL tutorial for better queries, and the Docker tutorial for production packaging. Build something for a real person; their feedback teaches faster than any course.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why keep logic in plain functions instead of inside the Streamlit script?

    Pure functions take data and return data, so unit tests are simple and fast.
  2. 2. What does AppTest let you do?

    AppTest simulates a session without a browser. It runs inside pytest and exposes widgets, elements and session state.
  3. 3. Why clear caches in a pytest fixture?

    Caches persist across calls in the same process, so tests could depend on each other without a cleanup.
  4. 4. What is a cheap smoke test for every page with AppTest?

    at.exception lists unhandled exceptions. An empty list after run() means the page at least renders without crashing.

Summary

  • Put logic in pure functions and unit test them with pytest, including failure paths and edge cases.
  • AppTest runs a script without a browser, so you can click buttons, set inputs and assert on output and session state.
  • Clear caches between tests and give widgets keys to keep tests stable.
  • Run tests in CI from a clean environment to validate requirements.txt too.
  • Practice by building the ten exercises, then review each app with the checklist.

Next: Back to the Streamlit track