Adding a log file to an Azure DevOps Test Execution

I have been encountering difficulties when trying to upload the log file generated from my automated tests in the Azure Release pipeline. My automated UI tests are conducted using selenium and MSTest. Initially, I believed that I could attach the file in the AssemblyCleanup Method of MSTest by utilizing the TestContext object. However, it turns out that the TestContext can only be utilized for attaching results to individual test cases. After some research online, I stumbled upon this API call:

POST {Organization}/{Project}/_apis/test/Runs/{runId}/attachments?api-version=5.1-preview.1

referenced in the Microsoft Documentation: https://learn.microsoft.com/en-us/rest/api/azure/devops/test/attachments/create%20test%20result%20attachment?view=azure-devops-rest-5.1

Unfortunately, I am unsure about how to obtain the test runId within my test code or how to authenticate with OAuth2. Below is as far as I have progressed using RestSharp to make the call;

RestClient httpClient = new RestClient("");
//I am uncertain if this includes the correct OAuth details
httpClient.Authenticator = new RestSharp.Authenticators.OAuth2AuthorizationRequestHeaderAuthenticator("");
RestRequest request = new RestRequest(Method.POST);
APIRequestBody body = new APIRequestBody
{
    //unsure if this is the accurate stream
    Stream = "",//not sure what to put in here
    FileName = "TestRun.log",
    Comment = "Test run log file.",
    AttachmentType = "GeneralAttachment"
};
request.AddJsonBody(body);
IRestResponse response = httpClient.Execute(request);

Any assistance would be greatly appreciated; I feel a bit overwhelmed by all of this.

Answer №1

If you're looking to call a restful api in C# using HttpClient with a Personal Access Token, check out the code example below. To obtain your Personal Access Token, follow the steps outlined here.

public static async void GetProjects()
{
    try
    {
        var personalaccesstoken = "PAT_FROM_WEBSITE";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(
                    System.Text.ASCIIEncoding.ASCII.GetBytes(
                        string.Format("{0}:{1}", "", personalaccesstoken))));

            using (HttpResponseMessage response = await client.GetAsync(
                        "https://dev.azure.com/{organization}/_apis/projects"))
            {
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

The example provided above is sourced from Microsoft's documentation. Feel free to explore it further.

If you need a test runId, consider calling the test runs API to retrieve a list of test runs and extract the current runid from the Response.

GET https://dev.azure.com/{organization}/{project}/_apis/test/runs?api-version=5.1

I hope the information above proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Handling session expiration in ASP.NET MVC when making an AJAX call by redirecting to the login page

I'm currently learning ASP.NET MVC and I'm a newbie in it, so I'm struggling to find a solution for a specific problem. If anyone has encountered this issue before, I would appreciate any advice. Thank you! In my project, I am using ASP.NET ...

The C# MVC Controller is having difficulty retrieving decimal or double values from an Ajax POST request

Having trouble sending decimal or double values via ajax to my C# MVC Controller. The values always come through as null, even though they work fine when sent as strings or integers. Why is this happening? When checking the client's request, the corre ...

Implementing JSON methods in C# WebService to enable communication with external servers

Is it possible to integrate an asp.net web service written in C# into an HTML5/JavaScript website? The challenge is that the web service and client are located on different domains, requiring a cross-domain request. ...

Contrasting the uses of element(...) versus element(...).getWebElement() in Protractor

What is the advantage of using element(...).getWebElement() instead of element(...) when they both perform similarly? Why are there two different APIs for the same purpose? ...

What is the best approach for finding the xPath of this specific element?

Take a look at this website Link I'm trying to capture the popup message on this site, but I can't seem to find the element for it in the code. Any ideas? ...

Showing C# File Content in JavaScript - A Step-by-Step Guide

Is there a way to showcase this File (c#) on a JavaScript site? return File(streams.First(), "application/octet-stream", Path.GetFileName(element.Path)); I am looking for something similar to this: <img id="myImg" src="_____&qu ...

Executing selenium tests on Internet Explorer 11 on a Windows 10 1809 machine without encountering any new pop-up windows

While testing on my computer, I encountered an issue where my test would start successfully, but after opening and closing several Internet Explorer windows during the test, no new windows would open. There were no error messages displayed, and the test se ...

Is there a way to trigger a JavaScript function upon checking a checkbox?

Is there a way to trigger a Javascript function when a checkbox within a gridview is checked? protected void ChangeStatusSevenDays_Click(object sender, EventArgs e) { for (int i = 0; i < grdImoveis2.Rows.Count; i++) { GridViewRow RowVie ...

Automating testing with JavaScript and Selenium WebDriver

Can testing be automated using the combination of JavaScript and Selenium? I am not familiar with Java, Python, or C#, but I do have expertise in Front-End development. Has anyone attempted this before? Is it challenging to implement? Are there any recom ...

Obtain the text that is shown for an input field

My website is currently utilizing Angular Material, which is causing the text format in my type='time' input field to change. I am looking for a way to verify this text, but none of the methods I have tried give me the actual displayed text. I a ...

"Displaying a popup message prompting users to refresh the page after clicking

I need to implement a feature where the page refreshes only after the user clicks the "OK" button on a dialog box that appears once a process is completed. The issue I'm facing is that in my current code, the page refreshes immediately after the proc ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...

I am attempting to access data through an ajax function, but it is not functioning correctly

When working with asp.net webform, I encountered an issue while trying to call data using an ajax call. Although a similar function on another page works without errors, on this particular page, I am facing an error. The error I am getting is pageCountInt ...

Encountering an issue with WebDriver in the realm of JavaScript

I am struggling to use JavaScript to locate specific controls and send values to them. One example is changing the text in a textbox with the ID "ID" to "123456". Below is the code I tried: ((IJavaScriptExecutor)driver).ExecuteScript("document.getElement ...

Working with JSON in AJAX with Javascript and C# to handle array data

When attempting to send an array via AJAX using JSON, I am encountering a problem where my C# handler is unable to properly handle the query. It seems that the querystrings are merging together inexplicably. In the scenario presented here, I am trying to ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

When items are removed client-side, the Listbox becomes null

Given a Web Forms project inherited by me, I am relatively new to the field of Web development. The page in question features 2 listboxes: lstCaseLoad, containing "Caseloads" (ID numbers), and lstAssignedCaseLoad, filled with Caseloads chosen by the Form U ...

Using Selenium to interact with a link's href attribute through JavaScript

New to Java and Selenium, I'm facing difficulties when trying to click on a link with JavaScript in href attribute. Here's the snippet from the page source: href="javascript:navigateToDiffTab('https://site_url/medications','Are y ...

Testing a cucumber scenario by comparing the redirect URL with a different URL

Currently, I am working on writing Cucumber tests for my project. One issue I have encountered is that when clicking a certain button in my code, it redirects to another page with a fixed URL. How can I retrieve the current URL within the Cucumber test? I ...

A combination of Tor Browser, Selenium, and Javascript for

I have been attempting to use selenium with Tor, but unfortunately it is not functioning correctly. I have come across a library that allows for this functionality, however, it appears to only work with Python. Is there a way to accomplish this using Jav ...