In a streamlit project, i have two pages and these two pages depends upon other moudules and these module contains several functions. one of the function i have mentioned below i.e
def delete_items(connection,id,db,schema, table):
col1, col2 = st.columns([0.1,1]) # Adjust the column widths as needed
with col1:
st.button("Yes",on_click=confirm_delete, args=[connection,id,db,schema, table])
with col2:
st.button("No",on_click=set_state, args=[0])
i am little confused that do i really need to test each and every function. if yes, how we can achieve it ?
for testing i tried
def test_delete_items():
' ' ' test wheather item is deleted ' ' '
app = AppTest.from_function(delete_items).run(timeout=5)
assert app.columns
# assert app.columns[0
assert 'Yes' in app.button[0].label
assert 'No' in app.button[1].label
however it failed. because the actual function takes some arguments and i am confusing how to ingest those arguments from the test file itself. i tried with *args to ingest arguments but also failed.
any kind of support would be highly appreciated.
cheers,
Swetansu
Hello @ss_mohanty ,
Hereβs how you might approach it using pytest
and unittest.mock
:
from unittest.mock import patch, MagicMock
import pytest
# Your function (simplified for demonstration)
def delete_items(connection, id, db, schema, table):
col1, col2 = st.columns([0.1, 1])
with col1:
st.button("Yes", on_click=confirm_delete, args=[connection, id, db, schema, table])
with col2:
st.button("No", on_click=set_state, args=[0])
# Test function
def test_delete_items():
with patch('streamlit.columns') as mock_columns, \
patch('streamlit.button') as mock_button:
# Mock the columns and button
mock_col1 = MagicMock()
mock_col2 = MagicMock()
mock_columns.return_value = [mock_col1, mock_col2]
mock_button.side_effect = [None, None] # Assuming no return value from button
# Call the function with mock arguments
delete_items('connection', 'id', 'db', 'schema', 'table')
# Assertions
mock_columns.assert_called_once_with([0.1, 1])
assert mock_button.call_count == 2
mock_button.assert_any_call("Yes", on_click=confirm_delete, args=['connection', 'id', 'db', 'schema', 'table'])
mock_button.assert_any_call("No", on_click=set_state, args=[0])
Kind Regards,
Sahir
P.S. Lets connect on LinkedIn!
Thank you Sahir for your valuable feedback
1 Like