liveBook · Manning

Test fixture

As explained in Build Python Web Apps with Streamlit

A test fixture is a reusable setup and teardown mechanism that provides a controlled environment or data for tests.

Tests often need the same starting point. A test fixture provides that setup in one reusable place. In pytest, decorate a function with @pytest.fixture, then name it as a test parameter. Pytest calls the fixture and passes its returned value to the test. section 11.3.2

Give backend tests a ready-to-use instance

A backend fixture returns Backend("test_api_key"). Any test with a backend parameter receives that instance. The dummy key is enough because the unit test separately patches requests.get and supplies a mock API response; it makes no real API call. section 11.3.2

@pytest.fixture
def setup_app():
  at = AppTest.from_file("frontend.py")
  at.secrets["api_key"] = "test_api_key"
  return at

The setup_app fixture creates a runnable Streamlit AppTest and puts a test API key in its secrets. Frontend tests receive it by declaring a setup_app parameter. section 11.4.1

Keep setup and isolation distinct: the fixture supplies the configured object, while a mock replaces an external dependency. These examples show setup through returned values, not teardown. section 11.3.2 section 11.4.1

How Build Python Web Apps with Streamlit covers it

How deep it goes
Shows decorator-based definition, parameter injection, and two setup functions, but does not demonstrate fixture teardown.
Examples
Uses a Backend instance with a dummy API key and an AppTest instance with a test secret.
What it assumes
Assumes familiarity with basic Python functions while introducing pytest fixture decoration and test-parameter injection.
What you can do after
Apply it via pytest fixtures to provide configured Backend or Streamlit AppTest instances to multiple tests.
How it connects
Connects pytest fixtures to unit testing, dependency mocking, and Streamlit AppTest.

Also explained in

Compare how 10 books explain test fixture →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.