Load Testing API
Using the LoadFocus API Client
This guide explains how to use the LoadFocus API Client, both through the command-line interface (CLI) and by directly using the JavaScript library in your applications.
Table of Contents
- Installation
- Configuration
- Command-Line Interface (CLI)
- JavaScript Library Usage
- Advanced Usage
- Troubleshooting
Installation
Global Installation
npm install -g @loadfocus/loadfocus-api-client
Local Project Installation
npm install @loadfocus/loadfocus-api-client
Configuration
Before using the LoadFocus API Client, you need to configure your API credentials.
CLI Configuration
# 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
JavaScript Configuration
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
Command-Line Interface (CLI)
The LoadFocus API Client provides a comprehensive CLI for interacting with the LoadFocus API.
JMeter Test Execution
Execute a Test
# 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
Run a Test and Wait for Completion
# 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
Test Status Monitoring
# 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
Results Retrieval
# 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
Working with Thresholds
The run-test
command supports threshold evaluation to automatically determine if a test passes or fails based on performance metrics.
# Run a test with multiple thresholdsloadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250,hitspersec>=10"
Supported threshold operators:
<=
- Less than or equal to<
- Less than>=
- Greater than or equal to>
- Greater than==
- Equal to!=
- Not equal to
Output Formats
# 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"
JavaScript Library Usage
The LoadFocus API Client can also be used directly as a JavaScript library in your applications.
Basic Setup
// Import the LoadFocus API Clientconst loadfocus = require('@loadfocus/loadfocus-api-client');// Access specific componentsconst { JMeterClient, configManager } = loadfocus;
JMeter Client
// Create a JMeter clientconst jmeterClient = new loadfocus.JMeterClient();// Or with explicit configurationconst jmeterClient = new loadfocus.JMeterClient({apikey: 'YOUR_API_KEY',teamid: 'YOUR_TEAM_ID'});
Executing Tests
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);}}
Monitoring Test Status
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);}}
Retrieving Results
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);}}
Complete Example
Here's a complete example that executes a test, waits for completion, and retrieves results:
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();
Advanced Usage
Custom HTTP Configuration
You can customize the HTTP client used by the LoadFocus API Client:
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'}}});
Error Handling
The LoadFocus API Client provides detailed error information:
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);}}
Troubleshooting
Common Issues
Authentication Errors:
- Ensure your API key and team ID are correctly configured
- Check that your API key has the necessary permissions
Test Execution Failures:
- Verify that the test name exists in your LoadFocus account
- Check if you have reached your account's concurrent test limit
Timeout Issues:
- For long-running tests, increase the
waitTimeout
parameter - Consider implementing a polling mechanism instead of waiting synchronously
- For long-running tests, increase the
Results Retrieval Problems:
- Ensure the test has completed before retrieving results
- Check if the test ID is correct
Debugging
Enable debug logging for more detailed information:
// In your JavaScript codeprocess.env.DEBUG = 'true';// Or when using the CLIDEBUG=true loadfocus-api jmeter run-test --name "My JMeter Test"
For additional help, please refer to the LoadFocus API documentation or contact support.