App testing example
Testing a login page
Let's consider a login page. In this example, secrets.toml is not present. We'll manually declare dummy secrets directly in the tests. To avoid timing attacks, the login script uses hmac to compare a user's password to the secret value as a security best practice.
Project summary
Login page behavior
Before diving into the app's code, let's think about what this page is supposed to do. Whether you use test-driven development or you write unit tests after your code, it's a good idea to think about the functionality that needs to be tested. The login page should behave as follows:
- Before a user interacts with the app:
- Their status is "unverified."
- A password prompt is displayed.
- If a user types an incorrect password:
- Their status is "incorrect."
- An error message is displayed.
- The password attempt is cleared from the input.
- If a user types a correct password:
- Their status is "verified."
- A confirmation message is displayed.
- A logout button is displayed (without a login prompt).
- If a logged-in user clicks the Log out button:
- Their status is "unverified."
- A password prompt is displayed.
Login page project structure
Login page Python file
The user's status mentioned in the page's specifications are encoded in st.session_state.status. This value is initialized at the beginning of the script as "unverified" and is updated through a callback when the password prompt receives a new entry.
Login page test file
These tests closely follow the app's specifications above. In each test, a dummy secret is set before running the app and proceeding with further simulations and checks.
See how Session State was modified in the last test? Instead of fully simulating a user logging in, the test jumps straight to a logged-in state by setting at.session_state["status"] = "verified". After running the app, the test proceeds to simulate the user logging out.
Automating your tests
If myproject/ was pushed to GitHub as a repository, you could add GitHub Actions test automation with Streamlit App Action. This is as simple as adding a workflow file at myproject/.github/workflows/:
Still have questions?
Our forums are full of helpful information and Streamlit experts.
