Get default Testers for Test Suite with powershell script - azure-devops-rest-api

trying to get the default testers that are assigned to a test suite in azure devops with a powershell script
$coreAreaId = "3b95fb80-fdda-4218-b60e-1052d070ae6b"
$tfsBaseUrl = GetUrl -orgUrl $orgUrl -header $header -AreaId $coreAreaId
$testerUrl = "$($tfsBaseUrl)$projectname/_apis/test/Plans/$testplanid/suites/$testsuiteid" +"?" + "`$expand" + "=1&api-version=5.0"
$tester = Invoke-RestMethod -Uri $testerUrl -Method Get -ContentType "application/json" -Headers $header
Url is like this:
"https://example.com/xxx/_apis/test/Plans/12572/suites/12583?$expand=1&api-version=5.0"
In the data I get back from devops there is no item
"defaultTesters ShallowReference[] Test suite default testers"
as described here:
https://learn.microsoft.com/en-us/rest/api/azure/devops/test/test%20%20suites/get%20test%20suite%20by%20id?view=azure-devops-server-rest-5.0

I tried and got the same result with powershell script calling test suite by id,
BTW,I found there was not an option allowing me to set a default tester for a test suite. Do not know how you assign a default tester to a test suite?
But for specific test case, assigned tester can be retrieved by rest API.
I have submitted an issue to Microsoft document team to track this issue.

Related

How to specify git author/committer for PullRequest merge in Azure DevOps?

I have defined a release pipeline to synchronize code between two git repositories in Azure DevOps. The process requires a PullRequest in the destination repo which is created and completed using the WebAPI.
The pipeline is executed by the build agent running using a Windows domain service account. So, the PullRequest is created and completed on behalf of the service account, which is also mentioned as author, committer, etc. in the git history after merge is completed. (According to our rules the PR must be merged using squash commit.)
I would like see a different user in the git history after (squash) merge.
Can I specify the user (e.g. the user triggering the release pipeline) using WebAPI?
I did not find such option in the API documentation.
Any other recommendation? Maybe convention like adding "co-authored-by" to commit message like github?
When you use Pull Requests-Create rest api to create a pull request, the pull request creator is determined by the creator of the PAT you used for authentication (e.g. I used the PAT of hughl01 user as the authentication to create the pull request, then the creator of the pull request is hughl01).
Test in Postman:
Sample test script in powershell task:
$token = "{User-created PAT}"
$url = "https://dev.azure.com/{org}/{pro}/_apis/git/repositories/{repoId}/pullrequests?api-version=6.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = #'
{
"sourceRefName": "refs/heads/dev2",
"targetRefName": "refs/heads/master",
"title": "ForTest",
"description": "Adding a new feature"
}
'#
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Post -ContentType application/json -body $JSON
You can create a variable group, with the release trigger as the variable name, and the PAT corresponding to the user as the variable value and set the value of the variable to secret. Then get the name of the triggerer through the predefined variable $(Release.RequestedFor) in the script, then obtain the corresponding PAT according to the trigger name to create pull request.

How can I tirgger vsts rest API for a release with auto approver?

We are automating the release trigger procedure.
in one of our scenarios we need to trigger release though rest api's, and triggering release should be auto approve.
is there a way I can auto approve the release, do we have any rest api which performs approval.
considering the account which is triggering it got permission to approve the release.
How can I tirgger vsts rest API for a release with auto approver?
For this issue ,you can use Approvals - Update rest api :
PATCH https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/approvals/{approvalId}?api-version=5.1
Sample request body:
{
"status": "approved",
"comments": "go!"
}
If you want to performs approval,you only need to set status to approved.
With Approvals - List rest api,you can get approvalId. You can add parameters to the request url according to your needs, and filter out the exact approval to get approvalId .
Below is my test result with postman :
I have tried this
$deployUrl = "https://vsrm.dev.azure.com/{ornizationName}/{projectName}/_apis/release/approvals/{approvalid}?api-version=5.1"
$body = #{
status = "approved"
comments = "go !"
} | ConvertTo-Json -Depth 4
"body= $body"
$verb= "Patch"
Invoke-RestMethod -Method $verb -ContentType "application/json" -Uri $deployUrl -Headers #{Authorization=("Basic {0}" -f $base64authinfo)} -Body $body

Is it possible to use a variable in the Agent.Name demand for tfs?

I am trying to force the run of a specific agent phase on a specific agent. My variable however does not seems to be picked up. I get the error:
No agent found in pool TEST which satisfies the specified demands:
Agent.Name -equals $(Release.ReleaseName)
vstest
Agent.Version -gtVersion 2.103.0
Is this possible?
I wanted to do something similar. I had 2 "environments" in the TFS release definition. The first one ("MyEnvironment-Setup") did setup like big file copies and database script generation. The second ("MyEnvironment") did the actual deployment. I needed them both to run on the same agent.
What I ended up doing is using the TFS API during "MyEnvironment-Setup" to modify the currently running release instance and set the agent demand for "MyEnvironment".
Several things were necessary to make this happen.
In "MyEnvironment-Setup" > Run on Agent > Additional Options, I enabled "Allow scripts to access the OAuth token"
In the left pane of the release definition screen where it lists all release definitions, I clicked the ellipsis next to "All release definitions" and selected "Security". Then for the "Project Collection Build Service (TEAM FOUNDATION)" user, I set "Edit release definition" and "Manage releases" to "Allow".
I called the following Powershell method in "MyEnvironment-Setup"
function Set-FinalAgent()
{
# Force the "MyEnvironment" step to run on the same agent as the "MyEnvironment-Setup" step
$baseApiUrl = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis"
$apiVersion = "3.1-preview"
$header = #{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }
$environmentToModify = $($env:Release_EnvironmentName).Replace("-Setup", "")
$releaseID = $env:Release_ReleaseID
$release = Invoke-RestMethod -Uri "$baseApiUrl/release/releases/$($releaseID)?api-version=$apiVersion" -Method GET -Header $header
($release.environments | where name -eq $environmentToModify).deployPhasesSnapshot[0].deploymentInput.demands += "Agent.Name -equals $($env:Agent_Name)"
# Compression is needed for the body to contain all of the info for larger release definitions when running on older servers
$body = $release | ConvertTo-Json -Depth 100 -Compress
Invoke-RestMethod -Uri "$baseApiUrl/release/releases/$($releaseID)?api-version=$apiVersion" -Method PUT -Header $header -ContentType application/json -Body $body
}
If you want to test and tweak this in Powershell ISE or something where you don't have access to the OAuth token, you can use a personal access token instead. In the top-right of your TFS Web UI, click your profile picture and select "Security" to generate a PAT. Then you can replace the header in the script above with the following:
$header = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($personalAccessToken)"))}

Setting TFS 2017 builds to Partially succeeded

We have an orchestration build that we would like to set status to partially succeeded if it didn't do certain things. With Xaml builds, we could do it by setting the CompilationStatus and TestStatus of the build.
For Tfs Builds, I can am trying to it by setting calling the TFS Rest API to update the build result.
$query = [uri]::EscapeUriString("$tfsCollection$tfsProject/_apis/build/builds/$buildId`?api-version=2.0")
$request = "{""result"":""$result""}"
try {
$result = Invoke-RestMethod -Method PATCH -UseDefaultCredentials -ContentType "application/json" -Uri $query -Body $request
}
catch{
Write-Output "StatusCode:" + $_.Exception.Response.StatusCode.value__ +
"`r`nStatusDescription:" + $_.Exception.Response.StatusDescription
}
After the call, I can see that the ribbon of the build changes to orange indicating that is partially succeeded. However, it gets changed to succeeded when the Finalize Build step of build is run.
What should I do that the end build finishes with a status partially succeeded.
You can add a task with its control options set to "Continue on Error". Whenever this tasks fails, your build will be partially succeeded.

How to post build result to team room in TFS 2015?

Is there a way to post build results from the build system (vNext?) in the Team Rooms?
I noticed there is an option to post build results in the team rooms, but the available list to choose from are only XAML build definitions and not the new build system (vNext?) definitions.
No there is not.
I have logged the issue here : https://connect.microsoft.com/VisualStudio/Feedback/Details/1874524
I have try it on my environment(TFS2015&VS2015) .
Sorry about that, this function seems only support XAML build by now.
You can raise your requirements to Microsoft.
The following Powershell code is a first attempt at getting something working for us:
Param($teamroom,$message)
# Example: Write-MessageToTeamRoom.ps1 -teamroom "Team Room Name" -message "Notify #User name about work item #54142"
# https://jaspergilhuis.nl/2014/02/18/utilize-the-tfs-team-room-rest-api/
# https://jaspergilhuis.nl/2014/02/23/encapsulate-team-room-api-calls-with-a-powershell-commandlet/
$rooms = Invoke-RestMethod -Method GET http://tfsapp02:8080/tfs/defaultcollection/_apis/chat/rooms?api-version=1.0 -UseDefaultCredentials
$room = $rooms.value | Where-Object {$_.Name -eq $teamroom}
$relevantRoomID = $room.id
$jsonbody = #{ content="$message"} | ConvertTo-Json
$response = Invoke-RestMethod -Method POST "http://{TfsDefaultCollectionPath}/_apis/chat/rooms/$relevantRoomID/messages?api-version=1.0" -Body $jsonbody -ContentType "application/json" -UseDefaultCredentials
My ambition is to expand this code to run whenever a build completes and then write the build result into the team room

Resources