liveBook · Manning

Assertion

As explained in Build Python Web Apps with Streamlit

An assertion is a test check that evaluates an expected condition and reports a failure when the condition is false.

A movie search can return the right-looking screen while hiding a wrong API request or missing result. An assertion turns an expectation into a test check: its condition must be true for the test to pass. If it is false, pytest fails the test and reports which check failed, helping you locate the mismatch. section 11.3.2

Start with a small check

In a Python test, `assert add(2, 3) == 5` checks one expected result; `assert add(-1, 1) == 0` checks another. Run the test with `pytest -v` to see whether its checks pass. section 11.2.3

For a movie search, check both what the code did and what it returned:

  • Check the API call: `mock_get.assert_called_once_with(...)` verifies that the mocked request received the expected URL and parameters. section 11.3.2
  • Check the results: assert that the returned count matches the mock data, each expected movie ID is present, and each title matches. A separate no-results test asserts that the return value is `{}`. section 11.3.2

Assertions can check the visible app state too. With Streamlit’s AppTest, an initial-state test checks for one sidebar input, one button labeled “Search,” and no displayed results. After a simulated search, assertions check session state and the number of result expanders. You can add a message to an `assert` to make a failure more informative, such as reporting the expected and actual expander counts. section 11.4.1

How Build Python Web Apps with Streamlit covers it

How deep it goes
Defines a passing condition and works through result, mock-call, and UI checks without examining Python assertion internals.
Examples
Uses arithmetic checks, mocked movie-search responses, sidebar controls, session state, and result expanders.
What it assumes
Introduces Python’s assert keyword with a small function before applying it to backend and frontend tests.
What you can do after
Apply it via pytest and AppTest to verify expected values, API calls, and app state, then identify failed checks.
How it connects
Connects assertions to pytest, unit testing, mocking, fixtures, and Streamlit AppTest.

Also explained in

Compare how 15 books explain assertion →

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.