### Running a PHP Performance Test Script Source: https://php.volt-test.com/docs/getting-started This command demonstrates how to execute a PHP script that uses the Volt-Test SDK. Ensure you have PHP installed and the script saved as 'example.php' in your current directory. ```bash php example.php ``` -------------------------------- ### GET Request Example Source: https://php.volt-test.com/docs/Steps Example of making a GET request to retrieve a list of users and setting the Accept header. ```APIDOC ## GET /api/users ### Description Retrieves a list of all users. ### Method GET ### Endpoint https://api.example.com/users ### Parameters #### Query Parameters - **Accept** (string) - Optional - Specifies the desired response format, e.g., 'application/json'. ### Request Example ```php $scenario->get('https://api.example.com/users') ->header('Accept', 'application/json'); ``` ### Response #### Success Response (200) - **users** (array) - A list of user objects. #### Response Example ```json { "users": [ { "id": 1, "name": "John Doe" } ] } ``` ``` -------------------------------- ### Complete Scenario Example Source: https://php.volt-test.com/docs/Steps An example demonstrating a multi-step scenario including GET and POST requests, data extraction, status validation, and think time. ```APIDOC ## Complete Example ### Description Demonstrates a complete scenario with two steps: fetching a form and processing a result. ### Method GET, POST ### Endpoint `https://example.com/form` ### Parameters #### Query Parameters None #### Request Body - **name** (string) - Name to be submitted in the form. ### Request Example ```php $scenario->step('Get Form') ->get('https://example.com/form') ->header('Content-Type', 'application/x-www-form-urlencoded') ->extractFromRegex('csrf', 'name="_token" value="(.+?)"') ->validateStatus('success', 200) ->setThinkTime('1s'); $scenario->step('Process Result') ->post('https://example.com/form', 'name=John') ->header('X-CSRF-TOKEN', '${csrf}') ->validateStatus('success', 200); ``` ### Response #### Success Response (200) - **message** (string) - Indicates the success of the operation. ``` -------------------------------- ### Basic PHP Performance Test with Volt-Test Source: https://php.volt-test.com/docs/getting-started This snippet demonstrates how to create a basic performance test using the Volt-Test SDK in PHP. It shows how to instantiate the VoltTest class, define a scenario with a single GET request and a header, run the test, and display the raw output. ```php scenario('Basic Scenario'); // Add a step to the scenario $scenario->step('Register') ->get('https://google.com') ->header('Content-Type', 'text/html'); // Run the test $result = $voltTest->run(true); // Echo the result echo $result->getRawOutput(); ``` -------------------------------- ### Clone PHP SDK Repository and Install Dependencies Source: https://php.volt-test.com/docs/installation Installs the Volt-Test PHP SDK by cloning the repository and manually installing dependencies with Composer. This method is useful if you prefer to manage the SDK as a separate entity or need to contribute to its development. It involves cloning the Git repository, navigating into the directory, and running Composer. ```bash git clone git@github.com:volt-test/php-sdk.git ``` ```bash cd php-sdk ``` ```bash composer install ``` -------------------------------- ### Install PHP and Extensions in WSL Source: https://php.volt-test.com/docs/installation Installs PHP and necessary extensions (CLI, curl, json) within the Windows Subsystem for Linux (WSL). This is part of the recommended setup for running Volt-Test on Windows, enabling a Linux-like environment. ```bash sudo apt update sudo apt install php-cli php-curl php-json ``` -------------------------------- ### Complete API Scenario Example in PHP Source: https://php.volt-test.com/docs/Steps A comprehensive example showing a two-step API test scenario. It includes getting form data, extracting a CSRF token, validating status codes, setting think time, and using the extracted token in a subsequent POST request. ```php $scenario->step('Get Form') ->get('https://example.com/form') ->header('Content-Type', 'application/x-www-form-urlencoded') ->extractFromRegex('csrf', 'name="_token" value="(.+?)"') ->validateStatus('success', 200) ->setThinkTime('1s'); $scenario->step('Process Result') ->post('https://example.com/form', 'name=John') ->header('X-CSRF-TOKEN', '${csrf}') ->validateStatus('success', 200); ``` -------------------------------- ### API Authentication Testing Source: https://php.volt-test.com/docs/Examples/JSON-API-Examples This example demonstrates how to test an API that requires authentication. It includes logging in to obtain an access token and then using that token in subsequent requests. ```APIDOC ## POST /auth/login ### Description Authenticates a user by sending credentials and returns an access token upon successful login. ### Method POST ### Endpoint `https://api.example.com/auth/login` ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "email": "some@mail.com", "password": "secret" } ``` ### Response #### Success Response (200) - **data** (object) - Contains the access token. - **token** (string) - The access token for subsequent authenticated requests. #### Response Example ```json { "data": { "token": "your_access_token_here" } } ``` ## GET /profile ### Description Retrieves the profile information for the authenticated user. ### Method GET ### Endpoint `https://api.example.com/profile` ### Parameters #### Query Parameters - **Authorization** (string) - Required - The access token obtained from the login endpoint, formatted as 'Bearer [token]'. ### Request Example ``` GET /profile HTTP/1.1 Host: api.example.com Authorization: Bearer ${access_token} ``` ### Response #### Success Response (200) - **(Response structure depends on the API, example assumes a basic user profile)** #### Response Example ```json { "id": 123, "name": "John Doe", "email": "some@mail.com" } ``` ``` -------------------------------- ### OPTIONS Request Example Source: https://php.volt-test.com/docs/Steps Example of making an OPTIONS request to determine the communication options for a resource. ```APIDOC ## OPTIONS /api/users ### Description Retrieves the communication options available for the users endpoint. ### Method OPTIONS ### Endpoint https://api.example.com/users ### Response #### Success Response (200) - **Allow** (string) - Comma-separated list of allowed HTTP methods. #### Response Example ```json { "Allow": "GET, POST, PUT, DELETE" } ``` ``` -------------------------------- ### Install PHP SDK using Composer Source: https://php.volt-test.com/docs/installation Installs the Volt-Test PHP SDK within your project using Composer. This is the recommended method for integrating the SDK into your existing Laravel project. Ensure you have Composer installed and are in your project's root directory. ```bash composer require volt-test/php-sdk ``` -------------------------------- ### HEAD Request Example Source: https://php.volt-test.com/docs/Steps Example of making a HEAD request to retrieve only the headers of a resource. ```APIDOC ## HEAD /api/status ### Description Retrieves the headers for the API status endpoint. ### Method HEAD ### Endpoint https://api.example.com/status ### Response #### Success Response (200) - Headers containing status information. #### Response Example (No body is returned for HEAD requests, only headers) ``` HTTP/1.1 200 OK Content-Type: application/json Date: Tue, 15 Nov 1994 08:12:31 GMT ``` ``` -------------------------------- ### Complete Test Configuration Example Source: https://php.volt-test.com/docs/VoltTest%20Configuration Demonstrates a comprehensive configuration for a VoltTest performance test, including virtual users, duration, ramp-up, and HTTP debugging. ```php $test = new VoltTest('Complete Test Configuration', 'Full configuration Example'); ->setVirtualUsers(100) // 100 concurrent users ->setDuration('5m') // Run for 5 minutes ->setRampUp('10s') // Gradually start users over 10 seconds ->setHttpDebug(true); // Enable HTTP debugging ``` -------------------------------- ### Test API Authentication with VoltTest PHP SDK Source: https://php.volt-test.com/docs/Examples/JSON-API-Examples This snippet demonstrates how to test an API that requires authentication. It shows how to perform a login request to obtain an access token and then use that token in subsequent API calls. The example includes setting virtual users, defining a scenario, and validating response statuses. ```php $test = new VoltTest('API Authentication Test'); $test->setVirtualUsers(10); $scenario = $test->scenario('API Authentication'); // Login Request $scenario->step('Login') ->post('https://api.example.com/auth/login', json_encode([ 'email' => 'some@mail.com', 'password' => 'secret' ])) ->header('Content-Type', 'application/json') ->validateStatus('login_success', 200) ->extractFromJson('access_token', 'data.token'); // Use Token in Subsequent Requests $scenario->step('Get Profile') ->get('https://api.example.com/profile') ->header('Authorization', 'Bearer ${access_token}') ->validateStatus('profile_success', 200); // Run the test and get the result $result = $test->run(); echo $result->getRawOutput(); ``` -------------------------------- ### Test Registration Form with CSRF Token Extraction (PHP) Source: https://php.volt-test.com/docs/Examples/html-form-examples This example shows how to test a registration form. It involves loading the registration page, extracting a CSRF token, and then submitting the registration form with user details and the token. The test validates the page load and registration success status. ```PHP $test = new VoltTest('Registration Form'); $test->setVirtualUsers(100); $test->setDuration('5s'); $scenario = $test->scenario('Registration Form'); // Load registration page $scenario->step('Load Register Page') ->get('https://example.com/register') ->extractFromHtml('csrf_token', 'input[name="_token"]', 'value') ->validateStatus('page_load', 200); // Submit registration with form data $scenario->step('Submit Registration') ->post('https://example.com/register', '_token=${csrf_token}&name=${name}&email=${email}&password=${password}&password_confirmation=${password}') ->header('Content-Type', 'application/x-www-form-urlencoded') ->validateStatus('registration_success', 302); // Run the test and get the result $result = $test->run(); ``` -------------------------------- ### Complete Example of Displaying Test Results in PHP Source: https://php.volt-test.com/docs/Result Provides a comprehensive example of how to run a test and then format and print all the available performance metrics using printf statements. This demonstrates a practical application of the TestResult class methods. ```php $result = $test->run(); printf("Test Summary:\n"); printf("Duration: %s\n", $result->getDuration()); printf("Total Requests: %d\n", $result->getTotalRequests()); printf("Success Rate: %.2f%%\n", $result->getSuccessRate()); printf("Requests/sec: %.2f\n", $result->getRequestsPerSecond()); printf("Success Requests: %d\n", $result->getSuccessRequests()); printf("Failed Requests: %d\n", $result->getFailedRequests()); printf("\nResponse Times:\n"); printf("Min: %s\n", $result->getMinResponseTime()); printf("Max: %s\n", $result->getMaxResponseTime()); printf("Avg: %s\n", $result->getAvgResponseTime()); printf("Median: %s\n", $result->getMedianResponseTime()); printf("P95: %s\n", $result->getP95ResponseTime()); printf("P99: %s\n", $result->getP99ResponseTime()); ``` -------------------------------- ### CRUD Operations API Testing Source: https://php.volt-test.com/docs/Examples/JSON-API-Examples This example demonstrates how to test a JSON API that supports CRUD (Create, Read, Update, Delete) operations for managing users. ```APIDOC ## POST /users ### Description Creates a new user in the system. ### Method POST ### Endpoint `https://api.example.com/users` ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. - **role** (string) - Required - The role of the user (e.g., 'user'). ### Request Example ```json { "name": "John Doe", "email": "some@mail.com", "role": "user" } ``` ### Response #### Success Response (201) - **data** (object) - Contains information about the created user. - **id** (integer) - The unique identifier of the newly created user. #### Response Example ```json { "data": { "id": 12345 } } ``` ## GET /users/{user_id} ### Description Retrieves the details of a specific user by their ID. ### Method GET ### Endpoint `https://api.example.com/users/{user_id}` ### Parameters #### Path Parameters - **user_id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **(Response structure depends on the API, example assumes user details)** #### Response Example ```json { "id": 12345, "name": "John Doe", "email": "some@mail.com", "role": "user" } ``` ## PUT /users/{user_id} ### Description Updates the details of an existing user. ### Method PUT ### Endpoint `https://api.example.com/users/{user_id}` ### Parameters #### Path Parameters - **user_id** (integer) - Required - The unique identifier of the user to update. #### Request Body - **name** (string) - Optional - The updated name of the user. - **email** (string) - Optional - The updated email address of the user. ### Request Example ```json { "name": "Jane Doe", "email": "update@mail.com" } ``` ### Response #### Success Response (200) - **(Response structure depends on the API, typically indicates success or returns updated user data)** #### Response Example ```json { "message": "User updated successfully." } ``` ## DELETE /users/{user_id} ### Description Deletes a specific user by their ID. ### Method DELETE ### Endpoint `https://api.example.com/users/{user_id}` ### Parameters #### Path Parameters - **user_id** (integer) - Required - The unique identifier of the user to delete. ### Response #### Success Response (204) - **(No content is typically returned for a successful deletion)** #### Response Example ``` (No content) ``` ``` -------------------------------- ### Run Volt-Test Script in WSL Source: https://php.volt-test.com/docs/installation Executes a Volt-Test script using the PHP CLI within a WSL environment. This command assumes you have already installed PHP and the necessary extensions in WSL and are in the directory containing your script. ```bash php your-script.php ``` -------------------------------- ### PUT Request Example Source: https://php.volt-test.com/docs/Steps Example of updating an existing user's information using a PUT request. ```APIDOC ## PUT /api/users/{id} ### Description Updates the information for a specific user identified by their ID. ### Method PUT ### Endpoint https://api.example.com/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the user to update. #### Request Body - **name** (string) - Required - The updated name of the user. ### Request Example ```php $scenario->put('https://api.example.com/users/1', '{"name": "Updated Name"}'); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "User updated successfully" } ``` ``` -------------------------------- ### DELETE Request Example Source: https://php.volt-test.com/docs/Steps Example of deleting a user by their ID using a DELETE request. ```APIDOC ## DELETE /api/users/{id} ### Description Deletes a specific user identified by their ID. ### Method DELETE ### Endpoint https://api.example.com/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the user to delete. ### Request Example ```php $scenario->delete('https://api.example.com/users/1'); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "User deleted successfully" } ``` ``` -------------------------------- ### Initialize VoltTest Instance Source: https://php.volt-test.com/docs/VoltTest%20Configuration Starts a new performance test by creating an instance of the VoltTest class. Requires a test name and optionally accepts a description. ```php patch('https://api.example.com/users/1', '{"status": "active"}'); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "User status updated successfully" } ``` ``` -------------------------------- ### Perform HTTP GET Request in PHP Source: https://php.volt-test.com/docs/Steps Shows how to execute an HTTP GET request within a test scenario and set custom headers. Useful for retrieving data from an API endpoint. ```php $scenario->get('https://api.example.com/users') ->header('Accept', 'application/json'); ``` -------------------------------- ### Run Volt-Test with Docker (Standard PHP) Source: https://php.volt-test.com/docs/installation Executes a Volt-Test script inside a Docker container using a standard PHP 8 CLI image. This command mounts the current directory into the container, sets the working directory, and runs the script. It's a portable way to run Volt-Test without local PHP installations. ```bash docker run --rm -v $(pwd):/app -w /app php:8-cli php your-script.php ``` -------------------------------- ### Run Volt-Test with Docker (Alpine PHP) Source: https://php.volt-test.com/docs/installation Executes a Volt-Test script inside a Docker container using an Alpine-based PHP 8 CLI image. This command installs necessary PHP extensions within the container before running the script, offering a smaller image footprint. It mounts the current directory and sets the working directory. ```bash docker run --rm -v $(pwd):/app -w /app php:8-alpine sh -c "apk add php-cli php-curl php-json && php your-script.php" ``` -------------------------------- ### PHP Data-Driven API Registration Test with VoltTest Source: https://php.volt-test.com/docs/Examples/JSON-API-Examples This PHP code snippet demonstrates how to set up and run a data-driven API test using VoltTest. It configures a test scenario to submit user registration data fetched from a CSV file, specifying the data source, selection method, and header presence. The test then sends POST requests to a registration API endpoint and validates the response status. ```php $test = new VoltTest('Data-Driven API Test'); $test->setVirtualUsers(50); // Configure data source $dataConfig = new DataSourceConfiguration( __DIR__ . '/test_users.csv', // CSV with test data 'random', // Random selection true // Has header row ); $scenario = $test->scenario('Registration Test') ->setDataSourceConfiguration($dataConfig); // Registration process using data from CSV $scenario->step('Submit Registration') ->post('https://api.example.com/register', json_encode([ 'name' => '${name}', 'email' => '${email}', 'phone' => '${phone}', ])) ->header('Content-Type', 'application/json') ->validateStatus('registration_success', 200); // Run the test and get the result $result = $test->run(); echo $result->getRawOutput(); ``` -------------------------------- ### Configure Ramp-Up Delay Source: https://php.volt-test.com/docs/VoltTest%20Configuration Defines the time over which new virtual users are introduced. This simulates real-world traffic patterns and prevents sudden load spikes. If not set, all users start simultaneously. ```php $test->setRampUp('10s'); // 10 seconds ``` -------------------------------- ### Data-Driven Form Testing with PHP Volt Source: https://php.volt-test.com/docs/Examples/html-form-examples This snippet demonstrates how to set up and run a data-driven form test using PHP Volt. It configures a test with virtual users, sets up a data source from a CSV file for sequential data retrieval, and defines a registration scenario that uses this data to submit form fields. The response status is validated to ensure successful registration. ```php $test = new VoltTest('Data-Driven Form Test'); $test->setVirtualUsers(10); // Configure data source $dataConfig = new DataSourceConfiguration( __DIR__ .'/test_users.csv', // CSV with test data actual file path 'sequential', // Sequential selection true // Has header row ); $scenario = $test->scenario('Registration Test') ->setDataSourceConfiguration($dataConfig); // Registration process using data from CSV $scenario->step('Submit Registration') ->post('https://example.com/register','name=${name}&email=${email}&phone=${phone}') ->header('Content-Type', 'application/x-www-form-urlencoded') ->validateStatus('registration_success', 200); // Run the test and get the result $result = $test->run(); ``` -------------------------------- ### Test Multi-Step Form with Session Management (PHP) Source: https://php.volt-test.com/docs/Examples/html-form-examples This snippet demonstrates testing a multi-step form. It shows how to manage session data across different steps by extracting a session ID from a cookie after the first step and using it in subsequent requests. The test validates the status of each step. ```PHP $test = new VoltTest('Multi-Step Form'); $test->setVirtualUsers(50); $scenario = $test->scenario('Multi-Step Form'); // Step 1: Personal Info $scenario->step('Personal Info') ->get('https://example.com/form/step1') ->extractFromHtml('form_token', 'input[name="_token"]', 'value') ->validateStatus('step1_load', 200); $scenario->step('Submit Step 1') ->post('https://example.com/form/step1',''form_token=${form_token}&name=${name}&email=${email}'') ->header('Content-Type', 'application/x-www-form-urlencoded') ->validateStatus('step1_success', 302) ->extractFromCookie('session_id', 'session_id'); // Step 2: Address Info $scenario->step('Address Info') ->get('https://example.com/form/step2') ->header('Cookie', 'session_id=${session_id}') ->validateStatus('step2_load', 200); $scenario->step('Submit Step 2') ->post('https://example.com/form/step2', 'address=${address}&city=${city}&country=${country}') ->header('Cookie', 'session_id=${session_id}') ->validateStatus('step2_success', 302); // Run the test and get the result $result = $test->run(); ``` -------------------------------- ### Test Login Form with CSRF Token Extraction (PHP) Source: https://php.volt-test.com/docs/Examples/html-form-examples This snippet demonstrates testing a login form. It includes extracting a CSRF token from the HTML response and then submitting the login form with the extracted token and user credentials. The test validates the page load and login success status. ```PHP $test = new VoltTest('Login Form Test'); $test->setVirtualUsers(10); $scenario = $test->scenario('Login Form Test'); // Get login page and extract CSRF token $scenario->step('Get Login Page') ->get('https://example.com/login') ->extractFromHtml('csrf_token', 'input[name="_token"]', 'value') ->validateStatus('page_load', 200); // Submit login form $scenario->step('Submit Login') ->post('https://example.com/login', '_token=${csrf_token}&email=user@example.com&password=secret') ->header('Content-Type', 'application/x-www-form-urlencoded') ->validateStatus('login_success', 302); // Run the test and get the result $result = $test->run(); ``` -------------------------------- ### POST Request with Form Data Source: https://php.volt-test.com/docs/Steps Example of making a POST request with URL-encoded form data. ```APIDOC ## POST /api/users (Form Data) ### Description Creates a new user using URL-encoded form data. ### Method POST ### Endpoint https://api.example.com/users ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```php $scenario->post('https://api.example.com/users', 'email=${email}&password=${password}') ->header('Content-Type', 'application/x-www-form-urlencoded'); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "User created successfully" } ``` ``` -------------------------------- ### Test CRUD Operations for a JSON API with VoltTest PHP SDK Source: https://php.volt-test.com/docs/Examples/JSON-API-Examples This snippet illustrates how to test a JSON API that supports CRUD (Create, Read, Update, Delete) operations for managing users. It covers setting virtual users and test duration, defining a scenario, and executing each CRUD operation with status validation and data extraction. ```php $test = new VoltTest('CRUD Operations Test'); $test->setVirtualUsers(100); $test->setDuration('1m'); $scenario = $test->scenario('CRUD Operations'); // Create $scenario->step('Create User') ->post('https://api.example.com/users', json_encode([ 'name' => 'John Doe', 'email' => 'some@mail.com', 'role' => 'user', ])) ->header('Content-Type', 'application/json') ->validateStatus('creation_success', 201) ->extractFromJson('user_id', 'data.id'); // Read $scenario->step('Get User') ->get('https://api.example.com/users/${user_id}') ->validateStatus('read_success', 200); // Update $scenario->step('Update User') ->put('https://api.example.com/users/${user_id}', json_encode([ 'name' => 'Jane Doe', 'email' => 'update@mail.com', ])) ->header('Content-Type', 'application/json') ->validateStatus('update_success', 200); // Delete $scenario->step('Delete User') ->delete('https://api.example.com/users/${user_id}') ->validateStatus('delete_success', 204); // Run the test and get the result $result = $test->run(); echo $result->getRawOutput(); ``` -------------------------------- ### POST Request with JSON Body Source: https://php.volt-test.com/docs/Steps Example of making a POST request with a JSON payload and setting the Content-Type header. ```APIDOC ## POST /api/users ### Description Creates a new user with the provided JSON data. ### Method POST ### Endpoint https://api.example.com/users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. ### Request Example ```php $scenario->post('https://api.example.com/users', '{"name": "John"}') ->header('Content-Type', 'application/json'); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "User created successfully" } ``` ``` -------------------------------- ### Accessing Raw Metrics and Output with TestResult in PHP Source: https://php.volt-test.com/docs/Result Explains how to get all collected metrics as an array or access the raw output string from the TestResult object. This is useful for custom processing or logging of test results. ```php // Get all metrics as array $metrics = $result->getAllMetrics(); // Access raw output $rawOutput = $result->getRawOutput(); ``` -------------------------------- ### Form Validation Testing with PHP Volt Source: https://php.volt-test.com/docs/Examples/html-form-examples This snippet illustrates how to perform form validation testing using PHP Volt. It sets up a scenario to test various validation scenarios, including submitting an empty form, submitting a form with an invalid email format, and submitting a form with mismatched passwords. Each step validates the HTTP status code to ensure that the server correctly returns a validation error (422). ```php $scenario = $test->scenario('Form Validation'); // Test required fields $scenario->step('Submit Empty Form') ->post('https://example.com/submit','') ->header('Content-Type', 'application/x-www-form-urlencoded') ->validateStatus('validation_error', 422); // Test invalid email $scenario->step('Submit Invalid Email') ->post('https://example.com/submit','email=invalid-email') ->header('Content-Type', 'application/x-www-form-urlencoded') ->validateStatus('validation_error', 422); // Test password mismatch $scenario->step('Password Mismatch') ->post('https://example.com/submit','password=test123&password_confirmation=test456') ->header('Content-Type', 'application/x-www-form-urlencoded') ->validateStatus('validation_error', 422); ``` -------------------------------- ### Create a Test Scenario and Step in PHP Source: https://php.volt-test.com/docs/Steps Demonstrates how to initialize a new test, create a scenario, and define a POST step with a URL. This is the foundational step for building API tests. ```php use VoltTest\VoltTest; $test = new VoltTest('API Test'); $scenario = $test->scenario('Login Flow'); $scenario->step('Login') ->post('https://api.example.com/login'); ``` -------------------------------- ### Configure Data Source for Scenario in VoltTest (PHP) Source: https://php.volt-test.com/docs/Scenarios Illustrates setting up data-driven testing for a scenario using a CSV file. This involves specifying the file path, iteration mode (sequential, random, unique), and whether the file includes a header row. Each virtual user can then consume data from this source. ```php use VoltTest\DataSourceConfiguration; $dataConfig = new DataSourceConfiguration( __DIR__ . '/test-data.csv', // Full file path 'random', // Mode: sequential/random/unique true // Has header row ); $scenario->setDataSourceConfiguration($dataConfig); ``` -------------------------------- ### Create a Scenario in VoltTest (PHP) Source: https://php.volt-test.com/docs/Scenarios Demonstrates how to instantiate VoltTest and create a new scenario with a name and an optional description. This is the foundational step for defining user flows in performance tests. ```php use VoltTest\VoltTest; $test = new VoltTest('API Test'); $scenario = $test->scenario( 'Login Flow', // Scenario name 'User authentication' // Optional description ); ``` -------------------------------- ### Creating a Step Source: https://php.volt-test.com/docs/Steps Demonstrates how to create a new step within a scenario for an API test. ```APIDOC ## POST /api/users ### Description Creates a new user via a POST request. ### Method POST ### Endpoint https://api.example.com/users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. ### Request Example ```php $scenario->step('Create User') ->post('https://api.example.com/users', '{"name": "John"}') ->header('Content-Type', 'application/json'); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "User created successfully" } ``` ``` -------------------------------- ### Perform HTTP OPTIONS Request in PHP Source: https://php.volt-test.com/docs/Steps Illustrates sending an HTTP OPTIONS request to determine the communication options for a target resource. Useful for understanding API capabilities. ```php $scenario->options('https://api.example.com/users'); ``` -------------------------------- ### Using Variables Source: https://php.volt-test.com/docs/Steps Demonstrates how to extract variables from one request and use them in subsequent requests. ```APIDOC ## Using Variables ### Description Extracts variables from responses and references them in subsequent requests. ### Method POST, GET ### Endpoint `/login`, `/profile` ### Parameters #### Query Parameters None #### Request Body - **username** (string) - Username for login. - **password** (string) - Password for login. ### Request Example ```php // Extract token from login response $scenario->post('/login', '{"username": "user", "password": "pass"}') ->extractFromJson('token', 'data.token'); // Use token in next request $scenario->get('/profile') ->header('Authorization', 'Bearer ${token}'); ``` ### Response #### Success Response (200) - **token** (string) - The extracted authentication token. ``` -------------------------------- ### Set Think Time for Scenario Steps in VoltTest (PHP) Source: https://php.volt-test.com/docs/Scenarios Shows how to configure a delay (think time) between steps within a scenario. This simulates realistic user pauses. Think time can be specified in seconds or minutes and can be overridden at the step level. ```php $scenario->setThinkTime('2s'); // 2-second delay $scenario->setThinkTime('1m'); // 1-minute delay ``` -------------------------------- ### Accessing Response Time Statistics with TestResult in PHP Source: https://php.volt-test.com/docs/Result Illustrates how to retrieve detailed response time statistics from the TestResult object, including minimum, maximum, average, median, P95, and P99 response times. These metrics are crucial for understanding latency and user experience. ```php // Time measurements $result->getMinResponseTime(); // Returns: "7.388011ms" $result->getMaxResponseTime(); // Returns: "18.179649581s" $result->getAvgResponseTime(); // Returns: "3.848391356s" $result->getMedianResponseTime(); // Returns: "8.997304894s" $result->getP95ResponseTime(); // Returns: "16.74641748s" $result->getP99ResponseTime(); // Returns: "17.552319263s" ``` -------------------------------- ### Adding Custom Headers Source: https://php.volt-test.com/docs/Steps Demonstrates how to add multiple custom headers to an API request. ```APIDOC ## POST /api/users (Custom Headers) ### Description Creates a new user with custom authorization and content type headers. ### Method POST ### Endpoint https://api.example.com/users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. #### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Accept** (string) - Optional - Specifies the desired response format. - **X-Custom-Header** (string) - Optional - A custom header for specific needs. ### Request Example ```php $scenario->post('https://api.example.com/users', '{"name": "John"}') ->header('Authorization', 'Bearer token') ->header('Accept', 'application/json') ->header('X-Custom-Header', 'value'); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "User created successfully" } ``` ``` -------------------------------- ### Run VoltTest Performance Test Source: https://php.volt-test.com/docs/VoltTest%20Configuration Executes the configured performance test. The `run()` method can optionally accept `true` to enable real-time progress tracking and HTTP debugging. ```php // Run without progress tracking $result = $test->run(); // Run with real-time progress or http debugging $result = $test->run(true); ``` -------------------------------- ### Perform HTTP HEAD Request in PHP Source: https://php.volt-test.com/docs/Steps Shows how to send an HTTP HEAD request, which retrieves only the headers of a response, not the body. Useful for checking resource existence or metadata. ```php $scenario->head('https://api.example.com/status'); ``` -------------------------------- ### Enable Automatic Cookie Handling in VoltTest (PHP) Source: https://php.volt-test.com/docs/Scenarios Demonstrates how to enable VoltTest's automatic cookie management for a scenario. When enabled, VoltTest will automatically handle cookies, which is essential for maintaining user sessions across requests. ```php $scenario->autoHandleCookies(); ``` -------------------------------- ### Perform HTTP PUT Request in PHP Source: https://php.volt-test.com/docs/Steps Shows how to execute an HTTP PUT request to update a resource at a specific URL with a given payload. Used for full resource replacement. ```php $scenario->put('https://api.example.com/users/1', '{"name": "Updated"}'); ``` -------------------------------- ### Configure Scenario Weight in VoltTest (PHP) Source: https://php.volt-test.com/docs/Scenarios Explains how to set the execution probability (weight) for a scenario relative to others. Higher weights mean a scenario is executed more frequently by virtual users. This is useful for prioritizing certain user flows. ```php $scenario->setWeight(75); // 75% weight ``` ```php $regitrationScenario = $test->scenario( 'Registration Flow' ); $browseCategoryScenario = $test->scenario( 'Browse Category Flow' ); $browseCategoryScenario->setWeight(70); // 70% weight $regitrationScenario->setWeight(30); // 30% weight ``` -------------------------------- ### Basic Usage of TestResult Class in PHP Source: https://php.volt-test.com/docs/Result Demonstrates the basic usage of the TestResult class to run a test and retrieve key performance metrics like success rate and total requests. This is the entry point for accessing test results. ```php $result = $test->run(); // Get key metrics echo "Success Rate: " . $result->getSuccessRate() . "%\n"; echo "Total Requests: " . $result->getTotalRequests() . "\n"; ``` -------------------------------- ### Retrieving Basic Performance Metrics with TestResult in PHP Source: https://php.volt-test.com/docs/Result Shows how to access fundamental performance metrics from the TestResult object, including test duration, total requests, successful requests, failed requests, success rate, and requests per second. These metrics provide a high-level overview of test performance. ```php // Test duration $result->getDuration(); // Returns: "24.000873057s" // Request counts $result->getTotalRequests(); // Returns: 5000 $result->getSuccessRequests(); // Returns: 4148 $result->getFailedRequests(); // Returns: 852 // Performance metrics $result->getSuccessRate(); // Returns: 82.96 $result->getRequestsPerSecond(); // Returns: 208.33 ``` -------------------------------- ### Configure Virtual Users Source: https://php.volt-test.com/docs/VoltTest%20Configuration Sets the number of concurrent virtual users to simulate during the performance test. The default is 1 virtual user. ```php $test->setVirtualUsers(10); // By default, 1 virtual user is used ``` -------------------------------- ### Add Multiple Custom Headers to a Request in PHP Source: https://php.volt-test.com/docs/Steps Demonstrates chaining multiple `header()` calls to add various custom headers to an HTTP request. This allows for comprehensive request configuration. ```php $scenario->post('https://api.example.com/users', '{"name": "John"}') ->header('Authorization', 'Bearer token') ->header('Accept', 'application/json') ->header('X-Custom-Header', 'value'); ``` -------------------------------- ### Perform HTTP POST Request with JSON Body in PHP Source: https://php.volt-test.com/docs/Steps Illustrates how to send a POST request with a JSON payload and set the appropriate Content-Type header. Essential for creating or updating resources via an API. ```php $scenario->post('https://api.example.com/users', '{"name": "John"}') ->header('Content-Type', 'application/json'); ``` -------------------------------- ### Set Think Time Source: https://php.volt-test.com/docs/Steps Configures a delay between scenario steps. ```APIDOC ## Set Think Time ### Description Sets a delay (think time) between steps in a scenario. ### Method N/A (Configuration) ### Endpoint N/A ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```php $scenario->setThinkTime('2s'); // 2-second delay $scenario->setThinkTime('1m'); // 1-minute delay ``` ### Response N/A ``` -------------------------------- ### Extracting Data from Cookies Source: https://php.volt-test.com/docs/Steps Demonstrates how to extract cookie values from a response. ```APIDOC ## POST /login (Extract Cookies) ### Description Submits login credentials and extracts session and CSRF tokens from cookies. ### Method POST ### Endpoint https://example.com/login ### Parameters #### Request Body - **_token** (string) - Required - CSRF token for the form. - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. #### Headers - **Content-Type** (string) - Required - Specifies the request body format. ### Request Example ```php $loginScenario->step('submit_login') ->post( 'https://example.com/login', '_token=${csrf_token}&email=tes11t1v@mai1l.com&password=12345678' ) ->extractFromCookie('session', 'laravel_session') ->extractFromCookie('XSRF-TOKEN', 'XSRF-TOKEN') ->header('Content-Type', 'application/x-www-form-urlencoded'); ``` ### Response #### Success Response (200) - Typically a redirect or a success page. #### Response Example (No specific body, but cookies are set) ``` Set-Cookie: laravel_session=your_session_id; ... Set-Cookie: XSRF-TOKEN=your_xsrf_token; ... ``` ### Extracted Data - **session**: 'your_session_id' - **XSRF-TOKEN**: 'your_xsrf_token' ``` -------------------------------- ### Enable HTTP Debugging Source: https://php.volt-test.com/docs/VoltTest%20Configuration Enables or disables HTTP debugging for the test. When enabled, request and response headers are visible, which is useful for troubleshooting. ```php $test->setHttpDebug(true); // By default, false ``` -------------------------------- ### Perform HTTP DELETE Request in PHP Source: https://php.volt-test.com/docs/Steps Demonstrates how to send an HTTP DELETE request to remove a resource at a specified URL. Used for resource deletion. ```php $scenario->delete('https://api.example.com/users/1'); ``` -------------------------------- ### Extracting Data from HTML Form Action Source: https://php.volt-test.com/docs/Steps Demonstrates extracting data from an HTML response by targeting a specific form action. ```APIDOC ## GET /login (Extract HTML by Form Action) ### Description Retrieves a login page and extracts CSRF token from a specific form based on its action URL. ### Method GET ### Endpoint https://example.com/login ### Parameters #### Query Parameters - **selector** (string) - Required - CSS selector for the element within the specified form. - **attribute** (string) - Optional - The attribute name to extract (defaults to 'value'). - **formAction** (string) - Required - The action URL of the form to target. ### Request Example ```php $scenario->get('https://example.com/login') ->extractFromHtml('csrf', 'form[action="http://localhost/login"] input[name="_token"]', 'value'); ``` ### Response #### Success Response (200) - HTML content of the login page. #### Response Example (HTML content) ```html
``` ### Extracted Data - **csrf**: 'another_csrf_value' ``` -------------------------------- ### Extracting Data from HTML by Class Source: https://php.volt-test.com/docs/Steps Shows how to extract data from an HTML response by targeting elements within a specific class. ```APIDOC ## GET /login (Extract HTML by Class) ### Description Retrieves a login page and extracts CSRF token from an input field within an element having a specific class. ### Method GET ### Endpoint https://example.com/login ### Parameters #### Query Parameters - **selector** (string) - Required - CSS selector for the element within the specified class. - **attribute** (string) - Optional - The attribute name to extract (defaults to 'value'). ### Request Example ```php $scenario->get('https://example.com/login') ->extractFromHtml('csrf', '.login-form input[name='_csrf']', 'value'); ``` ### Response #### Success Response (200) - HTML content of the login page. #### Response Example (HTML content) ```html