How Can I set chrome browser to automatically download a pdf using QAF and WebDriverManager - selenium

Using a datasheet, I usually pass a browser name into a class I created to select which browser I want to run my tests from. Recently, I've been working on an app in which I need to download a PDF and then verify its contents. I have everything working successfully other than downloading the PDF. With WebDriverManager, it creates a browser profile every time a test runs, and so, I need to update chromeOptions to download PDFs automatically before at the start of the script.
Here is the code that I already have. I just need help with what to put in the prefs for this to work. -
public static void selectBrowser(String strBrowser) {
switch (strBrowser) {
case "Chrome":
String chromePrefs = "{'goog:chromeOptions':{'prefs':{'profile.default_content_settings.popups':0}}}";
ConfigurationManager.getBundle().setProperty("chrome.additional.capabilities", chromePrefs);
TestBaseProvider.instance().get().setDriver("chromeDriver");
Reporter.log("Chrome Browser was set", MessageTypes.Info);
break;
}
}

After researching for hours, finally found that I needed to use the plugins.always_open_pdf_externally preference. Here is the code for anyone who might need it.
Note, the "goog:" before chromeOptions is necessary since I have WebDriverManager enabled. With 3rd party driver managers, we need to put "goog:" before chromeOptions for it to work.
You can simply put it in the application.properties like this -
chrome.additional.capabilities={"goog:chromeOptions":{"args":[--disable-extensions],"prefs":{"plugins.always_open_pdf_externally":true}}}
or you can put it in the code I have up top like this
String chromePrefs = "{'goog:chromeOptions':{'args':[],'prefs':{\"plugins.always_open_pdf_externally\":true}}}";

Related

How to find the driver instance in QAF framework

During execution I want to know which browser currently the script is running and do some actions based on the browser the script is running.
I am using
Option 1:
if (new QAFExtendedWebDriver().getUnderLayingDriver().equals("ChromeDriver")) {
// Do`enter code here` some thing if this is a chrome browser
}
else if (new QAFExtendedWebDriver().getUnderLayingDriver() instanceof FirefoxDriver) {
}
Thsi option is not working during my excution. What is the way to know which browser I am in ?
Below are few examples:
//to get driver name for this thread which provided using driver.name
String drivername = TestBaseProvider.instance().get().getDriverName();
//if running in browser, browser name for this thread, will not be avialable for mobile native or hybrid apps
String browserName =getDriver().getCapabilities().getBrowserName();
//underlying driver class name, which can be remote driver if you are using remote driver
String driverClassname = getDriver().getUnderLayingDriver().getClass().getSimpleName();
you didn't provided details about what you are trying to achieve. If you want to do something when browser opens, you can utilize driver listener.
If you are using bdd and you have platform/browser specific code, instead of using if else you can have separate step implementation for each platform/browser in different package and load step provider package accordingly, for example:
step.provider.pkg=com.exmple.steps.common;com.exmple.steps.chrome

How do I test a website without opening it using automation?

I am able to use Selenium web driver to test the website and get the result. But I need to get the result without opening a single web page. I made some R&D and found Selenium can't do this.
Can any body tell me how can I achieve this?
Thanks,
Rahul
Give Htmlunitdriver a try
Enter this line in your code
driver = new HtmlUnitDriver(true);
true = to enable javascript support.
In case you'll see many warnings in your console once you run your test. To ignore them simply do this
static Logger log = Logger.getLogger("com.gargoylesoftware");
log.setLevel(Level.OFF);
driver = new HtmlUnitDriver(true);
Else there is always other options like PhantomJS
Source: SoftwareAutomata

disable screenshots in phantomjs

How do I stop phantomjs from taking screenshots? I need to run a test in parrallel a bunch of times using jmeter. JMeter randomly fails on some of the tests and I'm suspecting it could be Phantomjs trying to save a screenshot of the test run. With multiple threads trying to write a file to the same place at the same time I'm assuming this may be an issue. If not I'd still like to try disabling the ability to save a screenshot.
I had needed to disable phantomjs from logging and had gotten it to work with the following code:
headlessNoLogs {
driver = {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("takesScreenshot", false);
ArrayList<String> cliArgsCap = new ArrayList<String>();
cliArgsCap.add("--webdriver-loglevel=NONE");
caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);
Logger.getLogger(PhantomJSDriverService.class.getName()).setLevel(Level.OFF);
new PhantomJSDriver(caps)
}
}
Disabling the logging is working as expected. But I'm setting takesScreenshot, false and phantomjs is still taking screenshots.

how does selenium webdriver upload files to the browser?

I am a javascript/java developer and I have been trying to figure out how the selenium webdriver automation framework uploads files from the file system. It is impossible to set a file input via javascript because it is a security violation. Yet somehow webdriver is able to do this with the following command:
driver.setFileDetector(new LocalFileDetector());
WebElement upload = driver.findElement(By.id("myfile"));
upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg");
driver.findElement(By.id("submit")).click();
So they are setting the value by sending keys to it? I don't get it. I have looked through the source code found here:
http://code.google.com/p/selenium/source/checkout
I am still not able to find where they do this.
Edit: My question is not how to do this with selenium, but how did the selenium developers make this possible? How did they get around the security restrictions in javascript? How are they uploading the file?
Nice question buddy...they have written a HTTP proxy to solve the Javascript secuirty restrictions. Using this proxy made it possible to side-step many of the constraints of the "same host origin" policy, where a browser won't allow Javascript to make calls to anything other than the server from which the current page has been served.
Moreover WebDriver uses the alternative approach of firing events at the OS level. As these "native events" aren't generated by the browser this approach circumvents the security restrictions placed on synthesized events and, because they are OS specific, once they are working for one browser on a particular platform reusing the code in another browser is relatively easy.
Most of the content above is referenced from the below..do read the following reference for more details on Selenium internals
http://www.aosabook.org/en/selenium.html
The upload windowns file function HTML codes are:
<input id="fileField" type="file" onchange="document.getElementById('textfield').value=this.value" name="position">
<input type="submit" value="导入">
You can use the following codes to finishing uploading a windows file. It works sucessfully and the codes don't include clicking a upload action.
driver.FileDetector = new LocalFileDetector();
FindElement(By.Id("fileField")).SendKeys(#"C:\Users\admin\Desktop\ProfessionCodes.txt"); FindElement(By.CssSelector("input[type='submit']")).Click();
I have Uploaded photo on Facebook Using Selenium Webdriver and AutoIt
Steps are as below
Step 1
On eclipse code Upto (Upload a Photo) is as below:
WebElement Upload = Firefox.findElement(By.cssSelector("input[id^='u_']"));
Upload.click();
Step 2
Downloaded and install AutoIt: http://www.autoitscript.com/site/autoit/downloads/ (Download ZIP)
Step 3
Write the code as below in notepad and saved it as PhotoUpload.au3
WinWaitActive("File Upload")
Send("D:\Photo0116.jpg")
Send("{ENTER}")
Step 4: Right click on this .au3 File & compile it.
Step 5: Add code in script file as below:
try {
String[] commands = new String[]{};
// Location of the autoit executable
commands = new String[] {"D:\\My softwares\\install software\\selenium\\UploadPhoto3.exe"};
Runtime.getRuntime().exec(commands);
}
catch (IOException e) {}
Step 6: Run script (PhotoUpload.java)
Step 7: Photo get uploaded successfully.
//assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
or
driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");
Try this and let me know
In some cases specially with Java you need to create a File object and pass the absolutePath() to the Driver, like the following:
File file = new File(sampleFile);
driver.findElement(By.id("<Your input tag with type of File>")).sendKeys(file.getAbsolutePath());
Sample file is a string that point to the file that needs to be uploaded.
This works for me in Firefox and Chrome.
This helped me to do file upload,
Code :
public class FileUpload {
#Test
public void test() {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.freepdfconvert.com/pdf-word");
driver.findElement(By.id("clientUpload")).click();
driver.switchTo()
.activeElement()
.sendKeys(
"/home/likewise-open/GLOBAL/123/Documents/filename.txt");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.id("convertButton"));
/*
* driver.switchTo().activeElement()
* .sendKeys("selenium_2_testing_tools.pdf"); ;
*/
{
driver.wait(30000);
} catch (Exception er) {
System.out.println(er);
}
}
}

Login popup window using selenium webdriver?

the popup window is only happening if I use the Fire Fox browser otherwise, is there a way to fix this problem? I have to enter userid/password every time the i use FF as my browser.
currently, I am entering every time i run my test which is very painful but looking to make it more automated....
I have goggled and found two links here and here but no avail
http://username:password#xyz.com
This worked for me (xyz.com being the site name)
After spending hours reading I finally found the solution which works pretty well and I hope this will help others too. - Enjoy!!
First - follow this steps:
1) Open the FireFox browser
2) Type the following `about:config`
3) Look for `network.http.phishy-userpass-length` if you don't find then create a new Integer key
Create a new Integer key (right-click->New->Integer): `network.http.phishy-userpass-length` with value `255`
Second: You need to create a Firefox driver with the following:
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("network.http.phishy-userpass-length", 255);
profile.SetPreference("network.automatic-ntlm-auth.trusted-uris", "YOUR HOST ADDRESS HERE");
_driver = new FirefoxDriver(profile);
let me know if you have any questions.
If this is a windows user account & password, then you need to enable the integrated windows login by setting
network.negotiate-auth.delegation-uris: MyIISServer.domain.com
network.automatic-ntlm-auth.trusted-uris: MyIISServer.domain.com
network.automatic-ntlm-auth.allow-proxies: True
network.negotiate-auth.allow-proxies: True
in the Firefox profile that WebDriver starts. Once you have the profile created and saved (run "Firefox -P" when no other instances are running to select a profile), you can do this in the code:
File profileDir = new File("C:/wherever/SeleniumFirefoxProfile");
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.setEnableNativeEvents(true);
driver = new FirefoxDriver(profile);
I have had to handle these a few times, but my approach is using a script outside Selenium. Are you working on Windows?
Basically what you do is this:
1) Prior to loading the page, clicking the URL, etc that causes that dialog to appear:
-- Launch an asynchronous script to handle the login
2) Then load the page, click the link, etc
-- Selenium will block until your asynch script completes
The async script:
-- Sleep for a few seconds
-- Activate the dialog
-- Send the username
-- Send a TAB
-- Send the password
-- Send a TAB
-- Send the Enter Key
If you are working on windows, I can post sample scripts to handle this. I've done it with Java and C#, but I would guess that basically the same thing would work regardless of how you are writing your tests (unless you are strictly using the FF plugin, in which case this won't work).
Let me know if you'd like more details.
You can use a FF plugin "autoauth". Download this plugin and create Firefox instance by the following way:
FirefoxProfile firefoxProfile = new ProfilesIni().getProfile("default");
File pluginAutoAuth = new File("D:\\autoauth-2.1-fx+fn.xpi");
firefoxProfile.addExtension(pluginAutoAuth);
driver = new FirefoxDriver(firefoxProfile);
I used "autoauth-2.1-fx+fn.xpi"