无法通过 Azure DevOps REST API 创建新的工作项类型状态

问题描述 投票:0回答:1

我一直在编写 Python 代码来自动化公司中组织创建过程的一些设置,但我无法在某些工作项类型中创建新状态。而且,奇怪的是,这种情况似乎只发生在系统中已有的工作项类型中。 这是完整的代码:

import base64
from os import environ as env
from dotenv import load_dotenv
import requests
import time
import json
import pandas as pd
import contador

load_dotenv()

AZURE_DEVOPS_PAT = env['AZURE_DEVOPS_PAT']

patEncoded = base64.b64encode((":" + AZURE_DEVOPS_PAT).encode()).decode()

organization = 'dummy-name'

headers = {
  'Content-Type': 'application/json',
  'Authorization': f'Basic {patEncoded}'
}

def getProcessID(testName, organization, headers):
  global contador
  getUrl = f'https://dev.azure.com/{organization}/_apis/process/processes?api-version=7.1-preview.1'
  while True:
    try:
        req = requests.get(getUrl, headers=headers)
        break
    except requests.exceptions.ConnectTimeout as e:
      contador.contador += 1
      print(f"Erro de timeout número {contador.contador}. Tentando novamente...")
      time.sleep(10)
  json_object = json.loads(req.text)
  reqTextSize = len(json_object['value'])
  for i in range(reqTextSize):
    name = json_object['value'][i]['name']
    if name == testName:
      processId = json_object['value'][i]['id']
  return processId

def criarEstados(tipo, processId, organization, headers):
    tabelaRefNames = getWorkItemTypes(processId, organization, headers)
    filePath = "printDebug.txt"
    if tipo == 'Agile':
        tabelaEstados = pd.read_excel('kanban.xlsx')
    elif tipo == 'Scrum':
        tabelaEstados = pd.read_excel('scrum.xlsx')
    tabelaEstados = tabelaEstados.merge(tabelaRefNames, left_on="workItemType", right_on="originName", how='left')
    tabelaEstadosDict = tabelaEstados.to_dict()
    tabelaEstadosDictSize = len(tabelaEstadosDict["workItemType"])
    linhas = []
    with open(filePath, 'w') as printDebug:
            for i in range(tabelaEstadosDictSize):
                workItemType = tabelaEstadosDict["workItemType"][i]
                witRefName = tabelaEstadosDict["referenceName"][i]
                name = tabelaEstadosDict["originName"][i]
                color = tabelaEstadosDict["color"][i]
                stateCategory = tabelaEstadosDict["stateCategory"][i]
                referenceName = f"{witRefName} foi passado\n"
                status = criarEstado(processId, organization, headers, witRefName, name, color, stateCategory)
                resultState = f'Estado {name} no Work Item Type {workItemType} deu este retorno:\n'
                linhas.extend([resultState, referenceName, f'{status}\n'])
                printDebug.writelines(linhas)
                linhas.clear()
    print("Debug finalizado.")

def main():
  testName = "Processo-Kanban"
  processId = getProcessID(testName, organization, headers)
  criarEstados('Agile', processId, organization, headers)

main()
For Microsoft.VSTS.WorkItemTypes.Bug as witRefName:
{
  "$id": "1",
  "innerException": null,
  "message": "VS402805: Cannot find work item type with reference name 'Microsoft.VSTS.WorkItemTypes.Bug' in process named '07c52453-a09e-4f35-a0f1-40bdb972afb9'.",
  "typeName": "Microsoft.TeamFoundation.WorkItemTracking.Server.Metadata.ProcessWorkItemTypeDoesNotExistException, Microsoft.TeamFoundation.WorkItemTracking.Server",
  "typeKey": "ProcessWorkItemTypeDoesNotExistException",
  "errorCode": 0,
  "eventId": 3200
}
For Microsoft.VSTS.WorkItemTypes.UserStory as witRefName:
{
  "$id": "1",
  "innerException": null,
  "message": "VS402805: Cannot find work item type with reference name 'Microsoft.VSTS.WorkItemTypes.UserStory' in process named '07c52453-a09e-4f35-a0f1-40bdb972afb9'.",
  "typeName": "Microsoft.TeamFoundation.WorkItemTracking.Server.Metadata.ProcessWorkItemTypeDoesNotExistException, Microsoft.TeamFoundation.WorkItemTracking.Server",
  "typeKey": "ProcessWorkItemTypeDoesNotExistException",
  "errorCode": 0,
  "eventId": 3200
}
For Microsoft.VSTS.WorkItemTypes.Task  as witRefName:
{
  "$id": "1",
  "innerException": null,
  "message": "VS402805: Cannot find work item type with reference name 'Microsoft.VSTS.WorkItemTypes.Task' in process named '07c52453-a09e-4f35-a0f1-40bdb972afb9'.",
  "typeName": "Microsoft.TeamFoundation.WorkItemTracking.Server.Metadata.ProcessWorkItemTypeDoesNotExistException, Microsoft.TeamFoundation.WorkItemTracking.Server",
  "typeKey": "ProcessWorkItemTypeDoesNotExistException",
  "errorCode": 0,
  "eventId": 3200
}
For Microsoft.VSTS.WorkItemTypes.Epic as witRefName:
{
  "$id": "1",
  "innerException": null,
  "message": "VS402805: Cannot find work item type with reference name 'Microsoft.VSTS.WorkItemTypes.Epic' in process named '07c52453-a09e-4f35-a0f1-40bdb972afb9'.",
  "typeName": "Microsoft.TeamFoundation.WorkItemTracking.Server.Metadata.ProcessWorkItemTypeDoesNotExistException, Microsoft.TeamFoundation.WorkItemTracking.Server",
  "typeKey": "ProcessWorkItemTypeDoesNotExistException",
  "errorCode": 0,
  "eventId": 3200
}

我已经使用此脚本成功创建了工作项状态,但仅限于自定义工作项类型。 我还可以通过 Web UI(Azure Devops 中的组织设置)创建新的工作项类型状态。

此外,一旦我通过 Web UI 将状态添加到 Bug 工作项类型,代码就会将 witRefName 捕获为“Processo-Kanban.Bug”,而不再是“Microsoft.VSTS.WorkItemTypes.Bug”。

Epic 工作项类型也发生了同样的情况。而且,对于这两者,我的代码似乎开始按预期工作。

witRefName 是否有可能类似于 f"{processName}.{workItemName)?

无论如何,有人可以帮助我吗?

我尝试了不同的方法来获取witRefName,但都失败了。 代码在上面。

python azure-devops azure-devops-rest-api
1个回答
0
投票

您似乎正在尝试在 default 流程中为工作项类型添加新状态。请注意,要定制工作跟踪系统,您需要定制一个

inherited
流程。

这是我的工作流程供您参考,在我继承的流程之一中为

Bug
创建新状态
AgileInherited

  1. 通过

    API
    获取(列出)目标继承进程的processId

    GET https://dev.azure.com/{organization}/_apis/work/processes?api-version=7.2-preview.2
    

    Agile
    是 4 个 default 进程之一,而
    AgileInherited
    是自定义的继承进程。

    …
            {
                "typeId": "adcc42ab-9882-485e-a3ed-7678f01f66bc",
                "name": "Agile",
                "referenceName": null,
                "description": "This template is flexible and will work great for most teams using Agile planning methods, including those practicing Scrum.",
                "parentProcessTypeId": "00000000-0000-0000-0000-000000000000",
                "isEnabled": true,
                "isDefault": false,
                "customizationType": "system"
            },
            {
                "typeId": "f37a3e41-85fc-4cbd-8a14-5b97df442661",
                "name": "AgileInherited",
                "referenceName": "Inherited.f37a3e4185fc4cbd8a145b97df442661",
                "description": "Inherited process from Agile",
                "parentProcessTypeId": "adcc42ab-9882-485e-a3ed-7678f01f66bc",
                "isEnabled": true,
                "isDefault": true,
                "customizationType": "inherited"
            },
    …
    
  2. 通过

    API
    获取(列出)目标工作项类型的referenceName

    GET https://dev.azure.com/{organization}/_apis/work/processes/{processId}/workitemtypes?api-version=7.2-preview.2
    

    根据我的

    Bug
    流程中的
    InheritedAgile
    工作项类型,其
    witRefName
    以及
    referenceName
    AgileInherited.Bug

    …
            {
                "referenceName": "AgileInherited.Bug",
                "name": "Bug",
                "description": "Describes a divergence between required and actual behavior, and tracks the work done to correct the defect and verify the correction.",
                "url": "https://dev.azure.com/{organization}/_apis/work/processes/f37a3e41-85fc-4cbd-8a14-5b97df442661/workItemTypes/AgileInherited.Bug",
                "customization": "inherited",
                "color": "CC293D",
                "icon": "icon_insect",
                "isDisabled": false,
                "inherits": "Microsoft.VSTS.WorkItemTypes.Bug"
            },
    …
    
  3. 通过

    API
    为我的
    Ready to test
    进程中的
    Bug
    创建新状态AgileInherited

    POST https://dev.azure.com/{organization}/_apis/work/processes/{processId}/workItemTypes/{witRefName}/states?api-version=7.2-preview.1
    

    我的样品

    POST https://dev.azure.com/{organization}/_apis/work/processdefinitions/f37a3e41-85fc-4cbd-8a14-5b97df442661/workItemTypes/AgileInherited.Bug/states?api-version=7.2-preview.1
    
    {
      "name": "Ready to test",
      "stateCategory": "InProgress",
      "color": "207752",
      "order": null
    }
    
  4. 新状态在

    Bug
    进程的
    AgileInherited
    中可见。

希望这些信息可以帮助解决您的疑虑。

© www.soinside.com 2019 - 2024. All rights reserved.