Python动态创建Robot Framework关键字遇识别异常求助
解决Robot Framework动态生成测试套件时自定义关键字无法识别的问题
问题原因
核心问题是通过TestSuite API动态创建测试时,测试套件未导入包含Request Api Call关键字的Python库。直接编写.robot文件时会用Library语句显式导入库,但动态生成场景下必须手动完成这一步,否则Robot Framework无法识别自定义关键字。
解决方案步骤
- 动态生成测试套件时,必须将自定义Python库导入到套件中,等价于在
.robot文件中添加Library导入语句 - 确保关键字名称、参数数量与定义完全匹配(注意空格和大小写)
- 为每个YAML文件创建独立的
TestSuite实例,运行时指定独立输出文件,实现单独的日志和测试结果
修改后的完整代码示例
from robot.api import TestSuite from robot.api.deco import keyword import yaml @keyword("Request Api Call") def request_api_call(request_type, api_url, query_params, headers, body, expected_status): # 实际API调用逻辑 print(f"执行{request_type}请求:{api_url}") @keyword("Generate Robot Tests") def generate_robot_tests(test_cases, suite_name, file_path): # 创建测试套件 suite = TestSuite(suite_name) # 关键步骤:导入包含自定义关键字的模块(若关键字在单独文件,替换为对应模块名) suite.resource.imports.library(__name__) for test_case in test_cases: # 从YAML用例数据中提取字段(根据你的YAML结构调整) test_name = test_case["name"] request_type = test_case["request_type"] api_url = test_case["api_url"] query_params = test_case["query_params"] headers = test_case["headers"] body = test_case["body"] expected_status = test_case["expected_status"] # 创建测试用例 test = suite.tests.create(test_name) # 添加关键字调用,此时套件已识别自定义关键字 test.body.create_keyword( 'Request Api Call', args=[request_type, api_url, query_params, headers, body, expected_status] ) # 运行套件并生成独立输出文件(每个YAML对应单独的日志/结果) suite.run( output=f"{file_path}_output.xml", log=f"{file_path}_log.html", report=f"{file_path}_report.html" ) return suite # 示例:加载YAML并生成测试 if __name__ == "__main__": with open("test_cases.yaml", "r") as f: test_cases = yaml.safe_load(f) generate_robot_tests(test_cases, "API_Test_Suite", "api_test")
关键说明
- 库导入:
suite.resource.imports.library(__name__)用于导入当前模块;如果关键字在单独文件(如api_keywords.py),则替换为suite.resource.imports.library("api_keywords") - 独立输出:通过
suite.run()的output、log、report参数指定不同文件名,确保每个YAML生成的套件拥有独立的日志和结果文件 - YAML结构示例:你的测试用例YAML可按以下格式编写:
- name: "获取用户信息接口测试" request_type: "GET" api_url: "https://api.example.com/users/1" query_params: {"page": 1} headers: {"Content-Type": "application/json"} body: {} expected_status: 200 - name: "创建用户接口测试" request_type: "POST" api_url: "https://api.example.com/users" query_params: {} headers: {"Content-Type": "application/json"} body: {"name": "Test User", "email": "test@example.com"} expected_status: 201
内容的提问来源于stack exchange,提问作者Diogo Vala
相关产品推荐
相关产品推荐

