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
- Configurazione
- Interfaccia a Riga di Comando (CLI)
- Utilizzo della Libreria JavaScript
- Utilizzo Avanzato
- Risoluzione dei Problemi
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 teamloadfocus-api config set apikey YOUR_API_KEYloadfocus-api config set teamid YOUR_TEAM_ID# Verificare la configurazioneloadfocus-api config show
Configurazione JavaScript
const { configManager } = require('@loadfocus/loadfocus-api-client');// Impostare la configurazioneconfigManager.set('apikey', 'YOUR_API_KEY');configManager.set('teamid', 'YOUR_TEAM_ID');// Verificare la configurazioneconsole.log(configManager.get('apikey')); // Dovrebbe stampare la vostra chiave APIconsole.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 nomeloadfocus-api jmeter execute --name "My JMeter Test"# Eseguire un test con parametri specificiloadfocus-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 completamentoloadfocus-api jmeter run-test --name "My JMeter Test"# Eseguire un test con soglieloadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250"# Eseguire un test con timeout e intervallo di polling personalizzatiloadfocus-api jmeter run-test --name "My JMeter Test" --waitTimeout 1800 --pollInterval 15
Monitoraggio Stato Test
# Verificare lo stato di un test per nome e IDloadfocus-api jmeter status --name "My JMeter Test" --id 12345# Ottenere un elenco delle esecuzioni recenti dei testloadfocus-api jmeter runs --limit 10
Recupero Risultati
# Ottenere risultati per un test specificoloadfocus-api jmeter results --name "My JMeter Test" --id 12345# Ottenere risultati con metriche specificheloadfocus-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 multipleloadfocus-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 JSONloadfocus-api jmeter run-test --name "My JMeter Test" --format json > results.json# Output predefinito formattatoloadfocus-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 LoadFocusconst loadfocus = require('@loadfocus/loadfocus-api-client');// Accedere a componenti specificiconst { JMeterClient, configManager } = loadfocus;
Client JMeter
// Creare un client JMeterconst jmeterClient = new loadfocus.JMeterClient();// O con configurazione esplicitaconst 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 testconst labels = await jmeterClient.getLabels({testrunname: testName,testrunid: testId});console.log('Etichette del test:', labels);// Ottenere risultati per ogni etichettaconst 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');// ConfigurazioneconfigManager.set('apikey', 'YOUR_API_KEY');configManager.set('teamid', 'YOUR_TEAM_ID');// Creare il clientconst jmeterClient = new JMeterClient();async function runCompleteTest() {try {// Eseguire il testconsole.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 completamentoconsole.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 nuovoawait new Promise(resolve => setTimeout(resolve, 10000));}}// Ottenere i risultaticonsole.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 testrunCompleteTest();
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 personalizzateconst jmeterClient = new JMeterClient({apikey: 'YOUR_API_KEY',teamid: 'YOUR_TEAM_ID',httpOptions: {timeout: 30000, // 30 secondiretries: 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 2xxconsole.error('Errore API:', error.response.status, error.response.data);} else if (error.request) {// La richiesta è stata effettuata ma non è stata ricevuta alcuna rispostaconsole.error('Errore di Rete:', error.request);} else {// Qualcosa è andato storto nella configurazione della richiestaconsole.error('Errore della Richiesta:', error.message);}}
Risoluzione dei Problemi
Problemi Comuni
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
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
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
- Per test di lunga durata, aumentate il parametro
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 JavaScriptprocess.env.DEBUG = 'true';// O quando utilizzate la CLIDEBUG=true loadfocus-api jmeter run-test --name "My JMeter Test"
Per ulteriore assistenza, consultate la documentazione API LoadFocus o contattate il supporto.