Testing streamlit using Mock

Hi, I am trying to test streamlit with Pytest. I want to test a function that update a document inside a mongodb collection. The values to update are stored using st.session_state(). I created a mock like that: `

from pytest_mock import mocker
mock_dict = {
        'mongodb_collections': {
            'preferences': {
                'user': 'test_user',
                'folder': '/path/to/folder'
        'username': 'test_user',
        'out_folder': '/path/to/folder'
        # Patch the session state dictionary with the mock dictionary
        mocker.patch.dict('st.session_state', mock_dict)

But it is not recognized running pytest. I also used mock from unittest without success. How can I solve it?

I’m not an expert in this area, but have you tried streamlit-mock? There’s also a lot of info on testing/future developments in this area in this GH Issue

What do you mean by “not recognized”?

Running your code raises AttributeError for me, as I expected:

Traceback (most recent call last):
  File "C:\Users\U938001\Desktop\test.py", line 14, in <module>
    mocker.patch.dict('st.session_state', mock_dict)
AttributeError: 'function' object has no attribute 'patch'