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

能否配置PyCharm Generate Test默认沿用源码子目录结构生成测试文件?

实现pytest测试文件自动匹配源码层级的配置方法

如果使用的是PyCharm/IntelliJ系列IDE,完全可以配置让Create Test功能自动把my.package模块的测试文件放到tests/my/package目录,无需手动构建路径:

  • 打开IDE设置(快捷键Ctrl+Alt+S),找到Tools > Python Integrated Tools
  • 在Testing区域,将默认测试 runner 设置为pytest
  • 在Test template file下方的Default test directory中,指定测试根目录为tests
  • 开启Inherit directory structure from sources选项——这个开关会让测试目录自动复刻源码的包结构,比如my/package下的类,测试文件会直接生成到tests/my/package,不存在的目录IDE会自动创建

如果项目源码放在src目录下,需要先在Project Structure里把src标记为Sources Root,tests标记为Tests Root,IDE就能自动识别两者的层级对应关系。

如果使用VS Code,可通过配置文件实现:
在.vscode/settings.json中添加以下内容:

{
  "python.testing.pytestArgs": ["tests"],
  "python.testing.unittestEnabled": false,
  "python.testing.pytestEnabled": true,
  "python.testing.testFilePattern": "test_*.py",
  "python.testing.generateTestStub": {
    "template": "pytest",
    "rootDirectory": "tests",
    "inheritFromSource": true
  }
}

该配置会让VS Code生成测试文件时,自动匹配源码包结构,将文件放到tests下对应子目录,缺失的目录也会自动创建。

内容的提问来源于stack exchange,提问作者WestCoastProjects

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:40:28