You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python调用GitLab API获取测试报告失败,请求排查授权及数据获取问题

Python调用GitLab API获取测试报告失败,请求排查授权及数据获取问题

我现在在做一个项目,需要通过GitLab提交Python代码后自动运行测试用例并展示结果,但遇到了一个问题:无论怎么尝试,都无法获取到测试结果数据。我怀疑是GitLab的授权出了问题,因为调试时发现代码好像卡在了登录页面,调用.json()的时候会报错,因为根本没拿到数据。下面是我的代码(已省略URL和Token):

def get_test_report(pipeline_id, job_name):
    """
    Fetches the test report for a specific job in a given pipeline from GitLab.
    """
    url = f"{GITLAB_API_URL}/projects/{PROJECT_ID}/pipelines/{pipeline_id}/builds"
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}"
    }

    response = requests.get(url, headers=headers)

    if response.status_code != 200:
        print(f"Error: Unable to fetch jobs for pipeline {pipeline_id}. Status code: {response.status_code}")
        return None

    jobs = response.json()

    for job in jobs:
        if job["name"] == job_name:
            job_id = job["id"]
            # Once the job is found, fetch the test report (if available) for the job
            test_report_url = f"{GITLAB_API_URL}/projects/{PROJECT_ID}/pipelines/{pipeline_id}/test-report?job_name=python_test"
            test_report_response = requests.get(test_report_url, headers=headers)

            if test_report_response.status_code == 200:
                return test_report_response.json()
            else:
                print(f"Error: Unable to fetch test report for job {job_name} in pipeline {pipeline_id}.")
                return None

    print(f"Error: Job {job_name} not found in pipeline {pipeline_id}.")
    return None
@app.route('/pipeline/<pipeline_id>/test-results', methods=['GET'])
def get_test_results(pipeline_id):
    """
    Fetches the test results for a pipeline by retrieving the test report for specific jobs in that pipeline.
    """
    job_name = "python_test"

    test_report = get_test_report(pipeline_id, job_name)

    if not test_report:
        return jsonify({"message": "No test report found for this job."}), 404

    return jsonify(test_report)
if __name__ == '__main__':
    app.run(debug=True)

看起来你遇到的核心问题是授权验证失败,导致请求被重定向到GitLab的登录页面,自然拿不到预期的JSON数据。我给你梳理几个排查和修复的方向:

  • 先确认Token的权限和有效性
    首先,你用的ACCESS_TOKEN必须是具有项目读取权限的个人访问令牌(PAT),或者是项目级的访问令牌。要检查:

    • 令牌是否在GitLab后台正确生成,有没有过期
    • 令牌的权限范围是否勾选了read_apiread_repository(如果需要读取测试报告,这两个权限是必须的)
    • 可以先在本地用curl测试一下令牌是否有效,比如运行:
      curl --header "Authorization: Bearer YOUR_TOKEN" "https://gitlab.example.com/api/v4/projects/YOUR_PROJECT_ID/pipelines/YOUR_PIPELINE_ID/builds"
      
      如果返回正常的JSON数据,说明令牌没问题;如果返回登录页面的HTML,那肯定是令牌权限或有效性有问题。
  • 检查API URL的正确性
    GitLab API的基础URL应该是https://your-gitlab-instance.com/api/v4,你要确认GITLAB_API_URL是否包含了/api/v4这个路径,很多人容易漏掉这部分,导致请求到错误的地址,进而被重定向到登录页。

  • 修复测试报告的API调用逻辑
    你当前调用测试报告的URL有个小问题:既然已经找到了对应的job_id,其实可以直接用job的测试报告端点,而不是通过pipeline的测试报告加job_name参数。正确的job测试报告URL应该是:

    test_report_url = f"{GITLAB_API_URL}/projects/{PROJECT_ID}/jobs/{job_id}/test_report"
    

    这个端点更直接,也能避免job_name匹配可能出现的问题(比如同名job的情况)。

  • 调试时查看原始响应内容
    建议在代码里加一句打印响应内容的代码,比如在response = requests.get(url, headers=headers)之后,打印response.text,这样就能看到到底是返回了登录页面的HTML,还是其他错误信息,方便定位问题:

    print("Response content:", response.text)
    
  • 处理重定向问题
    默认情况下,requests会自动跟随重定向,如果你被重定向到登录页,response.status_code可能会是200(因为登录页加载成功),但返回的是HTML而不是JSON。可以关闭自动重定向,看看真实的状态码:

    response = requests.get(url, headers=headers, allow_redirects=False)
    

    如果返回3xx的状态码,就说明确实被重定向了,大概率是授权失败。

备注:内容来源于stack exchange,提问作者PromptDirector

火山引擎 最新活动