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

如何从TestRail触发GitLab Pipeline?

从TestRail触发GitLab Pipeline的实现方法

核心逻辑

借助TestRail的自定义脚本/钩子能力,结合GitLab的API触发机制,直接完成流水线调用,无需第三方跳转工具。

具体实现步骤

1. 准备GitLab触发凭证

  • 在GitLab项目中创建个人访问令牌(PAT),权限需勾选api和read_repository,确保具备触发流水线的权限
  • 记录GitLab项目ID(可在项目主页「设置」-「通用」中找到)

2. 在TestRail中配置触发逻辑

TestRail支持两种主流实现方式,按需选择:

方式一:TestRail内置自定义脚本(推荐)

  • 进入TestRail后台「Administration」-「Customizations」-「Scripts」
  • 创建新脚本,绑定到目标操作(比如测试用例的「运行」按钮、测试计划的「执行」操作),核心代码示例:
    // 替换为你的实际配置
    const gitlabToken = '你的GitLab PAT';
    const projectId = '你的GitLab项目ID';
    const pipelineUrl = `https://你的GitLab域名/api/v4/projects/${projectId}/pipeline`;
    
    // 调用GitLab API触发流水线
    fetch(pipelineUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${gitlabToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        ref: 'main', // 指定要触发的分支
        variables: { // 可选:传递TestRail上下文参数,比如测试计划ID
          TESTRAIL_PLAN_ID: testPlan.id
        }
      })
    })
    .then(res => res.json())
    .then(data => {
      // 可选:在TestRail中添加反馈,比如更新测试用例状态
      testCase.status_id = 3; // 标记为「正在测试」
    })
    .catch(err => console.error('触发失败:', err));
    

方式二:TestRail API + 独立中间脚本

  • 编写独立脚本(Python/Shell均可),通过TestRail API监听特定事件(比如测试计划启动),再调用GitLab API触发流水线,Python示例:
    import requests
    
    # TestRail配置
    testrail_url = "https://你的TestRail域名/index.php?/api/v2/"
    testrail_auth = ("你的TestRail账号邮箱", "你的TestRail API令牌")
    
    # GitLab配置
    gitlab_token = "你的GitLab PAT"
    gitlab_project_id = "123"
    gitlab_api_url = f"https://你的GitLab域名/api/v4/projects/{gitlab_project_id}/pipeline"
    
    # 监听TestRail测试计划状态并触发流水线
    def trigger_pipeline():
        # 获取目标测试计划信息(替换为你的计划ID)
        plan_res = requests.get(f"{testrail_url}get_plan/1", auth=testrail_auth)
        plan = plan_res.json()
        # 当测试计划处于待执行状态时触发
        if not plan["is_completed"] and plan["status_id"] == 1:
            gitlab_res = requests.post(
                gitlab_api_url,
                headers={"Authorization": f"Bearer {gitlab_token}"},
                json={"ref": "main", "variables": {"TESTRAIL_PLAN_ID": plan["id"]}}
            )
            print("流水线触发成功" if gitlab_res.status_code == 201 else f"触发失败: {gitlab_res.text}")
    
    if __name__ == "__main__":
        trigger_pipeline()
    
  • 将脚本部署到服务器,通过定时任务或TestRail的webhook触发执行

3. 验证调试

  • 在TestRail中执行绑定的操作,查看GitLab项目「流水线」页面是否有新流水线启动
  • 若触发失败,检查TestRail脚本日志或中间脚本运行日志,排查API权限、参数配置问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:11:03