Integrazione API per Test di Carico

Questa guida spiega come utilizzare il Client API LoadFocus, sia attraverso l'interfaccia a riga di comando (CLI) che utilizzando direttamente la libreria JavaScript nelle vostre applicazioni.

Indice

Installazione

Installazione Globale

npm install -g @loadfocus/loadfocus-api-client

Installazione nel Progetto Locale

npm install @loadfocus/loadfocus-api-client

Configurazione

Prima di utilizzare il Client API LoadFocus, dovete configurare le vostre credenziali API.

Configurazione CLI

# Impostare chiave API e ID team
loadfocus-api config set apikey YOUR_API_KEY
loadfocus-api config set teamid YOUR_TEAM_ID
# Verificare la configurazione
loadfocus-api config show

Configurazione JavaScript

const { configManager } = require('@loadfocus/loadfocus-api-client');
// Impostare la configurazione
configManager.set('apikey', 'YOUR_API_KEY');
configManager.set('teamid', 'YOUR_TEAM_ID');
// Verificare la configurazione
console.log(configManager.get('apikey')); // Dovrebbe stampare la vostra chiave API
console.log(configManager.isConfigured()); // Dovrebbe stampare true se tutta la configurazione richiesta è impostata

Interfaccia a Riga di Comando (CLI)

Il Client API LoadFocus fornisce una CLI completa per interagire con l'API LoadFocus.

Esecuzione Test JMeter

Eseguire un Test

# Eseguire un test per nome
loadfocus-api jmeter execute --name "My JMeter Test"
# Eseguire un test con parametri specifici
loadfocus-api jmeter execute --name "My JMeter Test" --threads 50 --rampup 30 --duration 300

Eseguire un Test e Attendere il Completamento

# Eseguire un test e attendere il completamento
loadfocus-api jmeter run-test --name "My JMeter Test"
# Eseguire un test con soglie
loadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250"
# Eseguire un test con timeout e intervallo di polling personalizzati
loadfocus-api jmeter run-test --name "My JMeter Test" --waitTimeout 1800 --pollInterval 15

Monitoraggio Stato Test

# Verificare lo stato di un test per nome e ID
loadfocus-api jmeter status --name "My JMeter Test" --id 12345
# Ottenere un elenco delle esecuzioni recenti dei test
loadfocus-api jmeter runs --limit 10

Recupero Risultati

# Ottenere risultati per un test specifico
loadfocus-api jmeter results --name "My JMeter Test" --id 12345
# Ottenere risultati con metriche specifiche
loadfocus-api jmeter results --name "My JMeter Test" --id 12345 --include samples,avgresponse,errors

Lavorare con le Soglie

Il comando run-test supporta la valutazione delle soglie per determinare automaticamente se un test supera o fallisce in base alle metriche di prestazione.

# Eseguire un test con soglie multiple
loadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250,hitspersec>=10"

Operatori di soglia supportati:

  • <= - Minore o uguale a
  • < - Minore di
  • >= - Maggiore o uguale a
  • > - Maggiore di
  • == - Uguale a
  • != - Diverso da

Formati di Output

# Ottenere risultati in formato JSON
loadfocus-api jmeter run-test --name "My JMeter Test" --format json > results.json
# Output predefinito formattato
loadfocus-api jmeter run-test --name "My JMeter Test"

Utilizzo della Libreria JavaScript

Il Client API LoadFocus può anche essere utilizzato direttamente come libreria JavaScript nelle vostre applicazioni.

Configurazione di Base

// Importare il Client API LoadFocus
const loadfocus = require('@loadfocus/loadfocus-api-client');
// Accedere a componenti specifici
const { JMeterClient, configManager } = loadfocus;

Client JMeter

// Creare un client JMeter
const jmeterClient = new loadfocus.JMeterClient();
// O con configurazione esplicita
const jmeterClient = new loadfocus.JMeterClient({
apikey: 'YOUR_API_KEY',
teamid: 'YOUR_TEAM_ID'
});

Esecuzione dei Test

async function executeTest() {
try {
const result = await jmeterClient.execute({
testrunname: 'My JMeter Test',
threads: 50,
rampup: 30,
duration: 300
});
console.log('Esecuzione test avviata:', result);
return result.testrunid; // Restituire l'ID del test per uso successivo
} catch (error) {
console.error('Errore nell\'esecuzione del test:', error);
}
}

Monitoraggio dello Stato dei Test

async function checkTestStatus(testName, testId) {
try {
const status = await jmeterClient.getStatus({
testrunname: testName,
testrunid: testId
});
console.log('Stato del test:', status);
return status.state; // Restituire lo stato corrente
} catch (error) {
console.error('Errore nel controllo dello stato del test:', error);
}
}

Recupero dei Risultati

async function getTestResults(testName, testId) {
try {
// Ottenere le etichette disponibili per il test
const labels = await jmeterClient.getLabels({
testrunname: testName,
testrunid: testId
});
console.log('Etichette del test:', labels);
// Ottenere risultati per ogni etichetta
const allResults = [];
for (const label of labels) {
const labelResults = await jmeterClient.getResults({
testrunname: testName,
testrunid: testId,
filter: label
});
allResults.push({
label,
results: labelResults
});
}
console.log('Risultati del test:', allResults);
return allResults;
} catch (error) {
console.error('Errore nel recupero dei risultati del test:', error);
}
}

Esempio Completo

Ecco un esempio completo che esegue un test, attende il completamento e recupera i risultati:

const { JMeterClient, configManager } = require('@loadfocus/loadfocus-api-client');
// Configurazione
configManager.set('apikey', 'YOUR_API_KEY');
configManager.set('teamid', 'YOUR_TEAM_ID');
// Creare il client
const jmeterClient = new JMeterClient();
async function runCompleteTest() {
try {
// Eseguire il test
console.log('Esecuzione del test...');
const executeResult = await jmeterClient.execute({
testrunname: 'My JMeter Test'
});
const testId = executeResult.testrunid;
console.log(`Esecuzione test avviata con ID: ${testId}`);
// Attendere il completamento
console.log('In attesa del completamento del test...');
let completed = false;
while (!completed) {
const status = await jmeterClient.getStatus({
testrunname: 'My JMeter Test',
testrunid: testId
});
console.log(`Stato corrente: ${status.state}`);
if (status.state === 'finished') {
completed = true;
} else if (status.state === 'failed' || status.state === 'error') {
throw new Error(`Test fallito con stato: ${status.state}`);
} else {
// Attendere prima di controllare di nuovo
await new Promise(resolve => setTimeout(resolve, 10000));
}
}
// Ottenere i risultati
console.log('Recupero dei risultati del test...');
const labels = await jmeterClient.getLabels({
testrunname: 'My JMeter Test',
testrunid: testId
});
const allResults = [];
for (const label of labels) {
const labelResults = await jmeterClient.getResults({
testrunname: 'My JMeter Test',
testrunid: testId,
filter: label
});
allResults.push({
label,
results: labelResults
});
}
console.log('Risultati del test:', JSON.stringify(allResults, null, 2));
return allResults;
} catch (error) {
console.error('Errore nell\'esecuzione del test:', error);
}
}
// Eseguire il test
runCompleteTest();

Utilizzo Avanzato

Configurazione HTTP Personalizzata

Potete personalizzare il client HTTP utilizzato dal Client API LoadFocus:

const { JMeterClient } = require('@loadfocus/loadfocus-api-client');
// Creare client con opzioni HTTP personalizzate
const jmeterClient = new JMeterClient({
apikey: 'YOUR_API_KEY',
teamid: 'YOUR_TEAM_ID',
httpOptions: {
timeout: 30000, // 30 secondi
retries: 3,
headers: {
'User-Agent': 'My Custom Application'
}
}
});

Gestione degli Errori

Il Client API LoadFocus fornisce informazioni dettagliate sugli errori:

try {
const result = await jmeterClient.execute({
testrunname: 'My JMeter Test'
});
} catch (error) {
if (error.response) {
// La richiesta è stata effettuata e il server ha risposto con un codice di stato
// che non rientra nell'intervallo 2xx
console.error('Errore API:', error.response.status, error.response.data);
} else if (error.request) {
// La richiesta è stata effettuata ma non è stata ricevuta alcuna risposta
console.error('Errore di Rete:', error.request);
} else {
// Qualcosa è andato storto nella configurazione della richiesta
console.error('Errore della Richiesta:', error.message);
}
}

Risoluzione dei Problemi

Problemi Comuni

  1. Errori di Autenticazione:

    • Assicuratevi che la chiave API e l'ID team siano configurati correttamente
    • Verificate che la vostra chiave API abbia i permessi necessari
  2. Fallimenti nell'Esecuzione dei Test:

    • Verificate che il nome del test esista nel vostro account LoadFocus
    • Controllate se avete raggiunto il limite di test simultanei del vostro account
  3. Problemi di Timeout:

    • Per test di lunga durata, aumentate il parametro waitTimeout
    • Considerate l'implementazione di un meccanismo di polling invece di attendere in modo sincrono
  4. Problemi nel Recupero dei Risultati:

    • Assicuratevi che il test sia completato prima di recuperare i risultati
    • Verificate che l'ID del test sia corretto

Debug

Abilitate il logging di debug per informazioni più dettagliate:

// Nel vostro codice JavaScript
process.env.DEBUG = 'true';
// O quando utilizzate la CLI
DEBUG=true loadfocus-api jmeter run-test --name "My JMeter Test"

Per ulteriore assistenza, consultate la documentazione API LoadFocus o contattate il supporto.