Behat (+ Mink) Check for some text followed by some text (in sibling elements) - behat

The I should see... function is an essential feature of Behat but I regularly find myself wanting to write something like this in my scenarios:
Then I should see "Session ID" followed by "3"
Which is my humanly-parsable way of describing 2 pieces of text next to each other in the content. That is to say the first string is the content of any element and the second is the content of it's next immediate sibling.
This would be useful for checking label - value type layouts:
Or if I want to check header - cell value type layouts in tabulated data:
Or even definition title - definition.
Obviously I could add 'id' attributes to every element I want to test but in a complicated page where many parts of the content need testing this starts to feel like I am bloating the markup with single-use attributes.

To be able to use...
Then I should see "Session ID" followed by "3"
Add the following methods to your FeatureContext.php file:
/**
* #Then I should see :textA followed by :textB
*/
public function iShouldSeeFollowedBy($textA, $textB)
{
$content = $this->getSession()->getPage()->getContent();
// Get rid of stuff between script tags
$content = $this->removeContentBetweenTags('script', $content);
// ...and stuff between style tags
$content = $this->removeContentBetweenTags('style', $content);
$content = preg_replace('/<[^>]+>/', ' ',$content);
// Replace line breaks and tabs with a single space character
$content = preg_replace('/[\n\r\t]+/', ' ',$content);
$content = preg_replace('/ {2,}/', ' ',$content);
if (strpos($content,$textA) === false) {
throw new Exception(sprintf('"%s" was not found in the page', $textA));
}
$seeking = $textA . ' ' . $textB;
if (strpos($content,$textA . ' ' . $textB) === false) {
// Be helpful by finding the 10 characters that did follow $textA
preg_match('/' . $textA . ' [^ ]+/',$content,$matches);
throw new Exception(sprintf('"%s" was not found, found "%s" instead', $seeking, $matches[0]));
}
}
/**
* #param string $tagName - The name of the tag, eg. 'script', 'style'
* #param string $content
*
* #return string
*/
private function removeContentBetweenTags($tagName,$content)
{
$parts = explode('<' . $tagName, $content);
$keepers = [];
// We always want to keep the first part
$keepers[] = $parts[0];
foreach ($parts as $part) {
$subparts = explode('</' . $tagName . '>', $part);
if (count($subparts) > 1) {
$keepers[] = $subparts[1];
}
}
return implode('', $keepers);
}

Related

fix footer image in tcpdf

$path = Yii::app()->basePath;
require_once($path . '/extensions/tcpdf/tcpdf.php');
$pdf = new TCPDF();
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(true);
$pdf->SetAutoPageBreak(TRUE, 0);
$pdf->AddPage();
$pdf->SetLineWidth(0.1);
$pdf->SetFont('times', '', 10);
$pdf->SetMargins(20, 20, 20, true);
$footer_image_file = Yii::app()->request->baseUrl.'/images/logo.jpg';
$content = '<div> $content </div>';
$pdf->writeHTML($content, true, false, true, false, '');
ob_end_clean();
$pdf->Output("Reports.pdf", "D");
I want to add image in fooder for every new pages.. please anyone help me...
Simply put the code displaying the image within the Footer() base method. This base method is called for any new page by either the AddPage() method and Close().
Important : The Footer method should not be called directly.
This method is supposed to be implemented in your class, so override it like this :
function Footer()
{
.... /* Put your code here (see a working example below) */
$logoX = 186; // 186mm. The logo will be displayed on the right side close to the border of the page
$logoFileName = "/images/myLogo.jpg";
$logoWidth = 15; // 15mm
$logo = $this->PageNo() . ' | '. $this->Image($logoFileName, $logoX, $this->GetY()+2, $logoWidth);
$this->SetX($this->w - $this->documentRightMargin - $logoWidth); // documentRightMargin = 18
$this->Cell(10,10, $logo, 0, 0, 'R');
}
I hope this helps and I've well understood your question.
function Footer()
{
.... /* Put your code here (see a working example below) */
$logoX = 40; //
$logoFileName = "/images/myLogo.jpg";
$logoWidth = 130; // 15mm
$logoY = 280;
$logo = $this->PageNo() . ' | '. $this->Image($logoFileName, $logoX, $logoY, $logoWidth);
$this->SetX($this->w - $this->documentRightMargin - $logoWidth); // documentRightMargin = 18
$this->Cell(10,10, $logo, 0, 0, 'C');
}
This codes are perfectly placed a image in the center of page footer.Thanks a lot pti_jul.:-)))))

How to read PHP output row by row and create HTML-links from each row

I'm having this PHP-script:
<?php
$old_path = getcwd();
chdir('/var/www/html/SEARCHTOOLS/');
$term1 = $_POST['query1'];
$term2 = $_POST['query2'];
$var = "{$term1} {$term2}";
$outcome = shell_exec("searcher $var");
chdir($old_path);
echo "<pre>$outcome</pre>";
?>
On a searchpage two searchwords are written and the searchbutton is pushed. The search result turns up as a webpage like this:
/var/www/html/SEARCHTOOLS/1974-1991.pdf:1
/var/www/html/SEARCHTOOLS/1974-1991.pdf:3
/var/www/html/SEARCHTOOLS/1974-1991.pdf:7
/var/www/html/SEARCHTOOLS/1974-1991.pdf:7
/var/www/html/SEARCHTOOLS/1974-1991.pdf:9
/var/www/html/SEARCHTOOLS/1974-1991.pdf:13
/var/www/html/SEARCHTOOLS/1974-1991.pdf:13
The result shows links to individual PDF-files and pagenumber in that file, but are not clickable.
Is there a way to make these links clickable so that it opens up for instance in Evince or Acrobat at the correct page number?
Many thanks in advance.
/Paul
I found a correct answer to my problem. It took some time, but here it is:
<?php
// Get current working directory and put it as variable
$old_path = getcwd();
// Change directory
chdir('/var/www/html/SEARCHTOOLS/');
// Create first variable as result of first searchword on searchpage
$term1 = $_POST['query1'];
// Create second variable as result of second searchword on searchpage
$term2 = $_POST['query2'];
// Create a variable combining first AND second variable
$var = "{$term1} {$term2}";
// Create a variable as the result of the executed search using command "sokare" and variable "$var"
$outcome = shell_exec("sokare $var");
// Return to starting directory
chdir($old_path);
// Split the varible "$outcome" per line representing every page in PDF-file where variable "$var" is found
foreach(preg_split("/((\r?\n)|(\r\n?))/", $outcome) as $line){
// Create a variable out of the given pagenumber in PDF-file
$end = substr($line, strpos($line, ":") + 1);
// Trim the line by removing leading directories from line
$line2 = str_replace('/var/www/html', '', $line);
// Change a string from lower to upper case
$line2 = str_replace('searchtools', 'SEARCHTOOLS', $line2);
// Remove the colon and anything behind it from line
$line2 = array_shift(explode(':', $line2));
// Add suffix to line to facilitate linking to pagenumber in PDF-file
$line3 = str_replace(" ", "_", $line2).'#page=';
// Add pagenumber from the variable "$end"
$line3 = str_replace(" ", "_", $line3).$end;
// Print each line as a correct URL-link
echo "<pre><a href=$line3>$line3</a></pre>";
}
?>
The search results will now turn up as (and are clickable):
/SEARCHTOOLS/1974-1991.pdf#page=1
/SEARCHTOOLS/1974-1991.pdf#page=3
/SEARCHTOOLS/1974-1991.pdf#page=7
Just a small edit. The line ....
// Add suffix to line to facilitate linking to pagenumber in PDF-file
$line3 = str_replace(" ", "_", $line2).'#page=';
...works better with:
// Add suffix to line to facilitate linking to pagenumber in PDF-file
if (substr($line2, -3) == 'pdf') {
$line3 = $line2.'#page=';
}

Fiddler: Programmatically add word to Query string

Please be kind, I'm new to Fiddler
My purpose:I want to use Fiddler as a Google search filter
Summary:
I'm tired of manually adding "dog" every time I use Google.I do not want the "dog" appearing in my search results.
For example:
//www.google.com/search?q=cat+-dog
//www.google.com/search?q=baseball+-dog
CODE:
dog replaced with -torrent-watch-download
// ==UserScript==
// #name Tamper with Google Results
// #namespace http://superuser.com/users/145045/krowe
// #version 0.1
// #description This just modifies google results to exclude certain things.
// #match http://*.google.com
// #match https://*.google.com
// #copyright 2014+, KRowe
// ==/UserScript==
function GM_main () {
window.onload = function () {
var targ = window.location;
if(targ && targ.href && targ.href.match('https?:\/\/www.google.com/.+#q=.+') && targ.href.search("/+-torrent/+-watch/+-download")==-1) {
targ.href = targ.href +"+-torrent+-watch+-download";
}
};
}
//-- This is a standard-ish utility function:
function addJS_Node(text, s_URL, funcToRun, runOnLoad) {
var D=document, scriptNode = D.createElement('script');
if(runOnLoad) scriptNode.addEventListener("load", runOnLoad, false);
scriptNode.type = "text/javascript";
if(text) scriptNode.textContent = text;
if(s_URL) scriptNode.src = s_URL;
if(funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
targ.appendChild(scriptNode);
}
addJS_Node (null, null, GM_main);
At first I was going to go with Tampermonkey userscripts,Because I did not know about Fiddler
==================================================================================
Now,lets focus on Fiddler
Before Request:
I want Fiddler to add text at the end of Google Query string.
Someone suggested me to use
static function OnBeforeRequest(oSession: Session) {
if (oSession.uriContains("targetString")) {
var sText = "Enter a string to append to a URL";
oSession.fullUrl = oSession.fullUrl + sText;
}
}
Before Response:
This is where my problem lies
I totally love the HTML response,Now I just want to scrape/hide the word in the search box without changing the search results.How can it be done? Any Ideas?
http://i.stack.imgur.com/4mUSt.jpg
Can you guys please take the above information and fix the problem for me
Thank you
Basing on goal definition above, I believe you can achieve better results with your own free Google custom search engine service. In particular, because you have control over GCSE fine-tuning results, returned by regular Google search.
Links:
https://www.google.com/cse/all
https://developers.google.com/custom-search/docs/structured_search

How can I read Variables from data pool with Selenium IDE?

I am using Selenium IDE to test a web based HR/SW system.
There is a screen that used to enter vacation for employees.
I am having nearly 3000 employee.
I built a test case that enter vacations for one employee using variables.
How can I repeat the test case for all 3000 employees without creating the test case 3000 times. It will take an impossible effort to do that. Note: Each employee is having different vacation data (Type, start date, End date)
Is there any way that I can use a file (Excel,....) that variable can use to read its data from?
Is there any solution for my case???
I will be very very grateful I any one could help me.
Thank you.
You could use an XML file as an input.
1) At first you have to add following user extensions:
sideflow.js - (http://51elliot.blogspot.com/2008/02/selenium-ide-goto.html - additionally this article explains how to add user extension files)
datadriven.js
include.js
At the moment I can't find links where I took the last two, therefore I will give their code in the end of my post. Code is taken from my working directory. You just put the code to correspondent files, then add files to SelemiunIDE user extension and use them.
2) Create an XML file test_data.xml:
<testdata>
<test employee="1" type="1" startDate="01.01.2013" endDate="01.02.2013" />
<test employee="2" type="1" startDate="01.02.2013" endDate="01.03.2013" />
<test employee="3" type="1" startDate="01.03.2013" endDate="01.04.2013" />
...
</testdata>
3) In your test case use code like this:
${DataPath} - full path to a directory with XML-files
<!--BEGIN LOOP-->
<tr>
<td>loadTestData</td>
<td>file://${DataDir}/test_data.xml</td>
<td></td>
</tr>
<tr>
<td>while</td>
<td>!testdata.EOF()</td>
<td></td>
</tr>
<tr>
<td>nextTestData</td>
<td></td>
<td></td>
</tr>
<tr>
<td>echo</td>
<td>employee=${employee} type=${type} ...</td>
<td></td>
</tr>
...
<!--END LOOP-->
<tr>
<td>endWhile</td>
<td></td>
<td></td>
</tr>
Used user extensions:
include.js
/**
* Original Developer: Jerry Qian(qqqiansjtucs#hotmail.com)
* Modified By: John Witchel (jwitchel#colevalleygroup.com)
* include extension for Selenium-IDE edition
* refer to includeCommand_2.1.3 for Selenium-Core edition
* #version 1.3
*
*/
function IDEIncludeCommand() {}
IDEIncludeCommand.LOG_PREFIX = "IDEIncludeCommand: ";
IDEIncludeCommand.BEGIN_TEMPLATE = "begin$Template$";
IDEIncludeCommand.END_TEMPLATE = "end$Template$";
IDEIncludeCommand.VERSION = "1.1";
IDEIncludeCommand.prototype.prepareTestCaseAsText = function(responseAsText, paramsArray) {
/**
* Prepare the HTML to be included in as text into the current testcase-HTML
* Strip all but the testrows (tr)
* Stripped will be:
* - whitespace (also new lines and tabs, so be careful wirt parameters relying on this),
* - comments (xml comments)
* Replace variable according to include-parameters
* note: the include-variables are replaced literally. selenium does it at execution time
* also note: all selenium-variables are available to the included commands, so mostly no include-parameters are necessary
*
* #param responseAsText table to be included as text (string)
* #return testRows array of tr elements (as string!) containing the commands to be included
*
* TODO:
* - selenium already can handle testcase-html. use selenium methods or functions instead
* - find better name for requester
*/
// removing new lines, carret return and tabs from response in order to work with regexp
var pageText = responseAsText.replace(/\r|\n|\t/g,"");
// remove comments
// begin comment, not a dash or if it's a dash it may not be followed by -> repeated, end comment
pageText = pageText.replace(/<!--(?:[^-]|-(?!->))*-->/g,"");
// find the content of the test table = <[spaces]table[char but not >]>....< /[spaces]table[chars but not >]>
var testText = pageText.match(/<\s*table[^>]*>(.*)<\/\s*table[^>]*>/i)[1];
// Replace <td></td> with <td> </td> for iE - credits Chris Astall
// rz: somehow in my IE 7 this is not needed but is not bad as well
testText = testText.replace(/<\s*td[^>]*>\s*<\s*\/td[^>]*>/ig,"<td></td>");// jq: no space
// replace vars with their values in testText
for ( var k = 0 ; k < paramsArray.length ; k++ ) {
var pair = paramsArray[k];
testText = testText.replace(pair[0],pair[1]);
}
// removes all < /tr>
// in order to split on < tr>
testText = testText.replace(/<\/\s*tr[^>]*>/ig,"");
// split on <tr>
var testRows = testText.split(/<\s*tr[^>]*>/i);
return testRows;
};
IDEIncludeCommand.prototype.getIncludeDocumentBySynchronRequest = function(includeUrl) {
/**
* Prepare and do the XMLHttp Request synchronous as selenium should not continue execution meanwhile
*
* note: the XMLHttp requester is returned (instead of e.g. its text) to let the caller decide to use xml or text
*
* selenium-dependency: uses extended String from htmlutils
*
* TODO use Ajax from prototype like this:
* var sjaxRequest = new Ajax.Request(url, {asynchronous:false});
* there is discussion about getting rid of prototype.js in developer forum.
* the ajax impl in xmlutils.js is not active by default in 0.8.2
*
* #param includeUrl URI to the include-document (document has to be from the same domain)
* #return XMLHttp requester after receiving the response
*/
var url = this.prepareUrl(includeUrl);
// the xml http requester to fetch the page to include
var requester = this.newXMLHttpRequest();
if (!requester) {
throw new Error("XMLHttp requester object not initialized");
}
requester.open("GET", url, false); // synchron mode ! (we don't want selenium to go ahead)
try {
requester.send(null);
} catch(e) {
throw new Error("Error while fetching url '" + url + "' details: " + e);
}
if ( requester.status != 200 && requester.status !== 0 ) {
throw new Error("Error while fetching " + url + " server response has status = " + requester.status + ", " + requester.statusText );
}
return requester;
};
IDEIncludeCommand.prototype.prepareUrl = function(includeUrl) {
/** Construct absolute URL to get include document
* using selenium-core handling of urls (see absolutify in htmlutils.js)
*/
var prepareUrl;
// htmlSuite mode of SRC? TODO is there a better way to decide whether in SRC mode?
if (window.location.href.indexOf("selenium-server") >= 0) {
LOG.debug(IDEIncludeCommand.LOG_PREFIX + "we seem to run in SRC, do we?");
preparedUrl = absolutify(includeUrl, htmlTestRunner.controlPanel.getTestSuiteName());
} else {
preparedUrl = absolutify(includeUrl, selenium.browserbot.baseUrl);
}
LOG.debug(IDEIncludeCommand.LOG_PREFIX + "using url to get include '" + preparedUrl + "'");
return preparedUrl;
};
IDEIncludeCommand.prototype.newXMLHttpRequest = function() {
// TODO should be replaced by impl. in prototype.js or xmlextras.js
// but: there is discussion of getting rid of prototype.js
// and: currently xmlextras.js is not activated in testrunner of 0.8.2 release
var requester = 0;
var exception = '';
// see http://developer.apple.com/internet/webcontent/xmlhttpreq.html
// changed order of native and activeX to get it working with native
// xmlhttp in IE 7. credits dhwang
try {
// for IE/ActiveX
if(window.ActiveXObject) {
try {
requester = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
requester = new ActiveXObject("Microsoft.XMLHTTP");
}
}
// Native XMLHttp
else if(window.XMLHttpRequest) {
requester = new XMLHttpRequest();
}
}
catch(e) {
throw new Error("Your browser has to support XMLHttpRequest in order to use include \n" + e);
}
return requester;
};
IDEIncludeCommand.prototype.splitParamStrIntoVariables = function(paramString) {
/**
* Split include Parameters-String into an 2-dim array containing Variable-Name and -Value
*
* selenium-dependency: uses extended String from htmlutils
*
* TODO: write jsunit tests - this could be easy (if there were not the new RegExp)
*
* #param includeParameters string the parameters from include call
* #return new 2-dim Array containing regExpName (to find a matching variablename) and value to be substituted for
*/
var newParamsArray = new Array();
// paramString shall contains a list of var_name=value
var paramListPattern = /([^=,]+=[^=,]*,)*([^=,]+=[^=,]*)/;
if (! paramString || paramString === "") {
return newParamsArray;
} else if (paramString.match( paramListPattern )) {
// parse parameters to fill newParamsArray
var pairs = paramString.split(",");
for ( var i = 0 ; i < pairs.length ; i++ ) {
var pair = pairs[i];
var nameValue = pair.split("=");
//rz: use String.trim from htmlutils.js of selenium to get rid of whitespace in variable-name(s)
var trimmedNameValue = new String(nameValue[0]).trim();
// the pattern to substitute is ${var_name}
var regExpName = new RegExp("\\$\\{" + trimmedNameValue + "\\}", "g");
if (nameValue.length < 3) {
newParamsArray.push(new Array(regExpName,nameValue[1]));
} else {
var varValue = new String(nameValue[1]);
for (var j = 2; j < nameValue.length; j++) {
varValue=varValue.concat("="+nameValue[j]);
}
newParamsArray.push(new Array(regExpName,varValue));
}
}
} else {
throw new Error("Bad format for parameters list : '" + paramString + "'");
}
return newParamsArray;
};
IDEIncludeCommand.prototype.doInclude = function(locator, paramString) {
// Rewrite logic for Selenium IDE by Jerry Qian
var currentSelHtmlTestcase = testCase;
var includeCmdRow = testCase.debugContext.currentCommand();
if (!includeCmdRow) {
throw new Error("IDEIncludeCommand: failed to find include-row in source testtable");
}
var paramsArray = this.splitParamStrIntoVariables(paramString);
var inclDoc = this.getIncludeDocumentBySynchronRequest(locator);
// Get an array of commands from the include text with all whitespace stripped
var includedTestCaseHtml = this.prepareTestCaseAsText(inclDoc.responseText, paramsArray);
this.injectIncludeTestCommands(locator,includeCmdRow,includedTestCaseHtml);
};
IDEIncludeCommand.prototype.injectIncludeTestCommands = function(locator,includeCmdRow, testRows) {
// Rewrite logic for Selenium IDE by Jerry Qian
var newCommands = new Array();
// skip first element as it is empty or <tbody>
for (var i = 1 ; i < testRows.length; i++) {
if(i == 1){// add BEGIN-END block
var beginCommand = new Command(IDEIncludeCommand.BEGIN_TEMPLATE,locator,"");
newCommands.push(beginCommand);
}
var newText = testRows[i];
if(newText.match(/<\s*td.*colspan=.*>(.*)<\/\s*td[^>]*>/i)){//delete comment step
continue;
}
// removes all < /td>
// in order to split on <td>
newText = newText.replace(/<\/\s*td[^>]*>\s*<\/\s*tbody[^>]*>/ig,""); //remove </tbody>first
newText = newText.replace(/<\/\s*td[^>]*>/ig,"");
var newCols = newText.split(/<\s*td[^>]*>/i);
var new_cmd,new_target,new_value;
for (var j = 1 ; j < newCols.length; j++) {//skip 0
if(j == 1) {
new_cmd = newCols[j].replace(/\s/g,"");//trim \s
}else if(j == 2) {
new_target = newCols[j].replace(/\s+$/g,"");//trim end \s
}else if(j == 3) {
new_value = newCols[j].replace(/\s+$/g,"");//trim end \s
}
}
var newCommand = new Command(new_cmd,new_target,new_value);
newCommands.push(newCommand); //correct all steps
}
var endCommand = new Command(IDEIncludeCommand.END_TEMPLATE,locator,"");
newCommands.push(endCommand);//add BEGIN-END block
var cmsBefore = testCase.commands.slice(0,testCase.debugContext.debugIndex + 1);
var cmdsBehind = testCase.commands.slice(testCase.debugContext.debugIndex + 1, testCase.commands.length);
testCase.commands = cmsBefore.concat(newCommands).concat(cmdsBehind);//Injection
// Don't inject if it appears the injection has already been done
// (i.e., if the next command is the BEGIN).
if (testCase.commands.length <= testCase.debugContext.debugIndex+1
|| beginCommand.toString() != testCase.commands[testCase.debugContext.debugIndex+1].toString())
{
// The include command cannot be the last command in the TestCase, or else
// the de-injection code in doEnd$Template$ will cause an error. So we'll
// add a simple echo if it is the last.
if (testCase.commands.length == testCase.debugContext.debugIndex+1)
{
// Using concat instead of push so that we don't trigger the TestCase's set-modified flag.
testCase.commands = testCase.commands.concat(new Command("echo", "The include command cannot be the last line in a TestCase, so this command was added. It can be left in place or removed, as desired.", "The include command cannot be the last line in a TestCase, so this command was added. It can be left in place or removed, as desired."));
}
// This is original code.
var cmsBefore = testCase.commands.slice(0,testCase.debugContext.debugIndex + 1);
var cmdsBehind = testCase.commands.slice(testCase.debugContext.debugIndex + 1, testCase.commands.length);
testCase.commands = cmsBefore.concat(newCommands).concat(cmdsBehind);//Injection
}
};
Selenium.prototype.doInclude = function(locator, paramString) {
LOG.debug(IDEIncludeCommand.LOG_PREFIX + "Version " + IDEIncludeCommand.VERSION);
var ideIncludeCommand = new IDEIncludeCommand();
ideIncludeCommand.doInclude(locator, paramString);
// If goto scripts exist then reindex the labels. goto_sel_ide.js creates an array of labels when the
// script is initialized but an included file's labels are not part of that initial read, so this function
// re-initializes that array with the included files labels (if any). If goto_sel.ide.js is not included
// it's ignored.
try {
this.initialiseLabels();
}
catch (e) {
LOG.debug("Goto Script not used.");
}
};
// Array to hold the starting position of the Begin$Template$ marker. Pushing and popping the position onto an array
// allows us to correctly handle nested includes during clean up.
var beginTemplateIndex = new Array();
// Mark the beginning of the include
Selenium.prototype.doBegin$Template$ = function(locator){
LOG.info("Begin Template " + locator + " at position " + testCase.debugContext.debugIndex);
// Add the current position to the tail of the beginTemplateIndex
beginTemplateIndex.push(testCase.debugContext.debugIndex);
};
// Clean up everything between the closest Begin$Template$ and this $End$Template$, and pop the position off the array.
Selenium.prototype.doEnd$Template$ = function(locator){
// Remove the last Begin$Template$ from the tail of the beginTemplateIndex
var currentBeginTemplateIndex = beginTemplateIndex.pop();
LOG.info("End Template " + locator + " at position " + currentBeginTemplateIndex);
// Delete the commands that we injected in injectIncludeTestCommands.
testCase.commands =
testCase.commands.slice(0,currentBeginTemplateIndex).concat(
testCase.commands.slice(testCase.debugContext.debugIndex+1, testCase.commands.length));
// Set the current command to the next one after the injected block.
testCase.debugContext.debugIndex = currentBeginTemplateIndex-1;
//Must refresh to syncup UI
editor.view.refresh();
};
datadriven.js
/************************************ DATADRIVEN EXTENSION START ********************************************/
/*
NAME:
datadriven
Licensed under Apache License v2
http://www.apache.org/licenses/LICENSE-2.0
PURPOSE:
Basic data driven testing.
Full documentation at http://wiki.openqa.org/display/SEL/datadriven
EXAMPLE USE:
The structure of your data driven test case will be;
-------------------------------------------
COMMAND |TARGET |VALUE
-------------------------------------------
loadTestData |<file path> |
while |!testdata.EOF() |
testcommand1 | |
testcommand...| |
testcommandn | |
endWhile | |
-------------------------------------------
AUTHOR:
Jonathan McBrien
jonathan#mcbrien.org
2008-10-22: v0.1: Initial version.
2009-01-16: v0.2: Updated for Firefox 3.
xmlTestData.prototype.load now uses the include extension's getIncludeDocumentBySynchronRequest method for better portability.
(Why reinvent the wheel? :) - with appreciation to the include extension's authors.)
*/
XML.serialize = function(node) {
if (typeof XMLSerializer != "undefined")
return (new XMLSerializer()).serializeToString(node) ;
else if (node.xml) return node.xml;
else throw "XML.serialize is not supported or can't serialize " + node;
}
function xmlTestData() {
this.xmlDoc = null;
this.testdata = null;
this.index = null;
}
xmlTestData.prototype.load = function(xmlloc) {
loader = new IDEIncludeCommand();
var xmlHttpReq = loader.getIncludeDocumentBySynchronRequest(xmlloc);
this.xmlDoc = xmlHttpReq.responseXML;
this.index = 0;
this.testdata = this.xmlDoc.getElementsByTagName("test");
if (this.testdata == null || this.testdata.length == 0) {
throw new Error("Test data couldn't be loaded or test data was empty.");
}
}
xmlTestData.prototype.EOF = function() {
if (this.index != null && this.index < this.testdata.length) return false;
return true;
}
xmlTestData.prototype.more = function() {
return !this.EOF();
}
xmlTestData.prototype.next = function() {
if (this.EOF()) {
LOG.error("No test data.");
return;
}
LOG.info(XML.serialize(this.testdata[this.index])); // Log should anything go wrong while testing with this data.
if (this.testdata[this.index].attributes.length != this.testdata[0].attributes.length) {
LOG.error("Inconsistent attribute length in test data.");
return;
}
for (i=0; i<this.testdata[this.index].attributes.length; i++){
if (null == this.testdata[0].getAttribute(this.testdata[this.index].attributes[i].nodeName)) {
LOG.error("Inconsistent attribute names in test data.");
return;
}
selenium.doStore(this.testdata[this.index].attributes[i].nodeValue, this.testdata[this.index].attributes[i].nodeName);
}
this.index++;
}
Selenium.prototype.testdata = null;
Selenium.prototype.doLoadTestData = function(xmlloc) {
testdata = new xmlTestData();
testdata.load(xmlloc);
};
Selenium.prototype.doNextTestData = function() {
testdata.next();
};
/************************************ DATADRIVEN EXTENSION END **********************************************/
Current solution is a SelBlocks component which allows you to do cycles according to the dataset in XML
ForXML | XMLFileName.XML
... test case steps
EndForXML
The XML should have specific structure
<testdata>
<vars storedVariable1="xxxxx" storedVariable2="yyyyy" .. storedVariableN="zzzzz" />
.. other record(s)
</testdata>
Each stored variable vill be available in test case as ${storedVariableN}.
You can produce XML by MS Excel or LibreOffice using Formulas like this one and copy it to whole table:
="<vars "&
" "&$A$1&"="""&A2&""" "&
" "&$B$1&"="""&B2&""" "&
..
" "&$X$1&"="""&X2&""" "&
"/>")
XML can be easily copypasted after each change of the dataset.
Selblocks contains the while, datadriven, goto, loop and other extensions mentioned in previous answers. You can use other functionalities of the Selblocks as conditional jumps, conditions, catch-try blocks, functions, etc. See full reference here: http://refactoror.wikia.com/wiki/Selblocks_Reference
Beware with new Selenium 3 release and Sel Core absence it is not guaranteed, that tests with Selblock addon will work in the future versions of the firefox.
You can also check this very nice blog article:
http://seleniumworks.blogspot.com/2014/01/selenium-ide-data-driven.html
This gives an explanation on how to use the needed plugins and where to download them from. It worked perfectly for me.
This answer pretty much has the same approach as the one provided by #Yevgen Ulyanenkov as I used his answer in order to find the above article. But has some more googling to it that hopefully will be helpful to someone.
I think you need to use loop I don't see your code so just check this one for selenium-ide loop If you have any more problem if so comment my answer. I can't comment into your question because reputation is not enough so. If possible please add your code into your question.

i am having a issue with json codeigniter rest its not closing the tag

i am having a problem with json codeigniter rest
i am making this call to the server and the problem its that its not closing the json tags
s, USA","clientUID":"7","email":null,"idipad":"2","dateModified":null},{"id":"19","uid":null,"name":"Wayne Corporation, Inc.","phone":"932345324","address":"Second st. 312, Gotham City","clientUID":"7","email":"waynecorp#gmail.com","idipad":"1","dateModified":null}]
its missing the final }
this is the code that creates the response :
$this->response(array('login'=>'login success!','user_admin_id'=>$user_id,'client'=>$client,'users'=>$users,'projects'=>$projects,'plans'=>$plans,'meetings'=>$meetings,'demands'=>$demands,'tasks'=>$tasks,'presences'=>$presences,'contractors'=>$contractors,'companies'=>$companies), 200);
this is the client call using curl :
$this->curl->create('http://dev.onplans.ch/onplans/index.php/api/example/login/format/json');
// Option & Options
$this->curl->option(CURLOPT_BUFFERSIZE, 10);
$this->curl->options(array(CURLOPT_BUFFERSIZE => 10));
// More human looking options
$this->curl->option('buffersize', 10);
// Login to HTTP user authentication
$this->curl->http_login('admin', '1234');
// Post - If you do not use post, it will just run a GET request
//$post = array('remember'=>'true','email'=>'admin.architect#onplans.ch','password'=>'password');
$post = array('remember'=>'true','email'=>'admin.architect#onplans.ch','password'=>'password');
$this->curl->post($post);
// Cookies - If you do not use post, it will just run a GET request
$vars = array('remember'=>'true','email'=>'manuel#ffff.com','password'=>'password');
$this->curl->set_cookies($vars);
// Proxy - Request the page through a proxy server
// Port is optional, defaults to 80
//$this->curl->proxy('http://example.com', 1080);
//$this->curl->proxy('http://example.com');
// Proxy login
//$this->curl->proxy_login('username', 'password');
// Execute - returns responce
echo $this->curl->execute();
// Debug data ------------------------------------------------
// Errors
$this->curl->error_code; // int
$this->curl->error_string;
print_r('error :::::LOGINN REMOTE:::::'.$this->curl->error_string);
// Information
$this->curl->info; // array
print_r('info :::::::::::::'.$this->curl->info);
the response belong to the rest api codeigniter from phil
/**
* Response
*
* Takes pure data and optionally a status code, then creates the response.
*
* #param array $data
* #param null|int $http_code
*/
public function response($data = array(), $http_code = null)
{
global $CFG;
// If data is empty and not code provide, error and bail
if (empty($data) && $http_code === null)
{
$http_code = 404;
// create the output variable here in the case of $this->response(array());
$output = NULL;
}
// If data is empty but http code provided, keep the output empty
else if (empty($data) && is_numeric($http_code))
{
$output = NULL;
}
// Otherwise (if no data but 200 provided) or some data, carry on camping!
else
{
// Is compression requested?
if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE)
{
if (extension_loaded('zlib'))
{
if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
{
ob_start('ob_gzhandler');
}
}
}
is_numeric($http_code) OR $http_code = 200;
// If the format method exists, call and return the output in that format
if (method_exists($this, '_format_'.$this->response->format))
{
// Set the correct format header
header('Content-Type: '.$this->_supported_formats[$this->response->format]);
$output = $this->{'_format_'.$this->response->format}($data);
}
// If the format method exists, call and return the output in that format
elseif (method_exists($this->format, 'to_'.$this->response->format))
{
// Set the correct format header
header('Content-Type: '.$this->_supported_formats[$this->response->format]);
$output = $this->format->factory($data)->{'to_'.$this->response->format}();
}
// Format not supported, output directly
else
{
$output = $data;
}
}
header('HTTP/1.1: ' . $http_code);
header('Status: ' . $http_code);
// If zlib.output_compression is enabled it will compress the output,
// but it will not modify the content-length header to compensate for
// the reduction, causing the browser to hang waiting for more data.
// We'll just skip content-length in those cases.
if ( ! $this->_zlib_oc && ! $CFG->item('compress_output'))
{
header('Content-Length: ' . strlen($output));
}
exit($output);
}
This answer was referenced from Github issue. Also raised by Pedro Dinis, i guest.
I met this problem today and take me long hours to search for the solution. I share here with hope to help someone like me.
The key is to replace around line 430 in the library file: REST_Controller.php :
header('Content-Length: ' . strlen($output));
by
header('Content-Length: ' . strlen("'".$output."'"));
UPDATE: The problem was solved here
Or you can just comment out the code, it will run fine. :)