Hi everyone, I’m running an streamlit App locally and writing some tests to check if a function is called when I click a button.
The app is the following one:
import streamlit as st
def click_function():
return 1
st.write("Hello world")
dispatch_click_function = st.button("Test click")
if dispatch_click_function:
click_function()
and the test I’m writing is the following:
from streamlit.testing.v1 import AppTest
from unittest.mock import patch, MagicMock
mocked_click_function = MagicMock()
def test_click_function():
with patch("app.click_function") as mocked_click_function:
at = AppTest.from_file("app.py").run()
button = at.get("button")
button[0].click().run()
mocked_click_function.assert_called_once()
The error message I’m getting is because the test fails:
FAILED test_app.py::test_click_function - AssertionError: Expected ‘click_function’ to have been called once. Called 0 times.
But when I insert a logging statement inside the function and run the app as an streamlit app it shows a print (as it should be)…so I don’t understand why the mock is not working during the test.
I’m using streamlit version 1.31.0 and python 3.10.12