Session state changes within button `onclick` not making it back to AppTest instance

Hello,
Iā€™ve started using AppTest to test my streamlit app and it seems that a buttonā€™s onclick isnā€™t actually triggered by AppTest when using click().
Iā€™m using Streamlit 1.31

Hereā€™s an example. If my test functions uses if button to mutate session state, the test passes:

from streamlit.testing.v1 import AppTest

def test_testing():
    def test_fn():
        import streamlit as st

        st.session_state["clicked"] = False
        if st.button("Click me", key="button_key"):
            st.session_state["clicked"] = True

    at = AppTest.from_function(test_fn)
    at.run()

    assert at.session_state["clicked"] is False
    at.button("button_key").click().run()
    assert at.session_state["clicked"] is True

However, if I instead use onclick:

from streamlit.testing.v1 import AppTest

def test_testing():
    def test_fn():
        import streamlit as st

        def toggle():
            st.session_state["clicked"] = not st.session_state["clicked"]

        st.session_state["clicked"] = False
        st.button("Click me", key="button_key", on_click=toggle)

    at = AppTest.from_function(test_fn)
    at.run()

    assert at.session_state["clicked"] is False
    at.button("button_key").click().run()
    assert at.session_state["clicked"] is True

then the test fails.

Am I missing something, or is that something that AppTest cannot handle yet?

I can actually put a breakpoint inside the toggle function and the debugger does break on it, so toggle is actually executed.

It just seems like the session state update within toggle doesnā€™t make it back to the AppTest session state.

Closing this ā€“ the issue is that this line

st.session_state["clicked"] = False

gets run on every run of the app, including after clicking the button. Thatā€™s why the session state switches back to False.
I just need to Streamlitā€™s ā€œre-run all on every interactionā€ behavior, including in tests.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.