如何在外部应用的嵌入式Python解释器中运行VS Code测试?
在VS Code中测试嵌入式Python代码的可行性与配置方案
问题背景
我正在开发必须在嵌入自有Python解释器(非系统Python或虚拟环境)的外部应用中执行的Python代码,无法直接使用VS Code标准Python扩展运行代码。希望实现:
- 在VS Code中编写和维护Python代码
- 从VS Code测试资源管理器运行单元测试
- 通过附加到外部应用的嵌入式Python进程,让测试在外部应用的上下文中执行
具体需求是:
- 不通过VS Code启动
python进程运行测试 - 附加到正在运行的外部进程
- 在其嵌入式Python解释器中注入或执行测试
- 通过自定义测试运行器将执行转发到外部应用
业务代码示例
from pyrx import Db # 外部应用提供的模块 def open_db(path: str) -> Db.Database: """从指定路径打开数据库""" db = Db.Database(False, True) db.readDwgFile(path) db.closeInput(True) return db
测试代码示例
from pyrx import Db def test_open_db(): db = open_db("test_files/sample.dwg") assert isinstance(db, Db.Database) assert db.getFilename().endswith("sample.dwg")
补充说明:该场景是CAD应用的Python扩展模块,通过应用内的PYLOAD命令运行Python模块,调试已使用debugpy远程附加功能。已有远程运行测试的代码,需要将其与pytest对接,让VS Code能捕获测试结果。
可行性结论
完全可行,核心思路是通过自定义pytest插件/钩子结合VS Code的测试适配器协议,将测试执行转发到外部嵌入式Python进程,同时利用debugpy实现调试附加。
具体配置步骤
1. 实现pytest自定义钩子对接远程测试运行器
基于已有的远程测试运行代码,编写pytest插件,重写测试收集和执行的核心钩子:
- 重写
pytest_collection_modifyitems:跳过本地测试收集,从外部进程获取测试列表并构造pytest测试项 - 重写
pytest_runtest_protocol:将测试执行请求转发到外部嵌入式Python进程,接收执行结果并同步给pytest
示例钩子核心逻辑:
import pytest from your_remote_runner import run_test_remotely, collect_tests_remotely def pytest_collection_modifyitems(session, config, items): # 清空本地收集的测试,替换为远程进程返回的测试列表 items.clear() remote_test_ids = collect_tests_remotely() for test_id in remote_test_ids: item = session.getitem(test_id) items.append(item) def pytest_runtest_protocol(item, nextitem): # 将测试执行请求发送到外部进程 result = run_test_remotely(item.nodeid) # 根据远程结果设置测试状态 if result["passed"]: return True else: pytest.fail(result["error_msg"], pytrace=False)
2. 配置VS Code Python扩展识别自定义测试流程
在.vscode/settings.json中指定测试运行器为pytest,并加载自定义插件:
{ "python.testing.pytestEnabled": true, "python.testing.pytestPath": "pytest", "python.testing.pytestArgs": [ "-p", "your_custom_plugin_name", "--no-header", "--no-summary" ], "python.testing.unittestEnabled": false, "python.testing.nosetestsEnabled": false }
3. 配置debugpy远程调试附加
确保外部嵌入式Python进程已启动debugpy监听:
# 在外部应用的嵌入式Python初始化逻辑中添加 import debugpy debugpy.listen(("localhost", 5678))
在VS Code的.vscode/launch.json中配置远程附加规则:
{ "version": "0.2.0", "configurations": [ { "name": "Attach to Embedded Python", "type": "python", "request": "attach", "connect": { "host": "localhost", "port": 5678 }, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/对应外部应用中代码的路径" } ] } ] }
4. 关联测试执行与调试
在VS Code测试资源管理器中,右键目标测试项选择「Debug Test」,VS Code会自动附加到远程进程,再通过自定义pytest钩子触发远程测试执行,实现带断点调试的测试运行。
简化变通方案(若自定义插件开发复杂)
如果暂时不想开发完整的pytest插件,可使用以下轻量方案:
- 编写脚本将测试代码打包为可加载模块,通过外部应用的
PYLOAD命令加载执行 - 在测试代码中以JSON格式输出测试结果,编写VS Code任务(
.vscode/tasks.json)解析输出并展示 - 结合
debugpy远程附加,手动触发测试执行并调试
关键注意事项
- 确保本地代码路径与外部应用中代码路径一致,或通过
pathMappings完成正确映射 - 自定义pytest插件需严格遵循pytest的结果格式要求,确保VS Code测试资源管理器能正确识别
- 外部应用需提供测试触发接口,允许远程调用测试并返回结构化结果
内容的提问来源于stack exchange,提问作者Grzegorz
相关产品推荐
相关产品推荐

