I’m trying to create a new ADO pull request and complete it immediately (for unit testing purposes) but there seems to be an issue where if I try to complete it right after it was created, it simply doesn’t complete it.
On the other hand, if I add some timeout between the PR creation and completion (the commented line in the code below) it does work.
Any idea why this could be happening and how to resolve it?
This is an example code of what I’ve been testing.
// CREATE PR
const prRequestUrl = `https://system:${personalAccessToken}@dev.azure.com/${organization}/${project}/_apis/git/repositories/${repo}/pullRequests?api-version=7.0`;
const prRequestBody = {
sourceRefName: 'refs/heads/source',
targetRefName: 'refs/heads/target',
title: 'PR title',
description: 'PR description',
};
const prData = (await axios.post(prRequestUrl, prRequestBody)).data;
// This fixes the issue
// await new Promise((resolve) => setTimeout(resolve, 1000));
// COMPLETE PR
const approvePrRequestUrl = `https://system:${personalAccessToken}@dev.azure.com/${organization}/${project}/_apis/git/repositories/${repo}/pullRequests/${prData.pullRequestId}/?api-version=7.0`;
const approvePrRequestBody = {
lastMergeSourceCommit: prData.lastMergeSourceCommit,
completionOptions: {
deleteSourceBranch: false,
},
status: 'completed',
};
await axios.patch(
approvePrRequestUrl,
approvePrRequestBody
);
2
Answers
Azure DevOps uses a database as a backing store. It may be that the create PR request has queued work but that the PR doesn’t fully exist yet.
If your testing just needs a completed PR, create the PR with a completed status.
e.g.
Also consider querying on the PR Id provided by the initial request.
If you are using two request to create the completed PR, spinning on checking that the PR is retrievable may be better than an arbitrary timeout between the requests.
If you are using one request to create the completed PR, checking that the PR is retrievable adds robustness to your unit test. (You will want a difference between an issue with Azure DevOps and an issue with your code that is under test.)
When you create a PR, the thing you are waiting for is for the temporary merge commit to be created. This is how AzDO determines whether or not you have conflicts, and if you do, you won’t be able to complete the PR. The time it takes for the temporary merge can vary, but as you’ve witnessed, it’s usually fast, but is certainly greater than the time it takes to make multiple API calls.
Some possible solutions to this problem are: