持续交付 要将 ITP 集成到 Jenkins Pipeline 中,实现开发发版时自动触发自动化测试

测试-鹏哥 · November 07, 2025 · 286 hits
  1. 准备工作 Jenkins 插件安装 # 需要安装以下插件
  2. HTTP Request Plugin (用于调用 ITP API)
  3. Pipeline Plugin (Jenkins Pipeline 支持)
  4. Git Plugin (代码拉取)
  5. Workspace Cleanup Plugin (清理工作空间)

  6. ITP API 接口准备

根据提供的接口文档,需要使用以下关键 API:
用户认证接口

1. 登录获取 token

POST /users/authorizations/
{
    "username": "your_username",
    "password": "your_password"
}

返回 token 用于后续 API 调用

测试任务执行接口

2. 运行测试任务

POST  ​/testtask​/api​/testTask​/tasks​/run​/
{
    "env": 1,        # 测试环境 ID
    "task": 1        # 测试任务 ID
}

  1. Jenkins Pipeline 配置 Jenkinsfile 示例 pipeline {     agent any          environment {         ITP_USERNAME = credentials('ITP_USERNAME')         ITP_PASSWORD = credentials('ITP_PASSWORD')         ITP_BASE_URL = 'http://your-itp-server:8898'         ITP_ENV_ID = '1'  // 测试环境 ID         ITP_TASK_ID = '1' // 测试任务 ID     }          stages {         stage('Build') {             steps {                 // 构建步骤                 echo 'Building application...'             }         }                  stage('Deploy') {             steps {                 // 部署步骤                 echo 'Deploying application...'             }         }                  stage('Trigger ITP Automation Test') {             steps {                 script {                     // 1. 获取 ITP 认证 token                     def authToken = getITPAuthToken()                                          // 2. 触发自动化测试                     def testResult = triggerITPAutomationTest(authToken)                                          // 3. 等待测试完成并获取结果                     def report = getTestReport(testResult.report_id, authToken)                                          // 4. 根据测试结果决定流水线状态                     if (report.state != "success") {                         error "自动化测试失败,请检查测试报告"                     }                 }             }         }     }          post {         always {             // 清理工作             cleanWs()         }     } }

def getITPAuthToken() {
    def response = httpRequest(
        url: "${ITP_BASE_URL}/api/users/login/",
        httpMode: 'POST',
        requestBody: """{
            "username": "${ITP_USERNAME}",
            "password": "${ITP_PASSWORD}"
        }""",
        contentType: 'APPLICATION_JSON'
    )
    
    def json = readJSON text: response.content
    return json.token
}

def triggerITPAutomationTest(token) {
    def response = httpRequest(
        url: "${ITP_BASE_URL}/api/testTask/tasks/run/",
        httpMode: 'POST',
        requestBody: """{
            "env": ${ITP_ENV_ID},
            "task": ${ITP_TASK_ID}
        }""",
        contentType: 'APPLICATION_JSON',
        customHeaders: [[name: 'Authorization', value: "Bearer ${token}"]]
    )
    
    return readJSON text: response.content
}

def getTestReport(reportId, token) {
    def response = httpRequest(
        url: "${ITP_BASE_URL}/api/testTask/report/${reportId}/",
        httpMode: 'GET',
        customHeaders: [[name: 'Authorization', value: "Bearer ${token}"]]
    )
    
    return readJSON text: response.content
}

  1. 高级集成方案 轮询测试状态 def waitForTestCompletion(recordId, token, timeout=300) {     def startTime = new Date().getTime()     def status = "running"          while (status == "running" || status == "pending") {         def currentTime = new Date().getTime()         if ((currentTime - startTime) > (timeout * 1000)) {             error "测试执行超时"         }                  def response = httpRequest(             url: "${ITP_BASE_URL}/api/testTask/records/${recordId}/",             httpMode: 'GET',             customHeaders: [[name: 'Authorization', value: "Bearer ${token}"]]         )                  def record = readJSON text: response.content         status = record.status                  if (status == "running" || status == "pending") {             sleep 10 // 等待 10 秒后再次检查         }     }          return status } 发送测试报告到通知渠道

def sendTestReportToDingTalk(report, webhookUrl) {
    def message = """
    ITP 自动化测试报告:
    - 测试任务: ${report.task_name}
    - 执行状态: ${report.state}
    - 通过率: ${report.pass_rate}%
    - 总用例数: ${report.all}
    - 成功用例: ${report.success}
    - 失败用例: ${report.fail}
    """
    
    httpRequest(
        url: webhookUrl,
        httpMode: 'POST',
        requestBody: """{
            "msgtype": "text",
            "text": {
                "content": "${message}"
            }
        }""",
        contentType: 'APPLICATION_JSON'
    )
}

  1. 配置建议

Jenkins Credentials 配置

在 Jenkins 中配置以下 Credentials:

  1. ITP_USERNAME - ITP 平台用户名
  2. ITP_PASSWORD - ITP 平台密码
  3. DINGTALK_WEBHOOK - 钉钉机器人 webhook(可选)

环境变量配置

在 Jenkins Pipeline 中配置环境变量:

ITP_BASE_URL = 'http://your-itp-server:8898'
ITP_ENV_ID = '1'    # 根据实际情况调整
ITP_TASK_ID = '1'   # 根据实际情况调整

  1. 错误处理和重试机制

def withRetry(Closure operation, int maxRetries=3) {
    def lastException = null
    for (int i = 0; i <= maxRetries; i++) {
        try {
            return operation()
        } catch (Exception e) {
            lastException = e
            if (i < maxRetries) {
                echo "操作失败,${i+1}/${maxRetries}次重试: ${e.getMessage()}"
                sleep 5
            }
        }
    }
    throw lastException
}
通过以上配置,当开发发版时,Jenkins Pipeline 会自动触发 ITP 平台的自动化测试任务,并根据测试结果决定流水线的成功或失败状态。
ITP 体验网址: http://1.95.215.79:18899/ tester(88888888) ITP 项目地址: https://gitee.com/hp631012651/itp

No Reply at the moment.
需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up