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

GitHub Actions中subprocess执行pytest时CLI参数未生效问题求助

问题:GitHub Actions中subprocess执行pytest时-m参数未被识别

问题现象

本地Windows环境运行run_tests.py时,pytest能正确识别-m sum参数,仅执行标记为sum的测试用例;但在GitHub Actions的Ubuntu-latest环境中,所有测试用例都会被执行,-m参数完全失效。

相关代码与配置

GitHub Actions工作流配置

name: Manual_Run

on:
  workflow_dispatch:
    inputs:
      mark:
        description: 'Which tests are executed'
        default: ''
        required: false
        type: string

  workflow_call:
    inputs:
      env:
        description: 'Environment on which the tests are executed'
        default: 'Prod'
        required: true
        type: string

permissions:
  id-token: write
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      INPUT_MARK: ${{ github.event.inputs.mark }}
    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Setup python 3.10
      uses: actions/setup-python@v5
      with:
        python-version: '3.10'
        cache: 'pip'

    - name: Install python requirements
      run: pip install -r requirements.txt
    - name: Run Pytest
      run: python run_tests.py

run_tests.py代码

import subprocess

if __name__ == "__main__":
    cmd = ['pytest', '-m', 'sum']
    subprocess.Popen(cmd, text=True, shell=True)

测试用例文件test_feats.py

import pytest

@pytest.mark.sum
def test_sum():
    assert 1 + 1 == 2

@pytest.mark.minus
def test_minus():
    assert 1 - 1 == 0

问题原因

问题根源在subprocess.Popen的shell=True参数:

  • Windows系统中,shell=True调用cmd.exe,能正确解析列表形式的命令参数;
  • Unix-like系统(如Ubuntu)中,shell=True调用/bin/sh,此时列表形式的命令会被当作单个字符串传递给shell,shell只会执行第一个元素pytest,后续的-m和sum被直接忽略,导致所有测试用例都被执行。

解决方案

方案1:移除shell=True(推荐)

这是符合subprocess最佳实践的安全方式,让subprocess直接解析参数列表:

import subprocess

if __name__ == "__main__":
    cmd = ['pytest', '-m', 'sum']
    # 改用subprocess.run等待命令执行完成,check=True可在测试失败时抛出异常
    subprocess.run(cmd, text=True, check=True)

使用subprocess.run替代Popen能确保脚本等待pytest执行完毕,避免后台执行导致的日志丢失,check=True还能让GitHub Actions正确捕获测试失败状态。

方案2:将命令转为字符串形式(不推荐,存在安全风险)

若必须使用shell=True,需把命令整合成单个字符串:

import subprocess

if __name__ == "__main__":
    cmd = 'pytest -m sum'
    subprocess.Popen(cmd, text=True, shell=True)

注意:该方式存在命令注入风险,若参数来自不可信输入,绝对不能使用。

验证效果

修改后重新运行GitHub Actions工作流,pytest会正确识别-m sum参数,仅执行标记为sum的测试用例,输出与本地Windows环境一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:00:08