Pytest + session state = no key storage

Hi everyone :wave:

Iโ€™m having some trouble accessing the streamlit session state when running a unit test, even with a very simple call:

import pytest
import streamlit as st

def test_session_state():

    if 'cache' not in st.session_state:
        st.session_state['cache'] = {'init': True}

    assert(st.session_state['cache']['init'])

Output:

tests/test_streamlit.py::test_session_state Failed: [undefined]KeyError: 'st.session_state has no key "cache". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'
self = SessionState(_old_state={}, _new_session_state={}, _new_widget_state=WStates(states={}, widget_metadata={}), _key_id_mapping={})
key = 'cache'

I can see in the debug console that st.session_state does indeed exist as a global variable.

I suppose I could run the code using streamlit run {test location} and st.write() a whole bunch of True statements, but does someone have a better idea?

I was having the same problem.
The diference was that I was pushing the button โ€œRun Python Fileโ€ in the IDE instead of write โ€œstreamlit run app.pyโ€ in the terminal.
Despite the WORNING before the error in the terminal:
WARNING streamlit.runtime.state.session_state_proxy: Session state does not function when running a script without streamlit run

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