Merged
feat(build): Support mixed execution of STest and Examples in a single pytest command to reduce overall runtime #636
杨旭Add on Jan 23
feat(build): Support mixed execution of STest and Examples in a single pytest command to reduce overall runtime #636
Merged
杨旭Add on Jan 23
Total: 4 files changed+65-108
@@ -30,10 +30,6 @@ from importlib import metadata
30from packaging import requirements30from packaging import requirements
31 31 
32 32 
33-if str(Path(Path(__file__).parent, "tools")) not in sys.path:
34- sys.path.append(str(Path(Path(__file__).parent, "tools")))
35- 
36- 
37class CMakeParam(abc.ABC):33class CMakeParam(abc.ABC):
38 """需要向 CMake 传入 Option 的参数34 """需要向 CMake 传入 Option 的参数
39 """35 """
@@ -52,27 +48,46 @@ class CMakeParam(abc.ABC):
52 @staticmethod48 @staticmethod
53 @abc.abstractmethod49 @abc.abstractmethod
54 def reg_args(parser, ext: Optional[Any] = None):50 def reg_args(parser, ext: Optional[Any] = None):
51+ """
52+ 注册命令行参数
53+ 
54+ :param parser: 参数解析器
55+ :param ext: 扩展信息, 用于子类特殊实现扩展时使用
56+ :type ext: Optional[Any]
57+ """
55 pass58 pass
56 59 
57 @classmethod60 @classmethod
58 def _cfg_require(cls, opt: str, ctr: bool = True, tv: str = "ON", fv: str = "OFF") -> str:61 def _cfg_require(cls, opt: str, ctr: bool = True, tv: str = "ON", fv: str = "OFF") -> str:
59- """获取 CMake Config 阶段的必选 Option 配置62+ """
63+ 获取 CMake Config 阶段的必选 Option 配置
60 64 
61- :param opt: CMake 选项, 会最终体现到 CMake -D传入的参数中65+ :param opt: CMake Option 值, 会最终体现到 CMake -D传入的参数中
62- :param ctr: 控制变量66+ :type opt: str
63- :param tv: 控制变量为 True 时, 设置的值67+ :param ctr: 控制变量, 标识 CMake Option 布尔值
64- :param fv: 控制变量为 False 时, 设置的值68+ :type ctr: bool
65- :return: 设置的值69+ :param tv: ctr 为 True 时, 设置的值
70+ :type tv: str
71+ :param fv: ctr 为 False 时, 设置的值
72+ :type fv: str
73+ :return: 设置结果
74+ :rtype: str
66 """75 """
67 return f" -D{opt}=" + (tv if ctr else fv)76 return f" -D{opt}=" + (tv if ctr else fv)
68 77 
69 @classmethod78 @classmethod
70 def _cfg_optional(cls, opt: str, ctr: bool, v: str):79 def _cfg_optional(cls, opt: str, ctr: bool, v: str):
71- """获取 CMake Config 阶段的可选 Option 配置80+ """
81+ 获取 CMake Config 阶段的可选 Option 配置
72 82 
73- :param opt: CMake 选项, 会最终体现到 CMake -D传入的参数中83+ :param opt: CMake Option 值, 会最终体现到 CMake -D传入的参数中
74- :param ctr: 控制变量84+ :type opt: str
85+ :param ctr: 控制变量, 标识 CMake Option 布尔值
86+ :type ctr: bool
75 :param v: 控制变量为 True 时, 设置的值87 :param v: 控制变量为 True 时, 设置的值
88+ :type v: str
89+ :return: 设置结果
90+ :rtype: str
76 """91 """
77 return (f" -D{opt}=" + v) if ctr else ""92 return (f" -D{opt}=" + v) if ctr else ""
78 93 
@@ -661,9 +676,13 @@ class BuildCtrl(CMakeParam):
661 676 
662 @staticmethod677 @staticmethod
663 def which_cmake() -> Optional[Path]:678 def which_cmake() -> Optional[Path]:
664- """查找系统级 CMake 可执行文件路径679+ """
680+ 查找系统级 CMake 可执行文件路径
665 681 
666- 排除 cmake pip 包的干扰682+ 实现本函数是为了排除 cmake pip 包的干扰, 否则在 Python 中直接调用 cmake 会调用到 cmake pip 包.
683+ 
684+ :return: 系统级 cmake 可执行文件绝对路径
685+ :rtype: Path | None
667 """686 """
668 # 拆分 PATH 环境变量为单个目录列表(排除空目录)687 # 拆分 PATH 环境变量为单个目录列表(排除空目录)
669 path_dir_lst = [d.strip() for d in os.environ.get("PATH", "").split(os.pathsep) if d.strip()]688 path_dir_lst = [d.strip() for d in os.environ.get("PATH", "").split(os.pathsep) if d.strip()]
@@ -693,11 +712,15 @@ class BuildCtrl(CMakeParam):
693 712 
694 @staticmethod713 @staticmethod
695 def find_match_whl(name: str, path: Path) -> Optional[Path]:714 def find_match_whl(name: str, path: Path) -> Optional[Path]:
696- """在指定路径下, 查找对应匹配的 whl 包文件715+ """
716+ 在指定路径下, 查找对应匹配的 whl 包文件
697 717 
698 :param name: 包名718 :param name: 包名
719+ :type name: str
699 :param path: 指定路径720 :param path: 指定路径
700- :return: whl 包路径, None 表示未找到721+ :type path: Path
722+ :return: 指定路径
723+ :rtype: Path | None
701 """724 """
702 cpp_desc = f"cp{sys.version_info.major}{sys.version_info.minor}"725 cpp_desc = f"cp{sys.version_info.major}{sys.version_info.minor}"
703 pattern = f"{name}-*-{cpp_desc}-{cpp_desc}-*.whl"726 pattern = f"{name}-*-{cpp_desc}-{cpp_desc}-*.whl"
@@ -1046,30 +1069,36 @@ class BuildCtrl(CMakeParam):
1046 n_workers = str(self.build.job_num)1069 n_workers = str(self.build.job_num)
1047 else:1070 else:
1048 n_workers = "auto"1071 n_workers = "auto"
1049- self.py_tests_run_pytest(dist=dist, tests=self.tests.utest,1072+ self.py_tests_run_pytest(dist=dist, params=[(self.tests.utest, "python/tests/ut")],
1050- def_filter=str(Path(self.src_root, "python/tests/ut")),
1051 ext=f"-n {n_workers} -W ignore::DeprecationWarning")1073 ext=f"-n {n_workers} -W ignore::DeprecationWarning")
1052 1074 
1053- # 设置 Device 相关参数1075+ # 执行用例, Examples/STest, 支持混合执行
1054 dev_lst = [int(d) for d in self.tests.stest_exec.auto_execute_device_id.split(":")]1076 dev_lst = [int(d) for d in self.tests.stest_exec.auto_execute_device_id.split(":")]
1055 dev_ext = " ".join(f"{d}" for d in dev_lst)1077 dev_ext = " ".join(f"{d}" for d in dev_lst)
1056 ext_str = f"-n {len(dev_lst)} --device {dev_ext}"1078 ext_str = f"-n {len(dev_lst)} --device {dev_ext}"
1057- 1079+ self.py_tests_run_pytest(dist=dist, params=[(self.tests.example, "examples"),
1058- # 执行用例, STest1080+ (self.tests.stest, "python/tests/st")],
1059- self.py_tests_run_pytest(dist=dist, tests=self.tests.stest,
1060- def_filter=str(Path(self.src_root, "python/tests/st")),
1061 ext=ext_str)1081 ext=ext_str)
1062 1082 
1063- # 执行用例, Examples1083+ def py_tests_run_pytest(self, dist: Optional[Path], params: List[Tuple[TestsFilterParam, str]], ext: str = ""):
1064- self.py_tests_run_pytest(dist=dist, tests=self.tests.example,1084+ """
1065- def_filter=str(Path(self.src_root, "examples")),1085+ 调用 pytest 执行用例
1066- ext=ext_str)
1067 1086 
1068- def py_tests_run_pytest(self, dist: Optional[Path], tests: TestsFilterParam, def_filter: str, ext: str = ""):1087+ :param dist: 二进制分发包安装路径
1069- if not tests.enable:1088+ :type dist: Optional[Path]
1070- return1089+ :param params: 参数列表, 支持多路径下用例混跑
1090+ :type params: List[Tuple[TestsFilterParam, str]]
1091+ :param ext: 扩展命令参数
1092+ :type ext: str
1093+ """
1071 # filter 处理1094 # filter 处理
1072- filter_str = tests.get_filter_str(def_filter=def_filter)1095+ filter_str = ""
1096+ for cur_tests, cur_filter_str in params:
1097+ cur_filter_str = cur_tests.get_filter_str(def_filter=cur_filter_str)
1098+ if cur_filter_str:
1099+ filter_str += f" {cur_filter_str}"
1100+ if not filter_str:
1101+ return
1073 # 执行 pytest1102 # 执行 pytest
1074 self._py_tests_run_pytest(dist=dist, filter_str=filter_str, ext=ext)1103 self._py_tests_run_pytest(dist=dist, filter_str=filter_str, ext=ext)
1075 1104 
Rpython/tests/conftest.py→conftest.py+0-0
File renamed without changes.
@@ -1,72 +0,0 @@
1-#!/usr/bin/env python3
2-# coding: utf-8
3-# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5-# CANN Open Software License Agreement Version 2.0 (the "License").
6-# Please refer to the License for details. You may not use this file except in compliance with the License.
7-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9-# See LICENSE in the root of the software repository for the full text of the License.
10-# -----------------------------------------------------------------------------------------------------------
11-"""Pytest 配置控制
12-"""
13-import os
14-from typing import List, Optional
15- 
16-import pytest
17- 
18- 
19-def _set_process_desc(desc: str):
20- try:
21- import setproctitle
22- setproctitle.setproctitle(desc)
23- except ModuleNotFoundError:
24- pass
25- 
26- 
27-def pytest_addoption(parser: pytest.Parser):
28- """向 pytest 注册自定义参数
29- 
30- :param parser: pytest.Parser 类型
31- """
32- parser.addoption("--device", nargs="+", type=int,
33- help="Device ID, default 0")
34- 
35- 
36-def pytest_configure_node(node):
37- """pytest-xdist 回调函数, 在 pytest 主进程 fork 出 worker 进程之前被调用.
38- 
39- :param node: worker 节点
40- """
41- # 获取 DeviceId 列表, 当外部传入 --device 时, 是 STest 场景, 否则是 UTest 场景
42- device_id_lst: Optional[List[int]] = node.config.getoption("--device")
43- if device_id_lst:
44- # 获取 WorkerIdx, 并获取 DeviceId
45- worker_idx = int(str(node.gateway.id).lstrip("gw"))
46- if worker_idx >= len(device_id_lst):
47- raise ValueError(f"WorkerIdx[{worker_idx}] out of DeviceIdLst{device_id_lst} range.")
48- device_id: int = device_id_lst[worker_idx]
49- 
50- # 修改 worker 名称, 设置 worker 中的 DeviceId
51- node.gateway.id = f"Device[{device_id}]" # 体现在回显中
52- node.gateway.remote_exec(f'import os; os.environ["TILE_FWK_DEVICE_ID"] = "{device_id}"')
53- else:
54- node.gateway.remote_exec(f'import os; os.environ.pop("TILE_FWK_DEVICE_ID", None)')
55- 
56- 
57-@pytest.hookimpl(tryfirst=True)
58-def pytest_runtest_protocol(item, nextitem):
59- device_id: Optional[str] = os.environ.get("TILE_FWK_DEVICE_ID", None)
60- if device_id is not None:
61- _set_process_desc(f"Device[{device_id}]")
62- return None
63- 
64- 
65-@pytest.hookimpl(tryfirst=True)
66-def pytest_runtest_setup(item):
67- """case 进程启动后被调用"""
68- device_id: Optional[str] = os.environ.get("TILE_FWK_DEVICE_ID", None)
69- if device_id is not None:
70- case_name: str = str(item.name)
71- _set_process_desc(f"Case(Device[{device_id}]::{case_name})")
72- return None # 继续执行默认的测试流程
Rexamples/pytest.ini→pytest.ini+4-4
@@ -8,8 +8,8 @@
8# -----------------------------------------------------------------------------------------------------------8# -----------------------------------------------------------------------------------------------------------
9 9 
10[pytest]10[pytest]
11-# 忽略的文件夹11+# 全局测试文件匹配规则(包含 examples 定制规则和 pytest 默认规则)
12-# norecursedirs = utils deepseek_v32_exp12+python_files = test_*.py glm_*.py deepseekv32_*.py
13 13 
14-# 指定测试文件匹配模式14+# 指定默认测试路径
15-python_files = glm_*.py deepseekv32_*.py15+testpaths = examples python/tests/ut python/tests/st