locust參數化(數據庫取值)mysql
基於上一篇參數化的梳理,本篇用另外一種方法從數據庫中取出這100個用戶來登陸web
思路:在 TaskSet 中的 on_start 方法表示執行任務前的操做,能夠將數據庫取數據的這個操做放在裏面執行sql
from locust import task,TaskSet,HttpLocust import pymysql import os class MyTaskSet(TaskSet): def run_sql(self): self.connect = pymysql.connect( host = "192.168.x.xx", database = "xxx", user = "xxx", password = "xx" ) cursor = self.connect.cursor() sql = "SELECT userAccount FROM t_sys_user WHERE userAccount LIKE 'w0%';" # 查詢出用戶名語句 cursor.execute(sql) # 執行查詢語句 res = cursor.fetchall() # 保存查詢結果 self.user_list = [] # 查詢出來的結果爲元組中嵌套長度爲1的元組,不方便取值,這裏用列表保存下來 for i in res: self.user_list.append(i[0]) print(self.user_list) cursor.close() self.connect.commit() self.connect.close() return self.user_list # 返回列表 def on_start(self): self.run_sql() # 執行task前運行一次run_sql函數 def on_stop(self): print("----- Test over -----") @task def login(self,pwd="b123456"): self.headers = { "Origin": "http://192.168.1.9:8080", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36" } path = "/SSOAuth?action=login&code=undefined&gotoURL=http%3A%2F%2F192.168.1.9%3A8080%2Fportal%2Fgeoindex.do" for user_account in self.user_list: da = {"userAccount": user_account, "pwd": pwd} data = { "data": '%s' % da } self.client.post(path, headers=self.headers, data=data, verify=False) class MyLocust(HttpLocust): """w01~w0100爲有效用戶名,密碼爲默認的b123456""" task_set = MyTaskSet # 指向任務集合 host = "http://192.168.1.9:8080" # web項目的話這裏要設置host屬性,不然是報錯的 if __name__ == '__main__': # os模塊執行系統命令,至關於在cmd切換到當前腳本目錄,執行locust -f locust_login.py os.system("locust -f locust_login_db.py")
原文地址https://blog.csdn.net/qq_39620483/article/details/89639653數據庫