Monday, 12 June 2006

How to write a simple Monkey Tester in AutoIt

AutoIt is a simple windows automation language, and in this short code snippet I will give you the code for a very simple Monkey tester.

I'm tempted to talk a little bit about what AutoIt is, and what it does, but I'll save that for a later post. Right now I just want to dive into the action and show you a simple script that does a little monkey testing.
In this example we are using the built in Calculator for windows and all we are doing is randomly clicking on the application. It seems unlikely that this will expose any errors in Calculator but this code is here to demonstrate the principle and show how simple it all is.
In order to use the code you are going to have to go off to the AutoIt web site and download AutoIt v3 and I also recommend that you download the SciTE AutoIt Editor
  • Install the applications,
  • run SciTE,
  • paste the code below into the editor,
  • press F5 to run the code,
  • watch the monkey tester go to work.
See what you can learn from the code itself and by reading the AutoIt help files. It is extensively commented for such a little application.

; monkey tester

; This monkey tester just randomly
; clicks on the window of the calculator

; the title of the window
$parentWindowName = "Calculator"   
; the name of the application to run

$programRunName = "calc"   

; run the application

; wait until the window is showing, time out in 3 secs

; get the handle of the window
$mainHwnd = WinGetHandle($parentWindowName) 

; monkey around 100 times
for $x=1 to 100

    ; check if the window is still available and if so activate it
    if WinGetHandle($parentWindowName) <> $mainHwnd Then
        ; we lost the app

        MsgBox(1,"App Gone","App is lost")

        winActivate ($mainHwnd)

    ; get the position of the window
    ; - do it each time in the loop
    ; just in case it moved, or changed size
    $pos = WinGetPos($mainHwnd)

    ; choose an x y value in the window
    ;   (it might hit the close button)
    $rndX = random($pos[0],$pos[0]+$pos[2])

    $rndY = random($pos[1],$pos[1]+$pos[3])

    ; move to the position and click it
    mousemove ($rndX,$rndY,0)