48

Is it possible to create Selenium tests using the Firefox plugin that use randomly generated values to help do regression tests?

The full story: I would like to help my clients do acceptance testing by providing them with a suite of tests that use some smarts to create random (or at least pseudo-random) values for the database. One of the issues with my Selenium IDE tests at the moment is that they have predefined values - which makes some types of testing problematic.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Toby Hede
  • 36,755
  • 28
  • 133
  • 162

12 Answers12

48

First off, the Selenium IDE is rather limited, you should consider switching to Selenium RC, which can be driven by Java or Perl or Ruby or some other languages.

Using just Selenium IDE, you can embed JavaScript expressions to derive command parameters. You should be able to type a random number into a text field, for example:

type fieldName javascript{Math.floor(Math.random()*11)}

Update: You can define helper functions in a file called "user-extensions.js". See the Selenium Reference.

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • I use RC for my own testing, but in this case I would like to give my client some assisted tests they can run through in their browser (without having to have a copy of the dev environment). – Toby Hede Oct 02 '08 at 13:05
  • Just thinking ... do you know if Selenium can call Javascript functions embedded in the page? I could build some functions to generate some values. – Toby Hede Oct 02 '08 at 13:07
  • 1
    I had to make sure to use the javascript as my value as a separate command. I found out that I could not mix literal text with the javascript in the same command. Hence, mine looked like this: _ _ type fieldName Auto-generated user typeKeys fieldName javascript{Math.floor(Math.random()*11)} – Jared Jan 11 '10 at 21:59
  • I tried putting this right into the "Value" textbox in Selenium IDE. However it just put exactly that into the textbox and not the random value. – aron Apr 11 '11 at 18:26
  • Aron, I found using storeEval was helpful for this - see http://stackoverflow.com/questions/2105001/selenium-how-to-use-stored-value-in-a-javascript-comparison – somewhatoff Feb 16 '12 at 14:28
  • Didn't work for me. I had to use the javascript{code_goes_here} format that another answer uses. – Aaron Kreider Aug 23 '12 at 23:36
  • Now sould use command script, because: Warning parameter preprocessing using javascript{} tag is deprecated, please use execute script – Paulo Tiago Mariano Jul 13 '18 at 11:37
31

(Based on Thilo answer) You can mix literals and random numbers like this:

javascript{"joe+" + Math.floor(Math.random()*11111) + "@gmail.com";}

Gmail makes possible that automatically everything that use aliases, for example, joe+testing@gmail.com will go to your address joe@gmail.com

Multiplying *11111 to give you more random values than 1 to 9 (in Thilo example)

corbacho
  • 8,762
  • 1
  • 26
  • 23
  • 1
    +1 for showing the simplest way. (This can be directly used in HTML Selenium test cases etc. as argument to `type` command) – Jonik Mar 28 '12 at 14:07
  • I found that it only works when you have the javascript{code_goes_here} format that this answer uses. – Aaron Kreider Aug 23 '12 at 23:36
22

You can add user exentions.js to get the random values .

Copy the below code and save it as .js extension (randomgenerator.js) and add it to the Selenium core extensions (SeleniumIDE-->Options--->general tab)

Selenium.prototype.doRandomString = function( options, varName ) {

    var length = 8;
    var type   = 'alphanumeric';
    var o = options.split( '|' );
    for ( var i = 0 ; i < 2 ; i ++ ) {
        if ( o[i] && o[i].match( /^\d+$/ ) )
            length = o[i];

        if ( o[i] && o[i].match( /^(?:alpha)?(?:numeric)?$/ ) )
            type = o[i];
    }

    switch( type ) {
        case 'alpha'        : storedVars[ varName ] = randomAlpha( length ); break;
        case 'numeric'      : storedVars[ varName ] = randomNumeric( length ); break;
        case 'alphanumeric' : storedVars[ varName ] = randomAlphaNumeric( length ); break;
        default             : storedVars[ varName ] = randomAlphaNumeric( length );
    };
};

function randomNumeric ( length ) {
    return generateRandomString( length, '0123456789'.split( '' ) );
}

function randomAlpha ( length ) {
    var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split( '' );
    return generateRandomString( length, alpha );
}

function randomAlphaNumeric ( length ) {
    var alphanumeric = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split( '' );
    return generateRandomString( length, alphanumeric );
}

function generateRandomString( length, chars ) {
    var string = '';
    for ( var i = 0 ; i < length ; i++ )
        string += chars[ Math.floor( Math.random() * chars.length ) ];
    return string;
}

Way to use

Command                Target     Value
-----------           ---------   ----------
randomString           6           x
type                username       ${x}

Above code generates 6 charactes string and it assign to the variable x

Code in HTML format looks like below:

<tr>
    <td>randomString</td>
    <td>6</td>
    <td>x</td>
</tr>
<tr>
    <td>type</td>
    <td>username</td>
    <td>${x}</td>
</tr>
James
  • 5,622
  • 9
  • 34
  • 42
RajendraChary
  • 221
  • 2
  • 2
  • Note: If you get the following error, check that your user-extenstions.js file is in ASCII format not UTF-8. `Failed to load user-extensions.js!` `files=C:\TestScripts\random_generator.js` `lineNumber=1` `error=SyntaxError: illegal character` – lhoess Feb 06 '12 at 23:04
5

Here's a one-line solution to generating a random string of letters in JS:

"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").filter(function(e, i, a) { return Math.random() > 0.8 }).join("")

Useful for pasting into Selenium IDE.

afternoon
  • 1,285
  • 16
  • 25
2
<tr>
<td>store</td>
 <td>javascript{Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8)}</td>
<td>myRandomString</td>
</tr>
Saifur
  • 16,081
  • 6
  • 49
  • 73
  • Would you like to explain your code, or possibly format it a little bit to make it more readable? – ilter Apr 22 '15 at 19:50
  • nice trix, I like it. .toString(36) is hashing the number to a text string and by .replace everything what is not alphabet is replaced by empty string .substr will cut the length. Disadvantage: You cannot generate strings longer than 9? characters. – Dee Aug 24 '15 at 09:06
2

A one-liner for randomly choosing from a small set of alternatives:

javascript{['brie','cheddar','swiss'][Math.floor(Math.random()*3)]}
TomG
  • 1,751
  • 1
  • 12
  • 16
1

While making sense of RajendraChary's post above, I spent some time writing a new Selenium IDE extension.

My extension will let the user populate a variable with lorem ipsum text. There are a number of configurable options and it's turned into a nice little command. You can do things like "5 words|wordcaps|nomarks" to generate 5 lorem ipsum words, all capitalized, without punctuation.

I've thoroughly explained installation and usage as well as provided the full codebase here

If you take a peek at the code you'll get an idea of how to build similar functionality.

n00begon
  • 3,503
  • 3
  • 29
  • 42
agileadam
  • 51
  • 5
1

I made a little improvment to the function generateRandomString. When FF crashes, it's good to be able to use the same random number again.

Basically, it will ask you to enter a string yourself. If you don't enter anything, it will generate it.

function generateRandomString( length, chars ) { var string=prompt("Please today's random string",''); if (string == '') {for ( var i = 0 ; i < length ; i++ ) string += chars[ Math.floor( Math.random() * chars.length ) ]; return string;} else { return string;} }

bast
  • 11
  • 1
0

Selenium RC gives you much more freedom than Selenium IDE, in that you can:

  • (1) Enter any value to a certain field
  • (2) Choose any field to test in a certain HTML form
  • (3) Choose any execution order/step to test a certain set of fields.

You asked how to enter some random value in a field using Selenium IDE, other people have answered you how to generate and enter random values in a field using Selenium RC. That falls into the testing phase (1): "Enter any value to a certain field".

Using Selenium RC you could easily do the phase (2) and (3): testing any field under any execution step by doing some programming in a supported language like Java, PHP, CSharp, Ruby, Perl, Python.

Following is the steps to do phase (2) and (3):

  • Create list of your HTML fields so that you could easily iterate through them
  • Create a random variable to control the step, say RAND_STEP
  • Create a random variable to control the field, say RAND_FIELD
  • [Eventually, create a random variable to control the value entered into a certain field, say RAND_VALUE, if you want to do phase (1)]
  • Now, inside your fuzzing algorithm, iterate first through the values of RAND_STEP, then with each such iteration, iterate through RAND_FIELD, then finally iterate through RAND_VALUE.

See my other answer about fuzzing test, Selenium and white/black box testing

Community
  • 1
  • 1
CuongHuyTo
  • 1,333
  • 13
  • 19
0

Math.random may be "good enough" but, in practice, the Random class is often preferable to Math.random(). Using Math.random , the numbers you get may not actually be completely random. The book "Effective Java Second Edition" covers this in Item #47.

djangofan
  • 28,471
  • 61
  • 196
  • 289
0

One more solution, which I've copied and pasted into hundreds of tests :

<tr>
    <td>store</td>
    <td>javascript{var myDate = new Date(); myDate.getFullYear()+&quot;-&quot;+(myDate.getMonth()+1)+&quot;-&quot;+myDate.getDate()+&quot;-&quot;+myDate.getHours()+myDate.getMinutes()+myDate.getSeconds()+myDate.getMilliseconds();}</td>
    <td>S_Unique</td>
</tr>
<tr>
    <td>store</td>
    <td>Selenium Test InternalRefID-${S_Unique}</td>
    <td>UniqueInternalRefID</td>
</tr>
<tr>
    <td>store</td>
    <td>Selenium Test Title-${S_Unique}</td>
    <td>UniqueTitle</td>
</tr>
<tr>
    <td>store</td>
    <td>SeleniumEmail-${G_Unique}@myURL.com</td>
    <td>UniqueEmailAddress</td>
</tr>

Each test suite begins by setting a series of variables (if it's a big suite, use a separate file like Set_Variables.html). Those variables can then be used throughout your suite to set, test, and delete test data. And since the variables use the date rather than a random number, you can debug your test suite by looking for the objects which share a date.

andrew lorien
  • 2,310
  • 1
  • 24
  • 30
0

Here another variation on the gmail example:

<tr>
  <td>runScript</td>
  <td>emailRandom=document.getElementById('email');console.log(emailRandom.value);emailRandom.value=&quot;myEmail+&quot; + Math.floor(Math.random()*11111)+ &quot;@gmail.com&quot;;</td>
 <td></td>
</tr>
lhoess
  • 307
  • 3
  • 6