自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Locustfile中的User類和HttpUser類

開發(fā) 開發(fā)工具
locustfile是個普通的Python模塊,如果寫作locustfile.py,那么路徑切換到文件所在目錄,直接執(zhí)行命令就能運行。

[[399412]]

本文轉(zhuǎn)載自微信公眾號「dongfanger」,作者dongfanger。轉(zhuǎn)載本文請聯(lián)系dongfanger公眾號。

locustfile是什么?

locustfile是Locust性能測試工具的用戶腳本,描述了單個用戶的行為。

locustfile是個普通的Python模塊,如果寫作locustfile.py,那么路徑切換到文件所在目錄,直接執(zhí)行命令就能運行:

  1. $ locust 

如果換個名字,那么只能通過-f參數(shù)指定文件名運行:

  1. $ locust -f locust_files/my_locust_file.py 

與一般Python模塊不同的是:locustfile必須至少定義一個類,且繼承自User類。

User類

User類表示性能測試的模擬用戶,Locust會在運行時創(chuàng)建User類的實例。

wait_time屬性

設(shè)置等待時間,默認值不等待,立即執(zhí)行。

Locust支持4種方式設(shè)置wait_time屬性。

為了便于理解實際意義,我把源碼貼在了下面。

  • constant函數(shù),常量,任務(wù)執(zhí)行完畢等待X秒開始下一任務(wù)。
  1. def constant(wait_time): 
  2.     ""
  3.     Returns a function that just returns the number specified by the wait_time argument 
  4.  
  5.     Example:: 
  6.  
  7.         class MyUser(User): 
  8.             wait_time = constant(3) 
  9.     ""
  10.     return lambda instance: wait_time 
  • between函數(shù),區(qū)間隨機值,任務(wù)執(zhí)行完畢等待X-Y秒(中間隨機取值)開始下一任務(wù)。
  1. def between(min_wait, max_wait): 
  2.     ""
  3.     Returns a function that will return a random number between min_wait and max_wait. 
  4.  
  5.     Example:: 
  6.  
  7.         class MyUser(User): 
  8.             # wait between 3.0 and 10.5 seconds after each task 
  9.             wait_time = between(3.0, 10.5) 
  10.     ""
  11.     return lambda instance: min_wait + random.random() * (max_wait - min_wait) 
  • constant_pacing函數(shù),自適應(yīng),若任務(wù)耗時超過該時間,則任務(wù)結(jié)束后立即執(zhí)行下一任務(wù);若任務(wù)耗時不超過該時間,則等待達到該時間后執(zhí)行下一任務(wù)。
  1. def constant_pacing(wait_time): 
  2.     ""
  3.     Returns a function that will track the run time of the tasks, and for each time it's 
  4.     called it will return a wait time that will try to make the total time between task 
  5.     execution equal to the time specified by the wait_time argument. 
  6.  
  7.     In the following example the task will always be executed once every secondno matter 
  8.     the task execution time:: 
  9.  
  10.         class MyUser(User): 
  11.             wait_time = constant_pacing(1) 
  12.             @task 
  13.             def my_task(self): 
  14.                 time.sleep(random.random()) 
  15.  
  16.     If a task execution exceeds the specified wait_time, the wait will be 0 before starting 
  17.     the next task. 
  18.     ""
  19.  
  20.     def wait_time_func(self): 
  21.         if not hasattr(self, "_cp_last_run"): 
  22.             self._cp_last_wait_time = wait_time 
  23.             self._cp_last_run = time() 
  24.             return wait_time 
  25.         else
  26.             run_time = time() - self._cp_last_run - self._cp_last_wait_time 
  27.             self._cp_last_wait_time = max(0, wait_time - run_time) 
  28.             self._cp_last_run = time() 
  29.             return self._cp_last_wait_time 
  30.  
  31.     return wait_time_func 
  • 自定義wait_time方法,比如每次等待時間1秒2秒3秒遞增:
  1. class MyUser(User): 
  2.     last_wait_time = 0 
  3.  
  4.     def wait_time(self): 
  5.         self.last_wait_time += 1 
  6.         return self.last_wait_time 
  7.  
  8.     ... 

weight屬性

設(shè)置創(chuàng)建類實例的權(quán)重,默認每個類創(chuàng)建相同數(shù)量的實例。

locustfile中可以有多個繼承了User類的類。

命令行可以指定運行哪些類:

  1. $ locust -f locust_file.py WebUser MobileUser 

通過weight屬性可以讓類更大概率創(chuàng)建實例,比如:

  1. class WebUser(User): 
  2.     weight = 3 
  3.     ... 
  4.  
  5. class MobileUser(User): 
  6.     weight = 1 
  7.     ... 

WebUser類比MobileUser類多三倍概率創(chuàng)建實例。

host屬性

設(shè)置URL前綴。

一般是在Locust的Web UI或者命令行,通過--host指定URL前綴。如果沒有通過--host指定,并且類中設(shè)置了host屬性,那么類的host屬性才會生效。

environment屬性

對用戶運行環(huán)境的引用。

比如在task方法中通過environment屬性終止運行:

  1. self.environment.runner.quit() 

注意,單機會終止所有運行,分布式只會終止單個worker節(jié)點。

on_start和on_stop方法

測試前初始化和測試后清理。

HttpUser類

開篇文章的示例腳本,沒有繼承User類,而是繼承了它的子類HttpUser:

它比User類更常用,因為它添加了一個client屬性,用來發(fā)送HTTP請求。

client屬性/HttpSession

HttpUser類的client屬性是HttpSession類的一個實例:

HttpSession是requests.Session的子類,requests就是常用來做接口測試的那個requests庫:

HttpSession沒有對requests.Session做什么改動,主要是傳遞請求結(jié)果給Locust,比如success/fail,response time,response length,name。

示例:

  1. response = self.client.post("/login", {"username":"testuser""password":"secret"}) 
  2. print("Response status code:", response.status_code) 
  3. print("Response text:", response.text) 
  4. response = self.client.get("/my-profile"

由于requests.Session會暫存cookie,所以示例中登錄/login請求后可以繼續(xù)請求/my-profile。

斷言響應(yīng)結(jié)果

可以使用with語句和catch_response參數(shù)對響應(yīng)結(jié)果進行斷言:

  1. with self.client.get("/", catch_response=Trueas response: 
  2.     if response.text == "Success"
  3.         response.success() 
  4.     elif response.text != "Success"
  5.         response.failure("Got wrong response"
  6.     elif response.elapsed.total_seconds() > 0.5: 
  7.         response.failure("Request took too long"

或者直接拋出異常:

  1. from locust.exception import RescheduleTask 
  2. ... 
  3. with self.client.get("/does_not_exist/", catch_response=Trueas response: 
  4.     if response.status_code == 404: 
  5.         raise RescheduleTask() 

name參數(shù)

name參數(shù)用于把不同api按同一分組進行統(tǒng)計,比如:

  1. for i in range(10): 
  2.     self.client.get("/blog?id=%i" % i, name="/blog?id=[id]"

會按/blog/?id=[id]統(tǒng)計1條數(shù)據(jù),而不是分成10條數(shù)據(jù)。

HTTP代理

Locust默認設(shè)置了requests.Session的trust_env為False,不查找代理,以提高運行性能。如果需要可以設(shè)置locust_instance.client.trust_env為True。

示例代碼

請求REST API并斷言:

  1. from json import JSONDecodeError 
  2. ... 
  3. with self.client.post("/", json={"foo": 42, "bar": None}, catch_response=Trueas response: 
  4.     try: 
  5.         if response.json()["greeting"] != "hello"
  6.             response.failure("Did not get expected value in greeting"
  7.     except JSONDecodeError: 
  8.         response.failure("Response could not be decoded as JSON"
  9.     except KeyError: 
  10.         response.failure("Response did not contain expected key 'greeting'"

小結(jié)

locustfile是個普通Python模塊,必須繼承User類或其子類HttpUser等。本文對User類和HttpUser類的屬性和方法進行了介紹,使用它們可以編寫性能測試的用戶腳本。locustfile還有另外一個重要組成元素,@task。

 

責(zé)任編輯:武曉燕 來源: dongfanger
相關(guān)推薦

2009-08-06 14:53:41

C# User類

2010-03-15 18:42:52

Java多線程

2016-09-06 19:32:11

PythonWeb

2013-11-11 09:34:51

超6類7類網(wǎng)線

2024-04-02 11:34:09

成員對象封閉類C++

2010-07-20 09:13:55

Perl面向?qū)ο缶幊?/a>

2011-06-02 14:51:07

JAVA修飾符

2011-05-26 08:36:07

JDKJava

2009-06-22 08:39:27

Java常見錯誤Java類

2023-11-03 11:56:34

2024-03-12 07:44:53

JVM雙親委托機制類加載器

2010-07-09 15:29:51

UML類關(guān)系

2011-06-14 16:07:13

Qt QSettings類

2020-10-23 07:43:31

String

2009-05-21 13:25:50

.NETCountDownLa微軟

2015-03-24 15:08:21

mapreducehadoop

2023-10-27 08:25:35

PythonPyQt6

2009-07-22 07:53:00

Scala擴展類

2009-07-08 15:35:18

Case類Scala

2016-08-31 16:07:54

Python實例
點贊
收藏

51CTO技術(shù)棧公眾號