I. Use Extension file in IDE

Import extension files: Open Selenium IDE > Menu ‘Options’ > ‘Options’ > ‘Browse…’ *.js file > OK

Reopen Selenium IDE to effect changes.

– Reference other files in Resource to get full random text.

– File: extensions.docx

II. RANDOM in IDE

1. Random word – Lorem

– More at: https://github.com/f/loremjs/blob/master/lorem.js

  • Command: typeLorem
  • Target: locator
  • Value: number of words
Selenium.prototype.doTypeLorem = function(locator, how_many_words) {
	how_many_words = how_many_words || 10;
	var words = [
        "lorem", "ipsum", "dolor", "sit", "amet,", "consectetur", "adipiscing", "elit", "ut"
    ], iListLen = words.length;

	var element = this.page().findElement(locator);
	var valueToType = [];

	while ((how_many_words--) > 0)
		valueToType.push(words[ Math.floor(Math.random() * iListLen) ]);

	this.page().replaceText(element, valueToType.join(' '));
};

 

2. Random word, paragraph – Lipsum

– More at: https://github.com/agileadam/selenium-lipsumtext

Reference:

Options: words, paragraph, paragraphs|htmltags, words|wordcaps, words|wordcaps|nomarks…

Example:

lipsumText | 20 words | x
type | id=my-edit-field | ${x}
  • Command: lipsumText
  • Target: options
  • Value: varName
Selenium.prototype.doLipsumText = function (options, varName) {
    var length = 5, type = "word", useHtmlTags = false, useWordCaps = false, useMarks = true, opts = options.split("|"), i = 0;
    for (i = 0; i < opts.length; i += 1) {
        if (opts[i]) {
            var countAndType = opts[i].match(/^(\d+) ?(word|paragraph)s?$/);
            if (countAndType) {
                length = countAndType[1];
                type = countAndType[2];
            }
        }

        if (opts[i] && opts[i].match(/^(htmltags)$/)) {
            useHtmlTags = true;
        }

        if (opts[i] && opts[i].match(/^(wordcaps)$/)) {
            useWordCaps = true;
        }

        if (opts[i] && opts[i].match(/^(nomarks)$/)) {
            useMarks = false;
        }
    }

    switch (type) {
    case "paragraph":
        storedVars[varName] = lipsumParagraphs(length, useHtmlTags, useWordCaps, useMarks);
        break;
    case "word":
        storedVars[varName] = lipsumWords(length, useWordCaps, useMarks);
        break;
    default:
        storedVars[varName] = lipsumWords(length, useWordCaps, useMarks);
    }
}

// Returns paragraphs of words
function lipsumParagraphs(length, useHtmlTags, useWordCaps, useMarks) {
    var output = "", i = 0;
    for (i = 0; i < length; i += 1) {
        if (i > 0 && useHtmlTags === false) {
            output += "\r\r";
        }

        if (useHtmlTags === true) {
            output += "<p>" + getWords(15, 300, useWordCaps, useMarks) + "</p>";
        } else {
            output += getWords(15, 300, useWordCaps, useMarks);
        }
    }

    return output;
}

// Returns an exact number of words
function lipsumWords(length, useWordCaps, useMarks) {
    return getWords(length, length, useWordCaps, useMarks);
}

// Returns a string of lorem ipsum words
function getWords(minWordCount, maxWordCount, useWordCaps, useMarks) {
    var loremIpsumWordBank = new Array("lorem","ipsum","dolor","sit","amet,","consectetur","doloribus","asperiores","repellat");
    var numWords = minWordCount;
    if (minWordCount != maxWordCount) {
        numWords = Math.floor(Math.random() * (maxWordCount - minWordCount)) + minWordCount;
    }

    var ret = "", i = 0;
    for (i = 0; i < numWords; i += 1) {
        var newTxt = loremIpsumWordBank[Math.floor(Math.random() * (loremIpsumWordBank.length - 1))];
        if (useMarks) {
            if (ret.substring(ret.length - 1, ret.length) === "." || ret.substring(ret.length - 1, ret.length) === "?") {
                newTxt = newTxt.capitalizeFirstLetter();
            }
        }

        if (useWordCaps) {
            newTxt = newTxt.capitalizeFirstLetter();
        }

        ret += " " + newTxt;
    }

    // Remove beginning space
    ret = ret.replace(/(^[ ])/, "");

    // Remove end punctuation marks
    ret = ret.replace(/([.?, ]$)/gi, "");

    // Capitalize the string and add a period at the end
    ret = ret.capitalizeFirstLetter() + ".";

    if (useMarks === false) {
        // Remove all punctuation marks
        ret = ret.replace(/([.?,])/gi, "");
    }

    return ret;
}

// Provides a string method to capitalize the first letter of a string
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

 

3. Random alphabet

  • Command: typeRandomAlpha
  • Target: locator
  • Value: number of words
Selenium.prototype.doTypeRandomAlpha = function(locator, how_many_words) {
    how_many_words = how_many_words || 5;
    var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXTZ';
    var randomstring = '';
    var element = this.page().findElement(locator);

    for (var i=0; i<how_many_words; i++) {
        var rnum = Math.floor(Math.random()*chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    this.page().replaceText(element, randomstring);
}
  • Use directly in IDE
javascript{var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXTZ'; var randomstring = ''; for (var i=0; i<7; i++) { var rnum = Math.floor(Math.random()*chars.length); randomstring += chars.substring(rnum,rnum+1); }}

No stable length:

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

4. Random number

  • Command: typeRandomNumeric
  • Target: locator
  • Value: number of words
Selenium.prototype.doTypeRandomNumeric = function(locator, how_many_words) {
    how_many_words = how_many_words || 5;
    var chars = '0123456789';
    var randomstring = '';
    var element = this.page().findElement(locator);

    for (var i=0; i<how_many_words; i++) {
        var rnum = Math.floor(Math.random()*chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    this.page().replaceText(element, randomstring);
}
  • Use directly in IDE

– Simple

  • javascript{Math.floor(Math.random()*30)}

Normal

javascript{var chars = '0123456789'; var randomstring = ''; for (var i=0; i<7; i++) { var rnum = Math.floor(Math.random()*chars.length); randomstring += chars.substring(rnum,rnum+1); }}

4 numbers

javascript{Math.floor(Math.random()*10000)}

– 10 numbers

javascript{Math.random().toString(10).substring(2,12)}

– 10 Binary number

javascript{Math.random().toString(2).substring(2,12)}

5. Random alphanumeric

  • Command: typeRandomAlphaNumeric
  • Target: locator
  • Value: number of words
Selenium.prototype.doTypeRandomAlphaNumeric = function(locator, how_many_words) {
    how_many_words = how_many_words || 5;
    var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789';
    var randomstring = '';
    var element = this.page().findElement(locator);

    for (var i=0; i<how_many_words; i++) {
        var rnum = Math.floor(Math.random()*chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    this.page().replaceText(element, randomstring);
}
  • Use directly in IDE
javascript{Math.random().toString(36).substring(2,10)}
  • or
javascript{var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789'; var randomstring = ''; for (var i=0; i<7; i++) { var rnum = Math.floor(Math.random()*chars.length); randomstring += chars.substring(rnum,rnum+1); }}

6. Random email

  • Command: typeRandomEmail
  • Target: locator
  • Value: domain
Selenium.prototype.doTypeRandomEmail = function(locator, domain) {
    domain = domain || 'gmail.com';
    var element = this.page().findElement(locator);
    var allowedChars = "abcdefghiklmnopqrstuvwxyz";
    var stringLength = 10;
    var randomstring = '';

    for (var i=0; i<stringLength; i++) {
        var rnum = Math.floor(Math.random() * allowedChars.length);
        randomstring += allowedChars.substring(rnum,rnum+1);
    }
    randomstring += "@" + domain
    this.browserbot.replaceText(element, randomstring);
};
  • Use directly in IDE
javascript{"hydra" + Math.floor(Math.random()*1000) + "@gmail.com";}

7. Random Word with Date/Time (No space)

– More at: https://github.com/agileadam/selenium-lipsumtext

  • Command: typeRandomTextWithTime
  • Target: locator
  • Value: a stable word
Selenium.prototype.doTypeRandomTextWithTime = function(locator, domain) {
    domain = domain || 'example';
    var element = this.page().findElement(locator);
    var randomstring = '';
    var date = new Date();
    var random_date = date.getFullYear() + ""
                        + ("0" + (date.getMonth() + 1)).slice(-2) + ""
                        + ("0" + date.getDate()).slice(-2) + ""
                        + date.getHours() + ""
                        + date.getMinutes() + ""
                        + ("0" + date.getSeconds()).slice(-2);
    randomstring += domain + random_date;
    this.browserbot.replaceText(element, randomstring);
};

 

8. Random word with Date/Time

  • Command: testNameRandom
  • Target: locator
  • Value: number of words
Selenium.prototype.doTestNameRandom = function(locator, how_many_words) {
	how_many_words = how_many_words || 2;
    var words = [
        "lorem", "ipsum", "dolor", "sit", "amet", "molestie"
    ], iListLen = words.length;

	var element = this.page().findElement(locator);
	var valueToType = [];

	while ( (how_many_words--) > 0 )
		valueToType.push( words[ Math.floor( Math.random() * iListLen ) ]);

    var date = new Date();
	valueToType.push("in " + date.getDate() + " " + date.getMonth() + " " + date.getFullYear());
	this.page().replaceText(element, valueToType.join(' '));
};

 9. Choose random item from array

<tr>
	<td>storeEval</td>
	<td>new Array ('a','b','c','d','e','f')</td>
	<td>names</td>
</tr>
<tr>
	<td>storeEval</td>
	<td>javascript{storedVars['names'].length}</td>
	<td>length</td>
</tr>
<tr>
	<td>store</td>
	<td>javascript{Math.floor(Math.random()*storedVars['length'])}</td>
	<td>num</td>
</tr>
<tr>
	<td>type</td>
	<td>id=quiz-name</td>
	<td>javascript{storedVars['names'][storedVars.num]}</td>
</tr>

 10. Choose order item from array

<tr>
	<td>store</td>
	<td>1</td>
	<td>order</td>
</tr>
<tr>
	<td>storeEval</td>
	<td>new Array('en','de','da','cs','fi','fr','it','ja','ko','nl','no','pl','pt','ru','sv','tr')</td>
	<td>myArray</td>
</tr>
<tr>
	<td>getEval</td>
	<td>storedVars['item'] = storedVars['myArray'][${order}]</td>
	<td></td>
</tr>
<tr>
	<td>echo</td>
	<td>${item}</td>
	<td></td>
</tr>

III. LOOP

Copy to Source Tab

– Use – START:

<tr>
 <td>getEval</td>
 <td>storedVars['y'] = 5;</td>
 <td></td>
</tr>
<tr>
 <td>store</td>
 <td>-1</td>
 <td>x</td>
</tr>
<tr>
 <td>label</td>
 <td>top</td>
 <td></td>
</tr>
<tr>
 <td>getEval</td>
 <td>storedVars['x'] = ${x} + 1 ;</td>
 <td></td>
</tr>
<tr>
 <td>echo</td>
 <td>Running iteration ${x} of ${y}.</td>
 <td></td>
</tr>

 

– Use – END:

<tr>
<td>gotoIf</td>
<td>${x} &lt; ${y}-1</td>
<td>top</td>
</tr>

 

Code:

var gotoLabels= {};
var whileLabels = {};

Selenium.prototype.reset = function() {
    this.initialiseLabels();
    this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;
    this.browserbot.selectWindow("null");
    this.browserbot.resetPopups();
}

Selenium.prototype.initialiseLabels = function()
{
    gotoLabels = {};
    whileLabels = { ends: {}, whiles: {} };
    var command_rows = [];
    var numCommands = testCase.commands.length;
    for (var i = 0; i &amp;amp;amp;lt; numCommands; ++i) {
        var x = testCase.commands[i];
        command_rows.push(x);
    }
    var cycles = [];
    var forEachCmds = [];
    for(var i = 0; i &amp;amp;amp;lt; command_rows.length; i++) {
        if (command_rows[i].type == 'command')
        switch(command_rows[i].command.toLowerCase()) {
            case "label":
                gotoLabels[ command_rows[i].target ] = i;
                break;
            case "while":
            case "endwhile":
                cycles.push([command_rows[i].command.toLowerCase(), i])
                break;
            case "foreach":
            case "endforeach":
                forEachCmds.push([command_rows[i].command.toLowerCase(), i])
                break;
        }
    }
    var i = 0;
    while(cycles.length) {
        if(i &amp;amp;amp;gt;= cycles.length) {
            throw new Error("non-matching while/endWhile found");
        }
        switch(cycles[i][0]) {
            case "while":
                if((i+1 &amp;amp;amp;lt; cycles.length) &amp;amp;amp;amp;&amp;amp;amp;amp; ("endwhile" == cycles[i+1][0])) {
                    // pair found
                    whileLabels.ends[ cycles[i+1][1] ] = cycles[i][1];
                    whileLabels.whiles[ cycles[i][1] ] = cycles[i+1][1];
                    cycles.splice(i, 2);
                    i = 0;
                } else ++i;
                break;
            case "endwhile":
                ++i;
                break;
        }
    }
}

Selenium.prototype.continueFromRow = function(row_num)
{
    if(row_num == undefined || row_num == null || row_num &amp;amp;amp;lt; 0) {
        throw new Error("Invalid row_num specified.");
    }
    testCase.debugContext.debugIndex = row_num;
}

// do nothing. simple label
Selenium.prototype.doLabel = function(){};

Selenium.prototype.doGotoLabel = function(label) {
    if(undefined == gotoLabels[label]) {
        throw new Error("Specified label '" + label + "' is not found.");
    }
    this.continueFromRow(gotoLabels[ label ]);
};

Selenium.prototype.doGoto = Selenium.prototype.doGotoLabel;

Selenium.prototype.doGotoIf = function(condition, label) {
    if(eval(condition)) this.doGotoLabel(label);
}

Selenium.prototype.doWhile = function(condition) {
    if(!eval(condition)) {
        var last_row = testCase.debugContext.debugIndex;
        var end_while_row = whileLabels.whiles[ last_row ];
        if(undefined == end_while_row) throw new Error("Corresponding 'endWhile' is not found.");
        this.continueFromRow(end_while_row);
    }
}

Selenium.prototype.doEndWhile = function() {
    var last_row = testCase.debugContext.debugIndex;
    var while_row = whileLabels.ends[ last_row ] - 1;
    if(undefined == while_row) throw new Error("Corresponding 'While' is not found.");
    this.continueFromRow(while_row);
}

Selenium.prototype.doPush= function(value, varName) {
    if(!storedVars[varName]) {
        storedVars[varName] = new Array();
    }
    if(typeof storedVars[varName] !== 'object') {
        throw new Error("Cannot push value onto non-array " + varName);
    } else {
        storedVars[varName].push(value);
    }
}

 

IV. From Blog Testing

while
endWhile
gotoIf
gotoIfAndWait
gotoLabel
label
push
getEval
openMultipleWindow
disableJavascript
enableJavascript

 

V. Other Actions

  • Use JavaScript
type | name=username | javascript{...} 
store | javascript{...} | x
  • Store Random Value
typeRandom ... | id=... | param 
storeValue | id=... | x 
type | id=,,, | ${x}UpperCase / LowerCase
  • UpperCase / LowerCase
 javascript{"searchString".toUpperCase()} 
  • Get random number of question in datatable
 javascript{Math.floor(Math.random()*win.document.getElementById("QuestionDataTables").getElementsByTagName("tr").length);} 
  • Type in Contentable

* Type text in a contentable (HTML5) not support currently. So we use a special way.

Untitled


	runScript
	javascript{win = selenium.browserbot.getCurrentWindow();}

	runScript
	javascript{win.document.evaluate( '//div[@data-placeholder="Type something"]/p',win.document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null ).singleNodeValue.innerHTML = "What is your plan in next 3 years?";}
	New Difficult Multiple Choice Technical Question Test

	runScript
	javascript{win.document.evaluate( '//div[@data-placeholder="Type something"]/p',win.document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null ).singleNodeValue.innerHTML = "What is your plan in next 3 years?";}
	New Difficult Multiple Choice Technical Question Test

  • Data Table

a) Count number of pages

Untitled


	runScript
	javascript{win = selenium.browserbot.getCurrentWindow();}

	store
	javascript{win.document.getElementById("QuestionDataTables_paginate").getElementsByTagName("li").length - 2;}
	pagesCount

	echo
	${pagesCount}

 

b) How many entries per pages

Untitled


	store
	javascript{win.document.getElementsByName("QuestionDataTables_length")[0].value;}
	rowsPerPage

	echo
	${rowsPerPage}

 

c) Choose random number of question in table


	store
	javascript{win.document.getElementById("QuestionDataTables").getElementsByTagName("tr").length;}
	number

	echo
	${number}

	store
	javascript{Math.floor(Math.random()*win.document.getElementById("QuestionDataTables").getElementsByTagName("tr").length/4);}
	random

	echo
	${random}

 

d) Number of actual entries in current page

Untitled


	store
	javascript{win.document.getElementById('QuestionDataTables').rows.length - 1;}
	actualRowsOnPage

	echo
	${actualRowsOnPage}

 

e) Verify all result have the key word or not with “regexpi:.”

<tr>
 <td>verifyText</td>
 <td>//tr[contains(@class, &quot;even&quot;) or contains(@class, &quot;odd&quot;) ][${currentRow}]/td[2]</td>
 <td>regexpi:.*which*</td>
</tr>

 

f) Search in data table

* Loop comparing each entry if containing the key word (which)

Untitled


	while
	${currentPage} &amp;amp;lt;= ${pagesCount}

	click
	link=${currentPage}

	store
	javascript{win.document.getElementById('QuestionDataTables').rows.length - 1;}
	actualRowsOnPage

	store
	1
	currentRow

	while
	${currentRow} &amp;amp;lt;= ${actualRowsOnPage}

	echo
	Page: ${currentPage}, Row: ${currentRow}

	verifyText
	//tr[contains(@class, "even") or contains(@class, "odd") ][${currentRow}]/td[2]
	regexpi:.*which*

	store
	javascript{storedVars.currentRow++;}

	endWhile

	store
	javascript{storedVars.currentPage++;}

	endWhile

  • Combo Box

* Select normal

<tr>
 <td>select</td>
 <td>id=selSubject</td>
 <td>label=English</td>
</tr>

 

* Select random value in Combo Box


	store
	javascript{win.document.getElementById("package-category")[Math.floor(Math.random()*win.document.getElementById("package-category").length)].innerHTML.trim();}
	package_category

	select
	id=package-category
	label=${package_category}

  • Multi Window
<tr>
 <td>runScript</td>
 <td>javascript{win = selenium.browserbot.getCurrentWindow()}</td>
 <td></td>
</tr>
  • Get current date
    • command: storeEval
    • target: var d=new Date(); d.getDate()+’-‘+((d.getMonth()+1)) \n+’-‘+d.getFullYear();
    • value: date
  • Handle multiple windows
Command Target Value
open http://www.bing.com
storeTitle i
openWindow https://www.google.com
pause 5000
selectWindow Google
clickAndWait css=#gb_2 > span.gbts
storeTitle j
selectWindow ${i}
clickAndWait css=#scpt1 > a
storeTitle i
selectWindow ${j}
close j
selectWindow ${i}
close

 

VI. SELECTOR DATA TABLE

1. Selector

* Find the position of an element

  • target: xpath=//div/form/table/tbody/tr/td[2]
  • target: //tr[contains(td[2], “Difficult”)] (Shortway)

Untitled

 

2. Find value in table

* Click the edit button where having value ${levelName}

  • command: click
  • target: //table[@id=’dataTables-example’]/tbody/tr[contains(td[2], ‘${levelName}’)]/td[4]/a[1]

Untitled