C#: Deleting Test Runs in Azure DevOps using REST API

Last updated on 02nd July 2020

To view the progress of of tests plans in Azure DevOps, navigate to your project and click Test Plans, then select and expand a Test Suite to see the all test cases along with details such as test case id, tester, configuration and outcome of the last test execution.(see Figure 1 below). If you have run a test case multiple times, the outcome that is displayed against each test case, such as Passed or Failed, is the result of the last run of that test case. This means that if you accidently run a test that is already passed, you may not want to keep the results of that run. To view all test runs, click Test Plans → Runs. Currently, it is not possible to delete a test run from Azure DevOps GUI but this can be done using Azure DevOps REST API. Below is a C# console application to delete test runs from an Azure DevOps project.

This program will first list all the test runs and then prompts the user to input a Run Id to delete. The user can either input a Test Run ID or simply press the ENTER key to exit the program.

Azure Test Case Details
Figure1

Here is the full program source code.

using System;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;

namespace DeleteTestRun
{
    static class Azure
    {
        public const string BASE = "https://dev.azure.com";
        public const string PAT = "Enter your Personal Access Token here";
        public const string ORG = "OrganizationName";
        public const string API = "api-version=5.1";
        public const string PROJECT = "ProjectName";
    }

    class Program
    {
        static void Main(string[] args)
        {
            string runid =String.Empty;
            // Create and initialize HttpClient instance.
            HttpClient client = new HttpClient();
           

            // Set Media Type of Response.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Generate base64 encoded authorization header.
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", Azure.PAT))));

            //Build the URI to get all test runs
            // GET https://dev.azure.com/{organization}/{project}/_apis/test/runs?api-version=5.1
            string uri = String.Join("?", String.Join("/", Azure.BASE, Azure.ORG, Azure.PROJECT, "_apis/test/runs"), Azure.API);
            string result = SendRequest(client, uri).Result;
            JObject test_runs = Newtonsoft.Json.Linq.JObject.Parse(result);
            Console.WriteLine("Run ID | Test Case Name");
            Console.WriteLine("-------------------------------------");
            foreach (var run in test_runs["value"])
            {
                string state = (string)run["state"];
                if (state != "255") { 
                    string id = (string)run["id"];
                    string name = (string)run["name"];
                    Console.WriteLine("{0,6} | {1}", id, name);
                }   

            }

   
            string TestRunId = string.Empty;

            //Read Run ID from console
            do
            {
                Console.WriteLine("To delete a test run, input the Run ID and press ENTER.");
                Console.WriteLine("Or simply press ENTER with out a Run ID to exit the program.");
                TestRunId = Console.ReadLine();
                if (String.IsNullOrEmpty(TestRunId))
                {
                    break;
                }
                else
                {
                    uri = String.Join("?", String.Join("/", Azure.BASE, Azure.ORG, Azure.PROJECT, "_apis/test/runs", TestRunId), Azure.API);
                    if (DeleteRun(client, uri).Result)
                    {
                        Console.WriteLine("Successfully deleted test run with id {0}", TestRunId );
                    }
                    
                }
            } while (true);

            client.Dispose();
          //  Console.ReadLine();
        }

        // Send HTTP GET Request and get response
        public static async Task SendRequest(HttpClient client, string uri)
        {
            try
            {
               
                using (HttpResponseMessage response = await client.GetAsync(uri))
                {
                    response.EnsureSuccessStatusCode();
                    return (await response.Content.ReadAsStringAsync());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return string.Empty;
            }
        } // End of SendRequest method


        // Delete a Test Run
        public static async Task DeleteRun(HttpClient client, string uri)
        {
            try
            {
                using (HttpResponseMessage response = await client.DeleteAsync(uri))
                {
                    response.EnsureSuccessStatusCode();
                    return (response.IsSuccessStatusCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        } // End of DeleteRun method


    }
}

Sample program output

Run ID | Test Case Name
-------------------------------------
    14 | 19 : Function Test (Manual)
    16 | 19 : Function Test (Manual)
    20 | 19 : Function Test (Manual)
    22 | 19 : Function Test (Manual)
To delete a test run, input the Run ID and press ENTER.
Or simply press ENTER with out a Run ID to exit the program.
14
Successfully deleted test run with id 14
To delete a test run, input the Run ID and press ENTER.
Or simply press ENTER with out a Run ID to exit the program.

Post a comment

Comments

Nothing yet..be the first to share wisdom.