Jenkins

Denna guide förklarar hur du integrerar LoadFocus JMeter API-klienten med Jenkins för automatiserad prestandatestning.

Installationssteg

1. Lagra autentiseringsuppgifter i Jenkins

Lagra först dina LoadFocus API-autentiseringsuppgifter säkert i Jenkins:

  1. Navigera till Jenkins Dashboard > Manage Jenkins > Manage Credentials
  2. Välj lämplig autentiseringsdomän (t.ex. global)
  3. Klicka på "Add Credentials"
  4. Lägg till följande autentiseringsuppgifter:
    • Kind: Secret text
    • Scope: Global
    • Secret: Din LoadFocus API-nyckel
    • ID: loadfocus-api-key
    • Description: LoadFocus API Key
  5. Upprepa för ditt team-ID med ID: loadfocus-team-id

2. Skapa en Jenkins Pipeline

Skapa en Jenkinsfile i ditt repository:

pipeline {
agent {
docker {
image 'node:16-alpine'
}
}
environment {
LOADFOCUS_API_KEY = credentials('loadfocus-api-key')
LOADFOCUS_TEAM_ID = credentials('loadfocus-team-id')
}
stages {
stage('Build') {
steps {
// Dina byggsteg
sh 'npm install'
sh 'npm run build'
}
}
stage('Test') {
steps {
// Dina teststeg
sh 'npm test'
}
}
stage('Performance Test') {
steps {
// Installera LoadFocus JMeter API-klienten
sh 'npm install -g @loadfocus/loadfocus-api-client'
// Konfigurera LoadFocus API-klienten
sh 'loadfocus-api config set apikey $LOADFOCUS_API_KEY'
sh 'loadfocus-api config set teamid $LOADFOCUS_TEAM_ID'
// Kör prestandatester
sh '''
loadfocus-api jmeter run-test \
--name "Jenkins_${JOB_NAME}_${BUILD_NUMBER}" \
--thresholds "avgresponse<=200,errors==0,p95<=250" \
--format json > performance_results.json
'''
// Arkivera resultaten
archiveArtifacts artifacts: 'performance_results.json', fingerprint: true
}
}
stage('Deploy') {
when {
expression {
return currentBuild.resultIsBetterOrEqualTo('SUCCESS')
}
}
steps {
// Dina deployment-steg
echo 'Deploying...'
}
}
}
post {
always {
// Rensa arbetsytan
cleanWs()
}
}
}

3. Konfigurera Jenkins-jobbet

  1. Skapa ett nytt Pipeline-jobb i Jenkins
  2. Konfigurera pipelinen att använda din Jenkinsfile
  3. Konfigurera lämplig SCM-konfiguration för att hämta ditt repository

Avancerad konfiguration

Deklarativ pipeline med parallell testning

Kör flera prestandatester parallellt:

pipeline {
agent any
environment {
LOADFOCUS_API_KEY = credentials('loadfocus-api-key')
LOADFOCUS_TEAM_ID = credentials('loadfocus-team-id')
}
stages {
// Tidigare steg...
stage('Performance Tests') {
parallel {
stage('API Performance') {
agent {
docker {
image 'node:16-alpine'
}
}
steps {
sh 'npm install -g @loadfocus/loadfocus-api-client'
sh 'loadfocus-api config set apikey $LOADFOCUS_API_KEY'
sh 'loadfocus-api config set teamid $LOADFOCUS_TEAM_ID'
sh '''
loadfocus-api jmeter run-test \
--name "API_Performance_Test" \
--thresholds "avgresponse<=150,errors==0" \
--format json > api_performance_results.json
'''
archiveArtifacts artifacts: 'api_performance_results.json', fingerprint: true
}
}
stage('UI Performance') {
agent {
docker {
image 'node:16-alpine'
}
}
steps {
sh 'npm install -g @loadfocus/loadfocus-api-client'
sh 'loadfocus-api config set apikey $LOADFOCUS_API_KEY'
sh 'loadfocus-api config set teamid $LOADFOCUS_TEAM_ID'
sh '''
loadfocus-api jmeter run-test \
--name "UI_Performance_Test" \
--thresholds "avgresponse<=300,errors==0" \
--format json > ui_performance_results.json
'''
archiveArtifacts artifacts: 'ui_performance_results.json', fingerprint: true
}
}
}
}
// Nästa steg...
}
}

Skriptad pipeline

För mer flexibilitet, använd en skriptad pipeline:

node {
def performanceTestPassed = false
stage('Checkout') {
checkout scm
}
stage('Build & Test') {
// Dina bygg- och teststeg
}
stage('Performance Test') {
docker.image('node:16-alpine').inside {
withCredentials([
string(credentialsId: 'loadfocus-api-key', variable: 'LOADFOCUS_API_KEY'),
string(credentialsId: 'loadfocus-team-id', variable: 'LOADFOCUS_TEAM_ID')
]) {
sh 'npm install -g @loadfocus/loadfocus-api-client'
sh 'loadfocus-api config set apikey $LOADFOCUS_API_KEY'
sh 'loadfocus-api config set teamid $LOADFOCUS_TEAM_ID'
try {
sh '''
loadfocus-api jmeter run-test \
--name "Jenkins_${JOB_NAME}_${BUILD_NUMBER}" \
--thresholds "avgresponse<=200,errors==0,p95<=250" \
--format json > performance_results.json
'''
// Kontrollera om testet godkändes genom att granska JSON
def testResults = readJSON file: 'performance_results.json'
if (testResults.overallResult == 'PASSED') {
performanceTestPassed = true
echo "Performance test passed!"
} else {
echo "Performance test failed to meet thresholds!"
// Valfritt: Misslyckas bygget
// error "Performance test failed"
}
} catch (Exception e) {
echo "Error running performance test: ${e.message}"
}
archiveArtifacts artifacts: 'performance_results.json', fingerprint: true
}
}
}
stage('Deploy') {
if (performanceTestPassed) {
echo 'Deploying...'
// Dina deployment-steg
} else {
echo 'Skipping deployment due to performance test failure'
}
}
}

Delat bibliotek

Skapa ett delat bibliotek för återanvändbar prestandatestning:

// vars/performanceTest.groovy
def call(Map config = [:]) {
def testName = config.testName ?: "Jenkins_${env.JOB_NAME}_${env.BUILD_NUMBER}"
def thresholds = config.thresholds ?: "avgresponse<=200,errors==0,p95<=250"
def waitTimeout = config.waitTimeout ?: 1800
def resultsFile = config.resultsFile ?: "performance_results.json"
docker.image('node:16-alpine').inside {
withCredentials([
string(credentialsId: 'loadfocus-api-key', variable: 'LOADFOCUS_API_KEY'),
string(credentialsId: 'loadfocus-team-id', variable: 'LOADFOCUS_TEAM_ID')
]) {
sh 'npm install -g @loadfocus/loadfocus-api-client'
sh 'loadfocus-api config set apikey $LOADFOCUS_API_KEY'
sh 'loadfocus-api config set teamid $LOADFOCUS_TEAM_ID'
sh """
loadfocus-api jmeter run-test \\
--name "${testName}" \\
--thresholds "${thresholds}" \\
--waitTimeout ${waitTimeout} \\
--format json > ${resultsFile}
"""
archiveArtifacts artifacts: resultsFile, fingerprint: true
// Returnera testresultaten
def testResults = readJSON file: resultsFile
return testResults
}
}
}

Sedan i din Jenkinsfile:

@Library('my-shared-library') _
pipeline {
agent any
stages {
stage('Performance Test') {
steps {
script {
def results = performanceTest(
testName: "API_Performance_Test",
thresholds: "avgresponse<=150,errors==0"
)
if (results.overallResult != 'PASSED') {
error "Performance test failed"
}
}
}
}
}
}

Integration med Jenkins-plugins

Performance Plugin

Använd Jenkins Performance Plugin för att visualisera testresultat:

  1. Installera Performance Plugin i Jenkins
  2. Konvertera LoadFocus-resultat till ett format som stöds av pluginet (JMeter CSV eller JUnit XML)
  3. Konfigurera din pipeline:
stage('Performance Test') {
steps {
// Kör LoadFocus-test
sh '''
loadfocus-api jmeter run-test \
--name "Jenkins_${JOB_NAME}_${BUILD_NUMBER}" \
--thresholds "avgresponse<=200,errors==0,p95<=250" \
--format json > performance_results.json
# Konvertera till JMeter CSV-format (med ett anpassat skript)
node convert-to-jmeter.js performance_results.json performance_results.csv
'''
// Använd Performance Plugin
perfReport sourceDataFiles: 'performance_results.csv',
errorFailedThreshold: 0,
errorUnstableThreshold: 0,
errorUnstableResponseTimeThreshold: '200'
}
}

E-postnotifiering

Skicka e-postnotifieringar med testresultat:

post {
always {
script {
if (fileExists('performance_results.json')) {
def results = readJSON file: 'performance_results.json'
def resultStatus = results.overallResult == 'PASSED' ? 'SUCCESS' : 'FAILURE'
def subject = "Performance Test ${resultStatus}: ${env.JOB_NAME} #${env.BUILD_NUMBER}"
// Skapa e-postinnehåll
def body = """
<h2>Resultat av prestandatest</h2>
<p><strong>Övergripande resultat:</strong> ${results.overallResult}</p>
<h3>Resultat per etikett</h3>
<table border="1">
<tr><th>Etikett</th><th>Resultat</th><th>Genomsnittlig svarstid</th><th>Fel</th></tr>
"""
results.labels.each { label ->
body += """
<tr>
<td>${label.label}</td>
<td>${label.result}</td>
<td>${label.metrics.avgresponse}ms</td>
<td>${label.metrics.errors}</td>
</tr>
"""
}
body += "</table>"
emailext (
subject: subject,
body: body,
to: 'team@example.com',
attachmentsPattern: 'performance_results.json',
mimeType: 'text/html'
)
}
}
}
}

Tips för Jenkins-integration

  1. Timeout-hantering: Ange timeouts för långvariga prestandatester:

    stage('Performance Test') {
    options {
    timeout(time: 60, unit: 'MINUTES')
    }
    steps {
    // Prestandateststeg
    }
    }
  2. Villkorlig körning: Kör bara prestandatester på specifika brancher:

    stage('Performance Test') {
    when {
    anyOf {
    branch 'main'
    branch 'develop'
    tag pattern: "v\\d+\\.\\d+\\.\\d+", comparator: "REGEXP"
    }
    }
    steps {
    // Prestandateststeg
    }
    }
  3. Schemalagd testning: Kör prestandatester enligt schema:

    pipeline {
    agent any
    triggers {
    cron('0 0 * * *') // Kör vid midnatt varje dag
    }
    stages {
    // Pipeline-steg
    }
    }
  4. Parameteriserade tester: Tillåt anpassning av testparametrar:

    pipeline {
    agent any
    parameters {
    string(name: 'TEST_NAME', defaultValue: 'API_Performance_Test', description: 'Namn på LoadFocus-testet att köra')
    string(name: 'THRESHOLDS', defaultValue: 'avgresponse<=200,errors==0', description: 'Prestandatröskelvärden')
    string(name: 'WAIT_TIMEOUT', defaultValue: '1800', description: 'Maximal väntetid i sekunder')
    }
    stages {
    stage('Performance Test') {
    steps {
    // Kör test med parametrar
    sh """
    loadfocus-api jmeter run-test \\
    --name "${params.TEST_NAME}" \\
    --thresholds "${params.THRESHOLDS}" \\
    --waitTimeout ${params.WAIT_TIMEOUT} \\
    --format json > performance_results.json
    """
    }
    }
    }
    }

För mer information, se Jenkins-dokumentationen och LoadFocus API-klientdokumentationen.