The following test code fails as indicated depending on the params to a widget that I am not even testing:
test_col_val_filter.py
from streamlit.testing.v1 import AppTest
import pandas as pd
def test_col_val_filter():
at = AppTest.from_file("col_val_filter.py")
SS = at.session_state
SS.data = pd.DataFrame(
{
"col1": ["v1", "v1", "v3"],
"col3": [1, 2, 2],
"col2": ["a", "b", "a"],
"id": ["i1", "i2", "i3"],
}
)
SS.testing = True
SS.config = [
{
"fn": "column_filter",
"args": [{"var": "UI"}, 1],
"import": "col_val_filter",
"setup": [{"col": "col1", "vals": ["v1"]}],
}
]
at.run()
# canary
test_sb = at.selectbox(key="test_sb")
assert test_sb.value == ""
test_sb.set_value(
"foo"
).run() # fails here with FAILED test/test_col_val_filter.py::test_col_val_filter - AttributeError: _widget_state
assert test_sb.value == "foo"
This is the code being tested: col_val_filter.py
Commenting any of the spots as indicated breaks the test, otherwise it works.
import streamlit as UI
SS = UI.session_state
def count_cols(SS):
if "cols_counts" in SS and not SS.get("reset_data", True):
return
SS.col_counts = {}
SS.cols = []
for col in sorted(SS.data.columns):
SS.col_counts[col] = len(SS.data[col].unique())
SS.cols.append(col)
SS.reset_data = False
def count_chats(col, val):
non_none_df = SS.data[SS.data[col] == val]
return len(non_none_df["id"].unique())
def add_count(option):
if option == "":
return ""
return f"{option}:{SS.col_counts[option]}"
def column_filter(UI, i_cell, Context):
SS = UI.session_state
count_cols(SS)
Context.selectbox("Test", options=["", "foo", "bar"], key="test_sb")
for i, setting in enumerate(SS.config[i_cell]["setup"]):
option_list = [""] + SS.cols # comment out SS.cols, works
Context.selectbox(
f"Select",
options=option_list,
format_func=add_count, # comment param out and it works
index=option_list.index(setting["col"]), # or comment out and it works
key=f"coll_{i}_sb",
)
if SS.get("testing", False): # stands up UI for testing with simple example
column_filter(UI, 0, UI)
pytest test/test_col_val_filter.py
=========================== test session starts ============================
platform darwin -- Python 3.12.2, pytest-8.1.1, pluggy-1.5.0
rootdir: /Users/fbaldw522/ghe/SpeakPeek/streamlit/cells
collected 1 item
test/test_col_val_filter.py F [100%]
================================= FAILURES =================================
___________________________ test_col_val_filter ____________________________
def test_col_val_filter():
at = AppTest.from_file("col_val_filter.py")
SS = at.session_state
SS.data = pd.DataFrame(
{
"col1": ["v1", "v1", "v3"],
"col3": [1, 2, 2],
"col2": ["a", "b", "a"],
"id": ["i1", "i2", "i3"],
}
)
SS.testing = True
SS.config = [
{
"fn": "column_filter",
"args": [{"var": "UI"}, 1],
"import": "col_val_filter",
"setup": [{"col": "col1", "vals": ["v1"]}],
}
]
at.run()
# canary
test_sb = at.selectbox(key="test_sb")
assert test_sb.value == ""
test_sb.set_value(
"foo"
> ).run() # fails here with FAILED test/test_col_val_filter.py::test_col_val_filter - AttributeError: _widget_state
test/test_col_val_filter.py:34:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../../../../miniforge3/envs/sppk/lib/python3.12/site-packages/streamlit/testing/v1/element_tree.py:153: in run
return self.root.run(timeout=timeout)
../../../../miniforge3/envs/sppk/lib/python3.12/site-packages/streamlit/testing/v1/element_tree.py:1839: in run
widget_states = self.get_widget_states()
../../../../miniforge3/envs/sppk/lib/python3.12/site-packages/streamlit/testing/v1/element_tree.py:1822: in get_widget_states
w = get_widget_state(node)
../../../../miniforge3/envs/sppk/lib/python3.12/site-packages/streamlit/testing/v1/element_tree.py:1765: in get_widget_state
return node._widget_state
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = Selectbox(key='coll_0_sb', _value=InitialValue(), label='Select', options=['', 'col1:2', 'col2:2', 'col3:2', 'id:3'])
name = '_widget_state'
def __getattr__(self, name: str) -> Any:
"""Fallback attempt to get an attribute from the proto"""
> return getattr(self.proto, name)
E AttributeError: _widget_state
../../../../miniforge3/envs/sppk/lib/python3.12/site-packages/streamlit/testing/v1/element_tree.py:142: AttributeError
--------------------------- Captured stderr call ---------------------------
2024-04-28 13:36:50.469 Session state does not function when running a script without `streamlit run`
============================= warnings summary =============================
<frozen importlib._bootstrap>:488
<frozen importlib._bootstrap>:488: DeprecationWarning: Type google._upb._message.MessageMapContainer uses PyType_Spec with a metaclass that has custom tp_new. This is deprecated and will no longer be allowed in Python 3.14.
<frozen importlib._bootstrap>:488
<frozen importlib._bootstrap>:488: DeprecationWarning: Type google._upb._message.ScalarMapContainer uses PyType_Spec with a metaclass that has custom tp_new. This is deprecated and will no longer be allowed in Python 3.14.
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
========================= short test summary info ==========================
FAILED test/test_col_val_filter.py::test_col_val_filter - AttributeError: _widget_state
====================== 1 failed, 2 warnings in 0.69s =======================
OSX Sonomo 14.4
Python 3.12.2
Streamlit 1.33.0
Any help appreciated–awesome product btw.