编写Python函数结合Git定位Robot Framework已修改测试用例并自动执行
基于Git变更的Robot Framework测试用例定位功能实现
核心实现逻辑
- 触发校验:先定位文件内
*** Test Cases ***专属区域的行号范围,仅对落在该范围内的变更行执行后续匹配,其他配置、关键字区域的变更不触发用例定位 - 用例名匹配:从变更行的位置开始向上逐行回溯,跳过空行,找到第一处行首无缩进(列号为0)的非空行,该行的文本内容即为变更行所属的测试用例名称
完整功能代码实现
from pathlib import Path def get_modified_rf_test_cases(file_path: str, modified_line_numbers: list[int]) -> set[str]: """ 结合Git检测的文件变更行,定位对应的Robot Framework测试用例名 :param file_path: RF测试用例文件的本地路径 :param modified_line_numbers: Git输出的文件修改行号列表(行号从1开始计数) :return: 匹配到的需执行的测试用例名集合 """ lines = Path(file_path).read_text(encoding="utf-8").splitlines() test_section_start = None test_section_end = len(lines) matched_cases = set() # 定位*** Test Cases ***区域的边界 for line_idx, line_content in enumerate(lines): stripped_content = line_content.strip() # 命中测试用例区域标识,记录起始行 if stripped_content == "*** Test Cases ***": test_section_start = line_idx continue # 遇到其他区域标识时,说明测试用例区域结束 if test_section_start is not None and stripped_content.startswith("*** ") and stripped_content != "*** Test Cases ***": test_section_end = line_idx break # 未检测到测试用例区域时直接返回空结果 if test_section_start is None: return matched_cases # 过滤出落在测试用例区域内的变更行(转成0起始的索引方便遍历) target_lines = [ line_no - 1 for line_no in modified_line_numbers if test_section_start < (line_no - 1) < test_section_end ] # 逐行向上回溯匹配所属用例 for line_idx in target_lines: for backtrack_idx in range(line_idx, test_section_start, -1): current_line = lines[backtrack_idx] stripped_line = current_line.strip() # 跳过空行 if not stripped_line: continue # 命中行首无缩进的行,即为当前用例名 if not current_line.startswith((" ", "\t")): matched_cases.add(stripped_line) break return matched_cases # 调用示例 if __name__ == "__main__": # 模拟Git获取的变更行,以参考的RF文件为例 git_modified_lines = [4, 11] result = get_modified_rf_test_cases("demo.robot", git_modified_lines) # 最终输出为 {'robot_test_case_1', 'robot_test_case_2'} print("需执行的变更用例:", result)
落地使用流程
- 通过Git脚本获取每次提交涉及的RF测试文件路径、以及文件内的具体修改行号列表
- 将获取到的参数传入上述函数,得到本次变更涉及的所有测试用例名集合
- 把匹配到的用例名传入Robot Framework执行命令,即可实现仅自动运行发生变更的测试用例的目标
内容的提问来源于stack exchange,提问作者Tiago Feitor
相关产品推荐
相关产品推荐

