Jython and Python
Grinder3的腳本引擎是Jython,它是Python在java中的完全實現。Python學習參考script galleryand Richard Perks' tutorial。以及以下網站:
推薦閱讀《Jython Essentials》 ,可免費試讀 introductory chapter 。
爲了符合Grinder框架,腳本必須遵循以下幾個約定。
- 腳本必須定義一個名爲TestRunner的類
當一個worker線程啓動後,會立刻運行測試腳本。腳本必須定義一個名爲TestRunner的類。然後,Grinder引擎爲每個worker線程創建一個TestRunner實例。線程的TestRunner實例可用來存儲該線程特有的信息。
Note
儘管強烈建議定義TestRunner類,但是TestRunner不一定必須是類。參考Hello World with Functions。
- TestRunner實例必須是可調用的
一個Python對象如果定義了__call__方法,則它是可調用的。每個worker線程對測試腳本執行若干次run,依照屬性grinder.runs配置。對每次run,worker線程調用它的TestRunner,因此,__call__方法可看作對一個run的定義。
- 測試腳本可通過grinder對象訪問
Engine創建了一個名爲grinder的對象,用於腳本對其進行import。它同樣可以被腳本調用的任何模塊進行import。這是Grinder.ScriptContext類的一個實例,並提供了對上下文環境(如worker線程ID)和服務的(例如日誌記錄和數據統計)的訪問。
下面是一個符合上述規則的腳本示例。該腳本具備簡單的功能—每次run都記錄Hello World到output日誌中。
from net.grinder.script.Grinder import grinder
# An instance of this class is created for every thread.
class TestRunner:
# This method is called for every run.
def __call__(self):
# Per thread scripting goes here.
grinder.logger.output("Hello World")
如果要對一個網站或者web應用程序創建腳本,可以使用TCPProxy產生一個適用於Grinder的HTTPPlugin測試腳本。
儘管上例的簡單測試腳本可以用於Grinder框架,且可以在多個機器上由多個worker進程執行多次,但是它並不報告任何統計數據。因此,需要創建一些測試。一個Test具有一個唯一的測試號和描述。
下面將一個測試添加到腳本中:
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
# Create a Test with a test number and a description.
test1 = Test(1, "Log method") # test number 和description
class TestRunner:
def __call__(self):
log("Hello World")
上例中創建了一個Test,測試號爲“1”,描述爲“Log method”。注意,這裏對Test類的import方式與Java十分相似。另外,同樣明確地import了 Grinder對象,這樣使得我們的腳本能做爲一個Python模塊被其他腳本調用。
現在,console瞭解了我們的Test,但是我們並沒有使用它記錄任何信息。下面記錄grinder.logger.output花費了多長時間。爲了更好的測量grinder.logger.output方法,使用Test通過協議wrapper對其進行wrap。wrapper對象與grinder.logger.output方法相似,可以通過同樣的方式調用。
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
test1 = Test(1, "Log method")
# Wrap the log() method with our Test and call the result logWrapper.
logWrapper = test1.wrap(grinder.logger.output)
class TestRunner:
def __call__(self):
logWrapper("Hello World")
這是一個功能完整的測試腳本,可以在Grinder框架中執行,且報告測試結果到console。
調用wrap方法的方式不受限制,下面是一個使用Grinder HTTP plug-in的例子。
# A simple example using the HTTP plugin that shows the retrieval of a
# single page via HTTP.
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
from net.grinder.plugin.http import HTTPRequest
test1 = Test(1, "Request resource")
request1 = test1.wrap(HTTPRequest())
class TestRunner:
def __call__(self):
result = request1.GET("http://localhost:7001/")
測試腳本幾乎可以包含任何Java或者Python代碼。
Grinder Script API 可用來訪問Grinder提供的服務。Javadoc包含所有packages,classes和interfaces的所有信息,以及plug-ins添加的一些packages,組成了核心API。參考HTTP plugin documentation。