溫馨提示×

如何在Ubuntu中集成Postman與Jenkins

小樊
45
2025-10-07 17:39:38
欄目: 智能運維

在Ubuntu中集成Postman與Jenkins的完整步驟

1. 環境準備

1.1 安裝Jenkins

在Ubuntu服務器上安裝Jenkins(持續集成工具),用于自動化執行Postman測試:

# 添加Jenkins存儲庫密鑰和源
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'

# 更新包列表并安裝Jenkins
sudo apt update
sudo apt install jenkins

# 啟動Jenkins并設置開機自啟
sudo systemctl start jenkins
sudo systemctl enable jenkins

訪問http://<服務器IP>:8080完成Jenkins初始化配置(按提示輸入管理員密碼)。

1.2 安裝Newman(Postman命令行工具)

Newman是Postman的命令行接口,需通過Node.js安裝:

# 安裝Node.js和npm(Node包管理器)
sudo apt install nodejs npm -y

# 全局安裝Newman
sudo npm install -g newman

# 驗證安裝
newman -v

確保輸出Newman版本號(如5.3.0),表示安裝成功。

1.3 安裝Jenkins必要插件

登錄Jenkins管理界面,進入Manage JenkinsManage Plugins,安裝以下插件:

  • Pipeline:用于定義自動化流程;
  • HTML Publisher:發布測試報告;
  • Email Extension:發送郵件通知(可選,用于結果反饋)。

2. Postman測試配置

2.1 創建測試集合

在Postman客戶端中:

  1. 點擊左上角NewCollection,輸入集合名稱(如API_Tests);
  2. 點擊+ Add Request,配置API請求(URL、Method、Headers、Body等);
  3. 切換至Tests標簽頁,編寫測試腳本(如驗證狀態碼、響應數據):
    // 示例:驗證狀態碼為200
    pm.test("Status code is 200", function () {
        pm.response.to.have.status(200);
    });
    // 示例:驗證響應體包含"success"
    pm.test("Response contains 'success'", function () {
        const responseJson = pm.response.json();
        pm.expect(responseJson.message).to.eql("success");
    });
    
  4. 點擊Save保存集合。

2.2 導出測試集合與環境變量

  1. 選中集合,點擊右側三個點→Export,選擇Collection Format: v2.1,導出為collection.json;
  2. 進入Manage Environments,創建環境(如Test_Env),添加變量(如base_url: https://api.example.com),導出為environment.json;
  3. 將兩個文件存放在Jenkins工作空間的安全目錄(如/var/lib/jenkins/workspace/api_tests/),避免中文路徑。

3. Jenkins任務配置

3.1 創建Pipeline任務

  1. 進入Jenkins首頁,點擊New Item,輸入任務名稱(如Postman_API_Tests),選擇Pipeline,點擊OK;
  2. Pipeline配置頁,選擇Pipeline script from SCM(從代碼倉庫拉取腳本),SCM選擇Git,輸入倉庫URL(如https://github.com/your-username/api-tests.git),分支選擇main。

3.2 編寫Jenkinsfile(Pipeline腳本)

在代碼倉庫根目錄創建Jenkinsfile,內容如下(整合Newman執行與報告生成):

pipeline {
    agent any
    
    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', url: 'https://github.com/your-username/api-tests.git'
            }
        }
        
        stage('Run Postman Tests') {
            steps {
                sh '''
                    # 運行Postman測試,生成JUnit和HTML報告
                    newman run "collection.json" \
                    -e "environment.json" \
                    -d "testdata.csv" \  # 可選:數據驅動測試
                    -r cli,junit,htmlextra \
                    --reporter-junit-export "reports/junit.xml" \
                    --reporter-htmlextra-export "reports/report.html"
                '''
            }
        }
    }
    
    post {
        always {
            // 發布JUnit測試報告
            junit 'reports/junit.xml'
            
            // 發布HTML報告(需安裝HTML Publisher插件)
            publishHTML(target: [
                allowEmptyArchive: false,
                alwaysLinkToLastBuild: true,
                keepAll: true,
                reportDir: 'reports',
                reportFiles: 'report.html',
                reportName: 'Postman Test Report'
            ])
            
            // 郵件通知(需安裝Email Extension插件)
            emailext (
                subject: "Postman API Tests Result: ${currentBuild.result}",
                body: """<p>Check the test report here: ${BUILD_URL}HTML_Report/</p>""",
                to: 'dev-team@example.com'
            )
        }
        
        success {
            echo 'All Postman tests passed!'
        }
        
        failure {
            echo 'Some Postman tests failed!'
        }
    }
}

說明

  • newman run命令:執行collection.json,使用environment.json中的環境變量,生成JUnit(用于Jenkins解析)和HTML(可視化)報告;
  • junit步驟:將JUnit報告集成到Jenkins;
  • publishHTML步驟:發布HTML報告,方便查看詳細結果;
  • emailext步驟:發送郵件通知(可選)。

4. 觸發與驗證

4.1 手動觸發

保存Jenkins任務配置,點擊Build Now,Jenkins將自動:

  1. 從Git拉取代碼;
  2. 運行Newman命令執行Postman測試;
  3. 生成并發布測試報告;
  4. 根據結果發送郵件通知(若配置)。

4.2 自動觸發(可選)

若需代碼提交后自動觸發,可在Pipeline配置頁的Build Triggers中選擇GitHub hook trigger for GITScm polling,并在GitHub倉庫的Webhooks中添加Jenkins鉤子(URL格式:http://<服務器IP>:8080/github-webhook/)。

注意事項

  • 權限與路徑:確保Jenkins用戶對collection.json、environment.json等文件有讀取權限,避免中文路徑;
  • 環境變量安全:敏感信息(如API密鑰)應通過JenkinsCredentials管理(如Secret text),而非直接寫入環境變量文件;
  • 依賴優化:可在Jenkinsfile中添加npm install -g newman(若未全局安裝),或使用Docker容器運行Newman(避免污染主機環境)。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女