贡献组件测试
本指南概述了如何构建和实现应用程序组件测试,以确保一致性和充分的覆盖率。
文件命名
- 测试文件应该遵循与被测试组件相同的目录结构,但应放置在相应的单元测试文件夹中。
For example, if the file path for the component is src/backend/base/langflow/components/prompts/
, then the test file should be located at src/backend/tests/unit/components/prompts
.
- 测试文件名应使用蛇形命名法并遵循
test_<file_name>.py
模式。
For example, if the file to be tested is PromptComponent.py
, then the test file should be named test_prompt_component.py
.
文件结构
- 每个测试文件应按组件将测试分组到类中。文件中不应有独立的测试函数——只有类中的测试方法。
- 类名应遵循
Test<ClassName>
模式。 For example, if the component being tested isPromptComponent
, then the test class should be namedTestPromptComponent
.
导入、继承和强制方法
为了标准化组件测试,已创建基础测试类,应被所有组件测试类导入和继承。这些基础类位于文件 src/backend/tests/unit/base.py
中。
导入基础测试类:
_10from tests.base import ComponentTestBaseWithClient_10from tests.base import ComponentTestBaseWithoutClient
这些基础类强制要求组件测试类必须实现的强制方法。基础类确保在以前版本中构建的组件在当前版本中继续工作。通过继承这些基础类之一,开发者必须定义以下用 @pytest.fixture
装饰的方法:
component_class:
返回要测试的组件类。例如:
_10@pytest.fixture_10def component_class(self):_10 return PromptComponent
default_kwargs:
返回包含实例化组件所需默认参数的字典。例如:
_10@pytest.fixture_10def default_kwargs(self):_10 return {"template": "Hello {name}!", "name": "John", "_session_id": "123"}
file_names_mapping:
返回表示被测试组件随时间变化的version
、module
和file_name
之间关系的字典列表。如果是未发布的组件,可以留空。例如:
_10@pytest.fixture_10def file_names_mapping(self):_10 return [_10 {"version": "1.0.15", "module": "prompts", "file_name": "Prompt"},_10 {"version": "1.0.16", "module": "prompts", "file_name": "Prompt"},_10 {"version": "1.0.17", "module": "prompts", "file_name": "Prompt"},_10 {"version": "1.0.18", "module": "prompts", "file_name": "Prompt"},_10 {"version": "1.0.19", "module": "prompts", "file_name": "Prompt"},_10 ]
测试组件功能
一旦定义了测试文件的基本结构,就要为组件的功能实现测试方法。必须遵循以下准则:
- 测试方法名应具有描述性,使用蛇形命名法,并遵循
test_<case_name>
模式。 - 每个测试应遵循 Arrange, Act, Assert 模式:
- Arrange(准备):准备数据。
- Act(执行):执行组件。
- Assert(断言):验证结果。
示例
- Arrange(准备):准备数据。
建议使用基本结构中定义的夹具,但不是强制的。
_10def test_post_code_processing(self, component_class, default_kwargs):_10 component = component_class(**default_kwargs)
- Act(执行):执行组件。
调用在 Arrange 步骤中准备的组件的 .to_frontend_node()
方法。
_10def test_post_code_processing(self, component_class, default_kwargs):_10 component = component_class(**default_kwargs)_10_10 frontend_node = component.to_frontend_node()
- Assert(断言):验证结果。
执行 .to_frontend_node()
方法后,结果数据可在字典 frontend_node["data"]["node"]
中进行验证。断言应该清晰并涵盖预期结果。
_10def test_post_code_processing(self, component_class, default_kwargs):_10 component = component_class(**default_kwargs)_10_10 frontend_node = component.to_frontend_node()_10_10 node_data = frontend_node["data"]["node"]_10 assert node_data["template"]["template"]["value"] == "Hello {name}!"_10 assert "name" in node_data["custom_fields"]["template"]_10 assert "name" in node_data["template"]_10 assert node_data["template"]["name"]["value"] == "John"