The patch decorator temporarily replaces a real dependency with a fake during a test. This isolates the component under test so its behavior can be checked without relying on an external service or implementation. section 11.8
Use unittest.mock.patch with the path to the object used by the code under test. In a frontend test, @patch("backend.Backend", MockBackend) ensures references to Backend executed during the test use MockBackend instead. Pass the mock into the test when you need to modify it; provide it directly to the decorator when replacement is all you need. section 11.4.1
Replacing a backend in a Streamlit test
A test can run the app with a controlled backend, then inspect its initial interface: @patch("backend.Backend", MockBackend) def test_initial_state(setup_app): at = setup_app at.run() assert len(at.sidebar.text_input) == 1 assert len(at.sidebar.button) == 1 assert "results" not in at.session_state The same replacement supports a search test: enter a query, click the button, and verify that MOCK_RESULTS appear in session_state and that the expected number of expanders is rendered. section 11.4.1
Listing 11.7 Testing the frontend
import pytest
from unittest.mock import patch
from streamlit.testing.v1 import AppTest
from mock_data import MOCK_RESULTS
class MockBackend:
@staticmethod
def get_poster_url(path):
return "https://mock-image-server.com/poster.jpg"
def __init__(self, api_key):
self.api_key = api_key
def search_movies(self, query):
return MOCK_RESULTS
@pytest.fixture
def setup_app():
at = AppTest.from_file("frontend.py")
at.secrets["api_key"] = "test_api_key"
return at
@patch("backend.Backend", MockBackend)
def test_initial_state(setup_app):
at = setup_app
at.run()
# Check if sidebar has search input field and button
assert len(at.sidebar.text_input) == 1
assert len(at.sidebar.button) == 1
assert "Search" in at.sidebar.button[0].label
# Check that results are not visible initially
assert "results" not in at.session_state
assert len(at.expander) == 0
Inspect the complete frontend test, including MockBackend, the pytest fixture, the patch decorator, and initial-state assertions. section 11.4.1
