You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pytest中unittest.main()的等效实现:仅调试当前测试模块

仅调试当前pytest测试模块的方法

要让pytest仅调试当前测试模块,只需给pytest.main()传入当前文件的路径参数,避免扫描整个项目目录。修改后的代码如下:

# test_foo_module.py
import pytest

def test_foo():
    assert True

if __name__ == '__main__':
    pytest.main([__file__])

__file__会自动获取当前脚本的绝对路径,将其作为参数传入后,pytest就只会执行当前文件内的测试用例,和unittest的unittest.main()实现完全等效,此时按下F5即可直接调试当前模块。

如果不想用__file__,也可以直接传入当前文件的相对路径(比如pytest.main(["test_foo_module.py"])),但__file__的方式更灵活,无需手动修改文件名。

内容的提问来源于stack exchange,提问作者C. Claudio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 00:32:34