如何用pytest正确测试NiceGUI应用——解决上下文/插槽错误
如何正确配置NiceGUI的pytest测试环境,解决上下文相关错误
我在为NiceGUI应用编写pytest测试代码时,遇到了多个上下文相关的错误,尝试了多种修复方案但都未解决。需要正确配置测试环境,确保:
- 正确的客户端/用户设置
- UI创建时的上下文正确
- 测试过程中插槽栈有效
初始设置代码
@pytest.fixture async def f_ui(mock_f_core, user): init_ui(mock_f_core) await user.open("/") return await create_ui()
首次出现的错误
KeyError: '00000000-0000-0000-0000-000000000000'
测试文件结构
@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
尝试的修复方案及对应错误
方案1:设置客户端实例
@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)
错误:
RuntimeError: The current slot cannot be determined because the slot stack for this task is empty.
方案2:使用异步上下文管理器
@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
错误:
TypeError: 'User' object does not support the asynchronous context manager protocol
方案3:使用page_context
from nicegui.testing import page_context # ... with page_context('/'): ui_instance = await create_ui()
错误:
ImportError: cannot import name 'page_context' from 'nicegui.testing'
方案4:使用ui.builder
with ui.builder(): ui_instance = await create_ui()
错误:
AttributeError: module 'nicegui.ui' has no attribute 'builder'
当前尝试:使用ui.header
with ui.header(): ui_instance = await create_ui()
问题:仍存在上下文/插槽错误。
内容的提问来源于stack exchange,提问作者n0name
相关产品推荐
相关产品推荐

