接上文《JMeter與Python的多重交響:從入門到高級應用(上)》
在性能測試領域,Apache JMeter已經成為測試專業人士的首選工具,用于模擬用戶行為、測量響應時間、評估系統性能。但在某些情境下,為了滿足特定需求,我們需要更多的靈活性,比如引入Python來進行特定操作或處理復雜邏輯。
在OS Process Sampler中,可以直接執行系統命令,這也包括執行Python腳本以及其他亂七八糟的腳本或者文件,但是我們這里只介紹關于調用python腳本的知識。
如下:加密文件中的python代碼:
import base64import sysfrom Crypto.Cipher import AESimport binasciidef add_to_16(text): while len(text) % 16 != 0: text += '/0' return textdef encrypt(data, password): if isinstance(password, str): password = password.encode('utf8') bs = AES.block_size pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs) cipher = AES.new(password, AES.MODE_ECB) data = cipher.encrypt(pad(data).encode('utf8')) encrypt_data = binascii.b2a_hex(data) # 輸出hex # encrypt_data = base64.b64encode(data) # 取消注釋,輸出Base64格式 return encrypt_data.decode('utf8')if __name__ == '__main__': data = sys.argv[1] # 待加密數據 # data = '1915' # 待加密數據 password = '5544223414143242332423423423423' # 16,24,32位長的密碼(密鑰) password = add_to_16(password) encrypt_data = encrypt(data, password) # print('加密前數據:{}/n======================='.format(data)) print(f"sign={encrypt_data}") # decrypt_data = decrypt(encrypt_data, password) # print('解密后的數據:{}'.format(decrypt_data))
上述代碼的大概邏輯就是接收傳進來的待加密字符串,然后進行AES加密,最后打印加密后的數據結果。
windows舉例,.bat 文件內容如下:
c:cd C:/Users/chenyongzhi11/Desktop/python ./do_AES.py %1
上面文件內容就是在命令行執行python文件,由于前面的python文件接收參數,我們這里使用 %1 這個占位來接收jmeter傳進去的參數,我們把文件命名為 :execute_python_script.bat
添加一個OS Process Sampler:
我們看下這個界面該如何配置:
這會調用外部Python腳本,并傳入參數input_param。
添加一個正則表達式提取器,編寫正則,看看能不能提取到結果:
最后我們用debug sample檢測最終結果:
這樣整個流程完成了,也就可以很方便的調用外部文件做接口自動化了。
這里再簡單介紹兩種能夠處理python代碼的方案:
使用函數助手[jmeter-functions-execute-python-script-1.0.jar]鏈接:https://pan.baidu.com/s/1JrPW723es9rFbp18mNAvug?pwd=thjp 提取碼:thjp這個就直接放入到:/lib/ext 下面就行,然后重啟jmeter使用如圖:
使用BeanShell Sampler組件這個需要一定的java代碼能力,大伙可以自行看著玩,因煩不建議,前面的os process sample 舒服,也就是說,既然都要寫beanshell了,直接java代碼干就完事了,哈哈!。示例代碼,不保證能用:
import java.io.BufferedReader;import java.io.InputStreamReader;//1. 命令里的路徑改成自己腳本的路徑 String command = "/opt/homebrew/bin/python3 /Users/xxx/Code/python-mysql/gen_id.py";Runtime rt = Runtime.getRuntime();Process pr = rt.exec(command); pr.waitFor(); BufferedReader b = new BufferedReader(new InputStreamReader(pr.getInputStream()));String line = "";StringBuilder response = new StringBuilder();while ((line = b.readLine()) != null) { response.append(line);} String response_data = response.toString(); System.out.println(response_data);log.info(response_data);b.close();// 2. 定義Jmeter中引用的變量名vars.put("xxx",response_data); //把結果賦值給變量 ,方便后面調用
By the way,很多小伙伴反饋說既然用jmeter了,干嘛還往里整python代碼,不是多此一舉嘛?這里勇哥談談自己的幾點愚見:
總之jmeter既然可以這樣玩,那么給到用戶也就多一種使用體驗,多一種解決問題的可能性。
本文鏈接:http://www.tebozhan.com/showinfo-26-11289-0.htmlJMeter與Python的多重交響:從入門到高級應用(下)
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 編程新境界:從入門到精通Python中eval()函數的魔力
下一篇: C++11中auto關鍵字的使用詳解