Using MagicMock and AppTest

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

2 Likes

Hello @arielcv96,

Here’s a revised approach:

from streamlit.testing.v1 import AppTest
from unittest.mock import patch

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()

Hope this helps!

Kind Regards,
Sahir Maharaj
Data Scientist | AI Engineer

P.S. Lets connect on LinkedIn!

➤ Want me to build your solution? Lets chat about how I can assist!
➤ Join my Medium community of 30k readers! Sharing my knowledge about data science and AI
➤ Website: https://sahirmaharaj.com
➤ Email: sahir@sahirmaharaj.com
➤ 100+ FREE Power BI Themes: Download Now

2 Likes

Hi @sahirmaharaj, thanks for your answer but I tested it and it continues failing :frowning:
I think removing just MagicMock function is not enough

1 Like