cookies validation using selenium - selenium-webdriver

I am new to selenium. Actually I am working on some cookie validation project, which requires me to manually check the cookies present before and after clicking on some consent link in multiple browsers (Firefox, ie, chrome, safari).
Previously in the phase 1 project I ran a qtp script to treat the firefox as a window object and capture screenshots, but that is quite troublesome if the resolution changes or any minor look-n-feel changes. Also it is quite difficult to manage and it works on firefox only and I needed to write the same script again for chrome and safari. Apart from this since QTP is licensed product and currently we are using seat license so I can't run it on multiple machines to speed up execution.
So I thought moving to Selenium. As of now my requirement is:
1. open the page - take the screenshot once page loaded.
2. check the cookies using firebug or any other way - take the screenshot
3. click the link to close the consent - take screenshot once consent closed.
4. refresh the page and again check the cookies using firebug - take screenshot
So I done some research on selenium and found that I can validate the cookies using verifyCookie but still I need screenshot of firebug window for cookies. So I got stuck here.
please help me out here..
I found some possible way to do this on Firefox but now I was looking forward for something similar for Chrome if that possible. Thanks

Selenium cannot interact with firefox extensions, or the browser in the way you want it to.
What you can do is collect a list of cookies on the page by doing:
driver.manage().getCookies()
This will give you a list of all cookies that are visible to Selenium. Please note that this is the same as the cookies that are visible in the JavaScript console (Not all cookies are visible via JavaScript, for example cookies set with the HTTPOnly attribute) using:
document.cookie
I would suggest you use getCookies() to programatically validate the cookies.

In selenium IDE if you want to take screenshot of the page use captureEntirePageScreenshot command
captureEntirePageScreenshot | D:\\test.png |
D:\\test.png - path of file where you want to save the file

Got some solution
public class Selenium1st {
/**
* #param args
*/
public static void main(String[] args) throws IOException, AWTException{
// TODO Auto-generated method stub
System.setProperty("webdriver.firefox.bin","C:\\Program Files (x86)\\Mozilla Firefox\\Firefox.exe");
FirefoxProfile firefoxProfile = new FirefoxProfile();
String domain = "extensions.firebug.";
firefoxProfile.setPreference("app.update.enabled", false);
firefoxProfile.addExtension(new File("E:\\softs\\selenium-2.29.0\\firebug\\firebug-1.11.2-fx.xpi"));
firefoxProfile.setPreference(domain + "currentVersion", "1.11.2");
firefoxProfile.setPreference("extensions.firebug.cookies.enableSites", true);
firefoxProfile.setPreference("extensions.firebug.allPagesActivation", "on");
firefoxProfile.setPreference(domain + "framePosition", "bottom");
firefoxProfile.setPreference(domain + "defaultPanelName", "cookies");
WebDriver driver = new FirefoxDriver(firefoxProfile);
driver.get("http://www.google.com/webhp?complete=1&hl=en");
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("Cheese");
query.sendKeys("\n");
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(new Dimension(1024, 768)));
File path = new File("E:\\abc");//Path to your file
if(path.getName().indexOf(".jpg") == -1){
path = new File(path.getPath() + ".jpg");
}
ImageIO.write(img, "jpg", path);
}
}
might be useful.

Related

ReportViewer Custom Protocol

I am using the ReportViewer in my WPF application and I am trying to get a custom protocol to work with the application. So I get the ability to open sub-programs inside my application when a url is clicked inside the ReportViewer.
When I click on the custom-protocol-url (inside the ReportViewer) nothing happens.
When I open the same report via the Web-Browser, my URL works flawlessly.
It seems like the ReportViewer doesn't allow custom protocols? Has anyone experienced that aswell? Is there any documentation on that?
http, https and mailto are working in the ReportViewer.
I am just adding an Action in the Report pointing to my url
customurl://123
Url definition:
[HKEY_CLASSES_ROOT\customurl]
#="URL: customurl Protocol"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\customurl\shell]
[HKEY_CLASSES_ROOT\customurl\shell\open]
[HKEY_CLASSES_ROOT\customurl\shell\open\command]
#="\"C:\\Extra Programme\\TestAlert.exe\" \"%1\""
Testalert (just the test-program by microsoft):
static string ProcessInput(string s)
{
// TODO Verify and validate the input
// string as appropriate for your application.
return s;
}
static void Main(string[] args)
{
Console.WriteLine("Alert.exe invoked with the following parameters.\r\n");
Console.WriteLine("Raw command-line: \n\t" + Environment.CommandLine);
Console.WriteLine("\n\nArguments:\n");
foreach (string s in args)
{
Console.WriteLine("\t" + ProcessInput(s));
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
I have looked into the code of ReportViewer and found an if statement, that checks if the url starts with either http:// or https:// or mailto:.
It gets this information with Uri.UriSchemeHttp, Uri.UriSchemeHttps and Uri.UriSchemeMailto
So you could overwrite eg. Uri.UriSchemeHttp with "customurl" (if your url is customurl://123) before rendering the report.
var field = typeof(Uri).GetField("UriSchemeHttp");
field.SetValue(null, "customurl");
The more elegant solution would be, to use a webbrowser control and just show the SSRS Web-Page

Jmeter WebDriverSampler fail with Chromedriver headless

I have some tests with WebDriverSampler in Jmeter that work correctly with chromedriver. It is a selenium script that opens a web page and checks that it contains a series of elements. Everything works right until I've tried with the chromedriver headless option.
In this case I get the exception "Expected condition failed: waiting for presence of element located by: By.xpath: ..." as if that element did not exist yet to be loaded. I do not know what can happen, because if I stop using the headless option, if everything works correctly and find the element that really exists.
This is an example of code used(it works without the headless option):
var wait = new support_ui.WebDriverWait(WDS.browser, 30);
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
WDS.sampleResult.sampleStart();
WDS.sampleResult.getLatency();
WDS.browser.get('http://mi-app/');
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento_existente')));
WDS.log.info('OK')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail');
WDS.log.error(e.message)
}
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento2_existente')));
WDS.log.info('OK2')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail2');
WDS.log.error(e.message)
}
WDS.sampleResult.sampleEnd();
I hope someone can help me with this problem, because I need to use the headless option. Thank you very much for your time.
You can print the page source to jmeter.log file by using the following function:
WDS.log.info(WDS.browser.getPageSource())
Or even save it into a separate file like:
org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('test.html'), WDS.browser.getPageSource())
Or take screenshot on failure like:
WDS.browser.getScreenshotAs(org.openqa.selenium.OutputType.FILE).renameTo(new java.io.File('test.png'))
Check out The WebDriver Sampler: Your Top 10 Questions Answered article for more information.
Also be aware that if the machine where you run your Selenium tests doesn't have GUI you can still normally launch browsers using i.e. Xvfb on Linux or under Local System account on Windows

How can enroll student, using unique application number for run Multiple browsers like chrome, firefox in selenium webdriver

Scenario: Unique application number(Zee1106) using to enroll students and running testng for Multiple browsers(parallel) like chrome, firefox in selenium webdriver.
In the above scenario, I have run the test suite,first browser(chrome) enrolled successfully and the next browser(firefox) is not enrolled. Because already enrolled alert was coming. In this scenario, How can i enroll students using unique application number for multiple browser in webdriver.
Thanks,
Vairamuthu
There are quite a few ways to achieve this. One easiest way is to have the "Application Numbers" stored as a comma separated values in your test data sheet and use each for the respective browsers. Example:
//Assume applicationNo is stored as a comma separated value in test data. Something like this
String applicationNo="zee1106, zee1107, zee1108"; //please read these data from test data sheet
String[] unquieAppNo=applicationNo.split(",");
//get the browserName
Capabilities caps = ((RemoteWebDriver) driver).getCapabilities();
String browserName = caps.getBrowserName();
//if the browser name is chrome then use one of the application id and so on for each browser.
if(browserName.equalsIgnoreCase("chrome")){
driver.findElement(By.id("<employee app number>")).sendKeys(unquieAppNo[0]);
}else if (browserName.equalsIgnoreCase("firefox")) {
driver.findElement(By.id("<employee app number>")).sendKeys(unquieAppNo[1]);
}else{ //any other browser
driver.findElement(By.id("<employee app number>")).sendKeys(unquieAppNo[2]);
}
It is hard to tell with no code posted at all. Which Language you are working on?Please post the way you instantiate you Webdriver. From your description, I'm guessing that you are using something like this (static):
public static WebDriver driver;
Whilst you need a different WebDriver instance everytime:
public WebDriver driver;

How to take full page screen shot in internet explorer using selenium webdrivers

I am not able to take the whole page screen shot using selenium webdriver.I am using internet explorer.
I tried robot function of java using mouse roll button but failed.
Please try the following let me know if it works for you
WebDriver driver = new FirefoxDriver();
driver.get("http://www.somewebsite.com/");
File imgFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(imgFile , new File("c:\\tmp\\test.png"));
if i have misunderstood you que please let me know
If the above answer fails, you can give a try making using of Augemented WebDriver, which can be used with IEDriver on it's latest version, try following code
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenFile.getAbsolutePath(), new File("c:\\tmp\\test.png"));
You can also get screenshot in the form of bytes, by switching the OutputType as required
.getScreenshotAs(OutputType.BYTES)

Download file with JSF

everyone!
I have a trouble. I tried to save excel file in jsf web application.
I generated file by my utils and trying to get "save" window, but I failed.
Here is my code:
<div>
<h:commandButton value="Apply" actionListener="#{hornPhonesBean.generateReport}"/>
</div>
and:
public void generateReport(ActionEvent event) {
System.out.println("GENERATE REPORT FROM = " + this.dateFrom + "; TO = " + this.dateTo);
try {
XSSFWorkbook workbook = (XSSFWorkbook) HornReportGenerator.getWorkbook(null, null);
String fileName = "1.xlsx";
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
// Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.responseReset();
// Check http://www.w3schools.com/media/media_mimeref.asp for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentType("application/vnd.ms-excel");
// Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
//ec.setResponseContentLength(contentLength);
// The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream output = ec.getResponseOutputStream();
workbook.write(output);
output.flush();
output.close();
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
System.out.println("END");
} catch (Exception e) {
e.printStackTrace();
}
}
I read suggestions here and from another forums - everyone says I shouldnt use , but I didn't use it at all.
Then I thought that the problem could be in the
<ice:form>,
where I kept the
<h:commandButton>,
and I changed to
<h:form>,
but it didn't help.
Maybe the problem in the request - it has header Faces-Request partial/ajax. But I am not sure.
Please give me some ideas - I already spent 4 hours for this crazy jsf download issue)
Maybe the problem in the request - it has header Faces-Request partial/ajax. But I am not sure.
This suggests that the request is an ajax request. You can't download files by ajax. Ajax requests are processed by JavaScript which has for obvious security reasons no facilities to programmatically pop a Save As dialogue nor to access/manipulate client's disk file system.
Your code snippet does however not show that you're using ajax. Perhaps you oversimplified it too much or you're using ICEfaces which silently auto-enables ajax on all standard JSF command components.
In any case, you need to make sure that it's not sending an ajax request.
See also:
How to provide a file download from a JSF backing bean?
ICEfaces libary in classpath prevents Save As dialog from popping up on file download

Resources