I'm trying to write pytest tests for a NiceGUI application. I've been encountering various context-related errors and tried multiple approaches to fix them.
Initial setup:
@pytest.fixture
async def f_ui(mock_f_core, user):
init_ui(mock_f_core)
await user.open("/")
return await create_ui()
First error:
KeyError: '00000000-0000-0000-0000-000000000000'
What's the proper way to set up NiceGUI testing with pytest? How do I ensure:
- Proper client/user setup
- Correct context for UI creation
- Valid slot stack during testing
My test file structure:
@pytest.mark.asyncio
async def test_init(f_ui, mock_f_core):
ui = await f_ui
assert ui.f_core == mock_f_core
assert app.storage.client_id == "00000000-0000-0000-0000-000000000000"
assert ui.process_grid is not None
assert ui.status_label is not None
Attempted fix #1 - Setting up client instances:
@pytest.fixture
def client():
mock_client = Mock()
mock_client.instances = {}
mock_client.connected = True
return mock_client
@pytest.fixture
async def user(client) -> User:
client_id = "00000000-0000-0000-0000-000000000000"
client.instances[client_id] = client
return User(client)
Then got:
RuntimeError: The current slot cannot be determined because the slot stack for this task is empty.
Attempted fix #2 - Using async context manager:
@pytest.fixture
async def user(client) -> AsyncGenerator[User, None]:
client_id = "00000000-0000-0000-0000-000000000000"
client.instances[client_id] = client
async with User(client) as user:
yield user
Got:
TypeError: 'User' object does not support the asynchronous context manager protocol
Attempted fix #3 - Using page_context:
from nicegui.testing import page_context
# ...
with page_context('/'):
ui_instance = await create_ui()
Got:
ImportError: cannot import name 'page_context' from 'nicegui.testing'
Attempted fix #4 - Using ui.builder:
with ui.builder():
ui_instance = await create_ui()
Got:
AttributeError: module 'nicegui.ui' has no attribute 'builder'
Current attempt - Using ui.header:
with ui.header():
ui_instance = await create_ui()
Still getting context/slot errors.