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}



tests/ Failed: [undefined]KeyError: 'st.session_state has no key "cache". Did you forget to initialize it? More info:'
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” 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