Apkrovos testavimo API integracija

Sis vadovas paaisskina, kaip naudoti LoadFocus API klienta tiek per komandiines eilutes sasaja (CLI), tiek tiesiogiai naudojant JavaScript biblioteka jusu programose.

Turinys

Installation

Globalus diegimas

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

Vietinis projekto diegimas

npm install @loadfocus/loadfocus-api-client

Configuration

Pries naudojant LoadFocus API klienta, turite sukonfiguruoti savo API prisijungimo duomenis.

CLI konfiguracija

# Set API key and team ID
loadfocus-api config set apikey YOUR_API_KEY
loadfocus-api config set teamid YOUR_TEAM_ID
# Verify configuration
loadfocus-api config show

JavaScript konfiguracija

const { configManager } = require('@loadfocus/loadfocus-api-client');
// Set configuration
configManager.set('apikey', 'YOUR_API_KEY');
configManager.set('teamid', 'YOUR_TEAM_ID');
// Verify configuration
console.log(configManager.get('apikey')); // Should print your API key
console.log(configManager.isConfigured()); // Should print true if all required config is set

Command-Line Interface (CLI)

LoadFocus API klientas teikia issamia CLI sasaja bendravimui su LoadFocus API.

JMeter testo vykdymas

Testo paleidimas

# Execute a test by name
loadfocus-api jmeter execute --name "My JMeter Test"
# Execute a test with specific parameters
loadfocus-api jmeter execute --name "My JMeter Test" --threads 50 --rampup 30 --duration 300

Testo paleidimas ir laukimas kol baigsis

# Run a test and wait for completion
loadfocus-api jmeter run-test --name "My JMeter Test"
# Run a test with thresholds
loadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250"
# Run a test with custom timeout and polling interval
loadfocus-api jmeter run-test --name "My JMeter Test" --waitTimeout 1800 --pollInterval 15

Testo busenos stebejimas

# Check status of a test by name and ID
loadfocus-api jmeter status --name "My JMeter Test" --id 12345
# Get a list of recent test runs
loadfocus-api jmeter runs --limit 10

Rezultatu gavimas

# Get results for a specific test
loadfocus-api jmeter results --name "My JMeter Test" --id 12345
# Get results with specific metrics
loadfocus-api jmeter results --name "My JMeter Test" --id 12345 --include samples,avgresponse,errors

Darbas su ribinemis vertemis

run-test komanda palaiko ribiniu verciu ivertinima, kad automatiskai nustatytu, ar testas praeina, ar nepavyksta pagal nasumo rodiklius.

# Run a test with multiple thresholds
loadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250,hitspersec>=10"

Palaikomi ribiniu verciu operatoriai:

  • <= - Maziau arba lygu
  • < - Maziau negu
  • >= - Daugiau arba lygu
  • > - Daugiau negu
  • == - Lygu
  • != - Nelygu

Isvesties formatai

# Get results in JSON format
loadfocus-api jmeter run-test --name "My JMeter Test" --format json > results.json
# Default pretty-printed output
loadfocus-api jmeter run-test --name "My JMeter Test"

JavaScript bibliotekos naudojimas

LoadFocus API klienta taip pat galima naudoti tiesiogiai kaip JavaScript biblioteka jusu programose.

Pradinis nustatymas

// Import the LoadFocus API Client
const loadfocus = require('@loadfocus/loadfocus-api-client');
// Access specific components
const { JMeterClient, configManager } = loadfocus;

JMeter klientas

// Create a JMeter client
const jmeterClient = new loadfocus.JMeterClient();
// Or with explicit configuration
const jmeterClient = new loadfocus.JMeterClient({
apikey: 'YOUR_API_KEY',
teamid: 'YOUR_TEAM_ID'
});

Testu vykdymas

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);
}
}

Testo busenos stebejimas

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);
}
}

Rezultatu gavimas

async function getTestResults(testName, testId) {
try {
// Get available labels for the test
const labels = await jmeterClient.getLabels({
testrunname: testName,
testrunid: testId
});
console.log('Test labels:', labels);
// Get results for each label
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('Test results:', allResults);
return allResults;
} catch (error) {
console.error('Error retrieving test results:', error);
}
}

Pilnas pavyzdys

Stai pilnas pavyzdys, kuris vykdo testa, laukia pabaigos ir gauna rezultatus:

const { JMeterClient, configManager } = require('@loadfocus/loadfocus-api-client');
// Set up configuration
configManager.set('apikey', 'YOUR_API_KEY');
configManager.set('teamid', 'YOUR_TEAM_ID');
// Create client
const jmeterClient = new JMeterClient();
async function runCompleteTest() {
try {
// Execute the test
console.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 completion
console.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 again
await new Promise(resolve => setTimeout(resolve, 10000));
}
}
// Get results
console.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 test
runCompleteTest();

Pazangus naudojimas

Pasirinktine HTTP konfiguracija

Galite pritaikyti HTTP klienta, naudojama LoadFocus API kliento:

const { JMeterClient } = require('@loadfocus/loadfocus-api-client');
// Create client with custom HTTP options
const jmeterClient = new JMeterClient({
apikey: 'YOUR_API_KEY',
teamid: 'YOUR_TEAM_ID',
httpOptions: {
timeout: 30000, // 30 seconds
retries: 3,
headers: {
'User-Agent': 'My Custom Application'
}
}
});

Klaidu apdorojimas

LoadFocus API klientas teikia detalia klaidu informacija:

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 2xx
console.error('API Error:', error.response.status, error.response.data);
} else if (error.request) {
// The request was made but no response was received
console.error('Network Error:', error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.error('Request Error:', error.message);
}
}

Trukciu diagnostika

Dazniausios problemos

  1. Autentifikacijos klaidos:

    • Isitikinkite, kad jusu API raktas ir komandos ID yra teisingai sukonfigaruoti
    • Patikrinkite, ar jusu API raktas turi reikalingus leidimus
  2. Testo vykdymo nesekmes:

    • Patikrinkite, ar testo pavadinimas egzistuoja jusu LoadFocus paskyroje
    • Patikrinkite, ar nepasiekete savo paskyros vienalaikiu testu limito
  3. Laiko limito problemos:

    • Ilgai vykdomiems testams padidinkite waitTimeout parametra
    • Apsvarstykite apklausos mechanizmo igyvendinima vietoj sinchroninio laukimo
  4. Rezultatu gavimo problemos:

    • Isitikinkite, kad testas baigesi pries gaunant rezultatus
    • Patikrinkite, ar testo ID yra teisingas

Derinimas

Igalinkite derinimo zurnalizavima detalessnei informacijai:

// In your JavaScript code
process.env.DEBUG = 'true';
// Or when using the CLI
DEBUG=true loadfocus-api jmeter run-test --name "My JMeter Test"

Papildomos pagalbos iesskokite LoadFocus API dokumentacijoje arba susisiekite su palaikymu.