wtorek, 25 października 2011

SELECTING RANDOM LABEL from a DROPDOWN

So you’ve just recorded your first test – Selenium’s selecting label from a dropdown. Playback works! But what if you like to test, let say… more randomly?


For instance you’ve got script that opens Ebay, selects label “Books” from a dropdown (dropdown id in this case is “_sacat”); in nearby textbox (its id is “_nkw”) script types “eastwood” and clicks “Search” button:

Now you want to seek for eastwood but randomly choose label instead of choosing always “Books”.

First you need to generate random number using, for example, this javascript string:
javascript{Math.floor(Y*Math.random()+X)}

This string will generate integer in the range from X to (X +Y – 1).

In our case we’ve got 36 labels in a dropdown. Important thing you must know is that they don’t count from 1 to 36 but from 0 to 35. So we would like to generate random number from 0 to 35 (36 possible choices in total).

In Selenium we should use below command:
store || javascript{Math.floor(36*Math.random()+0)} || randomLabel

It stores result of javascript to variable with name of our choice (we would like to be meaningful “randomLabel” but it could be “abc123” as well):


Why we used 0 and 36 in javascript string?

Because, according to definition mentioned above, range of numbers used to generate random one would be from X to (X +Y – 1),
so: from 0 to (0 + 36 – 1) gives us range from 0 to 35 (36 possibilities – including 0 – and our dropdown has 36 labels).

Of course if you know Javascript you can use any other javascript string resulting with random number.


Next step is to replace “label” with “index” so that you can use numbers instead of label names (index=4, index=22 and so on instead of: label=Books, label=Music etc.):
But we won’t use numbers directly – we’ll use our variable.


And this is the last thing to do – replace index value with a variable – in our case it’s “randomLabel”. Remember to use variable in brackets and with dollar symbol at the beginning – ${randomLabel}:

In result script will search for eastwood using random label. If generated number is 24 then selected label will be this one placed on 25th position from the top of the dropdown (in our example it’s “Pet Supplies”). If random number was 0 then selected label would be this on the first position etc.






















open | http://www.ebay.com/
store | javascript{Math.floor(36*Math.random()+0)} | randomLabel
select | id=_sacat | index=${randomLabel}
type | id=_nkw | eastwood
clickAndWait | id=ghSearch