Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically add attachments to test results during a build in VSTS?

I'm looking for a way to add my own attachments to test results so that I can see them after a build has completed here...

enter image description here

I would like to add these programmatically, during a build and after a test has failed. The attachments will be screenshots.

Is this possible?

I had a quick look at the API reference but this looked to be concerned with adding attachments to existing test 'runs', or on the build, the side was for creating build definitions and triggering them. I may have missed it but I couldn't find how to add attachments from code during or immediately after a test task had completed.

Thanks,

like image 308
Konzy262 Avatar asked Dec 04 '17 10:12

Konzy262


1 Answers

You could get test run of the build first and then retrieve the test result from the test run:

class Program
{
    static void Main(string[] args)
    {
        string ur = "https://xxxxxxx/";
        TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(ur));
        //Get build information
        BuildHttpClient bhc = ttpc.GetClient<BuildHttpClient>();
        string projectname = "Project";
        int buildId = x;
        Build bui = bhc.GetBuildAsync(projectname,buildId).Result;
        //Get test run for the build
        TestManagementHttpClient ithc = ttpc.GetClient<TestManagementHttpClient>();

        Console.WriteLine(bui.BuildNumber);

        QueryModel qm = new QueryModel("Select * From TestRun Where BuildNumber Contains '" + bui.BuildNumber + "'");

        List<TestRun> testruns = ithc.GetTestRunsByQueryAsync(qm,projectname).Result;
        foreach (TestRun testrun in testruns)
        {

            List<TestCaseResult> testresults = ithc.GetTestResultsAsync(projectname, testrun.Id).Result;
            foreach (TestCaseResult tcr in testresults)
                {
                    Console.WriteLine(tcr.Id);
                    Console.WriteLine(tcr.Outcome);
                }

            Console.ReadLine();
        }
        Console.ReadLine();
    }
}

Once you get failed test result id, you could use Rest API to attach a file to test result:

POST https://{instance}/DefaultCollection/{project}/_apis/test/runs/{run}/results/{result}/attachments?api-version={version}
Content-Type: application/json
{
  "stream": { string },
  "fileName": { string },
  "comment": { string },
  "attachmentType": { string }
}
like image 82
Cece Dong - MSFT Avatar answered Oct 20 '22 20:10

Cece Dong - MSFT