Python Locust Performance Testing Framework Practice

Source: Internet
Author: User

[This article is from the Sky Cloud-owned blog Park]

Introduction of Locust

Locust is a Python performance testing tool that allows you to load test Web interfaces by writing Python scripts.

Installation of Locust

First you have to install python2.6 or above, and there are pip tools. After that, open the command line and install Locustio and PYZMQ respectively (the command is as follows):

InstallInstall PYZMQ

Then we can write the performance test script.

Locust Script Writing

Next we take two interfaces to do the test, the script is as follows (each step has comments). Let me explain, first of all, we're going to import three classes, the Httplocust (the class used to simulate the outgoing request), the TaskSet (as the name implies, the task set), the task class. Additionally, to facilitate observing the execution results of the interface tests, I introduced a JSON class to parse the return value of the Web interface. I also introduced the Subprocess class to execute the shell command, starting with the Locust. Here are three classes, one is Userbehavior (name casually, but passed the Taskset parameter, indicating that this is a class containing the task set), inside the On_Start function is optional, he will run before all the task functions. The rest of the @task decoration method is the task method, which contains the interface to be requested information, the incoming parameters represent the weight, as shown below two are @task decorated by the method passed into 1 and 2, which means two people per 3 people will have 1 simulated users to execute List_header method , 2 simulated users execute the List_goods method. This parameter can also not be passed in, which means that the simulated user will randomly access all the methods that are @task decorated. I have made a judgment on the return value of each interface, first to convert the returned string into JSON format and get the value of the return field result, and if it is not 100, print the error message with the error method of Locust. The other two classes are the Httplocust class (still the name is random but the incoming parameter must be Httplocust), is used to impersonate the user's class, contains some of the simulation user information, which task_ The value of the set variable is used to specify the requests that are contained in the Taskset class to be completed by the impersonated user, and the min_wait and max_wait (minimum wait time and maximum wait time are used to simulate the interval between each two-step operation of the user. This is the time between the simulated user's two requests per execution). For the Locust class we can specify weights and specify values for the weight variable. As shown below, the weights of the two locust classes are 1 and 3 respectively, which means that two locust classes have a relationship of 1:3 of the number of impersonated users. Finally I added a main function to execute the shell command, the shell command can no longer be executed in this file, if written in a script, directly on the command line to invoke the Python file, if not written in the script (comment out the last two lines), The Locust project needs to be started in the command line terminal.

 fromLocustImportHttplocust,taskset,taskImportsubprocessImportJSON#This is the TaskSet class.classUserbehavior (TaskSet):#Execute before any task.    defOn_Start (self):Pass    #The @task takes an optional weight argument.@task (1)    defList_header (self): R= Self.client.get ("/homepage/list_header.html")        ifJson.loads ((r.content)) ["result"]! = 100: R.failure ("Got Wrong response:"+r.content) @task (2)    deflist_goods (self): R= Self.client.get ("/homepage/list_goods.html")        ifJson.loads ((r.content)) ["result"]! = 100: R.failure ("Got Wrong response:"+r.content)#This is one Httplocust class.classWebuserlocust (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 = 5000max_wait= 15000#This is another Httplocust class.classMobileuserlocust (httplocust): Weight= 3Task_set=Userbehavior min_wait= 3000max_wait= 6000#if __name__ = = ' __main__ ':#subprocess. Popen (' locust-f. \locust_test_1.py--host=http://api.g.caipiao.163.com ', shell=true)
Locust Start-up

For the start of 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 to the Python file to execute, and "--host" specifies the host name of the impersonated user request interface. Executing the command, The Locust project is started. If you encounter the following error, note [Errorno 10048] that line, you can see that port 8089 is occupied causing the Locust project to fail to start, here we need to find the corresponding 8089 port process and kill:

In order to detect the process that occupies the port I wrote a powershell small script:

functionCheckpid ($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"the port you are querying is occupied by the following programs:"-Foregroundcolor Red$target= Tasklist|findstr$tPidWrite-host$target            $sig=$true        }Else{            $sig=$false        }     }Else{        $sig=$false    }    $sig}functionCheckport ($port){    $port=":"+$port    $results= Netstat-ano|findstr$port    if($results. Count-GT0){        if($results. Count-eq1){            $sig= Checkpid$results $port            if($sig -eq $false) {Write-host"the port you are querying is not occupied! "-foregroundcolor Green}}Else{            foreach($result inch $results){                if($result){                   $sig= Checkpid$result $port                   if($sig -eq $true){                        Break                   }                }            }            if($sig -eq $false) {Write-host"the port you are querying is not occupied! "-Foregroundcolor Green}} }Else{Write-host"the port you are querying is not occupied! "-foregroundcolor Green}}$port=$null while($port -ne "exit ()"){    $port= Read-host"Please enter the port number to query"    if($port -eq "exit ()"){         Break} checkport$port}

Run the script, enter the port number 8089 we can see that the Python.exe process occupies the port number:

Then we kill the process in PowerShell, and then start the Locust project, and it succeeds (as follows):

Locust Load Test

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

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

Click "Stop" button to stop the load test, now the status is "STOPPED", click "New Test" can be a new test:

It can be seen that 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, and so on. The upper-right corner shows the request failure rate and the total RPS (requests per second). Corresponding to the failures, Exceptions, and Download data tabs on the right side of statistic, we can view failed requests, caught exceptions, and download test results, respectively. Here do not introduce too much, you can actually use to see. If you want to know more about the Locust performance testing framework, go to the official website to see it.

Python Locust Performance Testing Framework Practice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.