如何获取构建管道的通过、失败、放弃测试的计数

问题描述 投票:0回答:1

需要对构建管道的通过/失败/放弃测试进行计数,有什么办法吗? 我的Python文件:


    project = ""
    personal_access_token = ""
    pipeline_id = ""
    end_date = datetime.datetime.now()
    start_date = end_date - relativedelta(weeks=1)
    start_date_str = start_date.strftime("%Y-%m-%dT%H:%M:%SZ")
    end_date_str = end_date.strftime("%Y-%m-%dT%H:%M:%SZ")
    url = f"https://dev.azure.com/{organization_encoded}/{project_encoded}/_apis/test/runs?$pipelineId={pipeline_id_encoded}&minLastUpdatedDate={start_date_str}&maxLastUpdatedDate={end_date_str}&api-version=6.0"
    headers = {
        "Content-Type": "application/json-patch+json",
        "Authorization": f"Basic {personal_access_token}"
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        test_runs = response.json()
        for test_run in test_runs["value"]:
            print(f"Test Run ID: {test_run['id']}")
            print(f"Title: {test_run['name']}")
            print(f"Outcome: {test_run['outcome']}")
            print(f"Last Updated Date: {test_run['lastUpdated']}")
            print()

我正在尝试这样做,但失败了。它在控制台上打印 html Azure DevOps Services 页面。

我在控制台上得到这个:

 <html lang="en-US">
    <head><title>
    
            Azure DevOps Services | Sign In

</title><meta http-equiv="X-UA-Compatible" 

content="IE=11;&#32;IE=10;&#32;IE=9;&#32;IE=8" />
        <link rel="SHORTCUT ICON" href="/favicon.ico"/>
    
        <link data-bundlelength="516193" data-bundlename="commoncss" data-highcontrast="/_static/tfs/M228_20230922.2/_cssbundles/HighContrast/vss-bundle-commoncss-vCZ9D6UIO_qlhG7RrGLDp5ecIS_cunZt7_o3iwWt7lrU=" data-includedstyles="jQueryUI-Modified;Core;Splitter;PivotView" href="/_static/tfs/M228_20230922.2/_cssbundles/Default/vss-bundle-commoncss-v-iQu887NdMc5JZJk3qLWWpoiugyfgcgvhjbmnbjhkWr3S8s=" rel="stylesheet" />
 href="/_static/tfs/M228_20230922.2/_cssbundles/Default/vss-bundle-viewcss-vZeWfVvRTo2a7DO4ptMBi0cCBa3W_gjANgU36Es8paWQ=" rel="stylesheet" />

    <!--UxServices customizations -->
    <link href="/_static/tfs/M228_20230922.2/_content/Authentication.css" type="text/css" rel="stylesheet" />
</head>
<body class="platform"> 
<script type="text/javascript"> if (window.performance && window.performance.mark) { window.performance.mark('requireStart'); } 
require(["Authentication/Scripts/SPS.Authentication.Controls","Authentication/Scripts/SPS.Authentication"], function(){  if (window.performance && window.performance.mark) { window.performance.mark('requireEnd'); } window.requiredModulesLoaded=true;  });  
</script>
</body>
</html>

我也尝试过使用base64:

base64_token = base64.b64encode(f"{personal_access_token}".encode("utf-8")).decode("utf-8")

headers = {
    "Content-Type": "application/json-patch+json",
    "Authorization": f"Basic {base64_token}"
}

我收到“无法检索测试运行错误代码 400”。这种方式也行不通。 我这样更新了我的代码:

credentials = ":" + pat
token = base64.b64encode(credentials.encode()).decode()
headers = {
    "Authorization": "Basic " + token
}
test_outcomes = Counter()

        if test_results_response.status_code == 200:
            test_results = test_results_response.json()
            for test_result in test_results.get('value', []):
                outcome = test_result['outcome']
                test_case = test_result['testCase']['name']
                print(f'Test Case: {test_case}, Outcome: {outcome}')
                test_outcomes[test_case] += 1
    most_frequent_failed = test_outcomes.most_common(1)
    if most_frequent_failed:
        test_case, frequency = most_frequent_failed[0]
        print(f"Most Frequent Failed Test Case: {test_case} (Frequency: {frequency})")
    else:
        print("No failed test cases found.")
else:
    print(f"Failed to retrieve test runs. Status code: {response.status_code}")

但是,如果我打印所有结果,它会不间断地显示通过的测试用例列表:

        if test_results_response.status_code == 200:
        test_results = test_results_response.json()
        for test_result in test_results.get('value', []):
            outcome = test_result['outcome']
            test_case = test_result['testCase']['name']
            print(f'Test Case: {test_case}, Outcome: {outcome}')
azure-devops azure-devops-rest-api
1个回答
0
投票

我可以使用此Resultsummarybypipeline - Query API获取构建的测试结果摘要。

import requests
import base64
PAT = ''
authorization = str(base64.b64encode(bytes(':'+PAT, 'ascii')), 'ascii')
headers = {
    'Accept': 'application/json',
    'Authorization': 'Basic '+authorization
}
response = requests.get(
    url="https://vstmr.dev.azure.com/{OrganizationName}/{ProjectName}/_apis/testresults/resultsummarybypipeline?pipelineId={Pipeline_ID}&api-version=7.2-preview.1", headers=headers)
print(response.text)

我的测试结果:

© www.soinside.com 2019 - 2024. All rights reserved.