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

Pytest从上级目录收集测试用例失败问题求助

跨目录运行Pytest测试用例失败的解决方案

目录结构

|- project/    
   |- test_dir2/
      |- <testfile> 
   |- tester/
      |- conftest.py
      |- pytest.ini
      |- test_dir1/
         |- <testfile>

现状说明

当前工作目录为~/<path>/project/tester:

  • 运行tester目录内的测试用例正常:

    pytest test_dir1/ --type Dev
    

    输出:

    platform linux -- Python 3.6.8, pytest-7.0.1, pluggy-1.0.0

    rootdir: //project/tester

    collected 1 item

    test_dir1/

  • 运行上级目录test_dir2的测试用例出现两种问题:

    1. 带--type参数执行报错:

      pytest ../test_dir2/ --type Dev
      

      错误输出:

      ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]

      pytest: error: unrecognized arguments: --type Dev

      inifile: None

      rootdir: //project/

    2. 去掉参数后执行,收集不到测试用例:

      pytest ../test_dir2/
      

      输出:

      platform linux -- Python 3.6.8, pytest-7.0.1, pluggy-1.0.0

      rootdir: //project

      collected 0 items

问题原因

  1. 自定义参数识别失败:当指定../test_dir2/作为测试目录时,pytest自动将rootdir切换为project/,而--type这个自定义参数是tester/目录下conftest.py或pytest.ini中定义的,project/下无相关配置,导致pytest无法识别该参数。
  2. 测试用例收集失败:rootdir切换到project/后,pytest默认的测试文件匹配规则可能无法覆盖test_dir2,或者project/下没有配置文件引导pytest识别该目录的测试用例。

解决办法

方法1:强制指定rootdir为tester目录

执行命令时添加--rootdir ./,让pytest强制使用当前tester/目录作为rootdir,从而加载该目录下的配置文件,识别自定义参数:

pytest ../test_dir2/ --type Dev --rootdir ./

方法2:复制配置文件到project目录

将tester/下的conftest.py和pytest.ini复制到project/目录下,这样无论从哪个子目录执行pytest,都能加载到自定义参数和测试文件匹配规则。

方法3:使用绝对路径指定测试文件

直接用绝对路径指定test_dir2中的测试文件,同时指定rootdir:

pytest /<path>/project/test_dir2/<testfile> --type Dev --rootdir ./

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:45:17