PHP code example of volt-test / laravel-performance-testing

1. Go to this page and download the library: Download volt-test/laravel-performance-testing library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

volt-test / laravel-performance-testing example snippets


return [
    // Test Configuration
    'name' => env('VOLTTEST_NAME', 'Laravel Application Test'),
    'description' => env('VOLTTEST_DESCRIPTION', 'Performance test for Laravel application'),

    // Load Configuration
    'virtual_users' => env('VOLTTEST_VIRTUAL_USERS', 10),
    'duration' => env('VOLTTEST_DURATION'), // e.g., '1m', '30s', '2h'
    'ramp_up' => env('VOLTTEST_RAMP_UP', null),

    // Debug Configuration
    'http_debug' => env('VOLTTEST_HTTP_DEBUG', false),

    // Test Paths
    'test_paths' => app_path('VoltTests'),

    // Reports
    'reports_path' => storage_path('volttest/reports'),
    'save_reports' => env('VOLTTEST_SAVE_REPORTS', true),

    // Base URL
    'use_base_url' => env('VOLTTEST_USE_BASE_URL', true),
    'base_url' => env('VOLTTEST_BASE_URL', 'http://localhost:8000'),

    // CSV Data Source Configuration
    'csv_data' => [
        'path' => storage_path('volttest/data'), // Default CSV location
        'validate_files' => true,                // Check file exists before run
        'default_distribution' => 'unique',      // Default distribution mode
        'default_headers' => true,               // Default header setting
    ],
];



namespace App\VoltTests;

use VoltTest\Laravel\Contracts\VoltTestCase;
use VoltTest\Laravel\VoltTestManager;

class UserTest implements VoltTestCase
{
    public function define(VoltTestManager $manager): void
    {
        $scenario = $manager->scenario('UserTest');

        // Step 1: Home Page
        $scenario->step('Home Page')
            ->get('/')
            ->expectStatus(200);
            
        // Step 2: Get Registration Page to extract CSRF token
        $scenario->step('Get Registration Page')
            ->get('/register')
            ->expectStatus(200)
            ->extractCsrfToken('csrf_token'); // Extract CSRF token for registration

        // Step 2: User Registration
        $scenario->step('User Registration')
            ->post('/register', [
                '_token' => '${csrf_token}',
                'name' => 'John Doe',
                'email' => '[email protected]',
                'password' => 'password',
                'password_confirmation' => 'password',
            ] , [
            'Content-Type' => 'application/x-www-form-urlencoded' // Specify content type for form submission
            ])
            ->expectStatus(201);
    }
}



namespace App\VoltTests;

use VoltTest\Laravel\Contracts\VoltTestCase;
use VoltTest\Laravel\VoltTestManager;

class CheckoutTest implements VoltTestCase
{
    public function define(VoltTestManager $manager): void
    {
        $scenario = $manager->scenario('E-commerce Checkout Flow');

        // Browse products
        $scenario->step('Browse Products')
            ->get('/products')
            ->expectStatus(200)
            ->extractHtml('product_id', '.product:first-child', 'data-id');
        // To know how to extract the product ID, you can use a CSS selector that matches the first product element.
        // Reference: https://php.volt-test.com/docs/Steps#html-response

        // Add to cart
        $scenario->step('Add to Cart')
            ->post('/cart/add', [
                '_token' => '${csrf_token}',
                'product_id' => '${product_id}',
                'quantity' => 1,
            ])
            ->expectStatus(200)
            ->thinkTime('2s');

        // Checkout
        $scenario->step('Checkout')
            ->get('/checkout')
            ->expectStatus(200)
            ->extractCsrfToken('checkout_token');

        // Complete order
        $scenario->step('Complete Order')
            ->post('/checkout/complete', [
                '_token' => '${checkout_token}',
                'payment_method' => 'credit_card',
                'shipping_address' => 'Test Address',
            ])
            ->expectStatus(302); // Redirect after successful order
    }
}



namespace App\VoltTests;

use VoltTest\Laravel\Contracts\VoltTestCase;
use VoltTest\Laravel\VoltTestManager;

class ApiTest implements VoltTestCase
{
    public function define(VoltTestManager $manager): void
    {
        $scenario = $manager->scenario('API Performance Test');

        // Login to get token - Using headers directly in the request method
        $scenario->step('API Login')
            ->post('/api/login', [
                'email' => '[email protected]',
                'password' => 'password',
            ], [
                'Accept' => 'application/json'  // Headers provided directly as third parameter
            ])
            ->expectStatus(200)
            ->extractJson('auth_token', 'meta.token');
        // Extract the authentication token from the response
        // Reference: https://php.volt-test.com/docs/Steps#json-response

        // Get user data - Using headers directly in the get method
        $scenario->step('Get User Data')
            ->get('/api/user', [
                'Authorization' => 'Bearer ${auth_token}',
                'Accept' => 'application/json'  // Headers provided directly in the GET method
            ])
            ->expectStatus(200)
            ->extractJson('user_id', 'data.id');

        // Update user - Automatic JSON conversion based on Content-Type header
        $scenario->step('Update User')
            ->put('/api/user/${user_id}', [
                'name' => 'Updated Name',
                'email' => '[email protected]',
            ], [
                'Authorization' => 'Bearer ${auth_token}',
                'Content-Type' => 'application/json'  // This automatically converts the array to JSON
            ])
            ->expectStatus(200);
            
        // Create new resource - Alternative way using header method
        $scenario->step('Create Resource')
            ->post('/api/resources', [
                'title' => 'New Resource',
                'description' => 'Resource description'
            ] , 
            [
                'Authorization' => 'Bearer ${auth_token}',
                'Content-Type' => 'application/json' // This automatically converts the array to JSON
            ])
            ->expectStatus(201);
    }
}

// HTTP Methods
$scenario->step('Step Name')
    ->get('/path')
    ->post('/path', $data)
    ->put('/path', $data)
    ->patch('/path', $data)
    ->delete('/path');
    
// HTTP Methods with headers parameter for automatic content type detection
$scenario->step('Step Name')
    ->get('/path', ['Accept' => 'application/json'])
    ->post('/path', $data, ['Content-Type' => 'application/json']) // Array will be automatically converted to JSON
    ->put('/path', $data, ['Content-Type' => 'application/json'])  // Array will be automatically converted to JSON
    ->patch('/path', $data, ['Content-Type' => 'application/json']) // Array will be automatically converted to JSON
    ->delete('/path', ['Accept' => 'application/json']);

// Headers
$scenario->step('Step Name')
    ->header('Authorization', 'Bearer token')
    ->header('Accept', 'application/json');
    
// Content-Type headers trigger automatic data format conversion:
$scenario->step('Step Name')
    ->post('/api/resources', ['name' => 'Product', 'price' => 19.99] , ['Content-Type'=>'application/json']); // This will automatically convert the array to JSON

// Expectations
$scenario->step('Step Name')
    ->expectStatus(200)
    ->expectStatus(201, 'custom_validation_name');

// Data Extraction
$scenario->step('Step Name')
    ->extractJson('variable_name', 'path.to.value') // Reference: https://php.volt-test.com/docs/Steps#json-response
    ->extractHeader('variable_name', 'Header-Name') // Reference: https://php.volt-test.com/docs/Steps#header-response
    ->extractHtml('variable_name', 'css-selector', 'attribute') // Reference: https://php.volt-test.com/docs/Steps#html-response
    ->extractRegex('variable_name', '/pattern/') // Reference: https://php.volt-test.com/docs/Steps#regular-expressions
    ->extractCsrfToken('csrf_token'); // Laravel-specific CSRF token extraction or u can use `extractHtml` with the CSRF token input field

// Think Time
$scenario->step('Step Name')
    ->thinkTime('2s'); // Pause between requests



namespace App\VoltTests;

use VoltTest\Laravel\Contracts\VoltTestCase;
use VoltTest\Laravel\VoltTestManager;

class RegisterTest implements VoltTestCase
{
    public function define(VoltTestManager $manager): void
    {
        // Configure CSV data source
        $scenario = $manager->scenario('RegisterTest')
            ->dataSource('users.csv');

        // Step 1: Get Register Page
        $scenario->step('Register')
            ->get('/register', [
            'Content-Type' => 'application/x-www-form-urlencoded'
            ])
            ->extractCsrfToken('token')
            ->expectStatus(200);

        // Step 2: Submit Registration
        $scenario->step('Register')
            ->post('/register', [
                '_token' => '${token}',
                'name' => '${name}',           // From CSV column
                'email' => '${email}',         // From CSV column
                'password' => '${password}',   // From CSV column
                'password_confirmation' => '${password}',
            ],[
                'Content-Type' => 'application/x-www-form-urlencoded' // Specify content type for form submission
            ])
            ->expectStatus(302);

        // Step 3: Access Dashboard
        $scenario->step('Get Dashboard')
            ->get('/dashboard', [
            'Content-Type' => 'text/html',
            ])
            ->expectStatus(200);
    }
}



namespace Tests\Performance;

use VoltTest\Laravel\Contracts\VoltTestCase;
use VoltTest\Laravel\Testing\PerformanceTestCase;
use VoltTest\Laravel\VoltTestManager;

class HomePagePerformanceTest extends PerformanceTestCase
{
    protected static bool $enableServerManagement = true;

    public function test_homepage_performance(): void
    {
        $testClass = new class implements VoltTestCase {
            public function define(VoltTestManager $manager): void
            {
                $scenario = $manager->scenario('Homepage Load Test');

                $scenario->step('Load Homepage')
                    ->get('/')
                    ->expectStatus(200);
            }
        };

        $result = $this->runVoltTest($testClass, [
            'virtual_users' => 10,
            'duration' => '30s',
        ]);

        // Assert performance metrics
        $this->assertVTSuccessful($result, 95.0);
        $this->assertVTP95ResponseTime($result, 500);
        $this->assertVTAverageResponseTime($result, 200);
    }
}

// Success rate assertions
$this->assertVTSuccessful($result, 95.0);           // >= 95% success rate
$this->assertVTErrorRate($result, 5.0);             // <= 5% error rate

// Response time assertions
$this->assertVTMinResponseTime($result, 10);        // Min response time
$this->assertVTMaxResponseTime($result, 2000);      // Max response time
$this->assertVTAverageResponseTime($result, 300);   // Average response time
$this->assertVTMedianResponseTime($result, 200);    // Median (P50) response time
$this->assertVTP95ResponseTime($result, 500);       // P95 response time
$this->assertVTP99ResponseTime($result, 1000);      // P99 response time

// Throughput assertions
$this->assertVTMinimumRequests($result, 100);       // Total requests >= 100
$this->assertVTMinimumRPS($result, 10.0);           // Requests/sec >= 10
$this->assertVTMaximumRPS($result, 1000.0);         // Requests/sec <= 1000

// Test a single URL
$result = $this->loadTestUrl('/');
$this->assertVTSuccessful($result);

// Test an API endpoint
$result = $this->loadTestApi('/api/users', 'POST', [
    'name' => 'John Doe',
    'email' => '[email protected]',
]);
$this->assertVTSuccessful($result);



namespace App\VoltTests;

use VoltTest\Laravel\Contracts\VoltTestCase;
use VoltTest\Laravel\VoltTestManager;

class RegistrationTest implements VoltTestCase
{
    public function define(VoltTestManager $manager): void
    {
        $scenario = $manager->scenario('RegistrationTest')
            ->dataSource('registration_users.csv', 'sequential');

        $scenario->step('Home')->get('/')->expectStatus(200);
        $scenario->step('Register')->get('/register')->extractCsrfToken('csrf_token')->expectStatus(200);
        $scenario->step('Submit Registration')
            ->post('/register', [
                '_token' => '${csrf_token}',
                'name' => '${name}',
                'email' => '${email}',
                'password' => '${password}',
                'password_confirmation' => '${password}',
            ])
            ->expectStatus(302);
        $scenario->step('Visit Dashboard')->get('/dashboard')->expectStatus(200);
    }
}



namespace Tests\Performance;

use App\VoltTests\RegistrationTest;
use VoltTest\Laravel\Testing\PerformanceTestCase;

class RegistrationPerformanceTest extends PerformanceTestCase
{
    protected static bool $enableServerManagement = true;

    public function test_registration_flow_performance(): void
    {
        $test = new RegistrationTest();

        $result = $this->runVoltTest($test, [
            'virtual_users' => 50,
            'duration' => '2m',
        ]);

        $this->assertVTSuccessful($result, 95.0);
        $this->assertVTP95ResponseTime($result, 1500);
        $this->assertVTAverageResponseTime($result, 800);
    }
}
bash
php artisan vendor:publish --tag=volttest-config
bash
php artisan volttest:run UserTest
bash
php artisan volttest:run