Obtenir les données de couverture de code par fichier

POST https://api.ap1.datadoghq.com/api/v2/code-coverage/fileshttps://api.ap2.datadoghq.com/api/v2/code-coverage/fileshttps://api.datadoghq.eu/api/v2/code-coverage/fileshttps://api.ddog-gov.com/api/v2/code-coverage/fileshttps://api.us2.ddog-gov.com/api/v2/code-coverage/fileshttps://api.uk1.datadoghq.com/api/v2/code-coverage/fileshttps://api.datadoghq.com/api/v2/code-coverage/fileshttps://api.us3.datadoghq.com/api/v2/code-coverage/fileshttps://api.us5.datadoghq.com/api/v2/code-coverage/files

Présentation

Retrieve per-file code coverage data for a specific commit, branch, or pull request. Exactly one of commit_sha, branch, or pr_number must be provided. Optionally filter by service, codeowner, or flag (at most one). This endpoint requires the code_coverage_read permission.

OAuth apps require the code_coverage_read authorization scope to access this endpoint.

Requête

Body Data (required)

Expand All

Champ

Type

Description

data [required]

object

Data object for files coverage request.

attributes [required]

object

Attributes for requesting per-file code coverage data. Exactly one of commit_sha, branch, or pr_number must be provided. At most one of service, codeowner, or flag may be provided.

branch

string

The branch name.

changed_only

boolean

When true, return coverage data only for files that were changed in the specified scope.

codeowner

string

Filter coverage by code owner. At most one of service, codeowner, or flag may be provided.

commit_sha

string

The commit SHA (40-character hexadecimal string).

flag

string

Filter coverage by coverage flag. At most one of service, codeowner, or flag may be provided.

pr_number

int64

The pull request number. Must be a positive integer.

repository_id

string

DEPRECATED: Deprecated: use repository_url instead. The repository URL.

repository_url

string

The repository URL. Accepts a full URL with or without a scheme (for example, https://github.com/org/repo or github.com/org/repo).

service

string

Filter coverage by service name. At most one of service, codeowner, or flag may be provided.

type [required]

enum

JSON:API type for files coverage request. The value must always be ci_app_coverage_files_request. Allowed enum values: ci_app_coverage_files_request

{
  "data": {
    "attributes": {
      "branch": "main",
      "changed_only": true,
      "codeowner": "@my-team",
      "commit_sha": "66adc9350f2cc9b250b69abddab733dd55e1a588",
      "flag": "unit-tests",
      "pr_number": 42,
      "repository_id": "github.com/datadog/shopist",
      "repository_url": "https://github.com/datadog/shopist",
      "service": "my-service"
    },
    "type": "ci_app_coverage_files_request"
  }
}

Réponse

OK

Response object containing per-file code coverage data.

Expand All

Champ

Type

Description

data

object

Data object for files coverage response.

attributes

object

Attributes of the per-file code coverage response.

base_commit_sha

string

The SHA of the base commit used for comparison (for example, the merge base for a PR).

event_timestamp

int64

Unix timestamp (milliseconds) of the coverage event.

files

object

Map of file paths to per-file coverage line data.

<any-key>

object

Per-file line coverage data including executable, covered, and added lines.

added_lines

[integer]

Line numbers that were added in the specified scope (for example, in a PR diff).

covered_lines

[integer]

Line numbers that were covered by tests.

executable_lines

[integer]

Line numbers that are executable (can be covered).

head_commit_sha

string

The SHA of the head commit for which coverage was evaluated.

report_count

int64

Number of coverage reports evaluated.

id

string

Unique identifier for the files coverage response.

type

enum

JSON:API type for files coverage response. The value must always be ci_app_coverage_files. Allowed enum values: ci_app_coverage_files

{
  "data": {
    "attributes": {
      "base_commit_sha": "abc1234567890abcdef1234567890abcdef12345",
      "event_timestamp": 1709564000000,
      "files": {
        "<any-key>": {
          "added_lines": [
            11,
            12
          ],
          "covered_lines": [
            10,
            11,
            15
          ],
          "executable_lines": [
            10,
            11,
            12,
            15,
            20
          ]
        }
      },
      "head_commit_sha": "66adc9350f2cc9b250b69abddab733dd55e1a588",
      "report_count": 3
    },
    "id": "ZGQxMjM0NV9tYWluXzE3MDk1NjQwMDA=",
    "type": "ci_app_coverage_files"
  }
}

Bad Request

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Not Authorized

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Not Found

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Too many requests

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Internal server error

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Exemple de code

                  ## default
# 

# Use a Personal Access Token or Service Access Token
export DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>"

# Curl command
curl -X POST "https://api.ap1.datadoghq.com"https://api.ap2.datadoghq.com"https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.us2.ddog-gov.com"https://api.uk1.datadoghq.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v2/code-coverage/files" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${DD_BEARER_TOKEN}" \ -d @- << EOF { "data": { "attributes": { "changed_only": true, "commit_sha": "66adc9350f2cc9b250b69abddab733dd55e1a588", "repository_url": "https://github.com/datadog/test-service" }, "type": "ci_app_coverage_files_request" } } EOF
"""
Get per-file code coverage data returns "OK" response
"""

from os import environ
from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v2.api.code_coverage_api import CodeCoverageApi
from datadog_api_client.v2.model.files_coverage_request import FilesCoverageRequest
from datadog_api_client.v2.model.files_coverage_request_attributes import FilesCoverageRequestAttributes
from datadog_api_client.v2.model.files_coverage_request_data import FilesCoverageRequestData
from datadog_api_client.v2.model.files_coverage_request_type import FilesCoverageRequestType

body = FilesCoverageRequest(
    data=FilesCoverageRequestData(
        attributes=FilesCoverageRequestAttributes(
            changed_only=True,
            commit_sha="66adc9350f2cc9b250b69abddab733dd55e1a588",
            repository_url="https://github.com/datadog/shopist",
        ),
        type=FilesCoverageRequestType.CI_APP_COVERAGE_FILES_REQUEST,
    ),
)

configuration = Configuration()
configuration.access_token = environ["DD_BEARER_TOKEN"]
with ApiClient(configuration) as api_client:
    api_instance = CodeCoverageApi(api_client)
    response = api_instance.get_code_coverage_files(body=body)

    print(response)

Instructions

First install the library and its dependencies and then save the example to example.py and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" python3 "example.py"
# Get per-file code coverage data returns "OK" response

require "datadog_api_client"
DatadogAPIClient.configure do |config|
  config.access_token = ENV["DD_BEARER_TOKEN"]
end
api_instance = DatadogAPIClient::V2::CodeCoverageAPI.new

body = DatadogAPIClient::V2::FilesCoverageRequest.new({
  data: DatadogAPIClient::V2::FilesCoverageRequestData.new({
    attributes: DatadogAPIClient::V2::FilesCoverageRequestAttributes.new({
      changed_only: true,
      commit_sha: "66adc9350f2cc9b250b69abddab733dd55e1a588",
      repository_url: "https://github.com/datadog/shopist",
    }),
    type: DatadogAPIClient::V2::FilesCoverageRequestType::CI_APP_COVERAGE_FILES_REQUEST,
  }),
})
p api_instance.get_code_coverage_files(body)

Instructions

First install the library and its dependencies and then save the example to example.rb and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" rb "example.rb"
// Get per-file code coverage data returns "OK" response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
)

func main() {
	body := datadogV2.FilesCoverageRequest{
		Data: datadogV2.FilesCoverageRequestData{
			Attributes: datadogV2.FilesCoverageRequestAttributes{
				ChangedOnly:   datadog.PtrBool(true),
				CommitSha:     datadog.PtrString("66adc9350f2cc9b250b69abddab733dd55e1a588"),
				RepositoryUrl: datadog.PtrString("https://github.com/datadog/shopist"),
			},
			Type: datadogV2.FILESCOVERAGEREQUESTTYPE_CI_APP_COVERAGE_FILES_REQUEST,
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	ctx = context.WithValue(ctx, datadog.ContextAccessToken, os.Getenv("DD_BEARER_TOKEN"))
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV2.NewCodeCoverageApi(apiClient)
	resp, r, err := api.GetCodeCoverageFiles(ctx, body)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `CodeCoverageApi.GetCodeCoverageFiles`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `CodeCoverageApi.GetCodeCoverageFiles`:\n%s\n", responseContent)
}

Instructions

First install the library and its dependencies and then save the example to main.go and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" go run "main.go"
// Get per-file code coverage data returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v2.api.CodeCoverageApi;
import com.datadog.api.client.v2.model.FilesCoverageRequest;
import com.datadog.api.client.v2.model.FilesCoverageRequestAttributes;
import com.datadog.api.client.v2.model.FilesCoverageRequestData;
import com.datadog.api.client.v2.model.FilesCoverageRequestType;
import com.datadog.api.client.v2.model.FilesCoverageResponse;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    defaultClient.setAccessToken(System.getenv("DD_BEARER_TOKEN"));
    CodeCoverageApi apiInstance = new CodeCoverageApi(defaultClient);

    FilesCoverageRequest body =
        new FilesCoverageRequest()
            .data(
                new FilesCoverageRequestData()
                    .attributes(
                        new FilesCoverageRequestAttributes()
                            .changedOnly(true)
                            .commitSha("66adc9350f2cc9b250b69abddab733dd55e1a588")
                            .repositoryUrl("https://github.com/datadog/shopist"))
                    .type(FilesCoverageRequestType.CI_APP_COVERAGE_FILES_REQUEST));

    try {
      FilesCoverageResponse result = apiInstance.getCodeCoverageFiles(body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling CodeCoverageApi#getCodeCoverageFiles");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}

Instructions

First install the library and its dependencies and then save the example to Example.java and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" java "Example.java"
// Get per-file code coverage data returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV2::api_code_coverage::CodeCoverageAPI;
use datadog_api_client::datadogV2::model::FilesCoverageRequest;
use datadog_api_client::datadogV2::model::FilesCoverageRequestAttributes;
use datadog_api_client::datadogV2::model::FilesCoverageRequestData;
use datadog_api_client::datadogV2::model::FilesCoverageRequestType;

#[tokio::main]
async fn main() {
    let body = FilesCoverageRequest::new(FilesCoverageRequestData::new(
        FilesCoverageRequestAttributes::new()
            .changed_only(true)
            .commit_sha("66adc9350f2cc9b250b69abddab733dd55e1a588".to_string())
            .repository_url("https://github.com/datadog/shopist".to_string()),
        FilesCoverageRequestType::CI_APP_COVERAGE_FILES_REQUEST,
    ));
    let configuration = datadog::Configuration::new();
    let api = CodeCoverageAPI::with_config(configuration);
    let resp = api.get_code_coverage_files(body).await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}

Instructions

First install the library and its dependencies and then save the example to src/main.rs and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
/**
 * Get per-file code coverage data returns "OK" response
 */

import { client, v2 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration({
  authMethods: {
    AuthZ: {
      accessToken: process.env.DD_BEARER_TOKEN as string,
    },
  },
});
const apiInstance = new v2.CodeCoverageApi(configuration);

const params: v2.CodeCoverageApiGetCodeCoverageFilesRequest = {
  body: {
    data: {
      attributes: {
        changedOnly: true,
        commitSha: "66adc9350f2cc9b250b69abddab733dd55e1a588",
        repositoryUrl: "https://github.com/datadog/shopist",
      },
      type: "ci_app_coverage_files_request",
    },
  },
};

apiInstance
  .getCodeCoverageFiles(params)
  .then((data: v2.FilesCoverageResponse) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));

Instructions

First install the library and its dependencies and then save the example to example.ts and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" tsc "example.ts"