Integrace API zátěžového testování
Tento průvodce vysvětluje, jak používat klienta LoadFocus API, a to jak přes rozhraní příkazové řádky (CLI), tak přímým použitím JavaScript knihovny ve vašich aplikacích.
Obsah
- Instalace
- Konfigurace
- Rozhraní příkazové řádky (CLI)
- Použití JavaScript knihovny
- Pokročilé použití
- Řešení problémů
Instalace
Globální instalace
npm install -g @loadfocus/loadfocus-api-client
Lokální instalace do projektu
npm install @loadfocus/loadfocus-api-client
Konfigurace
Před použitím klienta LoadFocus API musíte nakonfigurovat své API přihlašovací údaje.
Konfigurace CLI
# Set API key and team IDloadfocus-api config set apikey YOUR_API_KEYloadfocus-api config set teamid YOUR_TEAM_ID# Verify configurationloadfocus-api config show
Konfigurace v JavaScriptu
const { configManager } = require('@loadfocus/loadfocus-api-client');// Set configurationconfigManager.set('apikey', 'YOUR_API_KEY');configManager.set('teamid', 'YOUR_TEAM_ID');// Verify configurationconsole.log(configManager.get('apikey')); // Should print your API keyconsole.log(configManager.isConfigured()); // Should print true if all required config is set
Rozhraní příkazové řádky (CLI)
Klient LoadFocus API poskytuje komplexní CLI pro interakci s LoadFocus API.
Spuštění JMeter testu
Spuštění testu
# Execute a test by nameloadfocus-api jmeter execute --name "My JMeter Test"# Execute a test with specific parametersloadfocus-api jmeter execute --name "My JMeter Test" --threads 50 --rampup 30 --duration 300
Spuštění testu a čekání na dokončení
# Run a test and wait for completionloadfocus-api jmeter run-test --name "My JMeter Test"# Run a test with thresholdsloadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250"# Run a test with custom timeout and polling intervalloadfocus-api jmeter run-test --name "My JMeter Test" --waitTimeout 1800 --pollInterval 15
Monitorování stavu testu
# Check status of a test by name and IDloadfocus-api jmeter status --name "My JMeter Test" --id 12345# Get a list of recent test runsloadfocus-api jmeter runs --limit 10
Získání výsledků
# Get results for a specific testloadfocus-api jmeter results --name "My JMeter Test" --id 12345# Get results with specific metricsloadfocus-api jmeter results --name "My JMeter Test" --id 12345 --include samples,avgresponse,errors
Práce s prahovými hodnotami
Příkaz run-test podporuje vyhodnocování prahových hodnot pro automatické určení, zda test prošel nebo selhal na základě výkonnostních metrik.
# Run a test with multiple thresholdsloadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250,hitspersec>=10"
Podporované operátory prahových hodnot:
<=- Menší nebo rovno<- Menší než>=- Větší nebo rovno>- Větší než==- Rovná se!=- Nerovná se
Výstupní formáty
# Get results in JSON formatloadfocus-api jmeter run-test --name "My JMeter Test" --format json > results.json# Default pretty-printed outputloadfocus-api jmeter run-test --name "My JMeter Test"
Použití JavaScript knihovny
Klient LoadFocus API lze také použít přímo jako JavaScript knihovnu ve vašich aplikacích.
Základní nastavení
// Import the LoadFocus API Clientconst loadfocus = require('@loadfocus/loadfocus-api-client');// Access specific componentsconst { JMeterClient, configManager } = loadfocus;
JMeter klient
// Create a JMeter clientconst jmeterClient = new loadfocus.JMeterClient();// Or with explicit configurationconst jmeterClient = new loadfocus.JMeterClient({apikey: 'YOUR_API_KEY',teamid: 'YOUR_TEAM_ID'});
Spouštění testů
async function executeTest() {try {const result = await jmeterClient.execute({testrunname: 'My JMeter Test',threads: 50,rampup: 30,duration: 300});console.log('Test execution started:', result);return result.testrunid; // Return the test ID for later use} catch (error) {console.error('Error executing test:', error);}}
Monitorování stavu testu
async function checkTestStatus(testName, testId) {try {const status = await jmeterClient.getStatus({testrunname: testName,testrunid: testId});console.log('Test status:', status);return status.state; // Return the current state} catch (error) {console.error('Error checking test status:', error);}}
Získávání výsledků
async function getTestResults(testName, testId) {try {// Get available labels for the testconst labels = await jmeterClient.getLabels({testrunname: testName,testrunid: testId});console.log('Test labels:', labels);// Get results for each labelconst allResults = [];for (const label of labels) {const labelResults = await jmeterClient.getResults({testrunname: testName,testrunid: testId,filter: label});allResults.push({label,results: labelResults});}console.log('Test results:', allResults);return allResults;} catch (error) {console.error('Error retrieving test results:', error);}}
Kompletní příklad
Zde je kompletní příklad, který spustí test, počká na dokončení a získá výsledky:
const { JMeterClient, configManager } = require('@loadfocus/loadfocus-api-client');// Set up configurationconfigManager.set('apikey', 'YOUR_API_KEY');configManager.set('teamid', 'YOUR_TEAM_ID');// Create clientconst jmeterClient = new JMeterClient();async function runCompleteTest() {try {// Execute the testconsole.log('Executing test...');const executeResult = await jmeterClient.execute({testrunname: 'My JMeter Test'});const testId = executeResult.testrunid;console.log(`Test execution started with ID: ${testId}`);// Wait for completionconsole.log('Waiting for test to complete...');let completed = false;while (!completed) {const status = await jmeterClient.getStatus({testrunname: 'My JMeter Test',testrunid: testId});console.log(`Current state: ${status.state}`);if (status.state === 'finished') {completed = true;} else if (status.state === 'failed' || status.state === 'error') {throw new Error(`Test failed with state: ${status.state}`);} else {// Wait before checking againawait new Promise(resolve => setTimeout(resolve, 10000));}}// Get resultsconsole.log('Getting test results...');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('Test results:', JSON.stringify(allResults, null, 2));return allResults;} catch (error) {console.error('Error running test:', error);}}// Run the testrunCompleteTest();
Pokročilé použití
Vlastní HTTP konfigurace
HTTP klienta používaného klientem LoadFocus API můžete přizpůsobit:
const { JMeterClient } = require('@loadfocus/loadfocus-api-client');// Create client with custom HTTP optionsconst jmeterClient = new JMeterClient({apikey: 'YOUR_API_KEY',teamid: 'YOUR_TEAM_ID',httpOptions: {timeout: 30000, // 30 secondsretries: 3,headers: {'User-Agent': 'My Custom Application'}}});
Zpracování chyb
Klient LoadFocus API poskytuje podrobné informace o chybách:
try {const result = await jmeterClient.execute({testrunname: 'My JMeter Test'});} catch (error) {if (error.response) {// The request was made and the server responded with a status code// that falls out of the range of 2xxconsole.error('API Error:', error.response.status, error.response.data);} else if (error.request) {// The request was made but no response was receivedconsole.error('Network Error:', error.request);} else {// Something happened in setting up the request that triggered an Errorconsole.error('Request Error:', error.message);}}
Řešení problémů
Běžné problémy
Chyby autentizace:
- Ujistěte se, že váš API klíč a team ID jsou správně nakonfigurovány
- Zkontrolujte, zda má váš API klíč potřebná oprávnění
Selhání spuštění testu:
- Ověřte, že název testu existuje ve vašem účtu LoadFocus
- Zkontrolujte, zda jste nedosáhli limitu souběžných testů vašeho účtu
Problémy s timeoutem:
- Pro dlouho běžící testy zvyšte parametr
waitTimeout - Zvažte implementaci mechanismu dotazování místo synchronního čekání
- Pro dlouho běžící testy zvyšte parametr
Problémy se získáváním výsledků:
- Ujistěte se, že test byl dokončen před získáváním výsledků
- Zkontrolujte, zda je ID testu správné
Ladění
Povolte debug logování pro podrobnější informace:
// In your JavaScript codeprocess.env.DEBUG = 'true';// Or when using the CLIDEBUG=true loadfocus-api jmeter run-test --name "My JMeter Test"
Pro další pomoc se prosím obraťte na dokumentaci LoadFocus API nebo kontaktujte podporu.