性能測試-Locust腳本加強篇(關聯、檢查點、集合點)


1、關聯:通常在業務流程中有很多一系列的接口調用,從后面的接口依賴前邊接口的結果數據

from lxml import etree
from locust import TaskSet, task, HttpUser
class UserBehavior(TaskSet):
    @staticmethod
    def get_session(html):
        tree = etree.HTML(html)
        return tree.xpath("//div[@class='btnbox']/input[@name='session']/@value")[0] \
    @task(10)
    def test_login(self):
        html = self.client.get('/login').text
        username = 'user@compay.com'
        password = '123456'
        session = self.get_session(html)
        payload = { 'username': username, 'password': password, 'session': session }
        self.client.post('/login', data=payload)

class WebsiteUser(HttpUser):
    host = 'http://debugtalk.com'
    # task_set = UserBehavior
    tasks = [UserBehavior ]
    min_wait = 1000
    max_wait = 3000

2、檢查點:用來判斷返回值是否符合要求

from lxml import etree
from locust import TaskSet, task, HttpUser
class UserBehavior(TaskSet):
    @staticmethod
    def get_session(html):
        tree = etree.HTML(html)
        return tree.xpath("//div[@class='btnbox']/input[@name='session']/@value")[0] \
    @task(10)
    def test_login(self):
        html = self.client.get('/login').text
        assert "200" in html
        username = 'user@compay.com'
        password = '123456'
        session = self.get_session(html)
        payload = { 'username': username, 'password': password, 'session': session }
        self.client.post('/login', data=payload)

class WebsiteUser(HttpUser):
    host = 'http://debugtalk.com'
    # task_set = UserBehavior
    tasks = [UserBehavior ]
    min_wait = 1000
    max_wait = 3000

3、集合點:提高某個接口的並發度,當所有用戶運行到指定位置后集合等待,同時向下執行

from gevent._semaphore import Semaphore
from locust import TaskSet, events
from lxml import etree

all_locusts_spawned = Semaphore()
all_locusts_spawned.acquire()
def on_hatch_complete(**kwargs):
    all_locusts_spawned.release() # 創建鈎子方法

events.hatch_complete += on_hatch_complete # 掛載到locust鈎子函數(所有的Locust實例產生完成時觸發)

class TestTask(TaskSet):
    def on_start(self):
        """ on_start is called when a Locust start before any task is scheduled """
        all_locusts_spawned.wait() # 限制在所有用戶准備完成前處於等待狀態
        self.login()

    @staticmethod
    def get_session(html):
        tree = etree.HTML(html)
        return tree.xpath("//div[@class='btnbox']/input[@name='session']/@value")[0] \

    def login(self):
        html = self.client.get('/login').text
        username = 'user@compay.com'
        password = '123456'
        session = self.get_session(html)
        payload = {'username': username, 'password': password, 'session': session}
        self.client.post('/login', data=payload)

個人博客 蝸牛


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM