The most detailed Python Locust performance testing framework practice on the Internet

LocustIntervention

Locust is a python performance testing tool. You can write python scripts to perform load testing on the web interface.

Locust installation

First, you need to install python2.6 or above and have the pip tool. Then open the command line and install locustio and pyzmq respectively (the commands are as follows):

  1. pip install locustio

  2. pip install pyzmq

After that we can write the performance test script.

PS: If it is python3, you cannot use pip to install it currently. You need to download the locust project package locally on github, and then execute the command to install it in the package path:

python setup.py install

 Locust scripting

Next, we test the two interfaces and write the script as follows (each step is commented). Let me explain, first we need to import three classes, namely HttpLocust (a class used to simulate making requests), TaskSet (as the name suggests, task set), and task (task class). In addition, in order to facilitate the observation of the execution results of the interface test, I introduced the json class to parse the return value of the web interface. I also introduced the subprocess class to execute shell commands and start Locust automatically. There are three classes here, one is UserBehavior (the name can be chosen casually, but the TaskSet parameter is passed in, indicating that this is a class that contains a task set). The on_start function is optional, and it will run before all task functions. The remaining methods decorated by the @task decorator are all task methods, which contain information such as the interface to be requested. The parameters passed in represent the weight. As shown below, the two methods decorated by @task are passed in 1 and 2 respectively. , which means that out of every 3 simulated users, 1 simulated user executes the list_header method, and 2 simulated users execute the list_goods method. You don’t need to pass in this parameter, which means that the simulated user will randomly access all methods decorated with @task. Here I have made a judgment on the return value of each interface. First, convert the returned string into json format and obtain the value of the return field result. If it is not 100, use Locust's own error reporting method to print the error message; another The two classes are the HttpLocust class (the name is still arbitrary but the incoming parameters must be HttpLocust), which are classes used to simulate users and contain some simulated user information. The value of the task_set variable is used to specify the requirements corresponding to the simulated user. The requests included in the completed TaskSet class, min_wait and max_wait (the minimum waiting time and the maximum waiting time are used to simulate the interval between each two steps of the user's operations, here is also the time between each two requests executed by the user) ). For the Locust class, we can specify the weight and the value of the weight variable. As shown below, the weights of the two Locust classes are 1 and 3 respectively, which means that the number of simulated users of the two Locust classes has a 1:3 relationship. Finally, I added a main function to execute the shell command. This shell command can also be executed in this file. If it is written in the script, just call the python file directly in the command line. If it is not written in the script, (Comment out the last two lines), you need to start the Locust project in the command line terminal.

from locust import HttpLocust,TaskSet,task
import subprocess
import json
 
#This is the TaskSet class.
class UserBehavior(TaskSet):
    #Execute before any task.
    def on_start(self):
        pass
 
    #the @task takes an optional weight argument.
    @task(1)
    def list_header(self):
        r = self.client.get("/homepage/list_header.html")
        if json.loads((r.content))["result"] != 100:
            r.failure("Got wrong response:"+r.content)
 
    @task(2)
    def list_goods(self):
        r = self.client.get("/homepage/list_goods.html")
        if json.loads((r.content))["result"] != 100:
            r.failure("Got wrong response:"+r.content)
 
#This is one HttpLocust class.
class WebUserLocust(HttpLocust):
    #Speicify the weight of the locust.
    weight = 1
    #The taskset class name is the value of the task_set.
    task_set = UserBehavior
    #Wait time between the execution of tasks.
    min_wait = 5000
    max_wait = 15000
 
#This is another HttpLocust class.
class MobileUserLocust(HttpLocust):
    weight = 3
    task_set = UserBehavior
    min_wait = 3000
    max_wait = 6000
 
#if __name__ == '__main__':
#    subprocess.Popen('locust -f .\locust_test_1.py --host=http://api.g.caipiao.163.com', shell=True)

 

Launch of Locust

To start the Locust project, we can execute the following command in the command line terminal:

locust -f .\locust_test_1.py --host=http://api.g.caipiao.163.com

The "-f" here specifies the path of the python file to be executed, and "--host" specifies the host name of the simulated user request interface. Execute this command and the Locust project will be started. If you encounter the following error, pay attention to the line [Errorno 10048]. It can be seen that port 8089 is occupied, causing the Locust project to fail to start. Here we need to find the corresponding process occupying port 8089 and kill it:

In order to detect the process occupying the port I wrote a small PowerShell script:

function checkPid($result,$port){
    $port = $port.split(":")[1]
    if(($result.split())[6].split(":")[($result.split())[6].split(":").Count-1] -eq $port){
        $tPid = ($result.split())[($result.split()).count-1]
        if($tPid -ne "0"){
            Write-Host "您查询的端口被以下程序占用:" -ForegroundColor Red
            $target = tasklist|findstr $tPid
            Write-Host $target
            $sig = $true
        }else{
            $sig = $false
        } 
    }else{
        $sig = $false
    }
    $sig
}
function checkPort($port){
    $port = ":" + $port
    $results = netstat -ano|findstr $port
    if($results.count -gt 0){
        if($results.count -eq 1){
            $sig = checkPid $results $port
            if($sig -eq $false){
                Write-Host "您所查询的端口未被占用!" -ForegroundColor Green
            }
        }else{
            foreach($result in $results){
                if($result){
                   $sig = checkPid $result $port
                   if($sig -eq $true){
                       break
                   }
                }
            }
            if($sig -eq $false){
                Write-Host "您所查询的端口未被占用!" -ForegroundColor Green        
            }
        }
    }else{
        Write-Host "您所查询的端口未被占用!" -ForegroundColor Green
    }
}
$port = $null
while($port -ne "exit()"){
    $port = Read-Host "请输入要查询的端口号"
    if($port -eq "exit()"){
        break
    }
    checkPort $port
}

Run the script and enter the port number 8089. We can see that the python.exe process occupies this port number:

                

Then we killed the process in PowerShell and started the Locust project, and it was successful (as follows):

Next, you can access our locust page in the browser to complete the load test. If you do not want to set up and complete the load test through the browser, the pure command line mode is also supported. Enter the following command:

locust -f .\locust_test_1.py --host='http://api.winyyg.com' --no-web -c 1000 -r 10 -n 1000

Next, the load test will be executed automatically. Press "ctrl+c" to end the load test:

Explanation of the parameters in the command line: --no-web is used to select the no-browser mode, -c is followed by the number of simulated users, -r is followed by the number of simulated concurrent users per second, and -n is followed by is the number of simulated requests.

Locust load testing

Enter "http://localhost:8089/" in the browser to access, and you will see the following page:

                   

Here we follow the prompts to enter the total number of users to be simulated and the number of concurrent users per second, and click "Start swarming" to run the load test:

                

 

Click the "STOP" button to stop the load test. Now the STATUS is "STOPPED". Click "New test" to perform a new test:

               

As can be seen from the above figure, some performance-related test results are listed under the Statistics tab, such as the total number of requests, the number of failed requests, the number of requests per second, the minimum\maximum response time, the average response time, etc. The upper right corner shows the request failure rate and total RPS (requests per second). Corresponding to the Failures, Exceptions, and Download Data labels on the right side of Statistics, we can view failed requests, captured exceptions, and download test results respectively. I won’t introduce too much here, but you can take a look at the practical application. If you want to learn more about the Locust performance testing framework, check out the official website.

 Thank you to everyone who reads my article carefully. There is always a courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly:

 

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends, and this warehouse also accompanies Thousands of test engineers have gone through the most difficult journey, and I hope it can help you!Friends in need can click on the small card below to receive it 

 

Guess you like

Origin blog.csdn.net/okcross0/article/details/134880272